blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
86894c7eee40d9ca3604f89592fb7183fb001531 | b08639a23dd4d2ecde299a6da48c6c1fb256bd31 | /Hazel/src/Hazel/Renderer/SubTexture2D.hpp | 6c33ac2ba0f61471b807b17402f8f191bd4c3bcc | [
"Apache-2.0"
] | permissive | Ligh7bringer/Hazel | f03743c69291de66a7d00c3d3a1ee6f5511c975a | 1608ccb2abd911b5768f28de97082ec267beedd0 | refs/heads/master | 2023-06-07T17:13:17.089432 | 2023-05-29T01:27:03 | 2023-05-29T01:27:03 | 197,222,071 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 625 | hpp | #pragma once
#include "Texture.hpp"
#include <glm/glm.hpp>
namespace Hazel
{
class SubTexture2D
{
public:
SubTexture2D(const Ref<Texture2D>& texture, const glm::vec2& min, const glm::vec2& max);
const Ref<Texture2D> GetTexture() const { return m_Texture; }
const glm::vec2* GetTextureCoords() const { return m_TexCoords; }
static Ref<SubTexture2D> CreateFromCoords(const Ref<Texture2D>& texture,
const glm::vec2& coords,
const glm::vec2& cellSize,
const glm::vec2& spriteSize = {1, 1});
private:
Ref<Texture2D> m_Texture;
glm::vec2 m_TexCoords[4];
};
} // namespace Hazel
| [
"s.georgiev255@gmail.com"
] | s.georgiev255@gmail.com |
6190bc3c9f8844fed3301161a688d7304e02da9c | ced6b91821f1f3b9c8d8e209e4306b309256c2d7 | /algorithm/basic-algorithm/graph-theory/DFS.cpp | 381bbcb85515243dbe59923da9ec97009de9dda4 | [] | no_license | Aleda/libsummer | 9c3edd2d4f57203ca6b25e3604b3056bdc30c96e | 4cc7c88948a4a6a2c75f7ca1ddc214263f9fd09c | refs/heads/master | 2016-09-16T16:38:18.398349 | 2016-03-13T15:50:30 | 2016-03-13T15:50:30 | 32,668,783 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,578 | cpp | #include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
using namespace std;
const int maxe = 10011;
const int maxn = 111;
const int INF = 0x3fffffff;
int K;
int N;
int R;
struct Edge
{
int v;
int length;
int val;
int next;
}e[maxe];
int head[maxn];
int vis[maxn];
int min_len;
int idx;
void init()
{
idx = 0;
min_len = INF;
memset(head, -1, sizeof(head));
memset(vis, 0, sizeof(vis));
}
void addEdge(int a, int b, int length, int val)
{
e[idx].v = b;
e[idx].length = length;
e[idx].val = val;
e[idx].next = head[a];
head[a] = idx++;
}
void DFS(int v, int now_len, int now_money)
{
if (now_len >= min_len)
{
return ;
}
if (v == N && now_len < min_len)
{
min_len = now_len;
return ;
}
int p = head[v];
while (p != -1)
{
int point = e[p].v;
int len = e[p].length;
int money = e[p].val;
if (!vis[point] && now_money + money <= K)
{
vis[point] = 1;
DFS(point, now_len + len, now_money + money);
vis[point] = 0;
}
p = e[p].next;
}
return ;
}
int main()
{
while (scanf("%d", &K) != EOF)
{
init();
scanf("%d", &N);
scanf("%d", &R);
int S, D, L, T;
for (int i = 0; i < R; i++)
{
scanf("%d%d%d%d", &S, &D, &L, &T);
addEdge(S, D, L, T);
//addEdge(D, S, L, T);
}
DFS(1, 0, 0);
printf("%d\n", min_len);
}
return 0;
}
| [
"lishuo02@baidu.com"
] | lishuo02@baidu.com |
e5cd784bded254f2511751088b5cff2598e2c540 | df872c79b4547a12874fdaee0a363d1a3415c361 | /JumpPoint.cpp | 52d75bc458f609ed165959a58bb6e9956dfd3e23 | [
"MIT"
] | permissive | ugokce/Efficent-Path-Finding-Algorithms | b06985af349c123bd76406700a8ae406cea0f186 | 7f4766cad5b8229ac6adb323209e34b5f47e7b5d | refs/heads/master | 2022-12-15T05:46:03.940822 | 2020-07-06T22:46:45 | 2020-07-06T22:46:45 | 296,418,955 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,774 | cpp | #include <stdio.h>
#include <vector>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <list>
#include <map>
bool isForced = false;
struct Node
{
public:
void setPositon(const int xPosition, const int yPosition)
{
x = xPosition;
y = yPosition;
}
Node()
{
x = 0;
y = 0;
heuristicCost = 99999;
localCost = 99999;
isVisited = false;
parent = nullptr;
}
int x = 0;
int y = 0;
int heuristicCost = 99999;
int localCost = 99999;
bool isVisited = false;
Node* parent = nullptr;
};
struct Grid
{
public:
Grid(const unsigned int mapWidth, const unsigned int mapHeight, const unsigned char* pMap)
{
gridNodes = std::vector<Node*>(mapWidth * mapHeight);
for (int i = 0; i < mapWidth * mapHeight; i++)
{
gridNodes[i] = new Node();
const int y = i == 0 ? 0 : i / mapWidth;
gridNodes[i]->y = y;
gridNodes[i]->x = i - (y * mapWidth);
}
gridWidth = mapWidth;
gridHeight = mapHeight;
gridMap = pMap;
}
int getIndexFromPosition(const int posX, const int posY)
{
return posY * gridWidth + posX;
}
bool CheckIsObstacle(int positionX, int positionY)
{
return gridMap[getIndexFromPosition(positionX, positionY)] == '\0' ? true : false;
}
bool CheckIsObstacle(Node* node)
{
return gridMap[getIndexFromPosition(node->x, node->y)] == '\0' ? true : false;
}
bool IsNodeValid(int positionX, int positionY)
{
return positionX >= 0 && positionX < gridWidth
&& positionY >= 0 && positionY < gridHeight && !CheckIsObstacle(positionX, positionY);
}
Node* getNodeFromPosition(const int posX, const int posY)
{
if (IsNodeValid(posX, posY))
{
return gridNodes[getIndexFromPosition(posX, posY)];
}
return nullptr;
}
std::vector<Node*> getNeighbours(Node* currentNode)
{
auto* parentNode = currentNode->parent;
std::vector<Node*> neighbours;
if (parentNode == nullptr)
{
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
if (x == 0 && y == 0)
continue;
if (IsNodeValid(x + currentNode->x, y + currentNode->y))
{
neighbours.emplace_back(gridNodes[getIndexFromPosition(x + currentNode->x, y + currentNode->y)])
->setPositon(x + currentNode->x, y + currentNode->y);
}
}
}
}
else
{
int xDirection = std::clamp(currentNode->x - parentNode->x, -1, 1);
int yDirection = std::clamp(currentNode->y - parentNode->y, -1, 1);
if (xDirection != 0 && yDirection != 0)
{
bool neighbourUp = IsNodeValid(currentNode->x, currentNode->y + yDirection);
bool neighbourRight = IsNodeValid(currentNode->x + xDirection, currentNode->y);
bool neighbourLeft = IsNodeValid(currentNode->x - xDirection, currentNode->y);
bool neighbourDown = IsNodeValid(currentNode->x, currentNode->y - yDirection);
if (neighbourUp)
{
neighbours.emplace_back(gridNodes[getIndexFromPosition(currentNode->x, currentNode->y + yDirection)])
->setPositon(currentNode->x, currentNode->y + yDirection);
}
if (neighbourRight)
{
neighbours.emplace_back(gridNodes[getIndexFromPosition(currentNode->x + xDirection, currentNode->y)])
->setPositon(currentNode->x + xDirection, currentNode->y);
}
if (neighbourUp || neighbourRight)
{
if (IsNodeValid(currentNode->x + xDirection, currentNode->y + yDirection))
{
neighbours.emplace_back(gridNodes[getIndexFromPosition(currentNode->x + xDirection, currentNode->y + yDirection)])
->setPositon(currentNode->x + xDirection, currentNode->y + yDirection);
}
}
if (!neighbourLeft && neighbourUp)
{
if (IsNodeValid(currentNode->x - xDirection, currentNode->y + yDirection))
{
neighbours.emplace_back(gridNodes[getIndexFromPosition(currentNode->x - xDirection, currentNode->y + yDirection)])
->setPositon(currentNode->x - xDirection, currentNode->y + yDirection);
}
}
if (!neighbourDown && neighbourRight)
{
if (IsNodeValid(currentNode->x + xDirection, currentNode->y - yDirection))
{
neighbours.emplace_back(gridNodes[getIndexFromPosition(currentNode->x + xDirection, currentNode->y - yDirection)])
->setPositon(currentNode->x + xDirection, currentNode->y - yDirection);
}
}
}
else
{
if (xDirection == 0)
{
if (IsNodeValid(currentNode->x, currentNode->y + yDirection))
{
neighbours.emplace_back(gridNodes[getIndexFromPosition(currentNode->x, currentNode->y + yDirection)])
->setPositon(currentNode->x, currentNode->y + yDirection);
if (!IsNodeValid(currentNode->x + 1, currentNode->y))
if (IsNodeValid(currentNode->x + 1, currentNode->y + yDirection))
{
neighbours.emplace_back(gridNodes[getIndexFromPosition(currentNode->x + 1, currentNode->y + yDirection)])
->setPositon(currentNode->x + 1, currentNode->y + yDirection);
}
if (!IsNodeValid(currentNode->x - 1, currentNode->y))
if (IsNodeValid(currentNode->x - 1, currentNode->y + yDirection))
{
neighbours.emplace_back(gridNodes[getIndexFromPosition(currentNode->x - 1, currentNode->y + yDirection)])
->setPositon(currentNode->x - 1, currentNode->y + yDirection);
}
}
}
else
{
if (IsNodeValid(currentNode->x + xDirection, currentNode->y))
{
neighbours.emplace_back(gridNodes[getIndexFromPosition(currentNode->x + xDirection, currentNode->y)])
->setPositon(currentNode->x + xDirection, currentNode->y);
if (!IsNodeValid(currentNode->x, currentNode->y + 1))
{
neighbours.emplace_back(gridNodes[getIndexFromPosition(currentNode->x + xDirection, currentNode->y + 1)])
->setPositon(currentNode->x + xDirection, currentNode->y + 1);
}
if (!IsNodeValid(currentNode->x, currentNode->y - 1))
{
neighbours.emplace_back(gridNodes[getIndexFromPosition(currentNode->x + xDirection, currentNode->y - 1)])
->setPositon(currentNode->x + xDirection, currentNode->y - 1);
}
}
}
}
}
return neighbours;
}
private:
std::vector<Node*> gridNodes;
unsigned int gridWidth = 0;
unsigned int gridHeight = 0;
const unsigned char* gridMap;
};
Node* Jump(Node* currentNode, Node* parentNode, Node* targetNode, int directionX, int directionY, Grid* grid)
{
if (currentNode == nullptr || grid->CheckIsObstacle(currentNode))
{
return nullptr;
}
if (currentNode == targetNode)
{
return currentNode;
}
isForced = false;
if (directionX != 0 && directionY != 0)
{
if ((!grid->IsNodeValid(currentNode->x - directionX, currentNode->y) && grid->IsNodeValid(currentNode->x - directionX, currentNode->y + directionY)) ||
(!grid->IsNodeValid(currentNode->x, currentNode->y - directionY) && grid->IsNodeValid(currentNode->x + directionX, currentNode->y - directionY)))
{
return currentNode;
}
Node* nextHorizontalNode = grid->getNodeFromPosition(currentNode->x + directionX, currentNode->y);
Node* nextVerticalNode = grid->getNodeFromPosition(currentNode->x, currentNode->y + directionY);
if (nextHorizontalNode == nullptr || nextVerticalNode == nullptr)
{
bool found = false;
if (nextHorizontalNode != nullptr && grid->IsNodeValid(currentNode->x + directionX, currentNode->y + directionY))
{
found = true;
}
if (nextVerticalNode != nullptr && grid->IsNodeValid(currentNode->x + directionX, currentNode->y + directionY))
{
found = true;
}
if (!found)
return nullptr;
}
if (Jump(nextHorizontalNode, currentNode, targetNode, directionY, directionX, grid) != nullptr || Jump(nextVerticalNode, currentNode, targetNode, directionY, directionX, grid) != nullptr)
{
if (!isForced)
{
Node* temp = grid->getNodeFromPosition(currentNode->x + directionX, currentNode->y + directionY);
return Jump(temp, currentNode, targetNode, directionY, directionX, grid);
}
else
{
return currentNode;
}
}
}
if (directionX != 0)
{
if ((grid->IsNodeValid(currentNode->x + directionX, currentNode->y + 1) && !grid->IsNodeValid(currentNode->x, currentNode->y + 1)) ||
(grid->IsNodeValid(currentNode->x + directionX, currentNode->y - 1) && !grid->IsNodeValid(currentNode->x, currentNode->y - 1)))
{
isForced = true;
return currentNode;
}
}
else
{
if ((grid->IsNodeValid(currentNode->x + 1, currentNode->y + directionY) && !grid->IsNodeValid(currentNode->x + 1, currentNode->y)) ||
(grid->IsNodeValid(currentNode->x - 1, currentNode->y + directionY) && !grid->IsNodeValid(currentNode->x - 1, currentNode->y)))
{
isForced = true;
return currentNode;
}
}
Node* nextNode = grid->getNodeFromPosition(currentNode->x + directionX, currentNode->y + directionY);
return Jump(nextNode, currentNode, targetNode, directionX, directionY, grid);
}
float CalculateManhattanDistance(Node* firstNode, Node* secondNode)
{
return abs(firstNode->x - secondNode->x) + abs(firstNode->y - secondNode->y);
}
std::list<Node*> findSuccessors(Node* currentNode, Node* targetNode, Grid* grid)
{
std::list<Node*> successors;
std::vector<Node*> neighbours = grid->getNeighbours(currentNode);
for (Node* neighbour : neighbours)
{
int dirX = std::clamp(neighbour->x - currentNode->x, -1, 1);
int dirY = std::clamp(neighbour->y - currentNode->y, -1, 1);
Node* jumpPoint = Jump(neighbour, currentNode, targetNode, dirX, dirY, grid);
if (jumpPoint != nullptr)
{
successors.emplace_back(jumpPoint);
}
}
return successors;
}
std::vector<Node*> openList;
std::list<Node*> jumpNodes;
bool CompareNodes(Node* firstNode, Node* secondNode)
{
return firstNode->heuristicCost < secondNode->heuristicCost;
}
int RetracePath(Node* startNode, Node* targetNode, int* pOutBuffer, Grid* grid)
{
Node* currentNode = targetNode;
int index = 0;
while (currentNode != startNode)
{
pOutBuffer[index] = grid->getIndexFromPosition(currentNode->x, currentNode->y);
currentNode = currentNode->parent;
if (currentNode == nullptr || currentNode->parent == nullptr)
{
return -1;
}
}
return index;
}
void JumpPointSearch(Node* startNode, Node* endNode, Grid* grid)
{
Node* currentNode = startNode;
bool found = false;
currentNode->x = startNode->x;
currentNode->y = startNode->y;
currentNode->parent = currentNode;
openList.push_back(currentNode);
currentNode->heuristicCost = CalculateManhattanDistance(currentNode, endNode);
currentNode->localCost = 0;
while (!openList.empty())
{
std::sort(openList.begin(), openList.end(), CompareNodes);
currentNode = openList.front();
openList.erase(openList.begin());
if (currentNode == endNode)
{
found = true;
break;
}
currentNode->isVisited = true;
std::list<Node*> successorNodes = findSuccessors(currentNode, endNode, grid);
for (Node* successor : successorNodes)
{
jumpNodes.emplace_back(successor);
if (successor->isVisited)
{
continue;
}
int globalCost = currentNode->localCost + CalculateManhattanDistance(currentNode, successor);
if (globalCost < successor->localCost)
{
successor->localCost = globalCost;
successor->heuristicCost = CalculateManhattanDistance(successor, endNode);
successor->parent = currentNode;
openList.emplace_back(successor);
}
}
}
}
int FindPath(const int nStartX, const int nStartY, const int nTargetX, const int nTargetY, const unsigned char* pMap,
const int nMapWidth, const int nMapHeight, int* pOutBuffer, const int nOutBufferSize)
{
Grid* grid = new Grid(nMapWidth, nMapHeight, pMap);
Node* startNode = grid->getNodeFromPosition(nStartX, nStartY);
Node* targetNode = grid->getNodeFromPosition(nTargetX, nTargetY);
JumpPointSearch(startNode, targetNode, grid);
return RetracePath(startNode, targetNode, pOutBuffer, grid);
}
int main()
{
unsigned char pMap[] = { 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1 };
int pOutBuffer[12];
const int counter = FindPath(0, 0, 1, 2, pMap, 4, 3, pOutBuffer, 12);
printf("%d \n", counter);
for (int i = 0; i < counter; i++)
{
printf("%d, ", pOutBuffer[i]);
}
return 1;
}
| [
"32913922+ugokce@users.noreply.github.com"
] | 32913922+ugokce@users.noreply.github.com |
80c13e90481cba213e94c464807941f2995a65be | b2d70bc01464859761817522e6e4ef157b6bfda6 | /Competitions/Hackercup/2021/Qualification/Consistency - Chapter 1/solution.cpp | 47088a791f4d4f57f47dd44bb673b2438cdbfca5 | [] | no_license | ben-jnr/competitive-coding | a1b65b72db73a7b9322281ca9e788937ac71eb31 | 4e3bcd90b593749aa29228c54a211bf0da75501a | refs/heads/main | 2023-08-26T07:43:10.018640 | 2021-10-27T13:50:08 | 2021-10-27T13:50:08 | 273,961,346 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 835 | cpp | #include<iostream>
#include<unordered_map>
#include<climits>
using namespace std;
int main() {
int t,tlimit,i,minimum,vcount,ccount,ans;
char c;
string s;
cin>>tlimit;
t=1;
while(t<=tlimit) {
cin>>s;
unordered_map<char,int> m;
vcount = ccount = 0;
minimum = INT_MAX;
for(c='A'; c<='Z'; c++)
m.insert({c,0});
for(i=0; s[i]!='\0'; i++) {
m[s[i]]++;
switch(s[i]) {
case 'A': case 'E': case 'I': case 'O':
case 'U': vcount++;
break;
default: ccount++;
break;
}
}
for(c='A'; c<='Z'; c++) {
switch(c) {
case 'A': case 'E': case 'I': case 'O':
case 'U': minimum = min(minimum, ccount + 2*(vcount-m[c]));
break;
default: minimum = min(minimum, vcount + 2*(ccount-m[c]));
break;
}
}
cout<<"Case #"<<t<<": "<<minimum<<endl;
t++;
}
}
| [
"bichubenkuruvilla@gmail.com"
] | bichubenkuruvilla@gmail.com |
aba22086436a372f9849b632105d07de691ebcc7 | 96a72e0b2c2dae850d67019bc26b73864e680baa | /Study/System/Lecture/source/Chap.02/WQueNotify/WQueNotify.cpp | c5b8c3a456ac7e3e9bd5316e52577d46856e3f7f | [] | no_license | SeaCanFly/CODE | 7c06a81ef04d14f064e2ac9737428da88f0957c7 | edf9423eb074861daf5063310a894d7870fa7b84 | refs/heads/master | 2021-04-12T12:15:58.237501 | 2019-07-15T05:02:09 | 2019-07-15T05:02:09 | 126,703,006 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,530 | cpp | #include "stdafx.h"
#include "Windows.h"
#include "list"
#include "iostream"
using namespace std;
#define CMD_NONE 0
#define CMD_STR 1
#define CMD_POINT 2
#define CMD_TIME 3
#define CMD_EXIT 100
class WAIT_QUE
{
struct NOTI_ITEM
{
LONG _cmd, _size;
PBYTE _data;
NOTI_ITEM()
{
_cmd = _size = 0, _data = NULL;
}
NOTI_ITEM(LONG cmd, LONG size, PBYTE data)
{
_cmd = cmd, _size = size, _data = data;
}
};
typedef std::list<NOTI_ITEM> ITEM_QUE;
HANDLE m_hMutx;
HANDLE m_hSema;
ITEM_QUE m_queue;
public:
WAIT_QUE()
{
m_hMutx = m_hSema = NULL;
}
~WAIT_QUE()
{
if (m_hMutx != NULL) CloseHandle(m_hMutx);
if (m_hSema != NULL) CloseHandle(m_hSema);
}
public:
void Init()
{
m_hSema = CreateSemaphore(NULL, 0, LONG_MAX, NULL);
m_hMutx = CreateMutex(NULL, FALSE, NULL);
}
void Enqueue(LONG cmd, LONG size = 0, PBYTE data = NULL)
{
NOTI_ITEM ni(cmd, size, data);
WaitForSingleObject(m_hMutx, INFINITE);
m_queue.push_back(ni);
ReleaseMutex(m_hMutx);
ReleaseSemaphore(m_hSema, 1, NULL);
}
PBYTE Dequeue(LONG& cmd, LONG& size)
{
DWORD dwWaitCode = WaitForSingleObject(m_hSema, INFINITE);
if (dwWaitCode == WAIT_FAILED)
{
cmd = CMD_NONE, size = HRESULT_FROM_WIN32(GetLastError());
return NULL;
}
NOTI_ITEM ni;
WaitForSingleObject(m_hMutx, INFINITE);
ITEM_QUE::iterator it = m_queue.begin();
ni = *it;
m_queue.pop_front();
ReleaseMutex(m_hMutx);
cmd = ni._cmd, size = ni._size;
return ni._data;
}
};
DWORD WINAPI WorkerProc(LPVOID pParam)
{
WAIT_QUE* pwq = (WAIT_QUE*)pParam;
DWORD dwThrId = GetCurrentThreadId();
while (true)
{
LONG lCmd, lSize;
PBYTE pData = pwq->Dequeue(lCmd, lSize);
if (lSize < 0)
{
cout << " ~~~ WaitForSingleObject failed : " << GetLastError() << endl;
break;
}
if (lCmd == CMD_EXIT)
break;
switch (lCmd)
{
case CMD_STR:
{
pData[lSize] = 0;
printf(" <== R-TH %d read STR : %s\n", dwThrId, pData);
}
break;
case CMD_POINT:
{
PPOINT ppt = (PPOINT)pData;
printf(" <== R-TH %d read POINT : (%d, %d)\n", dwThrId, ppt->x, ppt->y);
}
break;
case CMD_TIME:
{
PSYSTEMTIME pst = (PSYSTEMTIME)pData;
printf(" <== R-TH %d read TIME : %04d-%02d-%02d %02d:%02d:%02d+%03d\n",
dwThrId, pst->wYear, pst->wMonth, pst->wDay, pst->wHour,
pst->wMinute, pst->wSecond, pst->wMilliseconds);
}
break;
}
delete[] pData;
}
cout << " *** WorkerProc Thread exits..." << endl;
return 0;
}
void _tmain()
{
cout << "======= Start WQueNotify Test ========" << endl;
WAIT_QUE wq;
wq.Init();
DWORD dwThrID;
HANDLE hThread = CreateThread(NULL, 0, WorkerProc, &wq, 0, &dwThrID);
char szIn[512];
while (true)
{
cin >> szIn;
if (_stricmp(szIn, "quit") == 0)
break;
LONG lCmd = CMD_NONE, lSize = 0;
PBYTE pData = NULL;
if (_stricmp(szIn, "time") == 0)
{
lSize = sizeof(SYSTEMTIME), lCmd = CMD_TIME;
pData = new BYTE[lSize];
SYSTEMTIME st;
GetLocalTime(&st);
memcpy(pData, &st, lSize);
}
else if (_stricmp(szIn, "point") == 0)
{
lSize = sizeof(POINT), lCmd = CMD_POINT;
pData = new BYTE[lSize];
POINT pt;
pt.x = rand() % 1000; pt.y = rand() % 1000;
*((PPOINT)pData) = pt;
}
else
{
lSize = strlen(szIn), lCmd = CMD_STR;
pData = new BYTE[lSize + 1];
strcpy((char*)pData, szIn);
}
wq.Enqueue(lCmd, lSize, pData);
}
wq.Enqueue(CMD_EXIT);
WaitForSingleObject(hThread, INFINITE);
cout << "======= End WQueNotify Test ==========" << endl;
}
| [
"seacanfly@gmail.com"
] | seacanfly@gmail.com |
377a8314f14fa42927fd1d491f11dee0ef7ff008 | 980d92ee425904d258c05e13d7cb6934f4f53892 | /Qt/gotocell/gotocelldialog.cpp | 37fe8144588296f188cd3da1f6b5787572d4959d | [] | no_license | Danvilgom/Interfaces | 68210641d7bfdccdbd621ec7e1f7ffbc99407ff8 | ef37a93aee7e627d8330cbe7048f12d098403412 | refs/heads/master | 2021-09-04T14:50:12.729289 | 2018-01-19T17:17:06 | 2018-01-19T17:17:06 | 109,845,813 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 703 | cpp | #include <QtGui>
#include "gotocelldialog.h"
GoToCellDialog::GoToCellDialog(QWidget *parent)
: QDialog(parent)
{
setupUi(this);
buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
QRegExp regExp("[A-Za-z][1-9][0-9]{0,2}");
lineEdit->setValidator(new QRegExpValidator(regExp, this));
connect(lineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(on_lineEdit_textChanged()));
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
}
void GoToCellDialog::on_lineEdit_textChanged()
{
buttonBox->button(QDialogButtonBox::Ok)->setEnabled(
lineEdit->hasAcceptableInput());
}
| [
"danielvalla96@gmail.com"
] | danielvalla96@gmail.com |
2d48413fa46b94448c9fa0c5c20a2f68edc0d250 | ad945123a757a40a2ee4a4f2af4a51846ad53c75 | /Projekt/Sensor/sensorhighlevel.cpp | 0585e39add7a4f252bab35102873d18f7b821bf4 | [
"MIT"
] | permissive | Koerner/TUM_AdvancedCourseCPP | 01ef34c3332d173eea9b044442df71c079760f6e | a9c25e15213a7df9b8a4766cfe1c16b3d83c77f8 | refs/heads/master | 2020-12-28T23:24:08.395684 | 2015-08-13T17:34:30 | 2015-08-13T17:34:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,171 | cpp | #include "sensorhighlevel.h"
#include <QtMath>
#include <QDebug>
#include <QtAlgorithms>
#include <QMutexLocker>
#include <QMutex>
#include <QElapsedTimer>
#include <QThread>
#include "Data/define.h"
#include "Data/mapdata.h"
#include "Sensor/orientierung.h"
#include "Sensor/medianfilter.h"
#include "Sensor/medianfilter_new.h"
#include "Sensor/cam.h"
#include "AI/pathplanning.h"
std::atomic_bool SensorHighLevel::streamSensorEnabled(false);
SensorHighLevel::SensorHighLevel()
{
mutexFilterParameter = new QMutex;
mutexState = new QMutex;
mutexTeamColor = new QMutex;
timerWaitForValidColorFrame = new QElapsedTimer;
timerToAbondonColorDetection = new QElapsedTimer;
transmissionPosition = Position();
previousPosition = Position();
currentPosition = Position();
dummyPosition = Position();
constrainedData = ConstrainedLaserData();
previousObjects = QList<Position>();
currentObjects = QList<Position>();
hadEmergency = false;
targetsSet = false;
isInSlowTurn = false;
prepositionInitialized = false;
counter = 0;
this->setState(SensorStates::WAIT);
this->setTeamColor(CamColor::NONE);
// all pole positions
cPolePositions = QVector<Position>() << Position(0.0, 0.0)
<< Position(0.0, 5.0/12.0)
<< Position(0.0, 5.0/3.0)
<< Position(0.0, 75.0/30.0)
<< Position(0.0, 10.0/3.0)
<< Position(0.0, 55.0/12.0)
<< Position(0.0, 5.0)
<< Position(3.0, 0.0)
<< Position(3.0, 5.0/12.0)
<< Position(3.0, 5.0/3.0)
<< Position(3.0, 75.0/30.0)
<< Position(3.0, 10.0/3.0)
<< Position(3.0, 55.0/12.0)
<< Position(3.0, 5.0);
}
SensorHighLevel::~SensorHighLevel()
{
delete mutexFilterParameter;
delete mutexState;
delete mutexTeamColor;
delete timerWaitForValidColorFrame;
delete timerToAbondonColorDetection;
cPolePositions.clear();
if (config::enableDebugSensorHighLevel)
qDebug() << "DELETE 'SensorHighLvl'";
}
void SensorHighLevel::slotGetLaserData(QVector<double> rawData, Position positionSignal)
{
// primitive Kollisionsvermeidung fuer handsteuerung
if(!PathPlanning::getEnabled())
avoideCollision(rawData);
transmissionPosition = positionSignal;
QVector<double> filteredData;
// wenn der kernel auf 1 gesetzt wird dann wird der filter auch in der realität ausgeschaltet
mutexFilterParameter->lock();
int kernel = filterParameter.kernel;
mutexFilterParameter->unlock();
// Rohdaten Median (nicht Mittelwert) filtern ueber den Winkel (nicht die Zeit)
filteredData = QVector<double>::fromStdVector(MedianFilter::filter(rawData.toStdVector(), kernel));
// Gefilterte Daten anzeigen
if(SensorHighLevel::streamSensorEnabled)
Q_EMIT signalSendLaserData(LaserPlotData(filteredData, LaserPlotData::MEDIAN));
// Datenpunkte ausserhalb der Arena oder einer Recihweite entfernen
constrainData(filteredData, rawData, constrainedData);
// Keys nach grad umwandeln und in Graph anzeigen
if(SensorHighLevel::streamSensorEnabled) {
QVector<double> keysDegrees(constrainedData.angles().length());
for(int i=0; i< constrainedData.angles().length(); ++i){
keysDegrees[i] = (constrainedData.angles().at(i) - M_PI_2) * 180.0 / M_PI;
}
Q_EMIT signalSendLaserData(LaserPlotData(keysDegrees, constrainedData.filteredDepths().toVector(), LaserPlotData::REDUCED));
}
// Extrahiert Objekte und speichert lokale Koordinaten und Breite des Objektes
currentObjects = extractObjects(constrainedData);
// Objekte in GUI Laser Display anzeigen
if(SensorHighLevel::streamSensorEnabled) {
LaserPlotData laserData;
laserData.dataType = LaserPlotData::OBJECTS;
laserData.data = QVector<double> (currentObjects.size());
laserData.angles = QVector<double> (currentObjects.size());
laserData.sizes = QVector<double> (currentObjects.size());
for(int i = 0; i < currentObjects.size(); ++i) {
laserData.data[i] = currentObjects.at(i).x(); // tiefe
laserData.angles[i] = (currentObjects.at(i).y() - M_PI_2) * 180.0 / M_PI; // winkel
laserData.sizes[i] = currentObjects.at(i).rot(); // breite
}
Q_EMIT signalSendLaserData(laserData);
}
// internal state machine
switch (this->getState()) {
case SensorStates::WAIT:
{
if (config::enableDebugSensorHighLevel)
qDebug() << "Waiting for AI to start";
}
break;
case SensorStates::ORIENTATION:
{
Position orientData = Orientation::beginOrientation(currentObjects);
///\todo magic number for certainty here
if (orientData.certainty() > 0.8)
{
Q_EMIT signalSendRobotControlParams(0,0);
///\todo consider removing the counter and replace through = new QElapsedTimer;
if(counter > config::SENSOR_WAIT_COUNTER)
{
previousPosition = orientData;
currentPosition = MapData::getRobotPosition(ObstacleType::ME);
dummyPosition = orientData;
//if ( currentPosition.r() > )
dummyAngleOffset = dummyPosition.rot() - currentPosition.rot();
qDebug() << "Dummy Offset: " << dummyAngleOffset;
// Setze Dummy bei gerade eben erkannter Position
MapData::setObstacle(Obstacle(dummyPosition, ObstacleType::DUMMY));
///\todo angle range?
minAngle = fmod(currentPosition.rot() + M_PI - config::SENSOR_DELTA_ANGLE / 2.0, M_PI*2);
maxAngle = fmod(currentPosition.rot() + M_PI + config::SENSOR_DELTA_ANGLE, M_PI*2);
qDebug() << "SensorState changed: " << "OIRENTATION_VALIDATION";
counter = 0; // Muss bei jedem Statewechsel zurückgesetzt werden, weil der Roboter beim Statewechsel noch 5 mal Laserdaten im Stehen messen soll
this->setState(SensorStates::ORIENTATION_VALIDATION);
}
else
{
counter ++;
if (config::enableDebugSensorHighLevel)
qDebug()<<"WAIT FIRST";
}
}
else
{
//qDebug() << "Nichts erkannt";
// Drehen, langsam, bis Abstände erkannt werden
Q_EMIT signalSendRobotControlParams(0,1.5*config::GUIREMOTETURNRATE);
}
}
break;
case SensorStates::ORIENTATION_VALIDATION:
{
currentPosition = MapData::getRobotPosition(ObstacleType::ME);
dummyPosition.rot(currentPosition.rot() + dummyAngleOffset);
//qDebug() << " new dummy Orientation: " << dummyPosition.r();
MapData::setObstacle(Obstacle(dummyPosition, ObstacleType::DUMMY));
if (config::enableDebugSensorHighLevel)
qDebug()<<"ANGLE DISTANCE::: "<< minAngle <<" - "<< maxAngle << " - " << currentPosition.rot();
// condition is working!
if(( minAngle < currentPosition.rot() &&
maxAngle > currentPosition.rot() )
||
((maxAngle<minAngle) &&
(minAngle > currentPosition.rot() ||
maxAngle < currentPosition.rot())) ||
isInSlowTurn)
{
if(counter == 0)
Q_EMIT signalSendRobotControlParams(0,0);
///\todo consider removing the counter and replace through = new QElapsedTimer;
if (counter > config::SENSOR_WAIT_COUNTER )
{
Position orientData = Orientation::beginOrientation(currentObjects);
ObstacleType type;
double abstandZuVorherigerPosition = sqrt(pow(orientData.x() - previousPosition.x(), 2) + pow(orientData.y() - previousPosition.y(), 2));
bool deviationIsOk = abstandZuVorherigerPosition < config::SENSOR_MEASUREMENT_DEVIATION ;
if (orientData.certainty() > 0.8 && deviationIsOk)
{
if (config::enableDebugSensorHighLevel)
qDebug() << "MEASUREMENT ::::::" << previousPosition.x() << "orientData.x" << orientData.x();
// Mean value here?
Position finalPos(0.5*previousPosition.x() + 0.5*orientData.x(),
0.5*previousPosition.y() + 0.5*orientData.y(),
orientData.rot(),
orientData.certainty());
if (MapData::getSimulationDetected())
{
type = ObstacleType::DUMMY;
if (config::enableDebugSensorHighLevel)
qDebug() << "type: DUMMY!";
MapData::setObstacle(Obstacle(finalPos,
ObstacleColor::UNIDENTIFIED,
type,
ObstacleStatus::UNBLOCKED));
}
else
{
type = ObstacleType::ME;
if (config::enableDebugSensorHighLevel)
qDebug() << "type: ME!";
Q_EMIT signalSendOdometryData(finalPos);
}
QList<Obstacle> cPoleList = QList<Obstacle>();
for (int i = 0; i < cPolePositions.size(); ++i) {
cPoleList << Obstacle(cPolePositions.at(i), ObstacleType::POLE);
}
MapData::setObstacle(cPoleList);
targetsSet = false;
if (config::enableDebugSensorHighLevel)
qDebug() << "SensorState changed: " << "COLOR_DETECTION_START";
counter = 0; // Muss bei jedem Statewechsel zurückgesetzt werden, weil der Roboter beim Statewechsel noch 5 mal Laserdaten im Stehen messen soll
PathPlanning::setAvoidRestOfField(true); // Der Pfadplanung mitteilen, dass sie nur innerhalb des eigenen Halbfelds planen darf
this->setState(SensorStates::COLOR_DETECTION_START);
}
else
{
counter ++;
if (config::enableDebugSensorHighLevel)
qDebug()<<"very slow turn for next LaserData";
// will be called once!
if (counter == config::SENSOR_WAIT_COUNTER + 2)
{
// now it can turn over the maxAngle
isInSlowTurn = true;
// Drehen, langsam, bis Abstände erkannt werden
Q_EMIT signalSendRobotControlParams(0,0.8*config::GUIREMOTETURNRATE);
}
// wenn wir zu lange gewartet haben oder die abweichung zu hoch war bei einer gemeldeten position von beginnOrientation
if (counter > config::SENSOR_WAIT_COUNTER * 4 ||
(!deviationIsOk && orientData.certainty() > 0.8))
{
isInSlowTurn = false;
Q_EMIT signalSendRobotControlParams(0,0);
counter = 0; // Muss bei jedem Statewechsel zurückgesetzt werden, weil der Roboter beim Statewechsel noch 5 mal Laserdaten im Stehen messen soll
this->setState(SensorStates::ORIENTATION);
}
}
}
else
{
counter++;
}
}
else
{
// the angle rotation speed is connected to the angle to go
double angleToGo;
if (minAngle > M_PI) {
angleToGo = minAngle - currentPosition.rot();
}
else {
if ( currentPosition.rot() > M_PI)
angleToGo = (2*M_PI - currentPosition.rot()) + minAngle;
else
angleToGo = minAngle - currentPosition.rot();
}
if (config::enableDebugSensorHighLevel)
qDebug() << "<<<<<<<<<<<<<<< ANGLE TO GO: " << angleToGo;
// Schnell um 180deg drehen
Q_EMIT signalSendRobotControlParams(0,(3*angleToGo/ M_PI + 1)*1.5*config::GUIREMOTETURNRATE);
}
}
break;
case SensorStates::COLOR_DETECTION_START:
{
// Erkennt Obstacles
recognition(currentObjects, transmissionPosition);
//Positioning
if (!targetsSet)
{
QPair<double,double> torSeite = (dummyPosition.x() > 1.5) ?
qMakePair(config::geoFieldWidth * 0.667, // Rechte Torkante
config::geoPol_1_2 * 1.5) : // Mittlere Torhöhe
qMakePair(config::geoFieldWidth * 0.333, // Rechte Torkante
config::geoPol_1_2 * 1.5); // Mittlere Torhöhe
MapData::setObstacle(Obstacle( torSeite,
ObstacleColor::UNIDENTIFIED,
ObstacleType::TARGET,
ObstacleStatus::UNBLOCKED,
(dummyPosition.x() > 1.5) ? M_PI : 0) // Nach links/rechts gucken
);
// wait 500ms for color detection
timerWaitForValidColorFrame->start();
targetsSet = true;
}
else
{
// the only 2 targets which have been set till now are completed
if(MapData::getObstacle(ObstacleType::TARGET).isEmpty() &&
timerWaitForValidColorFrame->isValid() &&
timerWaitForValidColorFrame->elapsed() > 500)
{
if(config::enableDebugSensorHighLevel)
qDebug() << "Wait 500ms to be sure to get the latest cam frame";
// start again for 50ms redetection cycle
timerWaitForValidColorFrame->start();
timerToAbondonColorDetection->start();
Q_EMIT signalStartColorDetection();
if(config::enableDebugSensorHighLevel) {
qDebug() << "Position erreicht --> Farbe prüfen";
qDebug() << "SensorState changed: " << "COLOR_DETECTION_WAIT";
}
this->setState(SensorStates::COLOR_DETECTION_WAIT);
//Löschen des Dummy
MapData::deleteObstacle(ObstacleType::DUMMY);
}
}
}
break;
case SensorStates::COLOR_DETECTION_WAIT:
{
// Erkennt Obstacles
recognition(currentObjects, transmissionPosition);
// wait 5secs to abort color detection
if(timerToAbondonColorDetection->isValid() &&
timerToAbondonColorDetection->elapsed() > 5000)
{
qDebug() << "Failed overall color detection";
timerToAbondonColorDetection->invalidate();
timerWaitForValidColorFrame->invalidate();
driveToPreposition();
this->setState(SensorStates::PRE_GAME_STATE);
}
if(timerWaitForValidColorFrame->isValid() &&
timerWaitForValidColorFrame->elapsed() > 50)
{
timerWaitForValidColorFrame->start();
// QThread::sleep removed problems with recognition of objects
Q_EMIT signalStartColorDetection();
}
// the rest is in the slotColorDetected()
}
break;
case SensorStates::PRE_GAME_STATE:
{
// Erkennt Obstacles
recognition(currentObjects, transmissionPosition);
// fährt zur Preposition und setzt State auf RECODNITION wenn er dort angekommen ist
driveToPreposition();
}
break;
case SensorStates::RECOGNITION:
{
// Erkennt Obstacles
recognition(currentObjects, transmissionPosition);
}
break;
default:
{
if (config::enableDebugSensorHighLevel)
qDebug() << "HighLevelSensor unknown state";
}
}
}
void SensorHighLevel::driveToPreposition()
{
// Target finden und setzen
if(!prepositionInitialized)
{
double distance = 99;
Position target = Position(config::geoFieldWidth/2,(config::geoFieldHeight / 3) - config::DISTANCE_TO_WAITING_LINE, M_PI/2);
QList<Obstacle> puckList = MapData::getObstacle(ObstacleType::PUCK);
for (int i = 0; i < puckList.size(); ++i)
{
if (puckList.at(i).isInSpecifiedArea(FieldArea::NEUTRAL_AREA))
{ // Puck muss sich in der neutralen Zone befinden
Position puckPos = puckList.at(i).getPosition();
bool isNotCloseToPole = puckPos.x() > 1.3 * config::SENSOR_RADIUS_ROBOT &&
puckPos.x() < config::geoFieldWidth - 1.3 * config::SENSOR_RADIUS_ROBOT;
if (isNotCloseToPole && puckPos.y() < distance)
{
distance = puckPos.y();
target.x(puckPos.x());
}
}
}
MapData::clearTargets();
MapData::setObstacle(Obstacle(target,ObstacleType::TARGET));
prepositionInitialized = true;
}
// Am Target angekommen --> nur noch erkennen
if(MapData::getObstacle(ObstacleType::TARGET).size() == 0)
this->setState(SensorStates::RECOGNITION);
}
// Kollisionsvermeidung fuer Handsteuerung ohne Pfadplanung
void SensorHighLevel::avoideCollision(QVector<double> &rawDepthsVector)
{
if(rawDepthsVector.length() == 0)
return;
// set true if detects emergency
bool isEmergency = false;
// how many data points have been send?
int iDataCount = rawDepthsVector.size();
// each data point covers "dRadPerValue" RAD of the 180degree in front of robot
double dRadPerValue = M_PI / static_cast<double>(iDataCount);
// calculate how many data points have to be evaluated to detect an obstacle in front of the robot
int iHalfRange = ceil(atan2(2*config::SENSOR_RADIUS_ROBOT, (config::SENSOR_COLLISION_AT + 2*config::SENSOR_RADIUS_ROBOT))
/ dRadPerValue);
int iFrom = floor(iDataCount / 2.0) - iHalfRange;
int iTo = floor(iDataCount / 2.0) + iHalfRange;
// there is an emergency, if only one Data Point detects an obstacle
for ( int i = iFrom; i <= iTo; ++i)
isEmergency |= (rawDepthsVector.at(i) < config::SENSOR_COLLISION_AT);
// send signal if the state of emergency has changed
if (isEmergency != hadEmergency) {
hadEmergency = isEmergency;
Q_EMIT signalEmergencyStopEnabled(isEmergency);
}
}
CamColor SensorHighLevel::getTeamColor() const
{
QMutexLocker locker (mutexTeamColor);
return teamColor;
}
void SensorHighLevel::setTeamColor(const CamColor &value)
{
QMutexLocker locker (mutexTeamColor);
teamColor = value;
}
/**
* @brief SensorHighLevel::recognition Soll Objekte,
* die sich im angemessenen Abstand befinden erkennen und ggf identifizieren
* @param objects QVector3Ds mit x=entfernung, y=winkel (0°=links vom roboter, 90°=vorm roboter), z=breite
* @return
*/
void SensorHighLevel::recognition(QList<Position> &objects, Position &transmissionPosition)
{
// calculate the correct global position of all objects
for (int i = 0; i < objects.size(); ++i) {
objects[i] = Orientation::getGlobalPolarPosition(objects.at(i), transmissionPosition);
}
bool listIsEqual = true;
if(previousObjects.size() != objects.size()) {
listIsEqual = false;
}
else {
bool hasElement = false;
for(int i = 0; i < objects.size(); ++i) {
for (int j = 0; j < previousObjects.size(); ++j) {
if( objects.at(i) == previousObjects.at(j)) {
hasElement = true;
break;
}
else {
hasElement = false;
}
}
listIsEqual = hasElement;
if(!listIsEqual)
break;
}
}
// targets must be updated
for (int i = 0; i < objects.size(); ++i){
if ( objects.at(i).sizeType() == SizeType::POLE )
{
MapData::setObstacle(Obstacle(objects.at(i),
ObstacleStatus::BLOCKED,
ObstacleType::POLE)
);
}
else if (objects.at(i).sizeType() == SizeType::PUCK)
{
MapData::setObstacle(Obstacle(objects.at(i),
ObstacleColor::NOMODIFY,
ObstacleType::PUCK,
ObstacleStatus::NOMODIFY),
transmissionPosition
);
}
else if (objects.at(i).sizeType() == SizeType::ROBOT)
{
MapData::setObstacle(Obstacle(objects.at(i),
ObstacleType::OPPONENT)
);
}
else // THIS WILL NOT HAPPEN TILL NOW!!!
{
MapData::setObstacle(Obstacle(objects.at(i),
ObstacleStatus::NOMODIFY,
ObstacleType::NOMODIFY)
);
}
}
// only with big differences the path will be planned again
if (!listIsEqual)
Q_EMIT signalPlanNewPath();
// speichere die neuen objekte ab
previousObjects = objects;
}
/**
* @brief SensorHighLevel::extractObjects Geht durch die sensorData list und überprüft auf entfernungen zwischen zwei sensordatenpunkten
* @param sensorData Eingangsvektor
* @param objects Referenz auf Vektor für Rückgabe - QVector3D beinhaltet Tiefe - Winkel (rad) - Breite
*/
QList<Position> SensorHighLevel::extractObjects(const ConstrainedLaserData &constrainedData)
{
// current state
SensorStates tempState = this->getState();
// vector with found objects
QList<Position> objects = QList<Position>();
// minimum value count for 1 object
int minObjectValues;
if(MapData::getSimulationDetected())
minObjectValues = 2;
else
minObjectValues = 2;
// check sizes of both vectors
int angleVectorSize = constrainedData.angles().size();
int depthVectorSize = constrainedData.filteredDepths().size();
if(angleVectorSize == 0 ||
angleVectorSize != depthVectorSize)
return objects;
// Der erste in den daten enthaltene wert ist auf jeden fall teil eines objekts, daher daten hier initialisieren
int objectBeginning = 0;
int objectEnd = 0;
// distance between two polar coordinates
double dist = 0.0;
Position polarCoordsPositionObject;
// start with second item in the vector
for (int i = 1; i < angleVectorSize; ++i)
{
// angleA, depthA, angleB, depthB
dist = Orientation::distancePolar(constrainedData.angles().at(i-1), constrainedData.filteredDepths().at(i-1),
constrainedData.angles().at(i), constrainedData.filteredDepths().at(i));
// Wenn die nebeneinanderliegenden Punkte nahe zu einander sind: die objektgrenze verschieben
// Problem: Ohne einen Punkt ganz rechts, wird das letzte Objekt nicht erkannt -> zweite Bedingung notwendig
if(dist < config::SENSOR_MAX_DISTANCE_OF_OBJ && i != angleVectorSize - 1)
{
objectEnd = i;
} else { // die punkte liegen nicht nahe beieinander: objektkante
// für den letzten Punkt muss die letzte Koordinate korrekt gesetzt werden!
if (dist < config::SENSOR_MAX_DISTANCE_OF_OBJ && i == angleVectorSize - 1)
objectEnd = i;
// ab 3 Punkten is es ein Objekt!
///\todo also ich mache es hier mal von der simulation abhängig, ob 2 oder 3 werte für ein object genügen!
if (objectEnd - objectBeginning >= minObjectValues)
{
// calculateObjCenter gibt zurück Position(realDepth, realAngle, radius, sizeType) statt (x,y,rot,sizeType)
polarCoordsPositionObject = calculateObjCenter(constrainedData, objectBeginning, objectEnd, tempState);
// position ist missbraucht - rot = width
double objectWidth = polarCoordsPositionObject.rot();
bool isValidObject = true;
switch(tempState)
{
case SensorStates::WAIT:
case SensorStates::ORIENTATION:
case SensorStates::ORIENTATION_VALIDATION:
{
// in these states only poles are relevant - everything else will be discarded
if(MapData::getSimulationDetected())
isValidObject = objectWidth < 2.1 * config::geoPoleRadiusSim;
else
isValidObject = objectWidth < 2.1 * config::geoPoleRadiusReal;
}
break;
default: // all other states
{
// if the object width is bigger than the robo diameter
// it wont be added -> it migth be a wall
isValidObject = objectWidth < 2.1* config::SENSOR_RADIUS_ROBOT;
}
}
if(isValidObject)
{
// dieses object darf übernommen werden
objects.append(polarCoordsPositionObject);
}
}
objectBeginning = i;
objectEnd = i;
}
}
return objects;
}
void SensorHighLevel::constrainData(const QVector<double> &filteredDepthsVector,
const QVector<double> &rawDepthsVector,
ConstrainedLaserData &constrainedData)
{
constrainedData.clearData();
SensorStates tempState = this->getState();
int dataInLength = filteredDepthsVector.length();
// Neu: Für die Validierung wird das Feld auf das Orientierungsfeld begrenzt, anschließend nicht mehr...
double lengthY;
double worldOrientationOfPoint;
double worldXOfPoint;
double worldYOfPoint;
double maxRange = (tempState == SensorStates::ORIENTATION) ? config::SENSOR_MAX_RANGE_ORIENTATION : config::SENSOR_MAX_RANGE_RECOGNITION;
for (int i = 0; i < dataInLength; ++i)
{
double currentAngle = i * M_PI / (dataInLength-1);
// keine datenpunkte, die weiter als maxrange entfernt sind
if(filteredDepthsVector.at(i) > maxRange){
continue;
}
switch(tempState) {
//case SensorStates::WAIT:
case SensorStates::COLOR_DETECTION_START:
case SensorStates::COLOR_DETECTION_WAIT:
case SensorStates::PRE_GAME_STATE:
case SensorStates::RECOGNITION:
{
lengthY = config::geoFieldHeight;
worldOrientationOfPoint = transmissionPosition.rot() + M_PI_2 - currentAngle; // winkel, auf arena bezogen
worldXOfPoint = transmissionPosition.x() + filteredDepthsVector.at(i) * cos(worldOrientationOfPoint);
worldYOfPoint = transmissionPosition.y() + filteredDepthsVector.at(i) * sin(worldOrientationOfPoint);
}
break;
case SensorStates::ORIENTATION_VALIDATION:
{
dummyPosition = MapData::getRobotPosition(ObstacleType::DUMMY);
lengthY = config::geoPol_1_2 + config::geoPol_2_3;
worldOrientationOfPoint = dummyPosition.rot() + M_PI_2 - currentAngle; // winkel, auf arena bezogen
worldXOfPoint = dummyPosition.x() + filteredDepthsVector.at(i) * cos(worldOrientationOfPoint);
worldYOfPoint = dummyPosition.y() + filteredDepthsVector.at(i) * sin(worldOrientationOfPoint);
}
break;
default: //SensorStates::ORIENTATION
{
// wenn wir hier ankommen, sollte der punkt in ordnung sein
constrainedData.addFilteredDepth(filteredDepthsVector.at(i));
constrainedData.addRawDepth(rawDepthsVector.at(i));
constrainedData.addAngle(currentAngle);
continue;
}
}
// ist der datenpunkt innerhalb des spielfelds?
if( worldXOfPoint < 0-config::SENSOR_OUT_OF_FIELD_TOLERANCE ||
worldYOfPoint < 0-config::SENSOR_OUT_OF_FIELD_TOLERANCE ||
worldXOfPoint > config::geoFieldWidth + config::SENSOR_OUT_OF_FIELD_TOLERANCE ||
worldYOfPoint > lengthY + config::SENSOR_OUT_OF_FIELD_TOLERANCE ){
continue;
}
// wenn wir hier ankommen, sollte der punkt in ordnung sein
constrainedData.addFilteredDepth(filteredDepthsVector.at(i));
constrainedData.addRawDepth(rawDepthsVector.at(i));
constrainedData.addAngle(currentAngle);
}
}
// Neue Filter-Parameter aus der GUI erhalten
void SensorHighLevel::slotSetFilterParams(FilterParams cp)
{
QMutexLocker locker(mutexFilterParameter);
filterParameter.kernel=cp.kernel;
if (config::enableDebugSensorHighLevel)
qDebug()<<"New Kernel parameter";
}
void SensorHighLevel::slotStartDetection(bool start)
{
if(start)
{
//qDebug() << "start detection";
this->setState(SensorStates::ORIENTATION);
}
else {
Q_EMIT signalSendRobotControlParams(0,0);
this->setState(SensorStates::WAIT);
}
}
void SensorHighLevel::slotColorDetected(CamColor color)
{
this->setTeamColor(color);
if ( getState() == SensorStates::COLOR_DETECTION_WAIT )
{
CamColor tempColor = this->getTeamColor();
switch(tempColor){
case CamColor::BLUE:
{
MapData::setProbableColor(tempColor);
Q_EMIT signalSendTeamColor( tempColor);
driveToPreposition();
this->setState(SensorStates::PRE_GAME_STATE);
timerToAbondonColorDetection->invalidate();
timerWaitForValidColorFrame->invalidate();
}
break;
case CamColor::YELLOW:
{
MapData::setProbableColor(tempColor);
Q_EMIT signalSendTeamColor( tempColor);
driveToPreposition();
this->setState(SensorStates::PRE_GAME_STATE);
timerToAbondonColorDetection->invalidate();
timerWaitForValidColorFrame->invalidate();
}
default:
{
if(config::enableDebugSensorHighLevel) {
qWarning() << "Unbekannte tatsächliche Teamfarbe: "
<< static_cast<int>(tempColor)
<< ", versuche es vielleicht in 50ms nochmal";
}
}
break;
} // switch color
} // if correct state
}
SensorStates SensorHighLevel::getState() const
{
QMutexLocker locker (mutexState);
return currentState;
}
void SensorHighLevel::setState(const SensorStates &value)
{
QMutexLocker locker (mutexState);
currentState = value;
}
// returning coordinates of the middle of the object, - depth - angle and width
Position SensorHighLevel::calculateObjCenter(const ConstrainedLaserData &constrainedData,
int objectBeginn, int objectEnd, SensorStates &tempState)
{
// Neuer Code
double radiusPole = config::geoPoleRadiusReal;
double radiusPuck = config::geoPuckRadiusTopReal;
double radius; // radius of different regognized elements
double distAB; // distance polar between beginn and end
double theta; // angle of triangle(pA,pB,Mid) at pA
double phi; // angle of triangle(robo,pA,pB) at pA
double realAngle; // the correct value for polar depth
double realDepth; // the correct value for polar angle
double pAAngle = constrainedData.angles().at(objectBeginn);
double pADepth = constrainedData.filteredDepths().at(objectBeginn);
double pBAngle = constrainedData.angles().at(objectEnd);
double pBDepth = constrainedData.filteredDepths().at(objectEnd);
/*
qDebug() << "Object Values left to right:";
for(int i = objectBeginn; i<= objectEnd; ++i)
qDebug() << "Value_" << i << ": " << anglesAndDepths.second.at(i);
*/
double meanAngle = 0.5 * (pAAngle + pBAngle);
double meanDepth = (pADepth > pBDepth) ? pADepth : pBDepth;
//
SizeType sizeType = SizeType::UNKNOWN;
// distance between pA and pB
distAB = Orientation::distancePolar(pAAngle, pADepth,
pBAngle, pBDepth);
if(MapData::getSimulationDetected())
{
radiusPole = config::geoPoleRadiusSim;
radiusPuck = config::geoPuckRadiusTopSim;
}
switch (tempState) {
case SensorStates::WAIT:
case SensorStates::ORIENTATION:
case SensorStates::ORIENTATION_VALIDATION:
{
if (distAB >= 2*radiusPole)
radius = 0.5 * distAB + distAB/100;
else
radius = radiusPole;
sizeType = SizeType::POLE;
}
break;
default: // CARLO WARUM MACHST DU KEINE KOMMENTARE!!1!elf Ist wahrscheinlich für SensorStates::RECOGNITION gedacht?!
{ // @Laurenz: JA, andere states auch aber das passiert fast nie
Position absolutePos = Orientation::getGlobalPolarPosition(Position(meanDepth, meanAngle, distAB, 1.0),
transmissionPosition);
///\todo may be cheating here with the distAB
if (cPolePositions.contains(absolutePos)) {
if (distAB >= 2*radiusPole)
radius = 0.5 * distAB + distAB/100;
else
radius = radiusPole;
sizeType = SizeType::POLE;
}
else if (distAB > config::SENSOR_OBJECTWIDTH_ROBO) {
radius = 0.5 * distAB + distAB/100;
sizeType = SizeType::ROBOT;
}
else {
if (distAB >= 2*radiusPuck)
radius = 0.5 * distAB + distAB/100;
else
radius = radiusPuck;
sizeType = SizeType::PUCK;
}
}
}
// theta (angle of triangle(pA,pB,Mid) at pA)
theta = 0.5 * (M_PI - qAcos(1 - distAB*distAB / (2 * radius * radius)));
// angle pA,pB, robot
phi = Orientation::angleBetweenAB(distAB, pADepth, pBDepth);
// distance mid - robo
realDepth = Orientation::distancePolar(radius, pADepth, theta + phi);
realAngle = pAAngle + Orientation::angleBetweenAB(pADepth, realDepth, radius);
if (config::enableDebugSensorHighLevel)
{
qDebug() << "****";
qDebug() << "ObjectAngle_" << objectBeginn << ": " << pAAngle;
qDebug() << "ObjectAngle_" << objectEnd << ": " << pBAngle;
qDebug() << "ObjectDepth_" << objectBeginn << ": " << pADepth;
qDebug() << "ObjectDepth_" << objectEnd << ": " << pBDepth;
qDebug() << "ObjectWidth: " << distAB;
qDebug() << "Theta: " << theta;
qDebug() << "phi: " << phi;
qDebug() << "RealDepth: " << realDepth;
qDebug() << "RealAngle: " << realAngle;
qDebug() << "RealWidth: " << 2 * radius;
qDebug() << "****";
}
return Position(realDepth, realAngle, radius, sizeType);
}
| [
"carlo@vandriesten.de"
] | carlo@vandriesten.de |
12f02761f73fd878c8edc69dbceb983896e5802c | 0a1e6605c5c39a3d39bacd2164dd5aa5a293d5b0 | /Final/src/particle_system.cpp | 36fd2f62659d9d86605e36e828d665e47176323e | [] | no_license | trushton/advancedGraphics | b5c00ad7dd97dae05d764295ffd3ad92c17dfeac | 9bd900a5ef4b0b3f160ac7496522d37c2dbfc80b | refs/heads/master | 2020-12-11T06:03:57.726773 | 2015-11-20T08:21:45 | 2015-11-20T08:21:45 | 38,222,389 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,871 | cpp | //
// Created by trushton on 7/28/15.
//
#include "particle_system.h"
#include "RandomTexture.h"
#include "Engine.h"
#include "graphics.h"
#define MAX_PARTICLES 1000
#define PARTICLE_LIFETIME 10.0f
#define PARTICLE_TYPE_LAUNCHER 0.0f
#define PARTICLE_TYPE_SHELL 1.0f
#define PARTICLE_TYPE_SECONDARY_SHELL 2.0f
#define COLOR_TEXTURE_UNIT GL_TEXTURE0
#define COLOR_TEXTURE_UNIT_INDEX 0
#define RANDOM_TEXTURE_UNIT GL_TEXTURE3
#define RANDOM_TEXTURE_UNIT_INDEX 3
ParticleSystem::ParticleSystem()
{
currVB = 0;
currTFB = 1;
isFirst = true;
time = 0;
update = new ParticleUpdateProgram();
render = new ParticleRenderProgram();
}
ParticleSystem::~ParticleSystem()
{
}
void ParticleSystem::initWithPos(const glm::vec3 &pos)
{
Particle particles[MAX_PARTICLES];
initialPosition = pos;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
particles[0].type = PARTICLE_TYPE_LAUNCHER;
particles[0].pos = pos;
particles[0].vel = glm::vec3(0.0f, 0.0001f, 0.0f);
particles[0].lifetime = 0.0f;
particles[0].color = glm::vec3(0.0,0.5,1.0);
glGenTransformFeedbacks(2, transformFeedback);
glGenBuffers(2, particleBuffer);
for (int i = 0; i < 2; i++)
{
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, transformFeedback[i]);
glBindBuffer(GL_ARRAY_BUFFER, particleBuffer[i]);
glBufferData(GL_ARRAY_BUFFER, sizeof(particles), particles, GL_DYNAMIC_DRAW);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, particleBuffer[i]);
}
texture = new Texture("../bin/fireworks_red.jpg", GL_TEXTURE_2D);
alphaTexture = new Texture("../bin/fireworks_red.jpg", GL_TEXTURE_2D);
random_texture = new RandomTexture(MAX_PARTICLES, GL_TEXTURE_1D);
update->enable();
update->set("random_texture", RANDOM_TEXTURE_UNIT_INDEX);
update->set("launcher_lifetime", 250.0f);
update->set("shell_lifetime", 5000.0f);
update->set("secondary_shell_lifetime", 2500.0f);
render->enable();
render->set("color_map", 6);
//render->set("alpha_map", 2);
render->set("billboard_size", 2.0f);
glBindVertexArray(0);
}
void ParticleSystem::renderWithDT(float dt)
{
time += (dt);
updateParticles(dt);
renderParticles();
currVB = currTFB;
currTFB = (currTFB + 1) & 0x1;
}
void ParticleSystem::updateParticles(float dt)
{
glBindVertexArray(vao);
update->enable();
update->set("time", time);
update->set("dt", dt);
glm::vec3 color(((rand()%11) / 10.0f), ((rand()%11) / 10.0f), ((rand()%11) / 10.0f));
update->set("particleColor", color);
random_texture->bind(RANDOM_TEXTURE_UNIT);
glEnable(GL_RASTERIZER_DISCARD);
glBindBuffer(GL_ARRAY_BUFFER, particleBuffer[currVB]);
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, transformFeedback[currTFB]);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
glVertexAttribPointer(0, 1, GL_FLOAT, GL_FALSE, sizeof(Particle), (void *) 0); // type
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Particle), (void *) 4); // position
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Particle), (void *) 16); // velocity
glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, sizeof(Particle), (void *) 28); // lifetime
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Particle), (void *) 32); // Color
glBeginTransformFeedback(GL_POINTS);
if (isFirst)
{
glDrawArrays(GL_POINTS, 0, 1);
isFirst = false;
}
else
{
glDrawTransformFeedback(GL_POINTS, transformFeedback[currVB]);
}
glEndTransformFeedback();
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
glDisableVertexAttribArray(3);
glDisableVertexAttribArray(4);
}
void ParticleSystem::renderParticles()
{
glBindVertexArray(vao);
auto vp = Engine::getEngine()->graphics->projection * Engine::getEngine()->graphics->view;
render->enable();
render->set("camera_pos", Engine::getEngine()->graphics->camera->getPos());
render->set("vp", vp);
if (texture)
{
texture->bind(6);
}
// if(alphaTexture)
// {
// alphaTexture->bind(GL_TEXTURE2);
// }
glDisable(GL_RASTERIZER_DISCARD);
glBindBuffer(GL_ARRAY_BUFFER, particleBuffer[currTFB]);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(4);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Particle), (void *) 4); // position
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Particle), (void *) 32); // Color
glDrawTransformFeedback(GL_POINTS, transformFeedback[currTFB]);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(4);
glBindVertexArray(0);
} | [
"trushton134@gmail.com"
] | trushton134@gmail.com |
6141b141f6ddef04b545c7fb4abb671a1e3a9f01 | 083ca3df7dba08779976d02d848315f85c45bf75 | /BinaryTreeInorderTraversal2.cpp | f5b1cfa0ef5600ad4e89f050d75b0f36c2863fc7 | [] | no_license | jiangshen95/UbuntuLeetCode | 6427ce4dc8d9f0f6e74475faced1bcaaa9fc9f94 | fa02b469344cf7c82510249fba9aa59ae0cb4cc0 | refs/heads/master | 2021-05-07T02:04:47.215580 | 2020-06-11T02:33:35 | 2020-06-11T02:33:35 | 110,397,909 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,039 | cpp | #include<iostream>
#include<vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
TreeNode *p=root;
vector<TreeNode*> stack;
while(p!=NULL||!stack.empty()){
while(p!=NULL){
stack.push_back(p);
p=p->left;
}
p=stack.back();
stack.pop_back();
result.push_back(p->val);
p=p->right;
}
return result;
}
};
int main(){
TreeNode *root=new TreeNode(1);
TreeNode *p=new TreeNode(2);
root->right=p;
TreeNode *q=new TreeNode(3);
p->left=q;
Solution *solution=new Solution();
vector<int> result=solution->inorderTraversal(root);
for(int i=0;i<result.size();i++){
cout<<result[i]<<" ";
}
return 0;
}
| [
"jiangshen95@163.com"
] | jiangshen95@163.com |
6886ca60b7d0e64a99666b0828a9c7408a77ac56 | c5cd71edf65863c30e4ed56ceaa80f7a8d3f6d4c | /ptlsim/build/cache/bus.cpp | 5c83621c4f3f63a4dece2df7691da7ecb6258516 | [] | no_license | zhongliang/cache_life | 687aa1cbafb262ee0d982c69162483fb71da3b06 | 1a024999035905091cd5946610c547f9719e55e2 | refs/heads/master | 2021-01-01T17:21:30.374958 | 2010-11-09T07:43:45 | 2010-11-09T07:43:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,296 | cpp |
/*
* MARSSx86 : A Full System Computer-Architecture Simulator
*
* 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.
*
* Copyright 2009 Avadh Patel <apatel@cs.binghamton.edu>
* Copyright 2009 Furat Afram <fafram@cs.binghamton.edu>
*
*/
#ifdef MEM_TEST
#include <test.h>
#else
#include <ptlsim.h>
#endif
#include <bus.h>
#include <memoryHierarchy.h>
using namespace Memory;
BusInterconnect::BusInterconnect(char *name,
MemoryHierarchy *memoryHierarchy) :
Interconnect(name,memoryHierarchy),
busBusy_(false)
{
GET_STRINGBUF_PTR(broadcast_name, name, "_broadcast");
broadcast_.set_name(broadcast_name->buf);
broadcast_.connect(signal_mem_ptr(*this,
&BusInterconnect::broadcast_cb));
GET_STRINGBUF_PTR(broadcastComplete_name, name,
"_broadcastComplete");
broadcastCompleted_.set_name(broadcastComplete_name->buf);
broadcastCompleted_.connect(signal_mem_ptr(*this,
&BusInterconnect::broadcast_completed_cb));
GET_STRINGBUF_PTR(dataBroadcast_name, name, "_dataBroadcast");
dataBroadcast_.set_name(dataBroadcast_name->buf);
dataBroadcast_.connect(signal_mem_ptr(*this,
&BusInterconnect::data_broadcast_cb));
GET_STRINGBUF_PTR(dataBroadcastComplete_name, name,
"_dataBroadcastComplete");
dataBroadcastCompleted_.set_name(dataBroadcastComplete_name->buf);
dataBroadcastCompleted_.connect(signal_mem_ptr(*this,
&BusInterconnect::data_broadcast_completed_cb));
lastAccessQueue = 0;
}
void BusInterconnect::register_controller(Controller *controller)
{
BusControllerQueue *busControllerQueue = new BusControllerQueue();
busControllerQueue->controller = controller;
// Set controller pointer in each queue entry
BusQueueEntry *entry;
foreach(i, busControllerQueue->queue.size()) {
entry = (BusQueueEntry*)&busControllerQueue->queue[i];
entry->controllerQueue = busControllerQueue;
entry = (BusQueueEntry*)&busControllerQueue->dataQueue[i];
entry->controllerQueue = busControllerQueue;
}
busControllerQueue->idx = controllers.count();
controllers.push(busControllerQueue);
lastAccessQueue = controllers[0];
}
int BusInterconnect::access_fast_path(Controller *controller,
MemoryRequest *request)
{
return -1;
}
void BusInterconnect::annul_request(MemoryRequest *request)
{
foreach(i, controllers.count()) {
BusQueueEntry *entry;
foreach_list_mutable(controllers[i]->queue.list(),
entry, entry_t, nextentry_t) {
if(entry->request == request) {
entry->annuled = true;
controllers[i]->queue.free(entry);
}
}
}
}
bool BusInterconnect::controller_request_cb(void *arg)
{
Message *message = (Message*)arg;
BusControllerQueue* busControllerQueue;
foreach(i, controllers.count()) {
if(controllers[i]->controller ==
(Controller*)message->sender) {
busControllerQueue = controllers[i];
}
}
if (busControllerQueue->queue.isFull()) {
memdebug("Bus queue is full\n");
return false;
}
BusQueueEntry *busQueueEntry;
busQueueEntry = busControllerQueue->queue.alloc();
if(busControllerQueue->queue.isFull()) {
memoryHierarchy_->set_interconnect_full(this, true);
}
busQueueEntry->request = message->request;
message->request->incRefCounter();
busQueueEntry->hasData = message->hasData;
if(!is_busy()) {
// address bus
memoryHierarchy_->add_event(&broadcast_, 1, null);
set_bus_busy(true);
} else {
memdebug("Bus is busy\n");
}
return true;
}
BusQueueEntry* BusInterconnect::arbitrate_round_robin()
{
memdebug("BUS:: doing arbitration.. \n");
BusControllerQueue *controllerQueue = null;
int i;
if(lastAccessQueue)
i = lastAccessQueue->idx;
else
i = 0;
do {
i = (i + 1) % controllers.count();
controllerQueue = controllers[i];
if(controllerQueue->queue.count() > 0) {
BusQueueEntry *queueEntry = (BusQueueEntry*)
controllerQueue->queue.peek();
assert(queueEntry);
assert(!queueEntry->annuled);
lastAccessQueue = controllerQueue;
return queueEntry;
}
} while(controllerQueue != lastAccessQueue);
return null;
}
bool BusInterconnect::broadcast_cb(void *arg)
{
BusQueueEntry *queueEntry;
if(arg != null)
queueEntry = (BusQueueEntry*)arg;
else
queueEntry = arbitrate_round_robin();
if(queueEntry == null) { // nothing to broadcast
set_bus_busy(false);
return true;
}
// first check if any of the other controller's receive queue is
// full or not
// if its full the don't broadcast untill it has a free
// entry and pass the queue entry as argument to the broadcast
// signal so next time it doesn't need to arbitrate
bool isFull = false;
foreach(i, controllers.count()) {
if(controllers[i]->controller ==
queueEntry->controllerQueue->controller)
continue;
isFull |= controllers[i]->controller->is_full(true);
}
if(isFull) {
memoryHierarchy_->add_event(&broadcast_,
BUS_BROADCASTS_DELAY, queueEntry);
return true;
}
set_bus_busy(true);
Message& message = *memoryHierarchy_->get_message();
message.sender = this;
message.request = queueEntry->request;
message.hasData = queueEntry->hasData;
Controller *controller = queueEntry->controllerQueue->controller;
foreach(i, controllers.count()) {
if(controller != controllers[i]->controller) {
bool ret = controllers[i]->controller->
get_interconnect_signal()->emit(&message);
assert(ret);
}
}
// Free the entry from queue
if(!queueEntry->annuled) {
queueEntry->controllerQueue->queue.free(queueEntry);
}
if(!queueEntry->controllerQueue->queue.isFull()) {
memoryHierarchy_->set_interconnect_full(this, false);
}
queueEntry->request->decRefCounter();
memoryHierarchy_->add_event(&broadcastCompleted_,
BUS_BROADCASTS_DELAY, null);
// Free the message
memoryHierarchy_->free_message(&message);
return true;
}
bool BusInterconnect::broadcast_completed_cb(void *arg)
{
assert(is_busy());
// call broadcast_cb that will check if any pending
// requests are there or not
broadcast_cb(null);
return true ;
}
bool BusInterconnect::data_broadcast_cb(void *arg)
{
}
bool BusInterconnect::data_broadcast_completed_cb(void *arg)
{
}
void BusInterconnect::print_map(ostream& os)
{
os << "Bus Interconnect: ", get_name(), endl;
os << "\tconnected to: ", endl;
foreach(i, controllers.count()) {
os << "\t\tcontroller[i]: ",
controllers[i]->controller->get_name(), endl;
}
}
| [
"zoo@nus.edu.sg"
] | zoo@nus.edu.sg |
3b5a59eb59be73e355d24b0e0cfabc1261e1db8f | d29399f93b50cc2c677c41a40b97767dac580604 | /PAT/A/1005.cpp | 398674032cbf1d9ee7a48fa84372a1a1e182371f | [] | no_license | lmh760008522/ProgrammingExercises | 81636f209a150062c2c7b1ea78c441a7b1c0b68d | 821fd0d36f2eab11386dec1b6bcdaba223727c48 | refs/heads/master | 2021-10-08T20:11:35.547047 | 2018-12-17T08:12:51 | 2018-12-17T08:12:51 | 157,045,843 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 787 | cpp | #include<iostream>
#include<stack>
#include<string>
using namespace std;
void pprint(int x){
switch(x){
case 1:printf("one");break;
case 2:printf("two");break;
case 3:printf("three");break;
case 4:printf("four");break;
case 5:printf("five");break;
case 6:printf("six");break;
case 7:printf("seven");break;
case 8:printf("eight");break;
case 9:printf("nine");break;
case 0:printf("zero");break;
}
}
int main(){
char s[1005];
gets(s);
int sum=0;
for(int i=0;s[i]!='\0';i++){
sum+=s[i]-'0';
}
stack<int> st;
int num=0;
while(sum!=0){
st.push(sum%10);
sum=sum/10;
num++;
}
while(st.empty()==false){
int a = st.top();
st.pop();
pprint(a);
if(num!=1){
printf(" ");
}
num--;
}
return 0;
}
| [
"lmh760008522@gmail.com"
] | lmh760008522@gmail.com |
a29bb22f15c8d559aafd9fc86e4ebcc7d903e819 | c5b9f0fabffb6b2d13c6e350c8187a922709ac60 | /devel/.private/dynamic_introspection/include/dynamic_introspection/DoubleParameter.h | 6824239d355873e147027133a5ece54a108f1d93 | [] | no_license | MohamedEhabHafez/Sorting_Aruco_Markers | cae079fdce4a14561f5e092051771d299b06e789 | 0f820921c9f42b39867565441ed6ea108663ef6c | refs/heads/master | 2020-12-09T02:43:00.731223 | 2020-01-15T17:31:29 | 2020-01-15T17:31:29 | 233,154,293 | 0 | 0 | null | 2020-10-13T18:46:44 | 2020-01-11T00:41:38 | Makefile | UTF-8 | C++ | false | false | 5,871 | h | // Generated by gencpp from file dynamic_introspection/DoubleParameter.msg
// DO NOT EDIT!
#ifndef DYNAMIC_INTROSPECTION_MESSAGE_DOUBLEPARAMETER_H
#define DYNAMIC_INTROSPECTION_MESSAGE_DOUBLEPARAMETER_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 dynamic_introspection
{
template <class ContainerAllocator>
struct DoubleParameter_
{
typedef DoubleParameter_<ContainerAllocator> Type;
DoubleParameter_()
: name()
, value(0.0) {
}
DoubleParameter_(const ContainerAllocator& _alloc)
: name(_alloc)
, value(0.0) {
(void)_alloc;
}
typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _name_type;
_name_type name;
typedef double _value_type;
_value_type value;
typedef boost::shared_ptr< ::dynamic_introspection::DoubleParameter_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::dynamic_introspection::DoubleParameter_<ContainerAllocator> const> ConstPtr;
}; // struct DoubleParameter_
typedef ::dynamic_introspection::DoubleParameter_<std::allocator<void> > DoubleParameter;
typedef boost::shared_ptr< ::dynamic_introspection::DoubleParameter > DoubleParameterPtr;
typedef boost::shared_ptr< ::dynamic_introspection::DoubleParameter const> DoubleParameterConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::dynamic_introspection::DoubleParameter_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::dynamic_introspection::DoubleParameter_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace dynamic_introspection
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'dynamic_introspection': ['/home/mohamed/tiago_public_ws/src/dynamic_introspection/msg'], 'visualization_msgs': ['/opt/ros/kinetic/share/visualization_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::dynamic_introspection::DoubleParameter_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::dynamic_introspection::DoubleParameter_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::dynamic_introspection::DoubleParameter_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::dynamic_introspection::DoubleParameter_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::dynamic_introspection::DoubleParameter_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::dynamic_introspection::DoubleParameter_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::dynamic_introspection::DoubleParameter_<ContainerAllocator> >
{
static const char* value()
{
return "d8512f27253c0f65f928a67c329cd658";
}
static const char* value(const ::dynamic_introspection::DoubleParameter_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xd8512f27253c0f65ULL;
static const uint64_t static_value2 = 0xf928a67c329cd658ULL;
};
template<class ContainerAllocator>
struct DataType< ::dynamic_introspection::DoubleParameter_<ContainerAllocator> >
{
static const char* value()
{
return "dynamic_introspection/DoubleParameter";
}
static const char* value(const ::dynamic_introspection::DoubleParameter_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::dynamic_introspection::DoubleParameter_<ContainerAllocator> >
{
static const char* value()
{
return "string name\n\
float64 value\n\
";
}
static const char* value(const ::dynamic_introspection::DoubleParameter_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::dynamic_introspection::DoubleParameter_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.name);
stream.next(m.value);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct DoubleParameter_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::dynamic_introspection::DoubleParameter_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::dynamic_introspection::DoubleParameter_<ContainerAllocator>& v)
{
s << indent << "name: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.name);
s << indent << "value: ";
Printer<double>::stream(s, indent + " ", v.value);
}
};
} // namespace message_operations
} // namespace ros
#endif // DYNAMIC_INTROSPECTION_MESSAGE_DOUBLEPARAMETER_H
| [
"mohamed@radiirobotics.com"
] | mohamed@radiirobotics.com |
ef5b8c4292fa7b3eb584d6de9b771c8f5c669baa | 3d739f27ee3e4c86e7aeb765d3b2668ec7918147 | /Others codes/con1F.cpp | 4fd803f2c8e62b12005ed9e7b8376a02c15b2796 | [] | no_license | monircse061/My-All-Codes | 4b7bcba59a4c8a3497d38b6da08fca1faf0f6110 | b5c9f4367efd134c08a4f1eff680202484963098 | refs/heads/master | 2023-04-13T18:55:50.848787 | 2021-04-24T03:46:45 | 2021-04-24T03:46:45 | 361,062,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,693 | cpp | #include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
//int password();
void addrecord();
void viewrecord();
void editrecord();
//void editpassword();
void deleterecord();
struct record
{
char time[6];
char name[30];
char place[25];
char duration[10];
char note[500];
} ;
int main()
{
int ch;
printf("\n\n\t***********************************\n");
printf("\t*PASSWORD PROTECTED PERSONAL DIARY*\n");
printf("\t***********************************");
while(1)
{
printf("\n\n\t\tMAIN MENU:");
printf("\n\n\tADD RECORD\t[1]");
printf("\n\tVIEW RECORD\t[2]");
printf("\n\tEDIT RECORD\t[3]");
printf("\n\tDELETE RECORD\t[4]");
// printf("\n\tEDIT PASSWORD\t[5]");
printf("\n\tEXIT\t\t[6]");
printf("\n\n\tENTER YOUR CHOICE:");
scanf("%d",&ch);
switch(ch)
{
case 1:
addrecord();
break;
case 2:
viewrecord();
break;
case 3:
editrecord();
break;
case 4:
deleterecord();
break;
//case 5:
///editpassword();
// break;
case 6:
//printf("\n\n\t\tTHANK YOU ");
//getch();
//exit(0);
return 0;
default:
printf("\nYOU ENTERED WRONG CHOICE..");
printf("\nPRESS ANY KEY TO TRY AGAIN");
getch();
break;
}
system("cls");
}
return 0;
}
void addrecord( )
{
system("cls");
FILE *fp ;
char another = 'Y' ,time[10];
struct record e ;
char filename[15];
int choice;
printf("\n\n\t\t***************************\n");
printf("\t\t* WELCOME TO THE ADD MENU *");
printf("\n\t\t***************************\n\n");
printf("\n\n\tENTER DATE OF YOUR RECORD:[yyyy-mm-dd]:");
fflush(stdin);
gets(filename);
fp = fopen (filename, "ab+" ) ;
if ( fp == NULL )
{
fp=fopen(filename,"wb+");
if(fp==NULL)
{
printf("\nSYSTEM ERROR...");
printf("\nPRESS ANY KEY TO EXIT");
getch();
return ;
}
}
while ( another == 'Y'|| another=='y' )
{
choice=0;
fflush(stdin);
printf ( "\n\tENTER TIME:[hh:mm]:");
scanf("%s",time);
rewind(fp);
while(fread(&e,sizeof(e),1,fp)==1)
{
if(strcmp(e.time,time)==0)
{
printf("\n\tTHE RECORD ALREADY EXISTS.\n");
choice=1;
}
}
if(choice==0)
{
strcpy(e.time,time);
printf("\tENTER NAME:");
fflush(stdin);
gets(e.name);
fflush(stdin);
printf("\tENTER PLACE:");
gets(e.place);
fflush(stdin);
printf("\tENTER DURATION:");
gets(e.duration);
fflush(stdin);
printf("\tNOTE:");
gets(e.note);
fwrite ( &e, sizeof ( e ), 1, fp ) ;
printf("\nYOUR RECORD IS ADDED...\n");
}
printf ( "\n\tADD ANOTHER RECORD...(Y/N) " ) ;
fflush ( stdin ) ;
another = getchar( ) ;
}
fclose ( fp ) ;
printf("\n\n\tPRESS ANY KEY TO EXIT...");
getch();
}
void viewrecord( )
{
FILE *fpte ;
system("cls");
struct record customer ;
char time[6],filename[14],choice;
int ch;
printf("\n\n\t\t*******************************\n");
printf("\t\t* HERE IS THE VIEWING MENU *");
printf("\n\t\t*******************************\n\n");
choice=0;
if(choice!=0)
{
return ;
}
do
{
printf("\n\tENTER THE DATE OF RECORD TO BE VIEWED:[yyyy-mm-dd]:");
fflush(stdin);
gets(filename);
fpte = fopen ( filename, "rb" ) ;
if ( fpte == NULL )
{
puts ( "\nTHE RECORD DOES NOT EXIST...\n" ) ;
printf("PRESS ANY KEY TO EXIT...");
getch();
return ;
}
system("cls");
printf("\n\tHOW WOULD YOU LIKE TO VIEW:\n");
printf("\n\t1.WHOLE RECORD OF THE DAY.");
printf("\n\t2.RECORD OF FIX TIME.");
printf("\n\t\tENTER YOUR CHOICE:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nTHE WHOLE RECORD FOR %s IS:",filename);
while ( fread ( &customer, sizeof ( customer ), 1, fpte ) == 1 )
{
printf("\n");
printf("\nTIME: %s",customer.time);
printf("\nMEETING WITH: %s",customer.name);
printf("\nMEETING AT: %s",customer.place);
printf("\nDURATION: %s",customer.duration);
printf("\nNOTE: %s",customer.note);
printf("\n");
}
break;
case 2:
fflush(stdin);
printf("\nENTER TIME:[hh:mm]:");
gets(time);
while ( fread ( &customer, sizeof ( customer ), 1, fpte ) == 1 )
{
if(strcmp(customer.time,time)==0)
{
printf("\nYOUR RECORD IS:");
printf("\nTIME: %s",customer.time);
printf("\nMEETING WITH: %s",customer.name);
printf("\nMEETING AT: %s",customer.place);
printf("\nDUARATION: %s",customer.duration);
printf("\nNOTE: %s",customer.note);
}
}
break;
default: printf("\nYOU TYPED SOMETHING ELSE...\n");
break;
}
printf("\n\nWOULD YOU LIKE TO CONTINUE VIEWING...(Y/N):");
fflush(stdin);
scanf("%c",&choice);
}while(choice=='Y'||choice=='y');
fclose ( fpte ) ;
return ;
}
void editrecord()
{
system("cls");
FILE *fpte ;
struct record customer ;
char time[6],choice,filename[14];
int num,count=0;
printf("\n\n\t\t*******************************\n");
printf("\t\t* WELCOME TO THE EDITING MENU *");
printf("\n\t\t*******************************\n\n");
choice=0;
if(choice!=0)
{
return ;
}
do
{
printf("\n\tENTER THE DATE OF RECORD TO BE EDITED:[yyyy-mm-dd]:");
fflush(stdin);
gets(filename);
printf("\n\tENTER TIME:[hh:mm]:");
gets(time);
fpte = fopen ( filename, "rb+" ) ;
if ( fpte == NULL )
{
printf( "\nRECORD DOES NOT EXISTS:" ) ;
printf("\nPRESS ANY KEY TO GO BACK");
getch();
return;
}
while ( fread ( &customer, sizeof ( customer ), 1, fpte ) == 1 )
{
if(strcmp(customer.time,time)==0)
{
printf("\nYOUR OLD RECORD WAS AS:");
printf("\nTIME: %s",customer.time);
printf("\nMEETING WITH: %s",customer.name);
printf("\nMEETING AT: %s",customer.place);
printf("\nDURATION: %s",customer.duration);
printf("\nNOTE: %s",customer.note);
printf("\n\n\t\tWHAT WOULD YOU LIKE TO EDIT..");
printf("\n1.TIME.");
printf("\n2.MEETING PERSON.");
printf("\n3.MEETING PLACE.");
printf("\n4.DURATION.");
printf("\n5.NOTE.");
printf("\n6.WHOLE RECORD.");
printf("\n7.GO BACK TO MAIN MENU.");
do
{
printf("\n\tENTER YOUR CHOICE:");
fflush(stdin);
scanf("%d",&num);
fflush(stdin);
switch(num)
{
case 1: printf("\nENTER THE NEW DATA:");
printf("\nNEW TIME:[hh:mm]:");
gets(customer.time);
break;
case 2: printf("\nENTER THE NEW DATA:");
printf("\nNEW MEETING PERSON:");
gets(customer.name);
break;
case 3: printf("\nENTER THE NEW DATA:");
printf("\nNEW MEETING PLACE:");
gets(customer.place);
break;
case 4: printf("\nENTER THE NEW DATA:");
printf("\nDURATION:");
gets(customer.duration);
break;
case 5: printf("ENTER THE NEW DATA:");
printf("\nNOTE:");
gets(customer.note);
break;
case 6: printf("\nENTER THE NEW DATA:");
printf("\nNEW TIME:[hh:mm]:");
gets(customer.time);
printf("\nNEW MEETING PERSON:");
gets(customer.name);
printf("\nNEW MEETING PLACE:");
gets(customer.place);
printf("\nDURATION:");
gets(customer.duration);
printf("\nNOTE:");
gets(customer.note);
break;
case 7: printf("\nPRESS ANY KEY TO GO BACK...\n");
getch();
return ;
break;
default: printf("\nYOU TYPED SOMETHING ELSE...TRY AGAIN\n");
break;
}
}while(num<1||num>8);
fseek(fpte,-sizeof(customer),SEEK_CUR);
fwrite(&customer,sizeof(customer),1,fpte);
fseek(fpte,-sizeof(customer),SEEK_CUR);
fread(&customer,sizeof(customer),1,fpte);
choice=5;
break;
}
}
if(choice==5)
{
system("cls");
printf("\n\t\tEDITING COMPLETED...\n");
printf("--------------------\n");
printf("THE NEW RECORD IS:\n");
printf("--------------------\n");
printf("\nTIME: %s",customer.time);
printf("\nMEETING WITH: %s",customer.name);
printf("\nMEETING AT: %s",customer.place);
printf("\nDURATION: %s",customer.duration);
printf("\nNOTE: %s",customer.note);
fclose(fpte);
printf("\n\n\tWOULD YOU LIKE TO EDIT ANOTHER RECORD.(Y/N)");
scanf("%c",&choice);
count++;
}
else
{
printf("\nTHE RECORD DOES NOT EXIST::\n");
printf("\nWOULD YOU LIKE TO TRY AGAIN...(Y/N)");
scanf("%c",&choice);
}
}while(choice=='Y'||choice=='y');
fclose ( fpte ) ;
if(count==1)
printf("\n%d FILE IS EDITED...\n",count);
else if(count>1)
printf("\n%d FILES ARE EDITED..\n",count);
else
printf("\nNO FILES EDITED...\n");
printf("\tPRESS ENTER TO EXIT EDITING MENU.");
getch();
}
/**int password()
{
char pass[15]={0},check[15]={0},ch;
FILE *fpp;
int i=0,j;
printf("::FOR SECURITY PURPOSE::");
printf("::ONLY THREE TRIALS ARE ALLOWED::");
for(j=0;j<3;j++)
{
i=0;
printf("\n\n\tENTER THE PASSWORD:");
pass[0]=getch();
while(pass[i]!='\r')
{
if(pass[i]=='\b')
{
i--;
printf("\b");
printf(" ");
printf("\b");
pass[i]=getch();
}
else
{
printf("*");
i++;
pass[i]=getch();
}
}
pass[i]='\0';
fpp=fopen("SE","r");
if (fpp==NULL)
{
printf("\nERROR WITH THE SYSTEM FILE...[FILE MISSING]\n");
getch();
return 1;
}
else
i=0;
while(1)
{
ch=fgetc(fpp);
if(ch==EOF)
{
check[i]='\0';
break;
}
check[i]=ch-5;
i++;
}
if(strcmp(pass,check)==0)
{
printf("\n\n\tACCESS GRANTED...\n");
return 0;
}
else
{
printf("\n\n\tWRONG PASSWORD..\n\n\tACCESS DENIED...\n");
}
}
printf("\n\n\t::YOU ENTERED WRONG PASSWORD::YOU ARE NOT ALLOWED TO ACCESS ANY FILE::\n\n\tPRESS ANY KEY TO GO BACK...");
getch();
return 1;
}
void editpassword()
{
system("cls");
printf("\n");
char pass[15]={0},confirm[15]={0},ch;
int choice,i,check;
FILE *fp;
fp=fopen("SE","rb");
if(fp==NULL)
{
fp=fopen("SE","wb");
if(fp==NULL)
{
printf("SYSTEM ERROR...");
getch();
return ;
}
fclose(fp);
printf("\nSYSTEM RESTORED...\nYOUR PASSWORD IS 'ENTER'\n PRESS ENTER TO CHANGE PASSWORD\n\n");
getch();
}
fclose(fp);
check=password();
if(check==1)
{
return ;
}
do
{
if(check==0)
{
i=0;
choice=0;
printf("\n\n\tENTER THE NEW PASSWORD:");
fflush(stdin);
pass[0]=getch();
while(pass[i]!='\r')
{
if(pass[i]=='\b')
{
i--;
printf("\b");
printf(" ");
printf("\b");
pass[i]=getch();
}
else
{
printf("*");
i++;
pass[i]=getch();
}
}
pass[i]='\0';
i=0;
printf("\n\tCONFIRM PASSWORD:");
confirm[0]=getch();
while(confirm[i]!='\r')
{
if(confirm[i]=='\b')
{
i--;
printf("\b");
printf(" ");
printf("\b");
confirm[i]=getch();
}
else
{
printf("*");
i++;
confirm[i]=getch();
}
}
confirm[i]='\0';
if(strcmp(pass,confirm)==0)
{
fp=fopen("SE","wb");
if(fp==NULL)
{
printf("\n\t\tSYSTEM ERROR");
getch();
return ;
}
i=0;
while(pass[i]!='\0')
{
ch=pass[i];
putc(ch+5,fp);
i++;
}
putc(EOF,fp);
fclose(fp);
}
else
{
printf("\n\tTHE NEW PASSWORD DOES NOT MATCH.");
choice=1;
}
}
}while(choice==1);
printf("\n\n\tPASSWORD CHANGED...\n\n\tPRESS ANY KEY TO GO BACK...");
getch();
}**/
void deleterecord( )
{
system("cls");
FILE *fp,*fptr ;
struct record file ;
char filename[15],another = 'Y' ,time[10];;
int choice,check;
printf("\n\n\t\t*************************\n");
printf("\t\t* WELCOME TO DELETE MENU*");
printf("\n\t\t*************************\n\n");
//check = 0;
//if(check==1)
//{
//
//}
while ( another == 'Y' )
{
printf("\n\n\tHOW WOULD YOU LIKE TO DELETE.");
printf("\n\n\t#DELETE WHOLE RECORD\t\t\t[1]");
printf("\n\t#DELETE A PARTICULAR RECORD BY TIME\t[2]");
do
{
printf("\n\t\tENTER YOU CHOICE:");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n\tENTER THE DATE OF RECORD TO BE DELETED:[yyyy-mm-dd]:");
fflush(stdin);
gets(filename);
fp = fopen (filename, "wb" ) ;
if ( fp == NULL )
{
printf("\nTHE FILE DOES NOT EXISTS");
printf("\nPRESS ANY KEY TO GO BACK.");
getch();
return ;
}
fclose(fp);
remove(filename);
printf("\nDELETED SUCCESFULLY...");
break;
case 2:
printf("\n\tENTER THE DATE OF RECORD:[yyyy-mm-dd]:");
fflush(stdin);
gets(filename);
fp = fopen (filename, "rb" ) ;
if ( fp == NULL )
{
printf("\nTHE FILE DOES NOT EXISTS");
printf("\nPRESS ANY KEY TO GO BACK.");
getch();
return ;
}
fptr=fopen("temp","wb");
if(fptr==NULL)
{
printf("\nSYSTEM ERROR");
printf("\nPRESS ANY KEY TO GO BACK");
getch();
return ;
}
printf("\n\tENTER THE TIME OF RECORD TO BE DELETED:[hh:mm]:");
fflush(stdin);
gets(time);
while(fread(&file,sizeof(file),1,fp)==1)
{
if(strcmp(file.time,time)!=0)
fwrite(&file,sizeof(file),1,fptr);
}
fclose(fp);
fclose(fptr);
remove(filename);
rename("temp",filename);
printf("\nDELETED SUCCESFULLY...");
break;
default:
printf("\n\tYOU ENTERED WRONG CHOICE");
break;
}
}while(choice<1||choice>2);
printf("\n\tDO YOU LIKE TO DELETE ANOTHER RECORD.(Y/N):");
fflush(stdin);
scanf("%c",&another);
}
printf("\n\n\tPRESS ANY KEY TO EXIT...");
getch();
}
| [
"monirahammod097@gmail.com"
] | monirahammod097@gmail.com |
39dd7cf19426180533b1c5ee145220b3d4c8ba41 | cdef6034b2b275a2c980d2bbfb2f14a77ce9c8f9 | /OpenEXR/openexr-1.7.0/IlmImf/ImfTileOffsets.cpp | 5447f8f51284e23bdb78e803ea7a50d58065147d | [] | no_license | exavi/ios-openexr | e1014f93542043d5f870c501ecd39955002990c8 | 0bea4ebef29a3bd22cf159643afc375c2f1a1b0a | refs/heads/master | 2021-01-19T21:28:32.942192 | 2013-03-21T21:20:18 | 2013-03-21T21:20:18 | 8,662,345 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,115 | cpp | ///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//
// class TileOffsets
//
//-----------------------------------------------------------------------------
#include "ImfTileOffsets.h"
#include "ImfXdr.h"
#include "ImfIO.h"
#include "Iex.h"
namespace Imf {
TileOffsets::TileOffsets (LevelMode mode,
int numXLevels, int numYLevels,
const int *numXTiles, const int *numYTiles)
:
_mode (mode),
_numXLevels (numXLevels),
_numYLevels (numYLevels)
{
switch (_mode)
{
case ONE_LEVEL:
case MIPMAP_LEVELS:
_offsets.resize (_numXLevels);
for (unsigned int l = 0; l < _offsets.size(); ++l)
{
_offsets[l].resize (numYTiles[l]);
for (unsigned int dy = 0; dy < _offsets[l].size(); ++dy)
{
_offsets[l][dy].resize (numXTiles[l]);
}
}
break;
case RIPMAP_LEVELS:
_offsets.resize (_numXLevels * _numYLevels);
for (unsigned int ly = 0; ly < _numYLevels; ++ly)
{
for (unsigned int lx = 0; lx < _numXLevels; ++lx)
{
int l = ly * _numXLevels + lx;
_offsets[l].resize (numYTiles[ly]);
for (unsigned int dy = 0; dy < _offsets[l].size(); ++dy)
{
_offsets[l][dy].resize (numXTiles[lx]);
}
}
}
break;
}
}
bool
TileOffsets::anyOffsetsAreInvalid () const
{
for (unsigned int l = 0; l < _offsets.size(); ++l)
for (unsigned int dy = 0; dy < _offsets[l].size(); ++dy)
for (unsigned int dx = 0; dx < _offsets[l][dy].size(); ++dx)
if (_offsets[l][dy][dx] <= 0)
return true;
return false;
}
void
TileOffsets::findTiles (IStream &is)
{
for (unsigned int l = 0; l < _offsets.size(); ++l)
{
for (unsigned int dy = 0; dy < _offsets[l].size(); ++dy)
{
for (unsigned int dx = 0; dx < _offsets[l][dy].size(); ++dx)
{
Int64 tileOffset = is.tellg();
int tileX;
Xdr::read <StreamIO> (is, tileX);
int tileY;
Xdr::read <StreamIO> (is, tileY);
int levelX;
Xdr::read <StreamIO> (is, levelX);
int levelY;
Xdr::read <StreamIO> (is, levelY);
int dataSize;
Xdr::read <StreamIO> (is, dataSize);
Xdr::skip <StreamIO> (is, dataSize);
if (!isValidTile(tileX, tileY, levelX, levelY))
return;
operator () (tileX, tileY, levelX, levelY) = tileOffset;
}
}
}
}
void
TileOffsets::reconstructFromFile (IStream &is)
{
//
// Try to reconstruct a missing tile offset table by sequentially
// scanning through the file, and recording the offsets in the file
// of the tiles we find.
//
Int64 position = is.tellg();
try
{
findTiles (is);
}
catch (...)
{
//
// Suppress all exceptions. This function is called only to
// reconstruct the tile offset table for incomplete files,
// and exceptions are likely.
//
}
is.clear();
is.seekg (position);
}
void
TileOffsets::readFrom (IStream &is, bool &complete)
{
//
// Read in the tile offsets from the file's tile offset table
//
for (unsigned int l = 0; l < _offsets.size(); ++l)
for (unsigned int dy = 0; dy < _offsets[l].size(); ++dy)
for (unsigned int dx = 0; dx < _offsets[l][dy].size(); ++dx)
Xdr::read <StreamIO> (is, _offsets[l][dy][dx]);
//
// Check if any tile offsets are invalid.
//
// Invalid offsets mean that the file is probably incomplete
// (the offset table is the last thing written to the file).
// Either some process is still busy writing the file, or
// writing the file was aborted.
//
// We should still be able to read the existing parts of the
// file. In order to do this, we have to make a sequential
// scan over the scan tile to reconstruct the tile offset
// table.
//
if (anyOffsetsAreInvalid())
{
complete = false;
reconstructFromFile (is);
}
else
{
complete = true;
}
}
Int64
TileOffsets::writeTo (OStream &os) const
{
//
// Write the tile offset table to the file, and
// return the position of the start of the table
// in the file.
//
Int64 pos = os.tellp();
if (pos == -1)
Iex::throwErrnoExc ("Cannot determine current file position (%T).");
for (unsigned int l = 0; l < _offsets.size(); ++l)
for (unsigned int dy = 0; dy < _offsets[l].size(); ++dy)
for (unsigned int dx = 0; dx < _offsets[l][dy].size(); ++dx)
Xdr::write <StreamIO> (os, _offsets[l][dy][dx]);
return pos;
}
bool
TileOffsets::isEmpty () const
{
for (unsigned int l = 0; l < _offsets.size(); ++l)
for (unsigned int dy = 0; dy < _offsets[l].size(); ++dy)
for (unsigned int dx = 0; dx < _offsets[l][dy].size(); ++dx)
if (_offsets[l][dy][dx] != 0)
return false;
return true;
}
bool
TileOffsets::isValidTile (int dx, int dy, int lx, int ly) const
{
switch (_mode)
{
case ONE_LEVEL:
if (lx == 0 &&
ly == 0 &&
_offsets.size() > 0 &&
_offsets[0].size() > dy &&
_offsets[0][dy].size() > dx)
{
return true;
}
break;
case MIPMAP_LEVELS:
if (lx < _numXLevels &&
ly < _numYLevels &&
_offsets.size() > lx &&
_offsets[lx].size() > dy &&
_offsets[lx][dy].size() > dx)
{
return true;
}
break;
case RIPMAP_LEVELS:
if (lx < _numXLevels &&
ly < _numYLevels &&
_offsets.size() > lx + ly * _numXLevels &&
_offsets[lx + ly * _numXLevels].size() > dy &&
_offsets[lx + ly * _numXLevels][dy].size() > dx)
{
return true;
}
break;
default:
return false;
}
return false;
}
Int64 &
TileOffsets::operator () (int dx, int dy, int lx, int ly)
{
//
// Looks up the value of the tile with tile coordinate (dx, dy)
// and level number (lx, ly) in the _offsets array, and returns
// the cooresponding offset.
//
switch (_mode)
{
case ONE_LEVEL:
return _offsets[0][dy][dx];
break;
case MIPMAP_LEVELS:
return _offsets[lx][dy][dx];
break;
case RIPMAP_LEVELS:
return _offsets[lx + ly * _numXLevels][dy][dx];
break;
default:
throw Iex::ArgExc ("Unknown LevelMode format.");
}
}
Int64 &
TileOffsets::operator () (int dx, int dy, int l)
{
return operator () (dx, dy, l, l);
}
const Int64 &
TileOffsets::operator () (int dx, int dy, int lx, int ly) const
{
//
// Looks up the value of the tile with tile coordinate (dx, dy)
// and level number (lx, ly) in the _offsets array, and returns
// the cooresponding offset.
//
switch (_mode)
{
case ONE_LEVEL:
return _offsets[0][dy][dx];
break;
case MIPMAP_LEVELS:
return _offsets[lx][dy][dx];
break;
case RIPMAP_LEVELS:
return _offsets[lx + ly * _numXLevels][dy][dx];
break;
default:
throw Iex::ArgExc ("Unknown LevelMode format.");
}
}
const Int64 &
TileOffsets::operator () (int dx, int dy, int l) const
{
return operator () (dx, dy, l, l);
}
} // namespace Imf
| [
"byexavi@gmail.com"
] | byexavi@gmail.com |
7871bcecaa06fbbf66f05eabcacf20e97e45426f | 9984cf39a4ca67c35f3fbdb6ce96c1d5630663e2 | /apps/evmc/vbucket_config.cc | 3d3c91a780974465f184300cd5759a3cd1140cd1 | [
"BSD-3-Clause"
] | permissive | Qihoo360/evpp | 89e7f24793a65e183edee6965fc71e3930073585 | 477033f938fd47dfecde43c82257cd286d9fa38e | refs/heads/master | 2023-08-25T04:46:21.628781 | 2022-11-06T10:33:10 | 2022-11-06T10:33:10 | 83,792,790 | 3,665 | 1,074 | BSD-3-Clause | 2023-08-02T07:15:36 | 2017-03-03T11:46:03 | C++ | GB18030 | C++ | false | false | 5,831 | cc | #include "vbucket_config.h"
#include <map>
#include <cassert>
#include <rapidjson/filereadstream.h>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <libhashkit/hashkit.h>
#include "random.h"
#include "extract_vbucket_conf.h"
#include "likely.h"
namespace evmc {
const uint16_t BAD_SERVER_ID = 65535;
VbucketConfig::VbucketConfig() : rand_(new Random(time(nullptr))) {
}
VbucketConfig::~VbucketConfig() {
delete rand_;
}
enum {
INIT_WEIGHT = 1000,
MAX_WEIGHT = 1000000,
MIN_WEIGHT = 100,
CLUSTER_MODE = 1,
STAND_ALONE_MODE = 2,
};
void VbucketConfig::OnVbucketResult(uint16_t vbucket, bool success) {
// 捎带更新健康值,不专门更新. 这样该函数就是多余的
// 健康值/权重更新策略:
// 1. 健康值快速(指数)衰减,慢速(线性)恢复
// 2. N个replica,目前是选不同端口重试两次. 是否需要全部重试一遍?
// 3. 更新健康值时,兼顾线程安全和性能
return;
}
uint16_t VbucketConfig::SelectServerFirstId(uint16_t vbucket) const {
uint16_t vb = vbucket % vbucket_map_.size();
const std::vector<int>& server_ids = vbucket_map_[vb];
return server_ids[0];
}
uint16_t VbucketConfig::SelectServerId(uint16_t vbucket, uint16_t last_id) const {
uint16_t vb = vbucket % vbucket_map_.size();
const std::vector<int>& server_ids = vbucket_map_[vb];
uint16_t server_id = BAD_SERVER_ID;
{
// 按健康权重选定server id
std::map<int64_t, uint16_t> weighted_items;
int64_t total_weight = 0;
for (size_t i = 0 ; i < server_ids.size(); ++i) {
if (server_ids[i] == last_id) {
continue;
}
total_weight += server_health_[server_ids[i]];
// total_weight += 1000; // for test only
weighted_items[total_weight] = server_ids[i];
}
if (total_weight > 0) {
server_id = weighted_items.upper_bound(rand_->Next() % total_weight)->second;
LOG_DEBUG << "SelectServerId selected_server_id=" << server_id << " last_id=" << last_id;
} else {
return BAD_SERVER_ID;
}
}
// 捎带更新健康值,不专门更新
server_health_[server_id] += 1000;
if (server_health_[server_id] > MAX_WEIGHT) {
server_health_[server_id] = MAX_WEIGHT;
}
if (last_id < server_health_.size()) {
server_health_[last_id] /= 2;
if (server_health_[last_id] <= MIN_WEIGHT) {
server_health_[last_id] = 100;
}
}
return server_id;
}
static hashkit_hash_algorithm_t algorithm(const std::string& alg) {
if (alg == "MD5") {
return HASHKIT_HASH_MD5;
}
return HASHKIT_HASH_MAX;
}
uint16_t VbucketConfig::GetVbucketByKey(const char* key, size_t nkey) const {
uint32_t digest = libhashkit_digest(key, nkey, algorithm(algorithm_));
return digest % vbucket_map_.size();
}
bool VbucketConfig::Load(const char* json_info) {
rapidjson::Document d;
d.Parse(json_info);
replicas_ = d["numReplicas"].GetInt();
algorithm_ = d["hashAlgorithm"].GetString();
rapidjson::Value& servers = d["serverList"];
LOG_DEBUG << "server count = " << servers.Size();
for (rapidjson::SizeType i = 0; i < servers.Size(); i++) {
server_list_.emplace_back(servers[i].GetString());
server_health_.emplace_back(INIT_WEIGHT);
}
rapidjson::Value& vbuckets = d["vBucketMap"];
for (rapidjson::SizeType i = 0; i < vbuckets.Size(); i++) {
rapidjson::Value& ids = vbuckets[i];
vbucket_map_.emplace_back(std::vector<int>());
for (rapidjson::SizeType j = 0; j < ids.Size(); j++) {
vbucket_map_.back().emplace_back(ids[j].GetInt());
}
}
return true;
}
bool MultiModeVbucketConfig::IsStandAlone(const char* serv) {
bool has_semicolon = false;
int i = 0;
char c = *(serv + i);
while (c != '\0') {
if (c == ':') {
has_semicolon = true;
}
if (c == '/') {
break;
}
++i;
c = *(serv + i);
}
if (c == '\0' && has_semicolon) {
return true;
}
return false;
}
bool MultiModeVbucketConfig::Load(const char* json_file) {
if (IsStandAlone(json_file)) {
mode_ = STAND_ALONE_MODE;
single_server_.emplace_back(json_file);
return true;
} else {
mode_ = CLUSTER_MODE;
std::string context;
int ret = GetVbucketConf::GetVbucketConfContext(json_file, context);
if (ret == 0) {
return VbucketConfig::Load(context.c_str());
}
return false;
}
}
uint16_t MultiModeVbucketConfig::GetVbucketByKey(const char* key, size_t nkey) const {
if (mode_ != STAND_ALONE_MODE) {
return VbucketConfig::GetVbucketByKey(key, nkey);
}
return 0;
}
uint16_t MultiModeVbucketConfig::SelectServerFirstId(uint16_t vbucket) const {
if (mode_ != STAND_ALONE_MODE) {
return VbucketConfig::SelectServerFirstId(vbucket);
}
return 0;
}
uint16_t MultiModeVbucketConfig::SelectServerId(uint16_t vbucket, uint16_t last_id) const {
if (mode_ != STAND_ALONE_MODE) {
return VbucketConfig::SelectServerId(vbucket, last_id);
}
return 0;
}
const std::string& MultiModeVbucketConfig::GetServerAddrById(uint16_t server_id) const {
if (mode_ != STAND_ALONE_MODE) {
return VbucketConfig::GetServerAddrById(server_id);
}
assert(single_server_.size() == 1);
return single_server_[0];
}
const std::vector<std::string>& MultiModeVbucketConfig::server_list() const {
if (mode_ != STAND_ALONE_MODE) {
return VbucketConfig::server_list();
}
return single_server_;
}
}
| [
"zieckey@gmail.com"
] | zieckey@gmail.com |
00f92d9398f74e3fe51a5aa1b316d9aafe9e98a2 | 3422d4a068bbb86d97e29c3a253e3e57426b6eee | /src/BVHNode.hpp | 8e1704e3098754ee5a9e6d08d814e113743a7912 | [
"MIT"
] | permissive | kiorisyshen/LearnRayTracing | 018077948788fe1910eb4bd89c3418188bac6cdd | 81527a43eb1c9034424be0b23d75839c580e1d79 | refs/heads/master | 2022-04-29T02:11:25.773210 | 2020-04-19T02:25:35 | 2020-04-19T02:25:35 | 254,781,428 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 975 | hpp | #pragma once
#include "HittableList.hpp"
namespace LearnRT {
class BVHNode : public IHittable {
public:
BVHNode(const HittableList &list, double time0, double time1) {
std::vector<std::shared_ptr<IHittable>> listCopy;
for (auto &item : list.getList()) {
listCopy.push_back(item);
}
*this = BVHNode(listCopy, 0, listCopy.size(), time0, time1);
}
BVHNode(std::vector<std::shared_ptr<IHittable>> &objects, size_t start, size_t end, double time0, double time1, int startAxis = 0);
virtual bool hit(const Ray &r, double t_min, double t_max, HitRecord &rec, GeometryProperty &geom) const;
virtual bool boundingBox(double t0, double t1, AABB &output_box) const;
virtual Vec3d getCenter() const {
return (m_Box->min() + m_Box->max()) / 2.0;
}
private:
std::shared_ptr<IHittable> m_Left;
std::shared_ptr<IHittable> m_Right;
std::shared_ptr<AABB> m_Box;
};
} // namespace LearnRT | [
"kiorisyshen@gmail.com"
] | kiorisyshen@gmail.com |
b2685d458b6b7890130329b1f7613469707d3316 | f1fca9dd580c9675d50c1f3e194e5763410850d4 | /EncryptedString/EncryptedString.cpp | 72bd7e9df71e721c3b8a049036872df572d076a6 | [] | no_license | zandratharp2012/CPP.Practice | 8b54258ff9bc4cd312ddc363bda360c6265cc617 | 0bec683e669bc252c67c687b070d4b60b0801105 | refs/heads/master | 2020-03-18T13:07:45.493081 | 2019-08-03T05:46:53 | 2019-08-03T05:46:53 | 134,762,084 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,522 | cpp | /*
***************************************************************
Program Description: EncryptedString Implementation File
*****************************************************************
*/
#include "EncryptedString.h"
#include <iostream>
using namespace std;
EncryptedString::EncryptedString() //Constructor
{
sentence = "";
}
EncryptedString::EncryptedString(string s) //Constructor Calling Set Function
{
setSentence(s);
}
void EncryptedString::setSentence(string str) //Set And Encrypt String
{
string temp; //Declare Temporary String Variable
for (int index=0; index <= str.length(); index++)
{
if (str[index] == 32) //Does Not Encrypt Space
temp += str[index];
else if (str[index] > 64 && str[index] < 90)
temp += (str[index]+1);
else if (str[index] > 96 && str[index] < 122)
temp += (str[index] +1);
else if (str[index] == 90 || str[index] == 122)
temp += (str[index] -25); //Allows 'z' & 'Z' To Wrap Around
}
sentence = temp; //Stores Encrypted String
}
string EncryptedString::getDecrypted() //Get Original String
{
for (int index=0; index <= sentence.length(); index++)
{
if (sentence[index] == 32) //Keeps Spaces
sentence[index] = sentence[index];
else
sentence[index] = sentence[index] -1; //Shifts String -1
}
return sentence;
}
string EncryptedString::getEncrypted()
{
return sentence; //Gets Encrypted String
}
| [
"zandra.tharp@g.austincc.edu"
] | zandra.tharp@g.austincc.edu |
655f427c0bc2fd960f5af9cbfbcb6cadbc5c5343 | 8bb7e4b0f6c47793c0f643dc7f2df8b7f5646ca6 | /1501 - Data Structures and Algorithms - Spring 2015/Assignments/DS-Spring2015-Assignment-03/DS-Spring2015-Assignment-03-Solution/DS-Spring2015-Assignment-03-Q3/MainQ3.cpp | 2ba5170d8242dc663707714ac98624716455f177 | [] | no_license | inf-eth/i02-0491-courses | 405cb0d534fed643434dd2126776cbe030af4d13 | f7e2ea222aeb2b21bcc9d2793a8652cc7f5afe23 | refs/heads/master | 2021-01-10T09:47:16.518013 | 2015-07-23T17:09:14 | 2015-07-23T17:09:14 | 46,210,614 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 311 | cpp | #include "Tree.h"
#include <iostream>
using namespace std;
int main()
{
Tree TestTree;
char* Prefix="(*(-(a)(*(d)(e)))(+(b)(c)))";
TestTree.MakeTree(Prefix);
TestTree.Preorder();
cout << endl;
TestTree.Inorder();
cout << endl;
TestTree.Postorder();
cout << endl;
return 0;
}
| [
"infinity.ethereal@9fa76b84-cec5-8abd-45b1-de927d2ca524"
] | infinity.ethereal@9fa76b84-cec5-8abd-45b1-de927d2ca524 |
954ac2a4292df05b1714d41dcb3d6e36140e5f8b | f348d86e9396896f616f31e9d5d15a1538105739 | /chapter2/c2_5.cpp | dadfe6f7f2d400ea441cd78ed712840b6d0b010d | [] | no_license | valleebleue/cpp_prime | 8434e809182e87db5943e5139608fb0a62642296 | ea87b56aa7036ea6ba13be8c186420f225a405a8 | refs/heads/master | 2023-01-02T05:30:21.409367 | 2020-10-15T18:52:52 | 2020-10-15T18:52:52 | 303,066,268 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 248 | cpp | #include <iostream>
int cal_Fahrenhit()
{
int i;
std::cout << "please enter a Celcius value:";
std::cin >> i;
std::cout << i << " degrees Celcius is " << i *1.8 + 32 << " degrees Fahrenhit" <<std::endl;
}
int main(){
cal_Fahrenhit();
} | [
"yujie_hu@hotmail.fr"
] | yujie_hu@hotmail.fr |
03d438e1217c7ece86e6cf90ab8f947e8dca59af | 8f0d8c50c7428263cbf6e78bf19c12c5f7730ea7 | /tutorial31/tutorial31.cpp | 42c753d21ffe8af3552fc906f577071dc817f9a2 | [] | no_license | tpphu/opengl | a69b3b2165e1302318b1458192a99e613c1f84ab | d05061c2ab0ada00dc7b3b32a17c6af9f6a6c995 | refs/heads/master | 2016-09-10T00:42:36.270607 | 2014-12-17T18:05:23 | 2014-12-17T18:05:23 | 27,969,727 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,464 | cpp | /*
Copyright 2011 Etay Meiri
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Tutorial 31 - PN Triangles Tessellation
*/
#include <math.h>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include "engine_common.h"
#include "ogldev_app.h"
#include "ogldev_util.h"
#include "ogldev_pipeline.h"
#include "ogldev_camera.h"
#include "lighting_technique.h"
#include "ogldev_glut_backend.h"
#include "mesh.h"
#define WINDOW_WIDTH 1680
#define WINDOW_HEIGHT 1050
class Tutorial31 : public ICallbacks, public OgldevApp
{
public:
Tutorial31()
{
m_pGameCamera = NULL;
m_directionalLight.Color = Vector3f(1.0f, 1.0f, 1.0f);
m_directionalLight.AmbientIntensity = 0.1f;
m_directionalLight.DiffuseIntensity = 0.9f;
m_directionalLight.Direction = Vector3f(0.0f, 0.0, 1.0);
m_persProjInfo.FOV = 60.0f;
m_persProjInfo.Height = WINDOW_HEIGHT;
m_persProjInfo.Width = WINDOW_WIDTH;
m_persProjInfo.zNear = 1.0f;
m_persProjInfo.zFar = 100.0f;
m_tessellationLevel = 5.0f;
m_isWireframe = false;
}
virtual ~Tutorial31()
{
SAFE_DELETE(m_pGameCamera);
SAFE_DELETE(m_pMesh);
}
bool Init()
{
Vector3f Pos(0.0f, 1.5f, -6.5f);
Vector3f Target(0.0f, -0.2f, 1.0f);
Vector3f Up(0.0, 1.0f, 0.0f);
m_pGameCamera = new Camera(WINDOW_WIDTH, WINDOW_HEIGHT, Pos, Target, Up);
if (!m_lightingEffect.Init()) {
printf("Error initializing the lighting technique\n");
return false;
}
GLint MaxPatchVertices = 0;
glGetIntegerv(GL_MAX_PATCH_VERTICES, &MaxPatchVertices);
printf("Max supported patch vertices %d\n", MaxPatchVertices);
glPatchParameteri(GL_PATCH_VERTICES, 3);
m_lightingEffect.Enable();
m_lightingEffect.SetColorTextureUnit(COLOR_TEXTURE_UNIT_INDEX);
m_lightingEffect.SetDirectionalLight(m_directionalLight);
m_pMesh = new Mesh();
return m_pMesh->LoadMesh("../Content/monkey.obj");
}
void Run()
{
GLUTBackendRun(this);
}
virtual void RenderSceneCB()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_pGameCamera->OnRender();
Pipeline p;
p.WorldPos(-3.0f, 0.0f, 0.0f);
p.Scale(2.0f, 2.0f, 2.0f);
p.Rotate(-90.0f, 15.0f, 0.0f);
p.SetCamera(m_pGameCamera->GetPos(), m_pGameCamera->GetTarget(), m_pGameCamera->GetUp());
p.SetPerspectiveProj(m_persProjInfo);
m_lightingEffect.SetEyeWorldPos(m_pGameCamera->GetPos());
m_lightingEffect.SetVP(p.GetVPTrans());
m_lightingEffect.SetWorldMatrix(p.GetWorldTrans());
m_lightingEffect.SetTessellationLevel(m_tessellationLevel);
m_pMesh->Render(NULL);
p.WorldPos(3.0f, 0.0f, 0.0f);
p.Rotate(-90.0f, -15.0f, 0.0f);
m_lightingEffect.SetVP(p.GetVPTrans());
m_lightingEffect.SetWorldMatrix(p.GetWorldTrans());
m_lightingEffect.SetTessellationLevel(1.0f);
m_pMesh->Render(NULL);
glutSwapBuffers();
}
virtual void KeyboardCB(OGLDEV_KEY OgldevKey)
{
switch (OgldevKey) {
case OGLDEV_KEY_ESCAPE:
case OGLDEV_KEY_q:
GLUTBackendLeaveMainLoop();
break;
case OGLDEV_KEY_PLUS:
m_tessellationLevel += 1.0f;
break;
case OGLDEV_KEY_MINUS:
if (m_tessellationLevel >= 2.0f) {
m_tessellationLevel -= 1.0f;
}
break;
case OGLDEV_KEY_z:
m_isWireframe = !m_isWireframe;
if (m_isWireframe) {
glPolygonMode(GL_FRONT, GL_LINE);
}
else {
glPolygonMode(GL_FRONT, GL_FILL);
}
break;
default:
m_pGameCamera->OnKeyboard(OgldevKey);
}
}
virtual void PassiveMouseCB(int x, int y)
{
m_pGameCamera->OnMouse(x, y);
}
private:
LightingTechnique m_lightingEffect;
Camera* m_pGameCamera;
DirectionalLight m_directionalLight;
Mesh* m_pMesh;
PersProjInfo m_persProjInfo;
float m_tessellationLevel;
bool m_isWireframe;
};
int main(int argc, char** argv)
{
Magick::InitializeMagick(*argv);
GLUTBackendInit(argc, argv, true, false);
if (!GLUTBackendCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, false, "Tutorial 31")) {
return 1;
}
Tutorial31* pApp = new Tutorial31();
if (!pApp->Init()) {
return 1;
}
pApp->Run();
delete pApp;
return 0;
} | [
"vietean@gmail.com"
] | vietean@gmail.com |
7177feb5320023e389ad6eef50572a2db1887a77 | dc81c76a02995eb140d10a62588e3791a8c7de0d | /PTv3/PTCommunication/StrategyItem.h | 24dff07d2e1b22a300a07d6de3363aec8044d94e | [] | no_license | xbotuk/cpp-proto-net | ab971a94899da7749b35d6586202bb4c52991461 | d685bee57c8bf0e4ec2db0bfa21d028fa90240fd | refs/heads/master | 2023-08-17T00:52:03.883886 | 2016-08-20T03:40:36 | 2016-08-20T03:40:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,974 | h | #pragma once
#include "Enums.h"
#include "TriggerItem.h"
#include "entity/message.pb.h"
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Runtime::InteropServices;
namespace PTEntity {
public ref class StrategyItem
{
public:
StrategyItem(void);
property int RetryTimes
{
int get()
{
return _retryTimes;
}
void set(int val)
{
_retryTimes = val;
}
}
property List<TriggerItem^>^ Triggers
{
List<TriggerItem^>^ get()
{
return _triggers;
}
}
property int OpenTimeout
{
int get()
{
return _openTimeout;
}
void set(int val)
{
_openTimeout = val;
}
}
property int MaxPosition
{
int get()
{
return _maxPosition;
}
void set(int val)
{
_maxPosition = val;
}
}
virtual void To(entity::StrategyItem* pNativeStrategyItem);
protected:
StrategyType _type;
int _retryTimes;
int _openTimeout;
int _maxPosition;
List<TriggerItem^> ^_triggers;
};
public ref class ArbitrageStrategyItem : StrategyItem
{
public:
ArbitrageStrategyItem()
{
_type = StrategyType::ARBITRAGE;
_bollPeriod = 26;
_stdDevMultiplier = 2;
}
virtual void To(entity::StrategyItem* pNativeStrategyItem) override;
property double BollPeriod
{
double get()
{
return _bollPeriod;
}
void set(double val)
{
_bollPeriod = val;
}
}
property double StdDevMultiplier
{
double get()
{
return _stdDevMultiplier;
}
void set(double val)
{
_stdDevMultiplier = val;
}
}
property String^ FirstLegSymbol
{
String^ get()
{
return _firstLegSymbol;
}
void set(String^ val)
{
_firstLegSymbol = val;
}
}
property String^ SecondLegSymbol
{
String^ get()
{
return _secondLegSymbol;
}
void set(String^ val)
{
_secondLegSymbol = val;
}
}
property int TimeFrame
{
int get()
{
return _timeFrame;
}
void set(int val)
{
_timeFrame = val;
}
}
property bool UseTargetGain
{
bool get()
{
return _useTargetGain;
}
void set(bool val)
{
_useTargetGain = val;
}
}
property bool AbsoluteGain
{
bool get()
{
return _absoluteGain;
}
void set(bool val)
{
_absoluteGain = val;
}
}
property int TargetGain
{
int get()
{
return _targetGain;
}
void set(int val)
{
_targetGain = val;
}
}
property bool SpecifyBandRange
{
bool get()
{
return _specifyBandRange;
}
void set(bool val)
{
_specifyBandRange = val;
}
}
property int BandRange
{
int get()
{
return _bandRange;
}
void set(int val)
{
_bandRange = val;
}
}
property ArbitrageStopLossType StoplossType
{
ArbitrageStopLossType get()
{
return _stoplossType;
}
void set(ArbitrageStopLossType val)
{
_stoplossType = val;
}
}
property CompareCondition StoplossCondition
{
CompareCondition get()
{
return _stoplossCondition;
}
void set(CompareCondition val)
{
_stoplossCondition = val;
}
}
property double StopLossThreshold
{
double get()
{
return _stopLossThreshold;
}
void set(double val)
{
_stopLossThreshold = val;
}
}
private:
String^ _firstLegSymbol;
String^ _secondLegSymbol;
int _timeFrame;
double _bollPeriod;
double _stdDevMultiplier;
bool _useTargetGain;
bool _absoluteGain;
int _targetGain;
bool _specifyBandRange;
int _bandRange;
ArbitrageStopLossType _stoplossType;
CompareCondition _stoplossCondition;
double _stopLossThreshold;
};
public ref class ArbitrageManualStrategyItem : StrategyItem
{
public:
ArbitrageManualStrategyItem()
{
_type = StrategyType::ARBITRAGE_MANUAL;
}
virtual void To(entity::StrategyItem* pNativeStrategyItem) override;
property CompareCondition OpenCondition
{
CompareCondition get()
{
return _openCondition;
}
void set(CompareCondition val)
{
_openCondition = val;
}
}
property double OpenThreshold
{
double get()
{
return _openThreshold;
}
void set(double val)
{
_openThreshold = val;
}
}
property CompareCondition CloseCondition
{
CompareCondition get()
{
return _closeCondition;
}
void set(CompareCondition val)
{
_closeCondition = val;
}
}
property double CloseThreshold
{
double get()
{
return _closeThreshold;
}
void set(double val)
{
_closeThreshold = val;
}
}
property PosiDirectionType Direction
{
PosiDirectionType get()
{
return _direction;
}
void set(PosiDirectionType val)
{
_direction = val;
}
}
property PosiOffsetFlag OffsetFlag
{
PosiOffsetFlag get()
{
return _offsetFlag;
}
void set(PosiOffsetFlag val)
{
_offsetFlag = val;
}
}
property bool CloseYesterday
{
bool get()
{
return _closeYesterday;
}
void set(bool val)
{
_closeYesterday = val;
}
}
private:
PosiDirectionType _direction;
PosiOffsetFlag _offsetFlag;
CompareCondition _openCondition;
double _openThreshold;
CompareCondition _closeCondition;
double _closeThreshold;
bool _closeYesterday;
};
public ref class ChangePositionStrategyItem : StrategyItem
{
public:
ChangePositionStrategyItem()
{
_type = StrategyType::CHANGE_POSITION;
}
virtual void To(entity::StrategyItem* pNativeStrategyItem) override;
private:
String ^_closeLeg;
PosiDirectionType _closeLegSide;
};
public ref class ManualStrategyItem : StrategyItem
{
public:
ManualStrategyItem()
{
_type = StrategyType::MANUAL;
}
virtual void To(entity::StrategyItem* pNativeStrategyItem) override;
property PosiDirectionType Direction
{
PosiDirectionType get()
{
return _direction;
}
void set(PosiDirectionType val)
{
_direction = val;
}
}
property CompareCondition StopGainCondition
{
CompareCondition get()
{
return _stopGainCondition;
}
void set(CompareCondition val)
{
_stopGainCondition = val;
}
}
property double StopGainThreshold
{
double get()
{
return _stopGainThreshold;
}
void set(double val)
{
_stopGainThreshold = val;
}
}
property CompareCondition StopLossCondition
{
CompareCondition get()
{
return _stopLossCondition;
}
void set(CompareCondition val)
{
_stopLossCondition = val;
}
}
property double StopLossThreshold
{
double get()
{
return _stopLossThreshold;
}
void set(double val)
{
_stopLossThreshold = val;
}
}
property StopPriceType StopLossType
{
StopPriceType get()
{
return _stopLossType;
}
void set(StopPriceType val)
{
_stopLossType = val;
}
}
private:
PosiDirectionType _direction;
CompareCondition _stopGainCondition;
double _stopGainThreshold;
CompareCondition _stopLossCondition;
double _stopLossThreshold;
StopPriceType _stopLossType;
};
public ref class ScalperStrategyItem : StrategyItem
{
public:
ScalperStrategyItem()
{
_type = StrategyType::SCALPER;
}
virtual void To(entity::StrategyItem* pNativeStrategyItem) override;
property double PriceTick
{
double get()
{
return _priceTick;
}
void set(double val)
{
_priceTick = val;
}
}
property DirectionDepends CaseLE2Tick
{
DirectionDepends get()
{
return _caseLE2Tick;
}
void set(DirectionDepends val)
{
_caseLE2Tick = val;
}
}
property DirectionDepends CaseLE3Tick
{
DirectionDepends get()
{
return _caseLE3Tick;
}
void set(DirectionDepends val)
{
_caseLE3Tick = val;
}
}
property DirectionDepends CaseGE4Tick
{
DirectionDepends get()
{
return _caseGE4Tick;
}
void set(DirectionDepends val)
{
_caseGE4Tick = val;
}
}
property DirectionDepends CaseNoChange
{
DirectionDepends get()
{
return _caseNoChange;
}
void set(DirectionDepends val)
{
_caseNoChange = val;
}
}
property StopLossCloseMethods StopLossStrategy
{
StopLossCloseMethods get()
{
return _stopLossStrategy;
}
void set(StopLossCloseMethods val)
{
_stopLossStrategy = val;
}
}
private:
double _priceTick;
DirectionDepends _caseLE2Tick;
DirectionDepends _caseLE3Tick;
DirectionDepends _caseGE4Tick;
DirectionDepends _caseNoChange;
StopLossCloseMethods _stopLossStrategy;
};
public ref class IcebergStrategyItem : StrategyItem
{
public:
IcebergStrategyItem()
{
_type = StrategyType::ICEBERG;
}
virtual void To(entity::StrategyItem* pNativeStrategyItem) override;
property double PriceTick
{
double get()
{
return _priceTick;
}
void set(double val)
{
_priceTick = val;
}
}
property double PxDiffThreshold
{
double get()
{
return _pxDiffThreshold;
}
void set(double val)
{
_pxDiffThreshold = val;
}
}
property int SizeDiffThreshold
{
int get()
{
return _sizeDiffThreshold;
}
void set(int val)
{
_sizeDiffThreshold = val;
}
}
property double TargetGainPercent
{
double get()
{
return _targetGainPercent;
}
void set(double val)
{
_targetGainPercent = val;
}
}
property String^ UserId
{
String^ get()
{
return _userId;
}
void set(String^ val)
{
_userId = val;
}
}
private:
double _priceTick;
double _pxDiffThreshold;
int _sizeDiffThreshold;
double _targetGainPercent;
String ^_userId;
};
public ref class DualScalperStrategyItem : StrategyItem
{
public:
DualScalperStrategyItem()
{
_type = StrategyType::DUAL_SCALPER;
}
virtual void To(entity::StrategyItem* pNativeStrategyItem) override;
property double Threshold
{
double get()
{
return _threshold;
}
void set(double val)
{
_threshold = val;
}
}
property double PriceTick
{
double get()
{
return _priceTick;
}
void set(double val)
{
_priceTick = val;
}
}
property String^ LongSideUserId
{
String^ get()
{
return _longSideUserId;
}
void set(String^ val)
{
_longSideUserId = val;
}
}
property String^ ShortSideUserId
{
String^ get()
{
return _shortSideUserId;
}
void set(String^ val)
{
_shortSideUserId = val;
}
}
property StopLossCloseMethods StopLossStrategy
{
StopLossCloseMethods get()
{
return _stopLossStrategy;
}
void set(StopLossCloseMethods val)
{
_stopLossStrategy = val;
}
}
property double OpenOffset
{
double get()
{
return _openOffset;
}
void set(double val)
{
_openOffset = val;
}
}
property double PercentOffset
{
double get()
{
return _percent;
}
void set(double val)
{
_percent = val;
}
}
property double CloseOffset
{
double get()
{
return _closeOffset;
}
void set(double val)
{
_closeOffset = val;
}
}
property double OppositeCloseThreshold
{
double get()
{
return _oppositeCloseThreshold;
}
void set(double val)
{
_oppositeCloseThreshold = val;
}
}
private:
double _threshold;
double _priceTick;
double _openOffset;
double _percent;
double _closeOffset;
double _oppositeCloseThreshold;
String ^_longSideUserId;
String ^_shortSideUserId;
StopLossCloseMethods _stopLossStrategy;
};
public ref class DualQueueStrategyItem : StrategyItem
{
public:
DualQueueStrategyItem()
{
_type = StrategyType::DUAL_QUEUE;
}
virtual void To(entity::StrategyItem* pNativeStrategyItem) override;
property double PriceTick
{
double get()
{
return _priceTick;
}
void set(double val)
{
_priceTick = val;
}
}
property PosiDirectionType Direction
{
PosiDirectionType get()
{
return _direction;
}
void set(PosiDirectionType val)
{
_direction = val;
}
}
property int StableTickThreshold
{
int get()
{
return _stableTickThreshold;
}
void set(int val)
{
_stableTickThreshold = val;
}
}
property int MinWorkingSize
{
int get()
{
return _minWorkingSize;
}
void set(int val)
{
_minWorkingSize = val;
}
}
private:
double _priceTick;
PosiDirectionType _direction;
int _stableTickThreshold;
int _minWorkingSize;
};
public ref class MACDSlopeStrategyItem : StrategyItem
{
public:
MACDSlopeStrategyItem()
{
_type = StrategyType::HIST_SLOPE;
}
virtual void To(entity::StrategyItem* pNativeStrategyItem) override;
property String^ Symbol
{
String^ get()
{
return _symbol;
}
void set(String^ val)
{
_symbol = val;
}
}
property int Short
{
int get()
{
return _short;
}
void set(int val)
{
_short = val;
}
}
property int Long
{
int get()
{
return _long;
}
void set(int val)
{
_long = val;
}
}
property int M
{
int get()
{
return _m;
}
void set(int val)
{
_m = val;
}
}
property int FastPeriod
{
int get()
{
return _fastPeriod;
}
void set(int val)
{
_fastPeriod = val;
}
}
property double FastStdDiff
{
double get()
{
return _fastStdDiff;
}
void set(double val)
{
_fastStdDiff = val;
}
}
property int FastAngleThreshold
{
int get()
{
return _fastAngleThreshold;
}
void set(int val)
{
_fastAngleThreshold = val;
}
}
property int SlowPeriod
{
int get()
{
return _slowPeriod;
}
void set(int val)
{
_slowPeriod = val;
}
}
property double SlowStdDiff
{
double get()
{
return _slowStdDiff;
}
void set(double val)
{
_slowStdDiff = val;
}
}
property int SlowAngleThreshold
{
int get()
{
return _slowAngleThreshold;
}
void set(int val)
{
_slowAngleThreshold = val;
}
}
property double TrailingStopValue
{
double get()
{
return _trailingStopValue;
}
void set(double val)
{
_trailingStopValue = val;
}
}
property double FastShortSeed
{
double get()
{
return _fastShortSeed;
}
void set(double val)
{
_fastShortSeed = val;
}
}
property double FastLongSeed
{
double get()
{
return _fastLongSeed;
}
void set(double val)
{
_fastLongSeed = val;
}
}
property double FastSignalSeed
{
double get()
{
return _fastSignalSeed;
}
void set(double val)
{
_fastSignalSeed = val;
}
}
property double SlowShortSeed
{
double get()
{
return _slowShortSeed;
}
void set(double val)
{
_slowShortSeed = val;
}
}
property double SlowLongSeed
{
double get()
{
return _slowLongSeed;
}
void set(double val)
{
_slowLongSeed = val;
}
}
property double SlowSignalSeed
{
double get()
{
return _slowSignalSeed;
}
void set(double val)
{
_slowSignalSeed = val;
}
}
private:
int _short;
int _long;
int _m;
int _fastPeriod;
double _fastStdDiff;
int _fastAngleThreshold;
int _slowPeriod;
double _slowStdDiff;
int _slowAngleThreshold;
double _trailingStopValue;
double _fastShortSeed;
double _fastLongSeed;
double _fastSignalSeed;
double _slowShortSeed;
double _slowLongSeed;
double _slowSignalSeed;
String^ _symbol;
};
public ref class WMATrendStrategyItem : StrategyItem
{
public:
WMATrendStrategyItem()
{
_type = StrategyType::WMA_TREND;
}
virtual void To(entity::StrategyItem* pNativeStrategyItem) override;
property String^ Symbol
{
String^ get()
{
return _symbol;
}
void set(String^ val)
{
_symbol = val;
}
}
property int WMA_Param
{
int get()
{
return _wmaP;
}
void set(int val)
{
_wmaP = val;
}
}
property int MA_N
{
int get()
{
return _maN;
}
void set(int val)
{
_maN = val;
}
}
property int Period
{
int get()
{
return _period;
}
void set(int val)
{
_period = val;
}
}
property double TrailingStopValue
{
double get()
{
return _trailingStopValue;
}
void set(double val)
{
_trailingStopValue = val;
}
}
private:
int _wmaP;
int _maN;
int _period;
double _trailingStopValue;
String^ _symbol;
};
public ref class LinerRegressionStrategyItem : StrategyItem
{
public:
LinerRegressionStrategyItem()
{
_type = StrategyType::LINER_REGRESSION;
}
virtual void To(entity::StrategyItem* pNativeStrategyItem) override;
property String^ Symbol
{
String^ get()
{
return _symbol;
}
void set(String^ val)
{
_symbol = val;
}
}
property int Period
{
int get()
{
return _period;
}
void set(int val)
{
_period = val;
}
}
property int Number
{
int get()
{
return _number;
}
void set(int val)
{
_number = val;
}
}
property double OpenThreshold
{
double get()
{
return _openThreshold;
}
void set(double val)
{
_openThreshold = val;
}
}
property double CloseThreshold
{
double get()
{
return _closeThreshold;
}
void set(double val)
{
_closeThreshold = val;
}
}
private:
int _period;
int _number;
double _openThreshold;
double _closeThreshold;
String^ _symbol;
};
public ref class ASCTrendStrategyItem : StrategyItem
{
public:
ASCTrendStrategyItem()
{
_type = StrategyType::ASC_TREND;
}
virtual void To(entity::StrategyItem* pNativeStrategyItem) override;
property String^ Symbol
{
String^ get()
{
return _symbol;
}
void set(String^ val)
{
_symbol = val;
}
}
property int Period
{
int get()
{
return _period;
}
void set(int val)
{
_period = val;
}
}
property int Risk
{
int get()
{
return _risk;
}
void set(int val)
{
_risk = val;
}
}
property int AveragePeriod
{
int get()
{
return _avgPeriod;
}
void set(int val)
{
_avgPeriod = val;
}
}
property int BreakoutLength
{
int get()
{
return _breakoutLength;
}
void set(int val)
{
_breakoutLength = val;
}
}
private:
int _risk;
int _avgPeriod;
int _period;
int _breakoutLength;
String^ _symbol;
};
public ref class RangeTrendStrategyItem : StrategyItem
{
public:
RangeTrendStrategyItem()
{
_type = StrategyType::RANGE_TREND;
}
virtual void To(entity::StrategyItem* pNativeStrategyItem) override;
property String^ Symbol
{
String^ get()
{
return _symbol;
}
void set(String^ val)
{
_symbol = val;
}
}
property int Period
{
int get()
{
return _period;
}
void set(int val)
{
_period = val;
}
}
property int OpenPeriod
{
int get()
{
return _openPeriod;
}
void set(int val)
{
_openPeriod = val;
}
}
property int ClosePeriod
{
int get()
{
return _closePeriod;
}
void set(int val)
{
_closePeriod = val;
}
}
property double StopLossFactor
{
double get()
{
return _stopLossFactor;
}
void set(double val)
{
_stopLossFactor = val;
}
}
property double TrendFactor
{
double get()
{
return _trendFactor;
}
void set(double val)
{
_trendFactor = val;
}
}
private:
int _openPeriod;
int _closePeriod;
double _stopLossFactor;
double _trendFactor;
int _period;
String^ _symbol;
};
} | [
"zxiaoyong@163.com"
] | zxiaoyong@163.com |
9beb87206164ae398e13736dc48e3266238bb192 | a3e638ce948335801a6c4498530c4b9dda34f415 | /prototypes/single-feather/single-feather.ino | d944d331995f8d5dabc4a3010fc7e22bffb61d1f | [] | no_license | chris-schmitz/pumpkin-cauldron | 31282e2280d394ae55609dc7a2ab8b867d952be3 | a1cdcb6e406f2d4c3fedb9c1b609156328d2f18a | refs/heads/master | 2020-08-01T03:49:18.920672 | 2019-11-10T03:22:08 | 2019-11-10T03:22:08 | 210,852,249 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,371 | ino | #include <SPI.h>
#include <MFRC522.h>
#include <Adafruit_NeoPixel.h>
#include <Adafruit_VS1053.h>
#include <SD.h>
#define DEBUG false
#define USING_MUSIC_MAKER true
// ^ Music Maker settings
#define VS1053_RESET -1 // VS1053 reset pin (not used!)
#define VS1053_DCS 10 // VS1053 Data/command select pin (output)
#define VS1053_DREQ 9 // VS1053 Data request, ideally an Interrupt pin
#define VS1053_CS 6 // VS1053 chip select pin (output)
#define CARDCS 5 // Card chip select pin
#define VOLUME 0
Adafruit_VS1053_FilePlayer musicPlayer =
Adafruit_VS1053_FilePlayer(VS1053_RESET, VS1053_CS, VS1053_DCS, VS1053_DREQ, CARDCS);
// ^ RFID settings
#define RST_PIN 18
#define SS_PIN 19
MFRC522 mfrc522(SS_PIN, RST_PIN);
// ^ LED strip settings
#define LED_PIN 12
#define TOTAL_LEDS 30
Adafruit_NeoPixel strip = Adafruit_NeoPixel(TOTAL_LEDS, LED_PIN, NEO_GRB + NEO_KHZ800);
// | NOTE: this include needs to happen after strip is defined so that we have access to
// | the `strip` object.
#include "src/colors.h"
// ^ Fan settings
#define FAN 17
enum FAN_STATUSES
{
FAN_OFF = 0,
FAN_ON = 1
};
// | Tags
String SQUIRTLE = " 04 59 d0 4a e6 4c 81";
String PIKACHU = " 04 60 d1 4a e6 4c 81";
String CUPCAKE = " 04 c8 cd 4a e6 4c 80";
String content;
boolean ledsOn = true;
boolean effectsActive = false;
void setup()
{
Serial.begin(115200);
if (DEBUG)
{
while (!Serial)
;
}
if (USING_MUSIC_MAKER)
{
setupMusicMaker();
}
// ^ LED Strip setup
strip.begin();
strip.show();
// ^ RFID setup
SPI.begin();
mfrc522.PCD_Init();
mfrc522.PCD_DumpVersionToSerial();
if (DEBUG)
{
Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}
// ^ Fan setup
pinMode(FAN, OUTPUT);
setFanStatus(FAN_ON);
delay(2000);
setFanStatus(FAN_OFF);
}
enum LIGHT_PATTERNS
{
LIGHT_PATTERN_BUBBLE = 0,
LIGHT_PATTERN_MONSTER_ROAR,
LIGHT_PATTERN_WITCH_CACKLE,
LIGHT_PATTERN_EVIL_LAUGH
};
uint8_t activePattern = LIGHT_PATTERN_BUBBLE;
void loop()
{
// ^ Advance the state machines
runActiveLightPattern();
// ^ Look for new RFID tags
if (!mfrc522.PICC_IsNewCardPresent())
{
return;
}
// ^ Select one of the tags
if (!mfrc522.PICC_ReadCardSerial())
{
return;
}
captureUID();
// return;
// ^ If we're running effects we don't need to set anything
// ! Note that nothing that needs to be run each loop pass (e.g. state machine driven
// ! code) should be put after this conditional
if (effectsActive)
{
return;
}
// ^ Prep a new run of the effects
effectsActive = true;
if (USING_MUSIC_MAKER)
{
musicPlayer.stopPlaying();
}
// TODO: Break each conditional out into it's own named function
// ^ Run the specific set of effects based on the RFID tag we captured
if (content == PIKACHU)
{
setFanStatus(FAN_ON);
if (USING_MUSIC_MAKER)
{
musicPlayer.startPlayingFile("SOUNDS/EFFECTS/TREX.MP3");
}
setActiveLightPattern(LIGHT_PATTERN_MONSTER_ROAR);
}
else if (content == SQUIRTLE)
{
setFanStatus(FAN_ON);
if (USING_MUSIC_MAKER)
{
musicPlayer.startPlayingFile("SOUNDS/EFFECTS/WITCH2.MP3");
}
setActiveLightPattern(LIGHT_PATTERN_WITCH_CACKLE);
}
else if (content == CUPCAKE)
{
Serial.println("Got the cupcake!");
setFanStatus(FAN_ON);
if (USING_MUSIC_MAKER)
{
musicPlayer.startPlayingFile("SOUNDS/EFFECTS/LAUGH3.MP3");
// musicPlayer.startPlayingFile("SOUNDS/PARADO/PC-TY.MP3");
}
setActiveLightPattern(LIGHT_PATTERN_WITCH_CACKLE);
}
// | Verified Good
// musicPlayer.startPlayingFile("SOUNDS/EFFECTS/WITCH1.MP3");
// musicPlayer.startPlayingFile("SOUNDS/EFFECTS/BUBBLE.MP3");
}
void setupMusicMaker()
{
// ^ Music maker setup
if (!musicPlayer.begin())
{
Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
while (1)
;
}
Serial.println(F("VS1053 found"));
if (!SD.begin(CARDCS))
{
Serial.println(F("SD failed, or not present"));
while (1)
;
}
printDirectory(SD.open("/SOUNDS/"), 0);
// ^ Add settings for the music maker and test
if (USING_MUSIC_MAKER)
{
musicPlayer.setVolume(VOLUME, VOLUME);
musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT); // DREQ int
// musicPlayer.playFullFile("SOUNDS/PARADO/HI-THERE.MP3");
}
}
// TODO: RENAME
// ! hmmm if we're going to deactivate the fan in here based on the music player status
// ! we should really rename this function
void runActiveLightPattern()
{
if (USING_MUSIC_MAKER)
{
if (musicPlayer.stopped())
{
setActiveLightPattern(LIGHT_PATTERN_BUBBLE);
setFanStatus(FAN_OFF);
effectsActive = false;
}
}
// | Note! we're intentionally using if else if statements here instead of a switch for speed purposes.
// | If we use switch, each case has to be evaluated even if the first one is the only one we're looking for,
// | but if we use an if/else if then we'll stop once we find our desired conditional.
if (activePattern == LIGHT_PATTERN_BUBBLE)
{
lightsBubble();
}
else if (activePattern == LIGHT_PATTERN_MONSTER_ROAR)
{
lightsMonsterRoar();
}
else if (activePattern == LIGHT_PATTERN_WITCH_CACKLE)
{
lightsWitchesCackle();
}
else if (activePattern == LIGHT_PATTERN_EVIL_LAUGH)
{
lightsEvilLaugh();
}
}
unsigned long previousMillis = 0;
unsigned long lightChangeInterval = 100;
const uint32_t lightsBubbleArray[5] = {PURPLE_DARK, PURPLE_LIGHT, PURPLE_MEDIUM, BLUE_DARK, GREEN_DARK};
/**
* |Slow purple and blue pulse pattern
**/
void lightsBubble()
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis > lightChangeInterval)
{
for (uint8_t i = 0; i < TOTAL_LEDS; i++)
{
uint32_t randomIndex = rand() % 5;
strip.setPixelColor(i, lightsBubbleArray[randomIndex]);
}
strip.show();
previousMillis = currentMillis;
}
}
uint8_t flashOffset = 0;
/**
* | Flashing yellow and red
**/
void lightsWitchesCackle()
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis > lightChangeInterval)
{
for (uint8_t i = 0; i < TOTAL_LEDS; i++)
{
if (flashOffset + i % 2 == 0)
{
strip.setPixelColor(i, RED_LIGHT);
}
else
{
strip.setPixelColor(i, YELLOW_LIGHT);
}
}
strip.show();
// TODO come back and do boolean casting here or up in the if to simplify this
if (flashOffset == 1)
{
flashOffset = 0;
}
else
{
flashOffset = 1;
}
previousMillis = currentMillis;
}
}
bool lightFlashToggle = true;
unsigned long previousMillisMONSTER = 0;
unsigned int lightChangeIntervalMONSTER = 10;
/**
* | Flashing red off and on
*
* * Note that we do not need to track duration here. This routine will stop running
* * once the music player is done playing the audio file.
**/
void lightsMonsterRoar()
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillisMONSTER > lightChangeIntervalMONSTER)
{
for (uint8_t i = 0; i < TOTAL_LEDS; i++)
{
if (lightFlashToggle)
{
strip.setPixelColor(i, RED_LIGHT);
}
else
{
strip.setPixelColor(i, YELLOW_DARK);
}
strip.show();
lightFlashToggle = !lightFlashToggle;
}
lightFlashToggle = !lightFlashToggle;
previousMillisMONSTER = currentMillis;
}
}
unsigned long prevMillisLAUGH = 0;
unsigned int intervalLAUGH = 10;
uint8_t colorIndex = 0;
const uint32_t laugh_array[9] = {GREEN_DARK, BLUE_DARK, RED_DARK, GREEN_MEDIUM, BLUE_MEDIUM, RED_MEDIUM, GREEN_LIGHT, BLUE_LIGHT, RED_LIGHT};
void lightsEvilLaugh()
{
unsigned long currentMillis = millis();
if (currentMillis - prevMillisLAUGH > intervalLAUGH)
{
for (uint8_t i = 0; i < TOTAL_LEDS; i++)
{
strip.setPixelColor(i, laugh_array[colorIndex]);
strip.show();
}
prevMillisLAUGH = currentMillis;
}
colorIndex++;
if (colorIndex > 8)
{
colorIndex = 0;
}
}
void lightsDogBark() {}
// ! switch this logic to state machine to remove the blocking nature
void fillStrip(uint32_t color)
{
for (uint8_t i = 0; i < TOTAL_LEDS; i++)
{
strip.setPixelColor(i, color);
strip.show();
delay(10);
}
}
void captureUID()
{
content = "";
for (byte i = 0; i < mfrc522.uid.size; i++)
{
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
if (DEBUG)
{
Serial.println(content);
}
}
void printDirectory(File dir, int numTabs)
{
while (true)
{
File entry = dir.openNextFile();
if (!entry)
{
// no more files
//Serial.println("**nomorefiles**");
break;
}
for (uint8_t i = 0; i < numTabs; i++)
{
Serial.print('\t');
}
Serial.print(entry.name());
if (entry.isDirectory())
{
Serial.println("/");
printDirectory(entry, numTabs + 1);
}
else
{
// files have sizes, directories do not
Serial.print("\t\t");
Serial.println(entry.size(), DEC);
}
entry.close();
}
}
void setActiveLightPattern(int pattern)
{
activePattern = pattern;
}
void setFanStatus(uint8_t fanStatus)
{
if (DEBUG && fanStatus == 1)
{
Serial.print("Fan status: ");
Serial.println(fanStatus);
}
digitalWrite(FAN, fanStatus);
}
| [
"schmitz.chris@gmail.com"
] | schmitz.chris@gmail.com |
338a64bbd0c16ce11e460329b12e0812f2133f4f | 19942c90af650e6f781c2048c069c274f4b2511c | /sa-acop/v2/simulation.h | 0b05c0b096467e9d030c2e8c278e04880d4f872b | [] | no_license | tarstars/coeff_tune | 48a9c0bca859e1bb1c3568675e98e519262eb66a | f9f2f6861be476e4d0eac45ce2ded9c8767b1db5 | refs/heads/master | 2021-01-17T06:35:25.030647 | 2018-03-29T21:48:25 | 2018-03-29T21:48:25 | 4,085,781 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,098 | h | #ifndef __SA_ACOP__SIMULATION__
#define __SA_ACOP__SIMULATION__
#include <iostream>
#include <gsl/gsl_rng.h>
using ::std::ostream;
struct Constants{
double a, b, c, d;
friend ostream& operator<<(ostream& os, const Constants& constants);
};
struct AnnealingParams{
int iterationsNumber;
double initialTemperature;
bool doCooling;
};
class Simulation{
private:
AnnealingParams params;
Constants true_constants;
gsl_rng *generator;
double cubicPolynomial(double x, Constants coeff);
double calculateResidual(Constants constants);
inline double randomUniform(double min, double max);
inline double randomGaussian(double dispersion);
Constants randomizeConstants(Constants, double dispersion);
public:
~Simulation();
void initializeRandomGenerator();
void freeRandomGenerator();
void setTrueConstants(Constants true_constants);
Constants tuneConstants(Constants constants, AnnealingParams params);
};
#endif // __SA_ACOP__SIMULATION__
| [
"eralde.g@gmail.com"
] | eralde.g@gmail.com |
819a6eeeca3675725387c49c4e40657c1e95afa6 | a13032cfb71844f8f44b12a74297293ddb85ed48 | /main.cpp | be286e14bf729ca3f5363a95d8fa1a8540387151 | [] | no_license | geeksKK8/maze | f0e8417eadadb84ac8da3e5b5778b335e171b943 | 434608c6251165c7acb1660f91136d60ca439894 | refs/heads/main | 2023-03-26T00:04:41.577644 | 2021-03-28T08:55:00 | 2021-03-28T08:55:00 | 352,281,737 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,238 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <cstdlib>
#include "gl/glut.h"
#include <cstdio>
#include <cstring>
#include <ctime>
#include <Windows.h>
#include <iostream>
#include <algorithm>
#include <mmsystem.h>
#pragma comment(lib,"winmm.lib")
using namespace std;
#define MAXN 40//地图数组的大小
#define MAX_TEXTURE 10//最多纹理数目
//#define MAP_SIZE (39)//迷宫大小
#define WinHeight 1080 //Display Height
#define WinWidth 1960 //Display Width
int MAP_SIZE = 5;
int ObjPrintLine = 0;
int status = 1;
float doorRotate1 = 0,doorRotate2 = 0;
GLint cubeList = 0;
int Map[MAXN][MAXN];
GLfloat light_color[] = { 0.5, 0.5, 0.5, 1 };
GLfloat light_pos[] = { MAP_SIZE / 2, 30, MAP_SIZE / 2, 1 };
GLfloat finalMaterialColor[] = { 0.5, 0.5, 0.5, 1 };
const float allone[] = { 0.2f, 0.2f, 0.2f, 1.0f };
const float allzero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
#define INF 1e8f
int start[2];
int finish[2];
//Global Variable start and finish position
//Start : 1,0
//Finish : 1,n-1
//Attention : n must be an odd number
int InGame = 0;
int InMenu = 0;
int gameover = 0;
int MenuGameFit;
int fa[MAXN*MAXN];
int getfa(int x)
{
if (x == fa[x]) return x;
else return fa[x] = getfa(fa[x]);
}
void MakeMap(int a[][MAXN], int n)
{
start[0] = 0;
start[1] = 1;
finish[0] = n - 1;
finish[1] = n - 2;
srand(time(0));
int id[MAXN][MAXN], idx = 0;
int edge[MAXN*MAXN][3], cnt = 0;
if (!(n & 1)) n |= 1;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
a[i][j] = 0;
memset(id, 0, sizeof id);
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
if (!(i & 1) || !(j & 1)) a[i][j] = 1;
else id[i][j] = ++idx;
for (int i = 1; i <= idx; ++i) fa[i] = i;
a[start[0]][start[1]] = 0;
a[finish[0]][finish[1]] = 0;
for (int i = 1; i < n - 1; ++i)
for (int j = 1; j < n - 1; ++j)
if (a[i][j] == 1 && ((i & 1) || (j & 1))) {
edge[cnt][0] = i;
edge[cnt][1] = j;
edge[cnt][2] = rand();
cnt++;
}
for (int i = 0; i < cnt; ++i)
for (int j = i + 1; j < cnt; ++j)
if (edge[j][2] < edge[i][2]) {
swap(edge[j][2], edge[i][2]);
swap(edge[j][1], edge[i][1]);
swap(edge[j][0], edge[i][0]);
}
for (int i = 0; i < cnt; ++i) {
int u, v;
if (edge[i][0] & 1) {
u = id[edge[i][0]][edge[i][1] - 1];
v = id[edge[i][0]][edge[i][1] + 1];
}
else {
u = id[edge[i][0] - 1][edge[i][1]];
v = id[edge[i][0] + 1][edge[i][1]];
}
if (getfa(u) != getfa(v)) {
fa[getfa(u)] = getfa(v);
a[edge[i][0]][edge[i][1]] = 0;
}
}
}
#define EyeHeight 0.1
#define ViewDistance 40.0f
#define pi (acos(-1.0))
#define TriFloatPair pair<pair<float,float>,float>
#define TriIntPair pair<pair<int,int>,int>
#define QuadIntPair pair<pair<int,int>,pair<int,int>>
#define X first.first
#define Y first.second
#define Z second
#define P second.first
#define Q second.second
float eye[] = { 0.9, 0.1,0.5 };//人眼位置
const float gamestart[] = { 0.9, 0.1, 0.5 };
const float gamestartang = 3 * pi / 2;
float center[] = { MAP_SIZE / 2.0, 0, -MAP_SIZE / 2.0 };
const float viewstartang = 3 * pi / 2;
float viewstart[] = { center[0] - (float)cos(viewstartang) * ViewDistance, 5.0f, center[2] - (float)sin(viewstartang) * ViewDistance };
float fitstep[3];
float fitang;
float faceang = 3 * pi / 2;
float fStep = 0.03f;//移动步长
float angStep = 0.02f;//视角步长
float moveangStep = 0.1f;
float nurbsphase = 0.0f;
float boundry[3] = { -fStep * 3, 0, fStep * 3 };
float fTranslate = 0.2f; //终点物体平移步长
float fScale = 1.0f;//终点物体缩放步长
float fRotate = 90;//终点物体旋转步长
int mainMenu;
int subMenu1, subMenu2, subMenu3, subMenu4, subMenu5;
float deltaA[] = { 52.0f + 8.0f - 10.5f + MAP_SIZE / 2, 4.0f , -MAP_SIZE / 2 }; int IDA = 2;
float deltaM[] = { 2.8f + 4.0f - 10.5f + MAP_SIZE / 2, 4.0f ,-MAP_SIZE / 2 }; int IDM = 14;
float deltaE[] = { 2.5f + 52.0f - 10.5f + MAP_SIZE / 2,4.0f ,-MAP_SIZE / 2 }; int IDE = 6;
float deltaZ[] = { -38.0f - 10.5f + MAP_SIZE / 2,4.0f ,-MAP_SIZE / 2 }; int IDZ = 27;
float deltaVoid[] = { 0.0f, 0.0f, 0.0f };
unsigned int texture[MAX_TEXTURE];
GLfloat ctlpoints[4][4][3];
int showPoints = 0;
GLUnurbsObj *theNurb;
void getobj(const char * filename, struct ObjFile * obj);
void getline(FILE * fin, char *s);
struct ObjFile {//OBJ文件读入区域
char name[101][101];
int st[101], ed[101]; //The Start of the surface ID
int vc;
int sc;
int mc;
TriFloatPair vertex[200001];
QuadIntPair surface[200001];
}letter;
//读入24位bmp图,仅限图片宽度为4的倍数时可用
unsigned char *LoadBitmapFile(char *filename, BITMAPINFOHEADER *bitmapInfoHeader)
{
FILE *filePtr;
BITMAPFILEHEADER bitmapFileHeader;
unsigned char *bitmapImage;
unsigned int imageIdx = 0;
unsigned char tempRGB;
filePtr = fopen(filename, "rb");
if (filePtr == NULL) {
printf("Error : Cant Open File %s\n", filename);
return NULL;
}
fread(&bitmapFileHeader, sizeof(BITMAPFILEHEADER), 1, filePtr);
if (bitmapFileHeader.bfType != 0x4D42) {
printf("Error in LoadBitmapFile: the file is not a bitmap file\n");
return NULL;
}
fread(bitmapInfoHeader, sizeof(BITMAPINFOHEADER), 1, filePtr);
fseek(filePtr, bitmapFileHeader.bfOffBits, SEEK_SET);
bitmapImage = new unsigned char[bitmapInfoHeader->biSizeImage];
if (!bitmapImage) {
printf("Error in LoadBitmapFile: memory error\n");
return NULL;
}
fread(bitmapImage, 1, bitmapInfoHeader->biSizeImage, filePtr);
if (bitmapImage == NULL) {
printf("Error in LoadBitmapFile: memory error\n");
return NULL;
}
for (imageIdx = 0; imageIdx < bitmapInfoHeader->biSizeImage; imageIdx += 3) {
tempRGB = bitmapImage[imageIdx];
bitmapImage[imageIdx] = bitmapImage[imageIdx + 2];
bitmapImage[imageIdx + 2] = tempRGB;
}
fclose(filePtr);
return bitmapImage;
}
//加载纹理
void texload(int i, char *filename)
{
BITMAPINFOHEADER bitmapInfoHeader;
unsigned char* bitmapData;
bitmapData = LoadBitmapFile(filename, &bitmapInfoHeader);
glBindTexture(GL_TEXTURE_2D, texture[i]);
// 指定当前纹理的放大/缩小过滤方式
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D,
0, //mipmap层次(通常为0,表示最上层)
GL_RGB, //我们希望该纹理有红、绿、蓝数据
bitmapInfoHeader.biWidth, //纹理宽带,必须是n,若有边框+2
bitmapInfoHeader.biHeight, //纹理高度,必须是n,若有边框+2
0, //边框(0=无边框, 1=有边框)
GL_RGB, //bitmap数据的格式
GL_UNSIGNED_BYTE, //每个颜色数据的类型
bitmapData); //bitmap数据指针
printf("Load Over %s\n", filename);
}
//输出24位bmp文件,截图时使用
void WriteBitmapFile(char * filename, int width, int height, unsigned char * bitmapData)
{
BITMAPFILEHEADER bitmapFileHeader;
memset(&bitmapFileHeader, 0, sizeof(BITMAPFILEHEADER));
bitmapFileHeader.bfSize = sizeof(BITMAPFILEHEADER);
bitmapFileHeader.bfType = 0x4d42; //BM
bitmapFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
BITMAPINFOHEADER bitmapInfoHeader;
memset(&bitmapInfoHeader, 0, sizeof(BITMAPINFOHEADER));
bitmapInfoHeader.biSize = sizeof(BITMAPINFOHEADER);
bitmapInfoHeader.biWidth = width;
bitmapInfoHeader.biHeight = height;
bitmapInfoHeader.biPlanes = 1;
bitmapInfoHeader.biBitCount = 24;
bitmapInfoHeader.biCompression = BI_RGB;
bitmapInfoHeader.biSizeImage = width * abs(height) * 3;
FILE * filePtr;
unsigned char tempRGB;
unsigned int imageIdx;
for (imageIdx = 0; imageIdx < bitmapInfoHeader.biSizeImage; imageIdx += 3)
{
tempRGB = bitmapData[imageIdx];
bitmapData[imageIdx] = bitmapData[imageIdx + 2];
bitmapData[imageIdx + 2] = tempRGB;
}
filePtr = fopen(filename, "wb");
if (filePtr == NULL) {
printf("Cant open file %s\n", filename);
return;
}
fwrite(&bitmapFileHeader, sizeof(BITMAPFILEHEADER), 1, filePtr);
fwrite(&bitmapInfoHeader, sizeof(BITMAPINFOHEADER), 1, filePtr);
fwrite(bitmapData, bitmapInfoHeader.biSizeImage, 1, filePtr);
fclose(filePtr);
return;
}
//截图并且保存
void PrtScrn()
{
static void * screenData;
int len = WinHeight * WinWidth * 3;
screenData = malloc(len);
memset(screenData, 0, len);
glReadPixels(0, 0, WinWidth, WinHeight, GL_RGB, GL_UNSIGNED_BYTE, screenData);
time_t tm = 0;
tm = time(NULL);
char lpstrFilename[256] = { 0 };
sprintf_s(lpstrFilename, sizeof(lpstrFilename), "%d.bmp", (int)tm);
WriteBitmapFile(lpstrFilename, WinWidth, WinHeight, (unsigned char*)screenData);
free(screenData);
}
//重置地图
void ResetMap()
{
MakeMap(Map, MAP_SIZE);
}
//菜单初始化,未用到
void Initial_Menu()
{
}
void OutObjFile(char * s, ObjFile * letter)
{
FILE * fin;
fin = fopen(s, "w");
for (int i = 1; i <= letter->vc; ++i) fprintf(fin, "v %.6f %.6f %.6f\n", letter->vertex[i].X, letter->vertex[i].Y, letter->vertex[i].Z);
for (int i = 1; i <= letter->sc; ++i) fprintf(fin, "f %d %d %d %d\n", letter->surface[i].X, letter->surface[i].Y, letter->surface[i].P, letter->surface[i].Q);
fclose(fin);
fin = NULL;
}
//全程序初始化
void Initial()
{
MakeMap(Map, MAP_SIZE);
Initial_Menu();
InGame = 0;
gameover = 0;
InMenu = 1;
getobj("Letter.obj", &letter);
glGenTextures(MAX_TEXTURE, texture); // 第一参数是需要生成标示符的个数, 第二参数是返回标示符的数组
texload(0, "Water.bmp");
texload(1, "Crack.bmp");
texload(2, "Gold.bmp");
texload(3, "Floor.bmp");
texload(4, "Door.bmp");
OutObjFile("Out.obj", &letter);
}
//画柱子并设置材质
void drawCube()
{
int i, j;
const GLfloat x1 = -0.5, x2 = 0.5;
const GLfloat y1 = -0.5, y2 = 0.5;
const GLfloat z1 = -0.5, z2 = 0.5;
//指定六个面的四个顶点,每个顶点用3个坐标值表示
GLfloat point[6][4][3] = {
{ { x1,y1,z1 },{ x2,y1,z1 },{ x2,y2,z1 },{ x1,y2,z1 } },
{ { x1,y1,z1 },{ x2,y1,z1 },{ x2,y1,z2 },{ x1,y1,z2 } },
{ { x2,y1,z1 },{ x2,y2,z1 },{ x2,y2,z2 },{ x2,y1,z2 } },
{ { x1,y1,z1 },{ x1,y2,z1 },{ x1,y2,z2 },{ x1,y1,z2 } },
{ { x1,y2,z1 },{ x2,y2,z1 },{ x2,y2,z2 },{ x1,y2,z2 } },
{ { x1,y1,z2 },{ x2,y1,z2 },{ x2,y2,z2 },{ x1,y2,z2 } }
};
int dir[4][2] = { {0,0},{1,0},{1,1},{0,1} };
//设置正方形绘制模式
glBegin(GL_QUADS);
for (i = 0; i < 6; i++) {
for (j = 0; j < 4; j++) {
glTexCoord2iv(dir[j]);
glVertex3fv(point[i][j]);
}
}
glEnd();
}
//绘制门
void drawdoor()
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[4]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glPushMatrix();
glTranslated(0.5, 0, -0.5);
glRotatef(doorRotate1, 0, 1, 0);
glTranslatef(0.5, 0, 0);
glScalef(1, 1, 0.1);
drawCube();
glPopMatrix();
glPushMatrix();
glTranslated(0.5+MAP_SIZE-3, 0, -0.5-MAP_SIZE+1);
glRotatef(doorRotate2, 0, 1, 0);
glTranslatef(0.5, 0, 0);
glScalef(1, 1, 0.1);
drawCube();
glPopMatrix();
glDisable(GL_TEXTURE);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);
}
//创建列表,在显示列表模式下绘制柱子
GLint GenCubeList()
{
GLint lid = glGenLists(1);
//创建柱子显示列表
glNewList(lid, GL_COMPILE);
glPushMatrix();
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, allone);
glMaterialfv(GL_FRONT, GL_SPECULAR, allone);
glMaterialfv(GL_FRONT, GL_SHININESS, allzero);
drawCube();
glPopMatrix();
glEndList();
return lid;
}
//显示列表模式柱子
void Draw_Cube_List()
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[status]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glPushMatrix();
for (int i = 0; i < MAP_SIZE; i++) {
for (int j = 0; j < MAP_SIZE; j++)
{
if (Map[i][j] == 1)
{
glCallList(cubeList);
}
glTranslatef(1, 0, 0);
}
glTranslatef(-MAP_SIZE, 0, -1);
}
glPopMatrix();
glDisable(GL_TEXTURE);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[3]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glPushMatrix();
//glTranslatef(0,0,MAP_SIZE);
glTranslatef(0, -0.5, 0);
glScalef(1, 0.1, 1);
for (int i = 0; i < MAP_SIZE; i++) {
for (int j = 0; j < MAP_SIZE; j++)
{
if (Map[i][j] == 0)
{
glCallList(cubeList);
}
glTranslatef(1, 0, 0);
}
glTranslatef(-MAP_SIZE, 0, -1);
}
glPopMatrix();
glDisable(GL_TEXTURE);
}
//绘制终点处多面体
void draw_gameover()
{
//圆柱
glPushMatrix();
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, finalMaterialColor);
glMaterialfv(GL_FRONT, GL_SPECULAR, finalMaterialColor);
GLUquadric *pObj;
pObj = gluNewQuadric();
glTranslatef(0, 1, 0);
glRotatef(90, 1, 0, 0);
gluCylinder(pObj, 1, 1, 2, 32, 5);
glPopMatrix();
//球
glPushMatrix();
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, finalMaterialColor);
glMaterialfv(GL_FRONT, GL_SPECULAR, finalMaterialColor);
glTranslatef(0, 1.7, 0);
glutSolidSphere(0.6, 30, 30);
glPopMatrix();
//圆锥
glPushMatrix();
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, finalMaterialColor);
glMaterialfv(GL_FRONT, GL_SPECULAR, finalMaterialColor);
glTranslatef(0, 2.3, 0);
GLUquadric *pObj1;
pObj1 = gluNewQuadric();
glRotatef(-90, 1, 0, 0);
gluCylinder(pObj, 0.7, 0, 1.5, 32, 5);
glPopMatrix();
//三棱柱
glPushMatrix();
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, finalMaterialColor);
glMaterialfv(GL_FRONT, GL_SPECULAR, finalMaterialColor);
GLUquadric *pObj2;
pObj2 = gluNewQuadric();
glRotatef(90, 1, 0, 0);
glRotatef(30, 0, 1, 0);
glTranslatef(1.1, 0, 0);
gluCylinder(pObj2, 0.5, 0.5, 1.2, 3, 5);
glPopMatrix();
glPushMatrix();
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, finalMaterialColor);
glMaterialfv(GL_FRONT, GL_SPECULAR, finalMaterialColor);
GLUquadric *pObj3;
pObj3 = gluNewQuadric();
glRotatef(90, 1, 0, 0);
glRotatef(-30, 0, 1, 0);
glTranslatef(-1.1, 0, 0);
gluCylinder(pObj2, 0.5, 0.5, 1.2, 3, 5);
glPopMatrix();
//棱台
glPushMatrix();
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, finalMaterialColor);
glMaterialfv(GL_FRONT, GL_SPECULAR, finalMaterialColor);
glTranslatef(0, -2, 0);
GLUquadric *pObj4;
pObj4 = gluNewQuadric();
glRotatef(-90, 1, 0, 0);
gluCylinder(pObj4, 1.5, 0.4, 1, 4, 5);
glPopMatrix();
}
//重要
void reshape(int width, int height)
{
if (height == 0) // Prevent A Divide By Zero By
{
height = 1; // Making Height Equal One
}
glViewport(0, 0, width, height); // Reset The Current Viewport
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix
float whRatio = (GLfloat)width / (GLfloat)height;
gluPerspective(40, whRatio, 0.1, 1000);
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
}
//重要
void idle()
{
glutPostRedisplay();
}
pair <int, int> FindPosition(double a, double b)
{
pair <int, int> ret;
ret.first = floor((a + 0.5) / 1.0);
ret.second = floor((-b + 0.5) / 1.0);
return ret;
}
//判断该位置是否离墙过近
bool IsWall(pair <int, int> pos)
{
if (Map[pos.second][pos.first] == 0) return false;
return true;
}
bool InFinish()
{
pair <int, int> pos;
pos = FindPosition(eye[0], eye[2]);
if (pos.first == MAP_SIZE - 2 && pos.second == MAP_SIZE - 1) return true;
// printf("now pos = %d %d\n", pos.first, pos.second);
return false;
}
bool OutRange(double a, double b)
{
if (a<-0.5 || a>MAP_SIZE - 0.5 || b > 0.61 || b < 0.5 - MAP_SIZE) return true;
else return false;
}
//判断是否可以向该点移动
bool CanMove(double a, double b)
{
pair <int, int> pos = FindPosition(a, b);
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j) {
if (OutRange(a + boundry[i], b + boundry[j]) || IsWall(FindPosition(a + boundry[i], b + boundry[j]))) {
return false;
}
}
return true;
}
//键盘读入
void key(unsigned char k, int x, int y)
{
if (MenuGameFit) return;
switch (k)
{
case 27://esc
exit(0);
break;
case 'q': {
if (InGame || gameover) {
MenuGameFit = 60;
fitstep[0] = (viewstart[0] - eye[0]) / 60;
fitstep[1] = (viewstart[1] - eye[1]) / 60;
fitstep[2] = (viewstart[2] - eye[2]) / 60;
float delta = INF, displace = 0;
if (fabs(viewstartang - faceang) < delta) delta = fabs(viewstartang - faceang), displace = viewstartang - faceang;
if (fabs(viewstartang - faceang + 2 * pi) < delta) delta = fabs(viewstartang - faceang), displace = viewstartang - faceang + 2 * pi;
if (fabs(viewstartang - faceang - 2 * pi) < delta) delta = fabs(viewstartang - faceang), displace = viewstartang - faceang - 2 * pi;
fitang = displace / 60;
if (gameover) {
eye[0] = viewstart[0];
eye[1] = viewstart[1];
eye[2] = viewstart[2];
MenuGameFit = 0;
}
InGame = 0;
gameover = 0;
InMenu = 1;
}
break;
}
case 'a':
{
if (InGame) {
if (CanMove(eye[0] + fStep * sin(faceang), eye[2] - fStep * cos(faceang))) {
eye[0] += fStep * sin(faceang);
eye[2] -= fStep * cos(faceang);
}
if (InFinish()) {
InGame = 0;
gameover = 1;
}
}
break;
}
case 'd':
{
if (InGame) {
if (CanMove(eye[0] - fStep * sin(faceang), eye[2] + fStep * cos(faceang))) {
eye[0] -= fStep * sin(faceang);
eye[2] += fStep * cos(faceang);
}
if (InFinish()) {
InGame = 0;
gameover = 1;
}
}
break;
}
case 'w':
{
int mod = glutGetModifiers();
if (InGame) {
if (CanMove(eye[0] + fStep * cos(faceang), eye[2] + fStep * sin(faceang))) {
if (mod == GLUT_ACTIVE_ALT)
{
eye[0] += 2 * fStep * cos(faceang);
eye[2] += 2 * fStep * sin(faceang);
}
else
{
eye[0] += fStep * cos(faceang);
eye[2] += fStep * sin(faceang);
}
}
if (InFinish()) {
InGame = 0;
gameover = 1;
}
}
break;
}
case 's':
{
int mod = glutGetModifiers();
if (InGame) {
if (CanMove(eye[0] - fStep * cos(faceang), eye[2] - fStep * sin(faceang))) {
if (mod == GLUT_ACTIVE_ALT)
{
eye[0] -= 2 * fStep * cos(faceang);
eye[2] -= 2 * fStep * sin(faceang);
}
else
{
eye[0] -= fStep * cos(faceang);
eye[2] -= fStep * sin(faceang);
}
}
if (InFinish()) {
InGame = 0;
gameover = 1;
}
}
break;
}
case 'n':
{
if (InGame) {
faceang -= moveangStep;
while (faceang < 0) faceang += 2 * pi;
}
break;
}
case 'm':
{
if (InGame) {
faceang += moveangStep;
while (faceang > 2 * pi) faceang -= 2 * pi;
}
break;
}
case 'r':
{
if (!InGame)
ResetMap();
break;
}
case '-':
{
PrtScrn();
break;
}
case 'i':
{
light_pos[1] += 1;
break;
}
case 'k':
{
light_pos[1] -= 1;
break;
}
case 'j':
{
light_pos[0] -= 1;
break;
}
case 'l':
{
light_pos[0] += 1;
break;
}
case 'u':
{
light_pos[2] += 1;
break;
}
case 'o':
{
light_pos[2] -= 1;
break;
}
case ' ':
{
if (InMenu) {
MenuGameFit = 60;
fitstep[0] = (gamestart[0] - eye[0]) / 60;
fitstep[1] = (gamestart[1] - eye[1]) / 60;
fitstep[2] = (gamestart[2] - eye[2]) / 60;
float delta = INF, displace = 0;
if (abs(gamestartang - faceang) < delta) delta = abs(gamestartang - faceang), displace = gamestartang - faceang;
if (abs(gamestartang - faceang + 2 * pi) < delta) delta = abs(gamestartang - faceang), displace = gamestartang - faceang + 2 * pi;
if (abs(gamestartang - faceang - 2 * pi) < delta) delta = abs(gamestartang - faceang), displace = gamestartang - faceang - 2 * pi;
fitang = displace / 60;
InMenu = 0;
InGame = 1;
}
break;
}
case '=':
{
ObjPrintLine ^= 1;
}
default:
printf("Get %d\n", k);
break;
}
}
//获取FPS值
void getFPS()
{
static int frame = 0, time, timebase = 0;
static char buffer[256];
char mode[64];
strcpy(mode, "display list");
frame++;
time = glutGet(GLUT_ELAPSED_TIME);
if (time - timebase > 1000) {
sprintf(buffer, "FPS:%4.2f %s",
frame*1000.0 / (time - timebase), mode);
timebase = time;
frame = 0;
}
char *c;
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION); // 选择投影矩阵
glPushMatrix(); // 保存原矩阵
glLoadIdentity(); // 装入单位矩阵
glOrtho(0, WinWidth, 0, WinHeight, -1, 1); // 位置正投影
glMatrixMode(GL_MODELVIEW); // 选择Modelview矩阵
glPushMatrix(); // 保存原矩阵
glLoadIdentity(); // 装入单位矩阵
glRasterPos2f(10, 10);
for (c = buffer; *c != '\0'; c++) {
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
}
glMatrixMode(GL_PROJECTION); // 选择投影矩阵
glPopMatrix(); // 重置为原保存矩阵
glMatrixMode(GL_MODELVIEW); // 选择Modelview矩阵
glPopMatrix(); // 重置为原保存矩阵
glEnable(GL_DEPTH_TEST);
}
//输出OBJ文件下的某一个模型
void OutPutObj(struct ObjFile * obj, int id, float * delta)
{
glColor3f(1, 1, 0);
for (int i = obj->st[id]; i <= obj->ed[id]; ++i) {
if (ObjPrintLine) {
glBegin(GL_LINES);
glVertex3f(obj->vertex[obj->surface[i].X].X + delta[0], obj->vertex[obj->surface[i].X].Y + delta[1], obj->vertex[obj->surface[i].X].Z + delta[2]);
glVertex3f(obj->vertex[obj->surface[i].Y].X + delta[0], obj->vertex[obj->surface[i].Y].Y + delta[1], obj->vertex[obj->surface[i].Y].Z + delta[2]);
glVertex3f(obj->vertex[obj->surface[i].Y].X + delta[0], obj->vertex[obj->surface[i].Y].Y + delta[1], obj->vertex[obj->surface[i].Y].Z + delta[2]);
glVertex3f(obj->vertex[obj->surface[i].P].X + delta[0], obj->vertex[obj->surface[i].P].Y + delta[1], obj->vertex[obj->surface[i].P].Z + delta[2]);
glVertex3f(obj->vertex[obj->surface[i].P].X + delta[0], obj->vertex[obj->surface[i].P].Y + delta[1], obj->vertex[obj->surface[i].P].Z + delta[2]);
glVertex3f(obj->vertex[obj->surface[i].Q].X + delta[0], obj->vertex[obj->surface[i].Q].Y + delta[1], obj->vertex[obj->surface[i].Q].Z + delta[2]);
glVertex3f(obj->vertex[obj->surface[i].Q].X + delta[0], obj->vertex[obj->surface[i].Q].Y + delta[1], obj->vertex[obj->surface[i].Q].Z + delta[2]);
glVertex3f(obj->vertex[obj->surface[i].X].X + delta[0], obj->vertex[obj->surface[i].X].Y + delta[1], obj->vertex[obj->surface[i].X].Z + delta[2]);
glEnd();
}
else {
glBegin(GL_POLYGON);
glVertex3f(obj->vertex[obj->surface[i].X].X + delta[0], obj->vertex[obj->surface[i].X].Y + delta[1], obj->vertex[obj->surface[i].X].Z + delta[2]);
glVertex3f(obj->vertex[obj->surface[i].Y].X + delta[0], obj->vertex[obj->surface[i].Y].Y + delta[1], obj->vertex[obj->surface[i].Y].Z + delta[2]);
glVertex3f(obj->vertex[obj->surface[i].P].X + delta[0], obj->vertex[obj->surface[i].P].Y + delta[1], obj->vertex[obj->surface[i].P].Z + delta[2]);
glVertex3f(obj->vertex[obj->surface[i].Q].X + delta[0], obj->vertex[obj->surface[i].Q].Y + delta[1], obj->vertex[obj->surface[i].Q].Z + delta[2]);
glEnd();
}
}
}
//读取obj文件
void getobj(const char * filename, struct ObjFile * obj)
{
FILE * fin;
fin = fopen(filename, "r");
if (fin == NULL) {
printf("Error! Can't find the file\n");
}
obj->vc = 0;
obj->sc = 0;
obj->mc = 0;
char buf[1 << 10];
while (fscanf(fin, "%s", buf) != EOF) {
switch (buf[0]) {
case '#':
getline(fin, buf);
printf("The Message %s\n", buf);
break;
case 'g':
getline(fin, obj->name[obj->mc + 1]);
printf("Find a name %s\n", obj->name[obj->mc + 1]);
obj->ed[obj->mc] = obj->sc;
obj->st[obj->mc + 1] = obj->sc + 1;
obj->mc++;
break;
case 'v':
++(obj->vc);
fscanf(fin, "%f", &((obj->vertex[obj->vc]).X));
fscanf(fin, "%f", &((obj->vertex[obj->vc]).Y));
fscanf(fin, "%f", &((obj->vertex[obj->vc]).Z));
break;
case 'f':
++(obj->sc);
fscanf(fin, "%d", &((obj->surface[obj->sc]).X));
fscanf(fin, "%d", &((obj->surface[obj->sc]).Y));
fscanf(fin, "%d", &((obj->surface[obj->sc]).P));
fscanf(fin, "%d", &((obj->surface[obj->sc]).Q));
break;
}
}
obj->ed[obj->mc] = obj->sc;
}
//直接读取一行的字符串
void getline(FILE * fin, char *s)
{
char ch;
int idx = 0;
fscanf(fin, "%c", &ch);
while (ch != '\n' && ch != '\r' && ch != EOF) {
s[idx++] = ch;
fscanf(fin, "%c", &ch);
}
s[idx++] = '\0';
}
//渲染MAZE四个字母
void render_maze()
{
glColor3f(0.0f, 0.0f, 1.0f);
glPushMatrix();
/*glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[2]);*/
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
const float diffuse[] = { 0.247250, 0.224500, 0.064500, 1.000000 };
const float ambient[] = { 0.346150, 0.314300, 0.090300, 1.000000 };
const float specular[] = { 0.797357, 0.723991, 0.208006, 1.000000 };
const float shininess[] = { 83.199997 };
/*
Meterial : Gold
0.247250, 0.224500, 0.064500, 1.000000,
0.346150, 0.314300, 0.090300, 1.000000,
0.797357, 0.723991, 0.208006, 1.000000,
83.199997,
*/
glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse);
glMaterialfv(GL_FRONT, GL_AMBIENT, ambient);
glMaterialfv(GL_FRONT, GL_SPECULAR, specular);
glMaterialfv(GL_FRONT, GL_SHININESS, shininess);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);
OutPutObj(&letter, IDA, deltaA);
OutPutObj(&letter, IDM, deltaM);
OutPutObj(&letter, IDZ, deltaZ);
OutPutObj(&letter, IDE, deltaE);
//glDisable(GL_TEXTURE);
glPopMatrix();
}
//游戏界面渲染
void render_game()
{
if (InMenu) render_maze();
Draw_Cube_List();
drawdoor();
if (InGame&&!MenuGameFit) {
if (doorRotate1 < 90 && eye[2] < 0.45) {
doorRotate1 += 1;
}
if (doorRotate2 < 90 && eye[2] < 0.45 - MAP_SIZE + 2) {
doorRotate2 += 1;
}
}
// getFPS();
}
void init_surface()
{
int u, v;
for (u = 0; u < 4; u++) {
for (v = 0; v < 4; v++) {
ctlpoints[u][v][0] = MAP_SIZE / 2 + 2.0*((GLfloat)u - 1.5);
ctlpoints[u][v][1] = 8.0f + sin((u + v)*7.0f + nurbsphase);
ctlpoints[u][v][2] = -MAP_SIZE / 2 + 2.0*((GLfloat)v - 1.5);
}
}
nurbsphase += 0.10f;
}
void render_nurbs()
{
GLfloat knots[8] = { 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0 };
init_surface();
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[2]);
theNurb = gluNewNurbsRenderer();
gluNurbsProperty(theNurb, GLU_SAMPLING_TOLERANCE, 25.0);
gluNurbsProperty(theNurb, GLU_DISPLAY_MODE, GLU_FILL);
gluBeginSurface(theNurb);
glTexCoord2i(1, 1); glVertex3i(ctlpoints[3][3][0], ctlpoints[3][3][1], ctlpoints[3][3][2]);
glTexCoord2i(1, 0); glVertex3i(ctlpoints[3][0][0], ctlpoints[3][0][1], ctlpoints[3][0][2]);
glTexCoord2i(0, 0); glVertex3i(ctlpoints[0][0][0], ctlpoints[0][0][1], ctlpoints[0][0][2]);
glTexCoord2i(0, 1); glVertex3i(ctlpoints[0][3][0], ctlpoints[0][3][1], ctlpoints[0][3][2]);
gluNurbsSurface(theNurb,
8, knots, 8, knots,
4 * 3, 3, &ctlpoints[0][0][0],
4, 4, GL_MAP2_VERTEX_3);
gluEndSurface(theNurb);
if (showPoints) {
glPointSize(5.0);
glDisable(GL_LIGHTING);
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_POINTS);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
glVertex3f(ctlpoints[i][j][0],
ctlpoints[i][j][1], ctlpoints[i][j][2]);
}
}
glEnd();
glEnable(GL_LIGHTING);
}
glPopMatrix();
glDisable(GL_TEXTURE);
}
//菜单界面渲染
void render_menu()//环绕迷宫进行观察
{
faceang += angStep / 5;
while (faceang > 2 * pi) faceang -= 2 * pi;
eye[0] = center[0] - cos(faceang) * ViewDistance;
eye[1] = 5;
eye[2] = center[2] - sin(faceang) * ViewDistance;
render_game();
render_nurbs();
}
void render_gameover() {
/*faceang += angStep / 5;
while (faceang > 2 * pi) faceang -= 2 * pi;*/
eye[0] = center[0] - cos(faceang) * ViewDistance;
eye[1] = 5;
eye[2] = center[2] - sin(faceang) * ViewDistance;
glPushMatrix();
glTranslatef(-8.0f, 0.0f,-6.0f);
glTranslatef(0.0f, fTranslate, 0.0f);
draw_gameover();
glPopMatrix();
glPushMatrix();
glTranslatef(0.0f, 0.0f,-6.0f);
glScalef(fScale, fScale, fScale);
draw_gameover();
glPopMatrix();
glPushMatrix();
glTranslatef(8.0f, 0.0f,-6.0f);
glRotatef(fRotate, 0, 1.0f, 0);
draw_gameover();
glPopMatrix();
fRotate += 3.0f;
fTranslate += 0.03f;
fScale += 0.005f;
if(fTranslate > 2.0f) fTranslate = -1.0f;
if(fScale > 1.5f) fScale = 0.5f;
}
//视角转变
void FitLookAt()//渐变调整视角
{
eye[0] += fitstep[0];
eye[1] += fitstep[1];
eye[2] += fitstep[2];
faceang += fitang;
while (faceang > 2 * pi) faceang -= 2 * pi;
render_game();
}
//主渲染函数
void render()//主渲染入口
{
// printf("Now Postion = %f, %f, %f block %d, %d\n", eye[0], eye[1], eye[2],FindPosition(eye[0],eye[2]).first, FindPosition(eye[0],eye[2]).second);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0, 0, 0, 1);
glLoadIdentity(); // Reset The Current Modelview Matrix
// printf("Now %f, %f, %f\n", eye[0], eye[1], eye[2]);
gluLookAt(eye[0], eye[1], eye[2],
eye[0] + cos(faceang), eye[1], eye[2] + sin(faceang),
0, 1, 0); // 场景(0,0,0)的视点中心 (0, 5, 50),Y轴向上
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
//开灯
glLightfv(GL_LIGHT0, GL_AMBIENT, light_color);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_color);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_color);
glLightfv(GL_LIGHT0, GL_POSITION, light_pos);
glEnable(GL_LIGHT0);
if (MenuGameFit) {//渐变效果
FitLookAt();
MenuGameFit--;
}
else if (gameover) {//如果游戏结束
render_gameover();
}
else if (InGame) {//如果在游戏当中
render_game();
}
else if (InMenu) {//如果在目录上
render_menu();
}
glutSwapBuffers();
}
//第一个子菜单响应函数
void submenufunc1(int data) {
switch (data) {
case 0:
light_color[0] = 0.5;
light_color[1] = 0.5;
light_color[2] = 0.5;
break;
case 1:
light_color[0] = 1;
light_color[1] = 1;
light_color[2] = 1;
break;
case 2:
light_color[0] = 1;
light_color[1] = 0;
light_color[2] = 0;
break;
case 3:
light_color[0] = 0;
light_color[1] = 1;
light_color[2] = 0;
break;
case 4:
light_color[0] = 0;
light_color[1] = 0;
light_color[2] = 1;
break;
}
}
//第二个子菜单响应函数
void submenufunc2(int data) {
//getcurrentmenu();
switch (data) {
case 1:
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 1.0);
break;
case 2:
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.5);
break;
case 3:
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.33);
break;
case 4:
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.25);
break;
case 5:
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1);
break;
}
}
//第三个子菜单响应函数
void submenufunc3(int data) {
switch (data) {
case 1:
status = 0;
break;
case 2:
status = 1;
break;
}
}
//第四个子菜单响应函数
void submenufunc4(int data) {
switch (data) {
case 1:
if (!InGame) {
MAP_SIZE = 5;
deltaA[0] = 52.0f + 8.0f - 10.5f + MAP_SIZE / 2;
deltaA[2] = -MAP_SIZE / 2;
deltaM[0] = 2.8f + 4.0f - 10.5f + MAP_SIZE / 2;
deltaM[2] = -MAP_SIZE / 2;
deltaE[0] = 2.5f + 52.0f - 10.5f + MAP_SIZE / 2;
deltaE[2] = -MAP_SIZE / 2;
deltaZ[0] = -38.0f - 10.5f + MAP_SIZE / 2;
deltaZ[2] = -MAP_SIZE / 2;
center[0] = MAP_SIZE / 2;
center[2] = -MAP_SIZE / 2;
viewstart[0] = center[0] - (float)cos(viewstartang) * ViewDistance;
viewstart[2] = center[2] - (float)sin(viewstartang) * ViewDistance;
ResetMap();
}
break;
case 2:
if (!InGame) {
MAP_SIZE = 13;
deltaA[0] = 52.0f + 8.0f - 10.5f + MAP_SIZE / 2;
deltaA[2] = -MAP_SIZE / 2;
deltaM[0] = 2.8f + 4.0f - 10.5f + MAP_SIZE / 2;
deltaM[2] = -MAP_SIZE / 2;
deltaE[0] = 2.5f + 52.0f - 10.5f + MAP_SIZE / 2;
deltaE[2] = -MAP_SIZE / 2;
deltaZ[0] = -38.0f - 10.5f + MAP_SIZE / 2;
deltaZ[2] = -MAP_SIZE / 2;
center[0] = MAP_SIZE / 2;
center[2] = -MAP_SIZE / 2;
viewstart[0] = center[0] - (float)cos(viewstartang) * ViewDistance;
viewstart[2] = center[2] - (float)sin(viewstartang) * ViewDistance;
ResetMap();
}
break;
case 3:
if (!InGame) {
MAP_SIZE = 21;
deltaA[0] = 52.0f + 8.0f - 10.5f + MAP_SIZE / 2;
deltaA[2] = -MAP_SIZE / 2;
deltaM[0] = 2.8f + 4.0f - 10.5f + MAP_SIZE / 2;
deltaM[2] = -MAP_SIZE / 2;
deltaE[0] = 2.5f + 52.0f - 10.5f + MAP_SIZE / 2;
deltaE[2] = -MAP_SIZE / 2;
deltaZ[0] = -38.0f - 10.5f + MAP_SIZE / 2;
deltaZ[2] = -MAP_SIZE / 2;
center[0] = MAP_SIZE / 2;
center[2] = -MAP_SIZE / 2;
viewstart[0] = center[0] - (float)cos(viewstartang) * ViewDistance;
viewstart[2] = center[2] - (float)sin(viewstartang) * ViewDistance;
ResetMap();
}
break;
case 4:
if (!InGame) {
MAP_SIZE = 29;
deltaA[0] = 52.0f + 8.0f - 10.5f + MAP_SIZE / 2;
deltaA[2] = -MAP_SIZE / 2;
deltaM[0] = 2.8f + 4.0f - 10.5f + MAP_SIZE / 2;
deltaM[2] = -MAP_SIZE / 2;
deltaE[0] = 2.5f + 52.0f - 10.5f + MAP_SIZE / 2;
deltaE[2] = -MAP_SIZE / 2;
deltaZ[0] = -38.0f - 10.5f + MAP_SIZE / 2;
deltaZ[2] = -MAP_SIZE / 2;
center[0] = MAP_SIZE / 2;
center[2] = -MAP_SIZE / 2;
viewstart[0] = center[0] - (float)cos(viewstartang) * ViewDistance;
viewstart[2] = center[2] - (float)sin(viewstartang) * ViewDistance;
ResetMap();
}
break;
case 5:
if (!InGame) {
MAP_SIZE = 37;
deltaA[0] = 52.0f + 8.0f - 10.5f + MAP_SIZE / 2;
deltaA[2] = -MAP_SIZE / 2;
deltaM[0] = 2.8f + 4.0f - 10.5f + MAP_SIZE / 2;
deltaM[2] = -MAP_SIZE / 2;
deltaE[0] = 2.5f + 52.0f - 10.5f + MAP_SIZE / 2;
deltaE[2] = -MAP_SIZE / 2;
deltaZ[0] = -38.0f - 10.5f + MAP_SIZE / 2;
deltaZ[2] = -MAP_SIZE / 2;
center[0] = MAP_SIZE / 2;
center[2] = -MAP_SIZE / 2;
viewstart[0] = center[0] - (float)cos(viewstartang) * ViewDistance;
viewstart[2] = center[2] - (float)sin(viewstartang) * ViewDistance;
ResetMap();
}
break;
}
}
//第五个子菜单响应函数
void submenufunc5(int data) {
switch (data) {
case 0:
finalMaterialColor[0] = 0.5;
finalMaterialColor[1] = 0.5;
finalMaterialColor[2] = 0.5;
break;
case 1:
finalMaterialColor[0] = 1;
finalMaterialColor[1] = 1;
finalMaterialColor[2] = 1;
break;
case 2:
finalMaterialColor[0] = 1;
finalMaterialColor[1] = 0;
finalMaterialColor[2] = 0;
break;
case 3:
finalMaterialColor[0] = 0;
finalMaterialColor[1] = 1;
finalMaterialColor[2] = 0;
break;
case 4:
finalMaterialColor[0] = 0;
finalMaterialColor[1] = 0;
finalMaterialColor[2] = 1;
break;
}
}
//主菜单响应函数——目前暂无
void menufunc(int data) {
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
glutInitWindowSize(WinWidth, WinHeight);
int windowHandle = glutCreateWindow("Maze");
Initial();
//构建子菜单1的内容
subMenu1 = glutCreateMenu(submenufunc1);
glutAddMenuEntry("Gray", 0);
glutAddMenuEntry("White", 1);
glutAddMenuEntry("Red", 2);
glutAddMenuEntry("Green", 3);
glutAddMenuEntry("Blue", 4);
glutAttachMenu(GLUT_RIGHT_BUTTON);
//构建子菜单2的内容
subMenu2 = glutCreateMenu(submenufunc2);
glutAddMenuEntry("弱", 1);
glutAddMenuEntry("较弱", 2);
glutAddMenuEntry("一般", 3);
glutAddMenuEntry("较强", 4);
glutAddMenuEntry("强", 5);
glutAttachMenu(GLUT_RIGHT_BUTTON);
//构建子菜单3的内容
subMenu3 = glutCreateMenu(submenufunc3);
glutAddMenuEntry("水波", 1);
glutAddMenuEntry("裂缝", 2);
glutAttachMenu(GLUT_RIGHT_BUTTON);
//构建子菜单4的内容
subMenu4 = glutCreateMenu(submenufunc4);
glutAddMenuEntry("新手模式", 1);
glutAddMenuEntry("简单模式", 2);
glutAddMenuEntry("一般模式", 3);
glutAddMenuEntry("困难模式", 4);
glutAddMenuEntry("噩梦模式", 5);
glutAttachMenu(GLUT_RIGHT_BUTTON);
//构建子菜单5的内容
subMenu5 = glutCreateMenu(submenufunc5);
glutAddMenuEntry("Gray", 0);
glutAddMenuEntry("White", 1);
glutAddMenuEntry("Red", 2);
glutAddMenuEntry("Green", 3);
glutAddMenuEntry("Blue", 4);
glutAttachMenu(GLUT_RIGHT_BUTTON);
//构建主菜单的内容
mainMenu = glutCreateMenu(menufunc);
//将两个菜单变为主菜单的子菜单
glutAddSubMenu("光源颜色", subMenu1);
glutAddSubMenu("光源强度", subMenu2);
glutAddSubMenu("墙体纹理", subMenu3);
glutAddSubMenu("游戏难度", subMenu4);
glutAddSubMenu("终点物体材质", subMenu5);
//点击鼠标右键时显示菜单
glutAttachMenu(GLUT_RIGHT_BUTTON);
//播放背景音乐
PlaySound(TEXT(".\\rise.wav"), NULL, SND_FILENAME | SND_ASYNC | SND_LOOP);
glutDisplayFunc(render);
glutReshapeFunc(reshape);
glutKeyboardFunc(key);
glutIdleFunc(idle);
cubeList = GenCubeList();
glutMainLoop();
return 0;
} | [
"3180104180@zju.edu.cn"
] | 3180104180@zju.edu.cn |
0dd9a620f58c6d62067a8b39718e6d7b27c8491f | e53f90f835c93a008ee042ebc66b44063dfbd395 | /book_algorithm_solution/4.recursive_divide-and-conquer/4.4.cpp | 76d93c0df2d0ecf88cce8f627e769791743f06cb | [] | no_license | tomonakar/practice-cpp-argorithm | 41805ac87f9686fa59178ce12c220f7ae5b4ffac | 8847df18db5ac3efacc6e1fbba3274bc3773f222 | refs/heads/main | 2023-04-03T06:32:20.591401 | 2021-04-08T22:33:46 | 2021-04-08T22:33:46 | 347,498,824 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 287 | cpp | #include <iostream>
using namespace std;
// ユークリッド互助法
// @see https://ja.wikipedia.org/wiki/%E3%83%A6%E3%83%BC%E3%82%AF%E3%83%AA%E3%83%83%E3%83%89%E3%81%AE%E4%BA%92%E9%99%A4%E6%B3%95
int GCD(int m, int n)
{
if (n == 0)
{
return m
}
return GCD(n, m % n);
} | [
"tomohisa.nak@gmail.com"
] | tomohisa.nak@gmail.com |
a4d9c8a97d6652504b0cb7804c906c4989f60aba | 95b0c785602c942bf6a5d762e905f29a4f129c11 | /mainwindow.h | f1ed579c3cca33a65204723f5294dc4a4b102687 | [] | no_license | veliKerril/Stock | 194933249d3da395876e90cb26828a28cba24871 | 6c5d98d3a5d0b6757265d82c91ac16d7fd82fbbe | refs/heads/master | 2022-10-18T03:29:36.458330 | 2020-06-09T12:14:35 | 2020-06-09T12:14:35 | 262,366,037 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 585 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "container.h"
#include "position.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_addPos_clicked();
void on_delPos_clicked();
void on_pushButton_clicked();
void on_swapPos_clicked();
void on_setChanges_clicked();
private:
Ui::MainWindow *ui;
//QList<Position> listPos;
QList<Container> listCont;
};
#endif // MAINWINDOW_H
| [
"velikirilll@gmail.com"
] | velikirilll@gmail.com |
ab15e3d3de713be1458ae4dc49ce92a15a56da06 | c10709c25dea90dbdd003fd96164867960dc600b | /src/I2T-iota-arduino-lib.cpp | c78f90667f338ab78fe28d22585b7b1a3a95e524 | [
"Apache-2.0"
] | permissive | iot2tangle/I2T-iota-arduino-lib | 95799d3d86e0fbcde936602e8b86f7f00eee2502 | 43a0f4a2f43321e8d22794670eed586916cce4dc | refs/heads/main | 2023-05-30T19:41:17.067869 | 2021-05-25T22:55:09 | 2021-05-25T22:55:09 | 357,567,231 | 0 | 1 | Apache-2.0 | 2021-05-25T22:55:10 | 2021-04-13T13:40:50 | C++ | UTF-8 | C++ | false | false | 7,791 | cpp | #include <Arduino.h>
#include "Wire.h"
#include <WiFi101.h>
#include <ArduinoHttpClient.h>
#include "I2T-iota-arduino-lib.h"
//Sensors
#include <TemperatureZero.h>
#include "BlueDot_BME280.h"
#include <MPU6050_light.h>
#include <BH1750_WE.h>
#define ENABLE_SOUND 5
#define VALUE_SOUND 4
TemperatureZero TempZero = TemperatureZero();
BlueDot_BME280 bme;
MPU6050 mpu(Wire);
BH1750_WE myBH1750(0x23);
char dev_name[32];
char json[1024];
char s_name[12][64], d[12][64];
bool en_bme, en_mpu, en_bh, en_sound;
char buffer[16];
char* s;
const char* int_str(int);
const char* float_str(float);
void init_I2T(const char* name)
{
delay(100);
strcpy(dev_name, name);
// Init Json static chars
strcpy(s_name[0],"InternalTemperature");
strcpy(s_name[1],"Temperature");
strcpy(s_name[2],"Humidity");
strcpy(s_name[3],"Pressure");
strcpy(s_name[4],"SoundLevel");
strcpy(s_name[5],"Light");
strcpy(s_name[6],"X");
strcpy(s_name[7],"Y");
strcpy(s_name[8],"Z");
strcpy(s_name[9],"X");
strcpy(s_name[10],"Y");
strcpy(s_name[11],"Z");
}
void init_WiFi(const char* ssid, const char* pass)
{
int status = WL_IDLE_STATUS;
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while (true);
}
// attempt to connect to WiFi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: \"");
Serial.print(ssid); Serial.println("\" ...");
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.print(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print(" --- IP Address: ");
Serial.println(ip);
}
void init_HTTP(const char* c, int d)
{
// Not necessary
}
void print_counter(int c)
{
Serial.print("\n-------------------------------------------------------------------------------------------------------\nData Collect - ");
Serial.println(c);
}
void init_sensors(bool ft)
{
if (ft){
Wire.begin();
}
TempZero.init(); // Internal Temperature Sensor
Serial.print("\tSensors Detection: || BME280: ");
if (ft){
bme.parameter.communication = 0; //I2C communication for Sensor 2 (bme2)
bme.parameter.I2CAddress = 0x76; //I2C Address for Sensor 2 (bme2)
bme.parameter.sensorMode = 0b11; //Setup Sensor mode for Sensor 2
bme.parameter.IIRfilter = 0b100; //IIR Filter for Sensor 2
bme.parameter.humidOversampling = 0b101; //Humidity Oversampling for Sensor 2
bme.parameter.tempOversampling = 0b101; //Temperature Oversampling for Sensor 2
bme.parameter.pressOversampling = 0b101; //Pressure Oversampling for Sensor 2
bme.parameter.pressureSeaLevel = 1013.25; //default value of 1013.25 hPa (Sensor 2)
bme.parameter.tempOutsideCelsius = 15; //default value of 15°C
bme.parameter.tempOutsideFahrenheit = 59; //default value of 59°F
}
if (bme.init() != 0x60)
{
Serial.print("NOT Detected");
en_bme = false;
}
else
{
Serial.print("OK");
en_bme = true;
}
Serial.print(" || MPU6050: ");
if (mpu.begin() != 0)
{
Serial.print("NOT Detected");
en_mpu = false;
}
else
{
Serial.print("OK");
en_mpu = true;
}
Serial.print(" || BH1750: ");
myBH1750.init();
if (int(myBH1750.getLux()) == 4703)
{
Serial.print("NOT Detected");
en_bh = false;
}
else
{
Serial.print("OK");
en_bh = true;
}
Serial.print(" || Acoustic: ");
if (ft){
pinMode(ENABLE_SOUND, INPUT);
pinMode(VALUE_SOUND, INPUT);
}
if (digitalRead(ENABLE_SOUND))
{
Serial.print("NOT Detected");
en_sound = false;
}
else
{
Serial.print("OK");
en_sound = true;
}
Serial.print(" ||\n");
}
void read_sensors()
{
strcpy(d[0] , float_str(TempZero.readInternalTemperature()));
if (en_bme)
{
strcpy(d[1] , float_str(bme.readTempC()));
strcpy(d[2] , float_str(bme.readHumidity()));
strcpy(d[3] , float_str(bme.readPressure()));
}
if (en_sound)
{
if (digitalRead(VALUE_SOUND))
strcpy(d[4] , "High");
else
strcpy(d[4] , "Low");
}
if (en_bh)
strcpy(d[5] , float_str(myBH1750.getLux()));
if (en_mpu)
{
strcpy(d[6] , float_str(mpu.getAccX()));
strcpy(d[7] , float_str(mpu.getAccY()));
strcpy(d[8] , float_str(mpu.getAccZ()));
strcpy(d[9] , float_str(mpu.getGyroX()));
strcpy(d[10] , float_str(mpu.getGyroY()));
strcpy(d[11] , float_str(mpu.getGyroZ()));
}
}
char* generate_json()
{
int i, aux;
strcpy(json, "{\"iot2tangle\":[");
aux = 0;
strcat(json, "{\"sensor\":\"Internal\",\"data\":[");
for (i=0;i<1;i++)
{
if (aux != i) strcat(json, ",");
strcat(json, "{\"");
strcat(json, s_name[i+0]);
strcat(json, "\":\"");
strcat(json, d[i+0]);
strcat(json, "\"}");
}
strcat(json, "]}");
if (en_bme)
{
aux = 0;
strcat(json, ",{\"sensor\":\"Environmental\",\"data\":[");
for (i=0;i<3;i++)
{
if (aux != i) strcat(json, ",");
strcat(json, "{\"");
strcat(json, s_name[i+1]);
strcat(json, "\":\"");
strcat(json, d[i+1]);
strcat(json, "\"}");
}
strcat(json, "]}");
}
if (en_sound)
{
aux = 0;
strcat(json, ",{\"sensor\":\"Acoustic\",\"data\":[");
for (i=0;i<1;i++)
{
if (aux != i) strcat(json, ",");
strcat(json, "{\"");
strcat(json, s_name[i+4]);
strcat(json, "\":\"");
strcat(json, d[i+4]);
strcat(json, "\"}");
}
strcat(json, "]}");
}
if (en_bh)
{
aux = 0;
strcat(json, ",{\"sensor\":\"Light\",\"data\":[");
for (i=0;i<1;i++)
{
if (aux != i) strcat(json, ",");
strcat(json, "{\"");
strcat(json, s_name[i+5]);
strcat(json, "\":\"");
strcat(json, d[i+5]);
strcat(json, "\"}");
}
strcat(json, "]}");
}
if (en_mpu)
{
aux = 0;
strcat(json, ",{\"sensor\":\"Acelerometer\",\"data\":[");
for (i=0;i<3;i++)
{
if (aux != i) strcat(json, ",");
strcat(json, "{\"");
strcat(json, s_name[i+6]);
strcat(json, "\":\"");
strcat(json, d[i+6]);
strcat(json, "\"}");
}
strcat(json, "]}");
aux = 0;
strcat(json, ",{\"sensor\":\"Gyroscope\",\"data\":[");
for (i=0;i<3;i++)
{
if (aux != i) strcat(json, ",");
strcat(json, "{\"");
strcat(json, s_name[i+9]);
strcat(json, "\":\"");
strcat(json, d[i+9]);
strcat(json, "\"}");
}
strcat(json, "]}");
}
strcat(json, "],\"device\":\"");
strcat(json, dev_name);
strcat(json, "\",\"timestamp\":\"0\"}");
Serial.print("JSON: ");
Serial.println(json);
return json;
}
void send_HTTP(const char* jsondata, const char* serverAddress, const char* serverEndpoint, int port)
{
Serial.println("\t\tSending Data to Tangle...");
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
client.setTimeout(1);
String contentType = "application/json";
client.post(serverEndpoint, contentType, jsondata);
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
if (statusCode == 200){
Serial.print("\t*** Data Sucessfully Sent to Tangle\n\t\tChannel ID: "); Serial.println(response);
}
else{
Serial.println("\tNETWORK ERROR!");
}
delay(200);
}
const char* int_str(int d)
{
s = " ";
sprintf(buffer, "%d", d);
s=buffer;
return s;
}
const char* float_str(float d)
{
s = " ";
sprintf(buffer, "%.02f", d);
s=buffer;
return s;
}
| [
"gustavobelbruno@gmail.com"
] | gustavobelbruno@gmail.com |
7e849e05081a5e8e4af8b2d24218465beb8fa89b | acfa86a0764bf5e7641c43e75255e5d38af0f73c | /main/structures/Matrix3.h | d5deaa4ea19e00fce223ff6f5d9104375df07714 | [
"MIT"
] | permissive | andrewwang101/kite | 9e58821e6fcb634f6fab9cb24bab0e04cab145ca | f33ee5d98330faa101b230bbb7ec2eb07526223a | refs/heads/master | 2023-07-18T22:08:54.363770 | 2021-07-02T18:42:13 | 2021-07-02T18:42:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 872 | h | //
// Created by Leonard Koll on 19.05.21.
//
#ifndef KITE_MATRIX3_H
#define KITE_MATRIX3_H
#include <array>
using namespace std;
class Matrix3 {
public:
static float get (array<float, 9>& m, int row, int col);
static void set (array<float, 9>& m, int row, int col, float value);
static array<float, 3> get (array<float, 9>& m, int index, bool colwise);
static void set (array<float, 9>& m, int index, bool colwise, array<float, 3>& v);
static void normalize(array<float, 9>& m);
static array<float, 9> multiply(array<float, 9>& m1, array<float, 9>& m2);
static array<float, 3> multiply(array<float, 9>& m, array<float, 3>& v);
static array<float, 9> transpose_right_multiply(array<float, 9>& m1, array<float, 9>& m2);
static array<float, 3> transpose_multiply(array<float, 9>& m, array<float, 3>& v);
};
#endif //KITE_MATRIX3_H
| [
"leonard.koll@netlight.com"
] | leonard.koll@netlight.com |
34c51c6c041ae5047c32456404a7d8694630fa96 | 12d85105c5260fb35e2352bbc18cce9953f7133c | /first-homework/include/Ball.hpp | 06136daeeaa33dd54e271d3914dcc614b31ed5e1 | [] | no_license | evrenvural/data-scientist-homework | bb48500d880dbef43ca3dcca3e43968f0a42209a | d53bd12ed6d2b12bba7ec0ef9846e5b1bc34e4db | refs/heads/master | 2020-12-08T23:57:46.069348 | 2020-01-10T21:17:29 | 2020-01-10T21:17:29 | 233,130,348 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 220 | hpp | #ifndef BALL_HPP
#define BALL_HPP
using namespace std;
#include <iostream>
#include <stdlib.h> /* srand, rand */
class Ball{
private:
char value;
public:
Ball();
~Ball();
char getValue();
};
#endif
| [
"evrenvural4@gmail.com"
] | evrenvural4@gmail.com |
0d8f0f722b754e687ed33a93c690bc82583d79b8 | 51635684d03e47ebad12b8872ff469b83f36aa52 | /external/gcc-12.1.0/libstdc++-v3/testsuite/20_util/unique_ptr/cons/ptr_deleter_neg.cc | 1a5a26c0b47a6ae71471557081accffdc23e7d86 | [
"LGPL-2.1-only",
"GPL-3.0-only",
"GCC-exception-3.1",
"GPL-2.0-only",
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"Zlib",
"LicenseRef-scancode-public-domain"
] | permissive | zhmu/ananas | 8fb48ddfe3582f85ff39184fc7a3c58725fe731a | 30850c1639f03bccbfb2f2b03361792cc8fae52e | refs/heads/master | 2022-06-25T10:44:46.256604 | 2022-06-12T17:04:40 | 2022-06-12T17:04:40 | 30,108,381 | 59 | 8 | Zlib | 2021-09-26T17:30:30 | 2015-01-31T09:44:33 | C | UTF-8 | C++ | false | false | 1,485 | cc | // { dg-do compile { target c++11 } }
// Copyright (C) 2010-2022 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 20.7.1 Class template unique_ptr [unique.ptr]
#include <memory>
using std::unique_ptr;
void
test01()
{
unique_ptr<long, void(*)(long*)> p1; // { dg-error "no matching" }
unique_ptr<short, void(*)(short*)> p2(nullptr); // { dg-error "no matching" }
unique_ptr<int, void(*)(int*)> p3(new int); // { dg-error "no matching" }
}
void
test02()
{
unique_ptr<long[], void(*)(long*)> p1; // { dg-error "no matching" }
unique_ptr<short[], void(*)(short*)> p2(nullptr); // { dg-error "no matching" }
unique_ptr<int[], void(*)(int*)> p3(new int[1]); // { dg-error "no matching" }
}
int
main()
{
test01();
test02();
return 0;
}
// { dg-prune-output "enable_if" }
| [
"rink@rink.nu"
] | rink@rink.nu |
27f6d2a297bf0617ca54202b83c01cd1dd4211b3 | 289288d0bf3f0d03fd590946c1c1f293aaf75726 | /Plugins/BlueprintAssist/Source/BlueprintAssist/GraphFormatters/AnimationGraphFormatter.cpp | 138f9bd9293df738590db6c6ef4c0a8d58e848bf | [] | no_license | BlenderGamer/PitchSample | 4722d9a37875ef23f0a84d1ddb824e46551c7170 | 52fa8941982e36c7cfae043e6d239d46333ed6b9 | refs/heads/master | 2023-02-25T16:57:22.260228 | 2021-02-02T14:42:35 | 2021-02-02T14:42:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 409 | cpp | // Copyright 2020 fpwong, Inc. All Rights Reserved.
#include "AnimationGraphFormatter.h"
FAnimationGraphFormatter::FAnimationGraphFormatter(const TSharedPtr<FBAGraphHandler>& InGraphHandler)
: FSimpleFormatter(InGraphHandler)
{
FormatterDirection = EGPD_Input;
}
FBAFormatterSettings FAnimationGraphFormatter::GetFormatterSettings()
{
return GetDefault<UBASettings>()->AnimationGraphFormatterSettings;
} | [
"77409105+Dmonics@users.noreply.github.com"
] | 77409105+Dmonics@users.noreply.github.com |
a91101ccae1d07e74cf77190410660e5865f928e | f4bbb7466cd386709bc9f5f66d47333ca2b16ed9 | /solutions/723-candy-crush/candy-crush.cpp | 4e1e613858eba469b850e2cb50ab74a5e81168a4 | [] | no_license | fr42k/leetcode | 790d4eeaafeb9f6af8471ee4f245c0bab5d5198a | de3455d82241d142ccb43c9e719defca7bf3ebd5 | refs/heads/master | 2022-11-05T15:47:50.778505 | 2022-10-22T03:38:49 | 2022-10-22T03:38:49 | 133,931,381 | 4 | 0 | null | 2018-05-18T09:12:48 | 2018-05-18T09:12:48 | null | UTF-8 | C++ | false | false | 3,561 | cpp | // This question is about implementing a basic elimination algorithm for Candy Crush.
//
// Given a 2D integer array board representing the grid of candy, different positive integers board[i][j] represent different types of candies. A value of board[i][j] = 0 represents that the cell at position (i, j) is empty. The given board represents the state of the game following the player's move. Now, you need to restore the board to a stable state by crushing candies according to the following rules:
//
//
// If three or more candies of the same type are adjacent vertically or horizontally, "crush" them all at the same time - these positions become empty.
// After crushing all candies simultaneously, if an empty space on the board has candies on top of itself, then these candies will drop until they hit a candy or bottom at the same time. (No new candies will drop outside the top boundary.)
// After the above steps, there may exist more candies that can be crushed. If so, you need to repeat the above steps.
// If there does not exist more candies that can be crushed (ie. the board is stable), then return the current board.
//
//
// You need to perform the above rules until the board becomes stable, then return the current board.
//
//
//
// Example:
//
//
// Input:
// board =
// [[110,5,112,113,114],[210,211,5,213,214],[310,311,3,313,314],[410,411,412,5,414],[5,1,512,3,3],[610,4,1,613,614],[710,1,2,713,714],[810,1,2,1,1],[1,1,2,2,2],[4,1,4,4,1014]]
//
// Output:
// [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[110,0,0,0,114],[210,0,0,0,214],[310,0,0,113,314],[410,0,0,213,414],[610,211,112,313,614],[710,311,412,613,714],[810,411,512,713,1014]]
//
// Explanation:
//
//
//
//
//
// Note:
//
//
// The length of board will be in the range [3, 50].
// The length of board[i] will be in the range [3, 50].
// Each board[i][j] will initially start as an integer in the range [1, 2000].
//
//
class Solution {
public:
vector<vector<int>> candyCrush(vector<vector<int>>& board) {
int m = board.size(), n = board[0].size();
bool found = true;
while (found) {
found = false;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 0) continue;
int val = abs(board[i][j]);
if (i + 2 < m && abs(board[i + 1][j]) == val && abs(board[i + 2][j]) == val) {
found = true;
int idx = i;
while (idx < m && abs(board[idx][j]) == val) {
board[idx++][j] = -val;
}
}
if (j + 2 < n && abs(board[i][j + 1]) == val && abs(board[i][j + 2]) == val) {
found = true;
int idx = j;
while (idx < n && abs(board[i][idx]) == val) {
board[i][idx++] = -val;
}
}
}
}
if (found) {
for (int j = 0; j < n; j++) {
int idx = m - 1;
for (int i = m - 1; i >= 0; i--) {
if (board[i][j] > 0) {
board[idx--][j] = board[i][j];
}
}
while (idx >= 0) {
board[idx--][j] = 0;
}
}
}
}
return board;
}
};
| [
"fr42k@yahoo.com"
] | fr42k@yahoo.com |
1927cea649feac762dbb617c3d69ddd4bb8bd2be | b487b9f5e05a100a20ae6662e359f002c44efc27 | /src/qt/bitcoingui.h | 247c97bcc66ac413e0a55d7c546e1f785d872771 | [
"MIT"
] | permissive | blacksteven/flowercoin | 5056715a251774c19eeb18a2ed5f8e0fc7367c91 | b200f4305b8e1df422d485e6b1be800f0b8add86 | refs/heads/main | 2023-02-25T03:05:49.410463 | 2021-01-31T04:22:46 | 2021-01-31T04:22:46 | 334,570,971 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,228 | h | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2017-2018 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_BITCOINGUI_H
#define BITCOIN_QT_BITCOINGUI_H
#if defined(HAVE_CONFIG_H)
#include "config/flowercoin-config.h"
#endif
#include "amount.h"
#include <QLabel>
#include <QMainWindow>
#include <QMap>
#include <QMenu>
#include <QPoint>
#include <QPushButton>
#include <QSystemTrayIcon>
class ClientModel;
class NetworkStyle;
class Notificator;
class OptionsModel;
class BlockExplorer;
class RPCConsole;
class SendCoinsRecipient;
class UnitDisplayStatusBarControl;
class WalletFrame;
class WalletModel;
class MasternodeList;
class CWallet;
QT_BEGIN_NAMESPACE
class QAction;
class QProgressBar;
class QProgressDialog;
QT_END_NAMESPACE
/**
Bitcoin GUI main class. This class represents the main window of the Bitcoin UI. It communicates with both the client and
wallet models to give the user an up-to-date view of the current core state.
*/
class BitcoinGUI : public QMainWindow
{
Q_OBJECT
public:
static const QString DEFAULT_WALLET;
explicit BitcoinGUI(const NetworkStyle* networkStyle, QWidget* parent = 0);
~BitcoinGUI();
/** Set the client model.
The client model represents the part of the core that communicates with the P2P network, and is wallet-agnostic.
*/
void setClientModel(ClientModel* clientModel);
#ifdef ENABLE_WALLET
/** Set the wallet model.
The wallet model represents a bitcoin wallet, and offers access to the list of transactions, address book and sending
functionality.
*/
bool addWallet(const QString& name, WalletModel* walletModel);
bool setCurrentWallet(const QString& name);
void removeAllWallets();
#endif // ENABLE_WALLET
bool enableWallet;
bool fMultiSend = false;
protected:
void changeEvent(QEvent* e);
void closeEvent(QCloseEvent* event);
void dragEnterEvent(QDragEnterEvent* event);
void dropEvent(QDropEvent* event);
bool eventFilter(QObject* object, QEvent* event);
private:
ClientModel* clientModel;
WalletFrame* walletFrame;
UnitDisplayStatusBarControl* unitDisplayControl;
QLabel* labelStakingIcon;
QPushButton* labelEncryptionIcon;
QPushButton* labelConnectionsIcon;
QLabel* labelBlocksIcon;
QLabel* progressBarLabel;
QProgressBar* progressBar;
QProgressDialog* progressDialog;
QMenuBar* appMenuBar;
QAction* overviewAction;
QAction* historyAction;
QAction* masternodeAction;
QAction* quitAction;
QAction* sendCoinsAction;
QAction* usedSendingAddressesAction;
QAction* usedReceivingAddressesAction;
QAction* signMessageAction;
QAction* verifyMessageAction;
QAction* bip38ToolAction;
QAction* multisigCreateAction;
QAction* multisigSpendAction;
QAction* multisigSignAction;
QAction* aboutAction;
QAction* receiveCoinsAction;
QAction* optionsAction;
QAction* toggleHideAction;
QAction* encryptWalletAction;
QAction* backupWalletAction;
QAction* changePassphraseAction;
QAction* unlockWalletAction;
QAction* lockWalletAction;
QAction* aboutQtAction;
QAction* openInfoAction;
QAction* openRPCConsoleAction;
QAction* openNetworkAction;
QAction* openPeersAction;
QAction* openRepairAction;
QAction* openConfEditorAction;
QAction* openMNConfEditorAction;
QAction* showBackupsAction;
QAction* openAction;
QAction* openBlockExplorerAction;
QAction* showHelpMessageAction;
QAction* multiSendAction;
QSystemTrayIcon* trayIcon;
QMenu* trayIconMenu;
Notificator* notificator;
RPCConsole* rpcConsole;
BlockExplorer* explorerWindow;
/** Keep track of previous number of blocks, to detect progress */
int prevBlocks;
int spinnerFrame;
/** Create the main UI actions. */
void createActions(const NetworkStyle* networkStyle);
/** Create the menu bar and sub-menus. */
void createMenuBar();
/** Create the toolbars */
void createToolBars();
/** Create system tray icon and notification */
void createTrayIcon(const NetworkStyle* networkStyle);
/** Create system tray menu (or setup the dock menu) */
void createTrayIconMenu();
/** Enable or disable all wallet-related actions */
void setWalletActionsEnabled(bool enabled);
/** Connect core signals to GUI client */
void subscribeToCoreSignals();
/** Disconnect core signals from GUI client */
void unsubscribeFromCoreSignals();
signals:
/** Signal raised when a URI was entered or dragged to the GUI */
void receivedURI(const QString& uri);
/** Restart handling */
void requestedRestart(QStringList args);
public slots:
/** Set number of connections shown in the UI */
void setNumConnections(int count);
/** Set number of blocks shown in the UI */
void setNumBlocks(int count);
/** Get restart command-line parameters and request restart */
void handleRestart(QStringList args);
/** Notify the user of an event from the core network or transaction handling code.
@param[in] title the message box / notification title
@param[in] message the displayed text
@param[in] style modality and style definitions (icon and used buttons - buttons only for message boxes)
@see CClientUIInterface::MessageBoxFlags
@param[in] ret pointer to a bool that will be modified to whether Ok was clicked (modal only)
*/
void message(const QString& title, const QString& message, unsigned int style, bool* ret = NULL);
#ifdef ENABLE_WALLET
void setStakingStatus();
/** Set the encryption status as shown in the UI.
@param[in] status current encryption status
@see WalletModel::EncryptionStatus
*/
void setEncryptionStatus(int status);
bool handlePaymentRequest(const SendCoinsRecipient& recipient);
/** Show incoming transaction notification for new transactions. */
void incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address);
#endif // ENABLE_WALLET
private slots:
#ifdef ENABLE_WALLET
/** Switch to overview (home) page */
void gotoOverviewPage();
/** Switch to history (transactions) page */
void gotoHistoryPage();
/** Switch to Explorer Page */
void gotoBlockExplorerPage();
/** Switch to masternode page */
void gotoMasternodePage();
/** Switch to receive coins page */
void gotoReceiveCoinsPage();
/** Switch to send coins page */
void gotoSendCoinsPage(QString addr = "");
/** Show Sign/Verify Message dialog and switch to sign message tab */
void gotoSignMessageTab(QString addr = "");
/** Show Sign/Verify Message dialog and switch to verify message tab */
void gotoVerifyMessageTab(QString addr = "");
/** Show MultiSend Dialog */
void gotoMultiSendDialog();
/** Show MultiSig Dialog */
void gotoMultisigCreate();
void gotoMultisigSpend();
void gotoMultisigSign();
/** Show BIP 38 tool - default to Encryption tab */
void gotoBip38Tool();
/** Show open dialog */
void openClicked();
#endif // ENABLE_WALLET
/** Show configuration dialog */
void optionsClicked();
/** Show about dialog */
void aboutClicked();
/** Show help message dialog */
void showHelpMessageClicked();
#ifndef Q_OS_MAC
/** Handle tray icon clicked */
void trayIconActivated(QSystemTrayIcon::ActivationReason reason);
#endif
/** Show window if hidden, unminimize when minimized, rise when obscured or show if hidden and fToggleHidden is true */
void showNormalIfMinimized(bool fToggleHidden = false);
/** Simply calls showNormalIfMinimized(true) for use in SLOT() macro */
void toggleHidden();
/** called by a timer to check if fRequestShutdown has been set **/
void detectShutdown();
/** Show progress dialog e.g. for verifychain */
void showProgress(const QString& title, int nProgress);
};
class UnitDisplayStatusBarControl : public QLabel
{
Q_OBJECT
public:
explicit UnitDisplayStatusBarControl();
/** Lets the control know about the Options Model (and its signals) */
void setOptionsModel(OptionsModel* optionsModel);
protected:
/** So that it responds to left-button clicks */
void mousePressEvent(QMouseEvent* event);
private:
OptionsModel* optionsModel;
QMenu* menu;
/** Shows context menu with Display Unit options by the mouse coordinates */
void onDisplayUnitsClicked(const QPoint& point);
/** Creates context menu, its actions, and wires up all the relevant signals for mouse events. */
void createContextMenu();
private slots:
/** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar */
void updateDisplayUnit(int newUnits);
/** Tells underlying optionsModel to update its current display unit. */
void onMenuSelection(QAction* action);
};
#endif // BITCOIN_QT_BITCOINGUI_H
| [
"sofa.somse@gmail.com"
] | sofa.somse@gmail.com |
90d48ae9d2f86692f1b36fcaaead63c0cfe44796 | 8a7219b0345e71a7e30227c1fc88455558151a52 | /Engine/Utils/Types/Profiler.h | 2dd149a58bae6d60cfb448b65e8e4b49c9f9b8ab | [] | no_license | sorcerer-com/MCS | eed1771bec6c3035e8a34c5ffe4a3c237dd7f8dc | 8f5787072e59c6365fba35c48936189af28fd199 | refs/heads/master | 2020-03-30T19:06:05.352121 | 2015-11-05T12:51:54 | 2015-11-05T12:51:54 | 25,826,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,532 | h | // Image.h
#pragma once
#include <chrono>
#include <mutex>
#include "..\..\Engine.h"
namespace MyEngine {
#define Profile Profiler prof(__FUNCTION__)
#define ProfileLog Profiler prof(__FUNCTION__, true)
string duration_to_string(chrono::system_clock::duration delta);
struct Profiler
{
private:
string name;
bool log;
chrono::system_clock::time_point time;
public:
Profiler()
{
if (Engine::Mode == EngineMode::EEngine)
return;
this->name = "";
this->log = false;
}
Profiler(const string& name, bool log = false)
{
if (Engine::Mode == EngineMode::EEngine)
return;
this->name = name;
this->log = log;
this->start();
}
~Profiler()
{
lock_guard<mutex> lck(Profiler::dataMutex);
if (Engine::Mode == EngineMode::EEngine || this->name == "")
return;
chrono::system_clock::duration delta = this->stop();
Profiler::data[this->name].deltaSum += delta;
Profiler::data[this->name].counter++;
if (this->log)
Engine::Log(LogType::ELog, "Profiler", this->name + " (" + duration_to_string(delta) + ")");
}
inline void start()
{
this->time = chrono::system_clock::now();
}
inline chrono::system_clock::duration stop()
{
if (this->time == chrono::system_clock::time_point())
return chrono::system_clock::duration();
chrono::system_clock::duration delta = chrono::system_clock::now() - this->time;
this->time = chrono::system_clock::now();
return delta;
}
inline chrono::system_clock::duration duration()
{
if (this->time == chrono::system_clock::time_point())
return chrono::system_clock::duration();
return chrono::system_clock::now() - this->time;
}
private:
struct Data
{
chrono::system_clock::duration deltaSum;
int counter;
Data()
{
deltaSum = chrono::system_clock::duration();
counter = 0;
}
};
static map<string, Data> data;
static mutex dataMutex;
public:
static map<string, long long> GetDurations()
{
lock_guard<mutex> lck(Profiler::dataMutex);
map<string, long long> durations;
for (auto& d : data)
{
long long milisecs = chrono::duration_cast<chrono::milliseconds>(d.second.deltaSum).count();
durations[d.first] = milisecs / d.second.counter;
}
return durations;
}
};
inline string duration_to_string(chrono::system_clock::duration delta)
{
int hours = chrono::duration_cast<chrono::hours>(delta).count();
int minutes = chrono::duration_cast<chrono::minutes>(delta).count();
long long seconds = chrono::duration_cast<chrono::seconds>(delta).count();
long long milisecs = chrono::duration_cast<chrono::milliseconds>(delta).count();
milisecs -= seconds * 1000;
seconds -= minutes * 60;
minutes -= hours * 60;
return to_string(hours) + "h " + to_string(minutes) + "min " + to_string(seconds) + "sec " + to_string(milisecs) + "milisec";
}
} | [
"sorcerer_com@abv.bg"
] | sorcerer_com@abv.bg |
93082705db9614d40f7b8bd7936fec5eb0577da1 | 64178ab5958c36c4582e69b6689359f169dc6f0d | /vscode/wg/sdk/UBP_InteractionWidget_C.hpp | 2bc8d95b371f79be15791138d55e6d8617373619 | [] | no_license | c-ber/cber | 47bc1362f180c9e8f0638e40bf716d8ec582e074 | 3cb5c85abd8a6be09e0283d136c87761925072de | refs/heads/master | 2023-06-07T20:07:44.813723 | 2023-02-28T07:43:29 | 2023-02-28T07:43:29 | 40,457,301 | 5 | 5 | null | 2023-05-30T19:14:51 | 2015-08-10T01:37:22 | C++ | UTF-8 | C++ | false | false | 12,694 | hpp | #pragma once
#include "UInteractionBaseWidget.hpp"
#ifdef _MSC_VER
#pragma pack(push, 1)
#endif
namespace PUBGSDK {
struct alignas(1) UBP_InteractionWidget_C // Size: 0x638
: public UInteractionBaseWidget // Size: 0x590
{
private:
typedef UBP_InteractionWidget_C t_struct;
typedef ExternalPtr<t_struct> t_structHelper;
public:
static ExternalPtr<struct UClass> StaticClass()
{
static ExternalPtr<struct UClass> ptr;
if(!ptr) ptr = UObject::FindClassFast(184908); // id32("WidgetBlueprintGeneratedClass BP_InteractionWidget.BP_InteractionWidget_C")
return ptr;
}
ExternalPtr<struct UWidgetAnimation> InteractionUnavaliableLooping; /* Ofs: 0x590 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.InteractionUnavaliableLooping */
ExternalPtr<struct UWidgetAnimation> InteractionUnavaliableVanishing; /* Ofs: 0x598 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.InteractionUnavaliableVanishing */
ExternalPtr<struct UWidgetAnimation> InteractionUnavaliableEmerging; /* Ofs: 0x5A0 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.InteractionUnavaliableEmerging */
ExternalPtr<struct UWidgetAnimation> ResetItemSwitchAnimation; /* Ofs: 0x5A8 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.ResetItemSwitchAnimation */
ExternalPtr<struct UWidgetAnimation> ItemSwitchAnimation; /* Ofs: 0x5B0 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.ItemSwitchAnimation */
ExternalPtr<struct UWidgetAnimation> AdditionalMessageVanishing; /* Ofs: 0x5B8 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.AdditionalMessageVanishing */
ExternalPtr<struct UWidgetAnimation> AdditionalMessageEmerging; /* Ofs: 0x5C0 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.AdditionalMessageEmerging */
ExternalPtr<struct UWidgetAnimation> AdditionalMessageNormal; /* Ofs: 0x5C8 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.AdditionalMessageNormal */
ExternalPtr<struct UWidgetAnimation> AdditionalMessageBlinking; /* Ofs: 0x5D0 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.AdditionalMessageBlinking */
ExternalPtr<struct UWidgetAnimation> Vanishing; /* Ofs: 0x5D8 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.Vanishing */
ExternalPtr<struct UWidgetAnimation> show; /* Ofs: 0x5E0 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.show */
ExternalPtr<struct UWidgetAnimation> Default; /* Ofs: 0x5E8 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.Default */
ExternalPtr<struct UImage> Image_2; /* Ofs: 0x5F0 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.Image_2 */
ExternalPtr<struct UImage> Image_6; /* Ofs: 0x5F8 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.Image_6 */
ExternalPtr<struct UImage> Image_7; /* Ofs: 0x600 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.Image_7 */
ExternalPtr<struct UImage> Image_157; /* Ofs: 0x608 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.Image_157 */
ExternalPtr<struct UBorder> InteractionBorder; /* Ofs: 0x610 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.InteractionBorder */
ExternalPtr<struct UImage> InteractionKeyImage_Left; /* Ofs: 0x618 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.InteractionKeyImage_Left */
ExternalPtr<struct UImage> InteractionKeyImage_Right; /* Ofs: 0x620 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.InteractionKeyImage_Right */
ExternalPtr<struct UImage> ProgressCircle; /* Ofs: 0x628 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.ProgressCircle */
ExternalPtr<struct UImage> ProgressCircleBg; /* Ofs: 0x630 Size: 0x8 - ObjectProperty BP_InteractionWidget.BP_InteractionWidget_C.ProgressCircleBg */
inline bool SetInteractionUnavaliableLooping(t_structHelper inst, ExternalPtr<struct UWidgetAnimation> value) { inst.WriteOffset(0x590, value); }
inline bool SetInteractionUnavaliableVanishing(t_structHelper inst, ExternalPtr<struct UWidgetAnimation> value) { inst.WriteOffset(0x598, value); }
inline bool SetInteractionUnavaliableEmerging(t_structHelper inst, ExternalPtr<struct UWidgetAnimation> value) { inst.WriteOffset(0x5A0, value); }
inline bool SetResetItemSwitchAnimation(t_structHelper inst, ExternalPtr<struct UWidgetAnimation> value) { inst.WriteOffset(0x5A8, value); }
inline bool SetItemSwitchAnimation(t_structHelper inst, ExternalPtr<struct UWidgetAnimation> value) { inst.WriteOffset(0x5B0, value); }
inline bool SetAdditionalMessageVanishing(t_structHelper inst, ExternalPtr<struct UWidgetAnimation> value) { inst.WriteOffset(0x5B8, value); }
inline bool SetAdditionalMessageEmerging(t_structHelper inst, ExternalPtr<struct UWidgetAnimation> value) { inst.WriteOffset(0x5C0, value); }
inline bool SetAdditionalMessageNormal(t_structHelper inst, ExternalPtr<struct UWidgetAnimation> value) { inst.WriteOffset(0x5C8, value); }
inline bool SetAdditionalMessageBlinking(t_structHelper inst, ExternalPtr<struct UWidgetAnimation> value) { inst.WriteOffset(0x5D0, value); }
inline bool SetVanishing(t_structHelper inst, ExternalPtr<struct UWidgetAnimation> value) { inst.WriteOffset(0x5D8, value); }
inline bool Setshow(t_structHelper inst, ExternalPtr<struct UWidgetAnimation> value) { inst.WriteOffset(0x5E0, value); }
inline bool SetDefault(t_structHelper inst, ExternalPtr<struct UWidgetAnimation> value) { inst.WriteOffset(0x5E8, value); }
inline bool SetImage_2(t_structHelper inst, ExternalPtr<struct UImage> value) { inst.WriteOffset(0x5F0, value); }
inline bool SetImage_6(t_structHelper inst, ExternalPtr<struct UImage> value) { inst.WriteOffset(0x5F8, value); }
inline bool SetImage_7(t_structHelper inst, ExternalPtr<struct UImage> value) { inst.WriteOffset(0x600, value); }
inline bool SetImage_157(t_structHelper inst, ExternalPtr<struct UImage> value) { inst.WriteOffset(0x608, value); }
inline bool SetInteractionBorder(t_structHelper inst, ExternalPtr<struct UBorder> value) { inst.WriteOffset(0x610, value); }
inline bool SetInteractionKeyImage_Left(t_structHelper inst, ExternalPtr<struct UImage> value) { inst.WriteOffset(0x618, value); }
inline bool SetInteractionKeyImage_Right(t_structHelper inst, ExternalPtr<struct UImage> value) { inst.WriteOffset(0x620, value); }
inline bool SetProgressCircle(t_structHelper inst, ExternalPtr<struct UImage> value) { inst.WriteOffset(0x628, value); }
inline bool SetProgressCircleBg(t_structHelper inst, ExternalPtr<struct UImage> value) { inst.WriteOffset(0x630, value); }
};
#ifdef VALIDATE_SDK
namespace Validation{
auto constexpr sizeofUBP_InteractionWidget_C = sizeof(UBP_InteractionWidget_C); // 1592
static_assert(sizeof(UBP_InteractionWidget_C) == 0x638, "Size of UBP_InteractionWidget_C is not correct.");
auto constexpr UBP_InteractionWidget_C_InteractionUnavaliableLooping_Offset = offsetof(UBP_InteractionWidget_C, InteractionUnavaliableLooping);
static_assert(UBP_InteractionWidget_C_InteractionUnavaliableLooping_Offset == 0x590, "UBP_InteractionWidget_C::InteractionUnavaliableLooping offset is not 590");
auto constexpr UBP_InteractionWidget_C_InteractionUnavaliableVanishing_Offset = offsetof(UBP_InteractionWidget_C, InteractionUnavaliableVanishing);
static_assert(UBP_InteractionWidget_C_InteractionUnavaliableVanishing_Offset == 0x598, "UBP_InteractionWidget_C::InteractionUnavaliableVanishing offset is not 598");
auto constexpr UBP_InteractionWidget_C_InteractionUnavaliableEmerging_Offset = offsetof(UBP_InteractionWidget_C, InteractionUnavaliableEmerging);
static_assert(UBP_InteractionWidget_C_InteractionUnavaliableEmerging_Offset == 0x5a0, "UBP_InteractionWidget_C::InteractionUnavaliableEmerging offset is not 5a0");
auto constexpr UBP_InteractionWidget_C_ResetItemSwitchAnimation_Offset = offsetof(UBP_InteractionWidget_C, ResetItemSwitchAnimation);
static_assert(UBP_InteractionWidget_C_ResetItemSwitchAnimation_Offset == 0x5a8, "UBP_InteractionWidget_C::ResetItemSwitchAnimation offset is not 5a8");
auto constexpr UBP_InteractionWidget_C_ItemSwitchAnimation_Offset = offsetof(UBP_InteractionWidget_C, ItemSwitchAnimation);
static_assert(UBP_InteractionWidget_C_ItemSwitchAnimation_Offset == 0x5b0, "UBP_InteractionWidget_C::ItemSwitchAnimation offset is not 5b0");
auto constexpr UBP_InteractionWidget_C_AdditionalMessageVanishing_Offset = offsetof(UBP_InteractionWidget_C, AdditionalMessageVanishing);
static_assert(UBP_InteractionWidget_C_AdditionalMessageVanishing_Offset == 0x5b8, "UBP_InteractionWidget_C::AdditionalMessageVanishing offset is not 5b8");
auto constexpr UBP_InteractionWidget_C_AdditionalMessageEmerging_Offset = offsetof(UBP_InteractionWidget_C, AdditionalMessageEmerging);
static_assert(UBP_InteractionWidget_C_AdditionalMessageEmerging_Offset == 0x5c0, "UBP_InteractionWidget_C::AdditionalMessageEmerging offset is not 5c0");
auto constexpr UBP_InteractionWidget_C_AdditionalMessageNormal_Offset = offsetof(UBP_InteractionWidget_C, AdditionalMessageNormal);
static_assert(UBP_InteractionWidget_C_AdditionalMessageNormal_Offset == 0x5c8, "UBP_InteractionWidget_C::AdditionalMessageNormal offset is not 5c8");
auto constexpr UBP_InteractionWidget_C_AdditionalMessageBlinking_Offset = offsetof(UBP_InteractionWidget_C, AdditionalMessageBlinking);
static_assert(UBP_InteractionWidget_C_AdditionalMessageBlinking_Offset == 0x5d0, "UBP_InteractionWidget_C::AdditionalMessageBlinking offset is not 5d0");
auto constexpr UBP_InteractionWidget_C_Vanishing_Offset = offsetof(UBP_InteractionWidget_C, Vanishing);
static_assert(UBP_InteractionWidget_C_Vanishing_Offset == 0x5d8, "UBP_InteractionWidget_C::Vanishing offset is not 5d8");
auto constexpr UBP_InteractionWidget_C_show_Offset = offsetof(UBP_InteractionWidget_C, show);
static_assert(UBP_InteractionWidget_C_show_Offset == 0x5e0, "UBP_InteractionWidget_C::show offset is not 5e0");
auto constexpr UBP_InteractionWidget_C_Default_Offset = offsetof(UBP_InteractionWidget_C, Default);
static_assert(UBP_InteractionWidget_C_Default_Offset == 0x5e8, "UBP_InteractionWidget_C::Default offset is not 5e8");
auto constexpr UBP_InteractionWidget_C_Image_2_Offset = offsetof(UBP_InteractionWidget_C, Image_2);
static_assert(UBP_InteractionWidget_C_Image_2_Offset == 0x5f0, "UBP_InteractionWidget_C::Image_2 offset is not 5f0");
auto constexpr UBP_InteractionWidget_C_Image_6_Offset = offsetof(UBP_InteractionWidget_C, Image_6);
static_assert(UBP_InteractionWidget_C_Image_6_Offset == 0x5f8, "UBP_InteractionWidget_C::Image_6 offset is not 5f8");
auto constexpr UBP_InteractionWidget_C_Image_7_Offset = offsetof(UBP_InteractionWidget_C, Image_7);
static_assert(UBP_InteractionWidget_C_Image_7_Offset == 0x600, "UBP_InteractionWidget_C::Image_7 offset is not 600");
auto constexpr UBP_InteractionWidget_C_Image_157_Offset = offsetof(UBP_InteractionWidget_C, Image_157);
static_assert(UBP_InteractionWidget_C_Image_157_Offset == 0x608, "UBP_InteractionWidget_C::Image_157 offset is not 608");
auto constexpr UBP_InteractionWidget_C_InteractionBorder_Offset = offsetof(UBP_InteractionWidget_C, InteractionBorder);
static_assert(UBP_InteractionWidget_C_InteractionBorder_Offset == 0x610, "UBP_InteractionWidget_C::InteractionBorder offset is not 610");
auto constexpr UBP_InteractionWidget_C_InteractionKeyImage_Left_Offset = offsetof(UBP_InteractionWidget_C, InteractionKeyImage_Left);
static_assert(UBP_InteractionWidget_C_InteractionKeyImage_Left_Offset == 0x618, "UBP_InteractionWidget_C::InteractionKeyImage_Left offset is not 618");
auto constexpr UBP_InteractionWidget_C_InteractionKeyImage_Right_Offset = offsetof(UBP_InteractionWidget_C, InteractionKeyImage_Right);
static_assert(UBP_InteractionWidget_C_InteractionKeyImage_Right_Offset == 0x620, "UBP_InteractionWidget_C::InteractionKeyImage_Right offset is not 620");
auto constexpr UBP_InteractionWidget_C_ProgressCircle_Offset = offsetof(UBP_InteractionWidget_C, ProgressCircle);
static_assert(UBP_InteractionWidget_C_ProgressCircle_Offset == 0x628, "UBP_InteractionWidget_C::ProgressCircle offset is not 628");
auto constexpr UBP_InteractionWidget_C_ProgressCircleBg_Offset = offsetof(UBP_InteractionWidget_C, ProgressCircleBg);
static_assert(UBP_InteractionWidget_C_ProgressCircleBg_Offset == 0x630, "UBP_InteractionWidget_C::ProgressCircleBg offset is not 630");
}
#endif
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"1395329153@qq.com"
] | 1395329153@qq.com |
38d488e5f60bd8469e70a6921db7299641f84951 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /chrome/browser/ash/login/screens/drive_pinning_screen.cc | 74f9c52630a83a57dc7310c892657f093c9763ca | [
"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 | 9,136 | cc | // Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <iomanip>
#include "ash/constants/ash_features.h"
#include "base/check_is_test.h"
#include "base/metrics/histogram_functions.h"
#include "chrome/browser/ash/drive/drive_integration_service.h"
#include "chrome/browser/ash/drive/file_system_util.h"
#include "chrome/browser/ash/login/login_pref_names.h"
#include "chrome/browser/ash/login/screens/drive_pinning_screen.h"
#include "chrome/browser/ash/login/wizard_controller.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/webui/ash/login/drive_pinning_screen_handler.h"
#include "chromeos/ash/components/drivefs/drivefs_pin_manager.h"
#include "components/drive/drive_pref_names.h"
#include "ui/base/text/bytes_formatting.h"
namespace ash {
namespace {
constexpr const char kUserActionNext[] = "driveNext";
constexpr const char kUserActionReturn[] = "return";
using drivefs::pinning::PinManager;
using drivefs::pinning::Progress;
bool ShouldShowChoobeReturnButton(ChoobeFlowController* controller) {
if (!features::IsOobeChoobeEnabled() || !controller) {
return false;
}
return controller->ShouldShowReturnButton(DrivePinningScreenView::kScreenId);
}
void ReportScreenCompletedToChoobe(ChoobeFlowController* controller) {
if (!features::IsOobeChoobeEnabled() || !controller) {
return;
}
controller->OnScreenCompleted(
*ProfileManager::GetActiveUserProfile()->GetPrefs(),
DrivePinningScreenView::kScreenId);
}
PinManager* GetPinManager() {
drive::DriveIntegrationService* const service =
drive::DriveIntegrationServiceFactory::FindForProfile(
ProfileManager::GetActiveUserProfile());
return service && service->IsMounted() ? service->GetPinManager() : nullptr;
}
void RecordOOBEScreenSkippedMetric(drivefs::pinning::Stage stage) {
base::UmaHistogramEnumeration(
"FileBrowser.GoogleDrive.BulkPinning.CHOOBEScreenStage", stage);
}
void RecordCHOOBEScreenBulkPinningInitializations(int initializations) {
base::UmaHistogramCounts100(
"FileBrowser.GoogleDrive.BulkPinning.CHOOBEScreenInitializations",
initializations);
}
void RecordSettingChanged(bool initial, bool current) {
base::UmaHistogramBoolean("OOBE.CHOOBE.SettingChanged.Drive-pinning",
initial != current);
}
void RecordUserSelection(bool option) {
base::UmaHistogramBoolean("OOBE.Drive-pinning.Enabled", option);
}
} // namespace
// static
std::string DrivePinningScreen::GetResultString(Result result) {
switch (result) {
case Result::NEXT:
return "Next";
case Result::NOT_APPLICABLE:
return BaseScreen::kNotApplicable;
}
}
void DrivePinningScreen::ApplyDrivePinningPref(Profile* profile) {
auto* prefs = profile->GetPrefs();
if (!prefs->HasPrefPath(prefs::kOobeDrivePinningEnabledDeferred)) {
return;
}
bool drive_pinning =
profile->GetPrefs()->GetBoolean(prefs::kOobeDrivePinningEnabledDeferred);
profile->GetPrefs()->SetBoolean(drive::prefs::kDriveFsBulkPinningEnabled,
drive_pinning);
drivefs::pinning::RecordBulkPinningEnabledSource(
drivefs::pinning::BulkPinningEnabledSource::kChoobe);
RecordUserSelection(drive_pinning);
prefs->ClearPref(prefs::kOobeDrivePinningEnabledDeferred);
}
DrivePinningScreen::DrivePinningScreen(
base::WeakPtr<DrivePinningScreenView> view,
const ScreenExitCallback& exit_callback)
: BaseScreen(DrivePinningScreenView::kScreenId,
OobeScreenPriority::DEFAULT),
view_(std::move(view)),
exit_callback_(exit_callback) {}
DrivePinningScreen::~DrivePinningScreen() {
Profile* profile = ProfileManager::GetActiveUserProfile();
if (drive::DriveIntegrationService* const service =
drive::DriveIntegrationServiceFactory::FindForProfile(profile)) {
service->RemoveObserver(this);
}
}
bool DrivePinningScreen::ShouldBeSkipped(const WizardContext& context) const {
if (context.skip_post_login_screens_for_tests) {
return true;
}
RecordOOBEScreenSkippedMetric(drive_pinning_stage_);
if (drive_pinning_stage_ != drivefs::pinning::Stage::kSuccess) {
return true;
}
if (features::IsOobeChoobeEnabled()) {
auto* choobe_controller =
WizardController::default_controller()->choobe_flow_controller();
if (choobe_controller && choobe_controller->ShouldScreenBeSkipped(
DrivePinningScreenView::kScreenId)) {
return true;
}
}
return false;
}
bool DrivePinningScreen::MaybeSkip(WizardContext& context) {
if (ShouldBeSkipped(context)) {
exit_callback_.Run(Result::NOT_APPLICABLE);
return true;
}
return false;
}
void DrivePinningScreen::StartCalculatingRequiredSpace() {
if (started_calculating_space_) {
return;
}
started_calculating_space_ = true;
CalculateRequiredSpace();
}
void DrivePinningScreen::CalculateRequiredSpace() {
drive::DriveIntegrationService* const service =
drive::DriveIntegrationServiceFactory::FindForProfile(
ProfileManager::GetActiveUserProfile());
if (!service) {
return;
}
if (!service->HasObserver(this)) {
service->AddObserver(this);
}
if (PinManager* const pin_manager = GetPinManager()) {
RecordCHOOBEScreenBulkPinningInitializations(
bulk_pinning_initializations_ > 0 ? bulk_pinning_initializations_
: ++bulk_pinning_initializations_);
LOG_IF(ERROR, !pin_manager->CalculateRequiredSpace())
<< "Failed to calculate required space";
return;
}
VLOG(1) << "Calculating required space called but manager is not initialized";
}
void DrivePinningScreen::OnProgressForTest(
const drivefs::pinning::Progress& progress) {
CHECK_IS_TEST();
OnBulkPinProgress(progress);
}
void DrivePinningScreen::OnBulkPinProgress(
const drivefs::pinning::Progress& progress) {
drive_pinning_stage_ = progress.stage;
if (progress.stage == drivefs::pinning::Stage::kSuccess) {
VLOG(1) << "Finished calculating required space";
std::u16string free_space = ui::FormatBytes(progress.free_space);
std::u16string required_space = ui::FormatBytes(progress.required_space);
view_->SetRequiredSpaceInfo(required_space, free_space);
}
}
void DrivePinningScreen::OnBulkPinInitialized() {
VLOG_IF(1, !started_calculating_space_)
<< "Bulk pinning initialized, but have not started calculating space";
if (started_calculating_space_) {
CalculateRequiredSpace();
} else {
++bulk_pinning_initializations_;
}
}
void DrivePinningScreen::OnNext(bool drive_pinning) {
Profile* profile = ProfileManager::GetActiveUserProfile();
bool old_value =
profile->GetPrefs()->GetBoolean(prefs::kOobeDrivePinningEnabledDeferred);
RecordSettingChanged(old_value, drive_pinning);
profile->GetPrefs()->SetBoolean(prefs::kOobeDrivePinningEnabledDeferred,
drive_pinning);
exit_callback_.Run(Result::NEXT);
}
void DrivePinningScreen::ShowImpl() {
if (!view_) {
return;
}
base::Value::Dict data;
data.Set(
"shouldShowReturn",
ShouldShowChoobeReturnButton(
WizardController::default_controller()->choobe_flow_controller()));
view_->Show(std::move(data));
}
void DrivePinningScreen::HideImpl() {}
void DrivePinningScreen::OnUserAction(const base::Value::List& args) {
const std::string& action_id = args[0].GetString();
if (action_id == kUserActionNext) {
CHECK_EQ(args.size(), 2u);
ReportScreenCompletedToChoobe(
WizardController::default_controller()->choobe_flow_controller());
const bool drive_pinning = args[1].GetBool();
OnNext(drive_pinning);
return;
}
if (action_id == kUserActionReturn) {
CHECK_EQ(args.size(), 2u);
ReportScreenCompletedToChoobe(
WizardController::default_controller()->choobe_flow_controller());
const bool drive_pinning = args[1].GetBool();
LoginDisplayHost::default_host()
->GetWizardContext()
->return_to_choobe_screen = true;
OnNext(drive_pinning);
return;
}
BaseScreen::OnUserAction(args);
}
std::string DrivePinningScreen::RetrieveChoobeSubtitle() {
Profile* profile = ProfileManager::GetActiveUserProfile();
bool drive_pinning =
profile->GetPrefs()->GetBoolean(prefs::kOobeDrivePinningEnabledDeferred);
if (drive_pinning) {
return "choobeDevicePinningSubtitleEnabled";
}
return "choobeDevicePinningSubtitleDisabled";
}
ScreenSummary DrivePinningScreen::GetScreenSummary() {
ScreenSummary summary;
summary.screen_id = DrivePinningScreenView::kScreenId;
summary.icon_id = "oobe-40:drive-pinning-choobe";
summary.title_id = "choobeDrivePinningTitle";
summary.is_revisitable = true;
summary.is_synced = false;
if (WizardController::default_controller()
->choobe_flow_controller()
->IsScreenCompleted(DrivePinningScreenView::kScreenId)) {
summary.subtitle_resource = RetrieveChoobeSubtitle();
}
return summary;
}
} // namespace ash
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
247721eafe37dfeb6b5b1434e1d13a2b79ee4b3e | f86cd3e4e6f35fc0664b8765b4ea8e1eaf9a4e2c | /client/client/main.cpp | 8878826cc8dc90665eec3ac6e45d18282dda6b39 | [] | no_license | shybovycha/multiplayer-test1 | 3d9275ec6be1eb7ae3e0f5f7ce2ebe5ea710006a | 1a44d09f8d8efc4850e59d73851d4e0bb84b68ea | refs/heads/master | 2020-05-26T21:32:51.782585 | 2014-02-09T01:10:59 | 2014-02-09T01:10:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,037 | cpp | #include <QString>
#include <QStringList>
#include <QMap>
#include <QRegExp>
#include <QDebug>
#include <stdio.h>
#include <vector>
#include <map>
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <SFML/Network.hpp>
#include <SFML/Window.hpp>
#define PLAYER_UPDATE_DELAY 0.02
class Player
{
public:
Player() : position(sf::Vector2f(0, 0))
{
previousPosition = position;
lastUpdateTime = 1.0;
}
Player(const sf::Vector2f &pos) : position(pos)
{
previousPosition = position;
lastUpdateTime = 1.0;
}
void update()
{
if (lastUpdateTime == 0.0)
lastUpdateTime = 1.0;
double t = updateTimer.getElapsedTime().asMilliseconds() / lastUpdateTime;
if (t > 1.0)
t = 1.0;
// position = lerp(previousPosition, position, t);
}
void setPosition(const sf::Vector2f &pos)
{
this->previousPosition = this->position;
this->position = pos;
this->lastUpdateTime = this->updateTimer.getElapsedTime().asMilliseconds();
this->updateTimer.restart();
}
sf::Vector2f getPosition()
{
return this->position;
}
protected:
sf::Vector2f position;
sf::Vector2f previousPosition;
sf::Clock updateTimer;
double lastUpdateTime;
sf::Vector2f lerp(const sf::Vector2f &start, const sf::Vector2f &end, float t)
{
return start + ((end - start) * t);
}
};
class ClientApplication
{
public:
ClientApplication(const QString &playerName, const QString &serverIp, const unsigned short serverPort)
{
this->serverIp = serverIp.toStdString().c_str();
this->serverPort = serverPort;
this->playerName = playerName;
this->players.clear();
this->players[playerName] = new Player();
this->socket = new sf::UdpSocket();
this->socket->setBlocking(false);
this->font = new sf::Font();
this->font->loadFromFile("arial.ttf");
this->isWindowActive = true;
}
void sendingFunc()
{
sf::Clock delayTimer;
while (true)
{
receivingFunc();
if (delayTimer.getElapsedTime().asSeconds() > PLAYER_UPDATE_DELAY)
{
sendAtMessage();
delayTimer.restart();
}
}
}
void receivingFunc()
{
sf::Packet packet;
sf::IpAddress senderIp;
unsigned short senderPort;
sf::Socket::Status status = this->socket->receive(packet, senderIp, senderPort);
if (status != sf::Socket::Done)
{
// qDebug() << "Error";
return;
}
std::string name, command;
packet >> name >> command;
if (name.empty())
return;
qDebug() << QString("[%1] says `%2`").arg(name.c_str()).arg(command.c_str());
QString packetName = name.c_str();
if (players.find(packetName) == players.end())
{
players[packetName] = new Player();
}
if (command == "at")
{
float x, y;
packet >> x >> y;
players[packetName]->setPosition(sf::Vector2f(x, y));
} else if (command == "die")
{
players.remove(packetName);
} else if (command == "ping")
{
sendAtMessage();
}
}
void sendAtMessage()
{
sf::Packet packet;
packet << this->playerName.toStdString() << "at" << this->players[this->playerName]->getPosition().x << this->players[this->playerName]->getPosition().y;
this->socket->send(packet, this->serverIp, this->serverPort);
}
void mainFunc()
{
sendAtMessage();
sf::Thread receivingThread(&ClientApplication::receivingFunc, this);
receivingThread.launch();
sf::Thread sendingThread(&ClientApplication::sendingFunc, this);
sendingThread.launch();
window = new sf::RenderWindow(sf::VideoMode(800, 600), "Multiplayer Client");
while (window->isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window->pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window->close();
if (event.type == sf::Event::LostFocus)
isWindowActive = false;
if (event.type == sf::Event::GainedFocus)
isWindowActive = true;
}
handleUserInput();
render();
}
}
void render()
{
window->clear(sf::Color::Black);
for (int i = 0; i < players.size(); i++)
{
Player *player = players.values().at(i);
if (players.keys().at(i) != this->playerName)
player->update();
sf::CircleShape shape(10.0);
shape.setFillColor(sf::Color(rand() % 255, rand() % 255, rand() % 255));
shape.setOutlineThickness(4.0);
shape.setOutlineColor(sf::Color(50, 200, 25));
shape.setPosition(player->getPosition());
window->draw(shape);
sf::Text text(players.keys().at(i).toStdString(), *this->font);
text.setCharacterSize(10);
text.setPosition(player->getPosition());
window->draw(text);
}
window->display();
}
void handleUserInput()
{
if (!isWindowActive)
return;
sf::Vector2f pos = this->players[this->playerName]->getPosition();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
pos += sf::Vector2f(0, -1);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
pos += sf::Vector2f(0, 1);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
pos += sf::Vector2f(-1, 0);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
pos += sf::Vector2f(1, 0);
this->players[this->playerName]->setPosition(pos);
}
protected:
sf::IpAddress serverIp;
unsigned short serverPort;
sf::UdpSocket *socket;
QString playerName;
QMap<QString, Player*> players;
sf::RenderWindow *window;
sf::Font *font;
bool isWindowActive;
};
int main(int argc, char **argv)
{
QString name;
if (argc < 2)
{
printf("Too few arguments. Usage:\n\t%s [name]\n", argv[0]);
//return 1;
name = QString("player-%1").arg(rand() % 1500);
} else
{
name = QString("player-%1").arg(argv[1]);
}
qDebug() << QString("Starting as %1").arg(name);
ClientApplication *app = new ClientApplication(name, "192.168.1.237", 19501);
app->mainFunc();
return 0;
}
| [
"shybovycha@gmail.com"
] | shybovycha@gmail.com |
5457980123a0e8450f75ff6aac93ac081d4b5451 | 47e7526dfd0f84cf95d4da8f7cbc7143b4742de3 | /libxbkio/include/.svn/text-base/xbkio.h.svn-base | 159d3ee6ce3ce63a93f09675745b2e901b81ae90 | [] | no_license | x-itec/libxbkio | 79b6c07b6c1d409eea3c95e8209013a46d71a2f5 | c0102d9848172ab2307563993ea35678e7eca5f7 | refs/heads/master | 2021-01-23T08:56:52.183576 | 2012-09-06T22:52:07 | 2012-09-06T22:52:07 | null | 0 | 0 | null | null | null | null | ISO-8859-3 | C++ | false | false | 1,119 | #ifndef libxbkioh
#define libxbkioh
#include<string>
#include<stdio.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <vector>
#include <time.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <string.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <map>
#include <iostream>
#include <fstream>
class xbkio_base
{
public:
string file_name;//der zuletzt benutze Filename
off_t file_size;
string file_content;//Inhalt der Datei
struct stat stat_buffer;//wird von filesize gefuellt
//rueckgabewerte von getparam
string param_name;
string param_value;
virtual int file_exists(string filename)=0;//0=nein,1=ja
virtual int load(string filename)=0;//0=Problem;1=ok
virtual off_t filesize(string filename)=0;//liefert den Rückgabewert von ::stat() und setzt Dateigroesse nach file_size
virtual string getparam(string parameter)=0;//leer = nicht gefunden oder eben leer
};
class xbkio : public xbkio_base
{
public:
int file_exists(string filename);
int load(string filename);
string getparam(string parameter);
off_t filesize(string filename);
};
#endif
| [
"x-itec@freenet.de"
] | x-itec@freenet.de | |
033c78be03f59cc4651367c3e1cf2aa66aaac43f | 34bdedfcfddfe090165a9072b3940604997b4843 | /src_arr/permutations_array.h | 888237055b54bf5e945ae336f9d2ae805644fd8c | [] | no_license | innovatelogic/junk | 84850baa589d11701b636a0f384c38f46edb1539 | f6f36ac0a9cd6e0d978fe0621ddabd3f33b91638 | refs/heads/master | 2021-11-15T06:28:35.966336 | 2021-10-04T21:50:25 | 2021-10-04T21:56:16 | 63,451,848 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,430 | h | #pragma once
#include "defexport.h"
#include <vector>
#include <functional>
#include <assert.h>
namespace junk
{
//----------------------------------------------------------------------------------------------
template<typename T>
JUNK_EXPORT void permutate_impl(const std::vector<T> &in,
std::vector<T> &out,
std::vector<bool> &used,
const std::function<void(const std::vector<T>&)> &func)
{
if (out.size() == in.size())
{
func(out);
return;
}
for (size_t i = 0; i < in.size(); ++i)
{
if (used[i]) continue;
used[i] = true;
out.push_back(in[i]);
permutate_impl<T>(in, out, used, func);
out.resize(out.size() - 1);
used[i] = false;
}
}
//----------------------------------------------------------------------------------------------
template<class T>
JUNK_EXPORT void permutate(const std::vector<T> &in,
const std::function<void(const std::vector<T> &res)> &func)
{
std::vector<bool> used; // vector of bool revise
used.resize(in.size());
for (size_t i = 0; i < in.size(); ++i) {
used[i] = false;
}
std::vector<T> out;
permutate_impl<T>(in, out, used, func);
used.resize(in.size());
}
}
| [
"westgames@gmail.com"
] | westgames@gmail.com |
96209dafe8080796fde82c98dacb944fc2633756 | 50f8c138da0165fa140c3241291aa2b0a8a14f99 | /barrels.cpp | 78eae4a04e8285d41834b7d5a43a69274d768010 | [] | no_license | Priybhanu99/My-Codes | c5da0821348939d75498e2751bc6c63d5e572294 | 4dc2e93fb941c4166b3b687a76358a1f309cc976 | refs/heads/master | 2021-05-19T12:22:09.830851 | 2021-01-17T15:22:23 | 2021-01-17T15:22:23 | 251,694,773 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 577 | cpp | #include <bits/stdc++.h>
using namespace std;
#define int long long int
#define P pair<int,int>
#define pb push_back
#define F first
#define S second
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t;
cin>>t; while(t--){
int n,k;
cin>>n>>k;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
sort(a,a+n);
reverse(a,a+n);
int ans = 0;
for (int i = 0; i < k+1; ++i)
{
ans += a[i];
}
cout<<ans<<"\n";
}
} | [
"bhanuyadav1999.by@gmail.com"
] | bhanuyadav1999.by@gmail.com |
7bc416e6bcf514a34c1b4e63557c022268c36b87 | 7f2ea1087250105349c33163854fe04e2f88e3b5 | /src/core/include/openOR/Plugin/Config.hpp | ecec77b82e10745847d5d180f6525d97effe53f5 | [
"MIT"
] | permissive | avinfinity/UnmanagedCodeSnippets | f5adbd5e72bd0919bf3621da14e60c60f0132401 | 2bd848db88d7b271209ad30017c8f62307319be3 | refs/heads/master | 2021-04-16T15:31:52.673438 | 2020-03-23T07:55:27 | 2020-03-23T07:55:27 | 249,366,746 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,824 | hpp | //****************************************************************************
// (c) 2008, 2009 by the openOR Team
//****************************************************************************
// The contents of this file are available under the GPL v2.0 license
// or under the openOR comercial license. see
// /Doc/openOR_free_license.txt or
// /Doc/openOR_comercial_license.txt
// for Details.
//****************************************************************************
//! OPENOR_INTERFACE_FILE(openOR_core)
//****************************************************************************
/**
* @file
* @ingroup openOR_core
*/
#ifndef openOR_Plugin_Config_hpp
#define openOR_Plugin_Config_hpp
#include <openOR/coreDefs.hpp>
#include <vector>
#include <map>
#include <string>
#include <boost/filesystem.hpp>
namespace openOR {
namespace Plugin {
//----------------------------------------------------------------------------
//! \brief Configuration for plugin autoloading.
//!
//! This can be used to guide the plugin autoload mechanism to on which
//! plugin class resides in which library file. Used by Loader::autoload.
//! \todo This might be a bit brittle. It is tested only in the simplest
//! config where all plugins reside in the same directory as the
//! executable and the pwd is correctly set.
//----------------------------------------------------------------------------
struct OPENOR_CORE_API Config {
//----------------------------------------------------------------------------
//! \brief Application specific plugin search path
//!
//! A simple collection of paths that will be searched in addition
//! to the default locations.
//! You can read the pathes using the const iterators retained from
//! begin() / end(), and add paths using add()
//----------------------------------------------------------------------------
struct OPENOR_CORE_API SearchPath {
typedef std::vector<boost::filesystem::path>::const_iterator const_iterator;
const_iterator begin() const;
const_iterator end() const;
void add(const boost::filesystem::path& path);
private:
std::vector<boost::filesystem::path> m_searchPath;
};
//----------------------------------------------------------------------------
//! \brief Create an empty config object.
//!
//! The default configuration is to search the system path and the current pwd
//----------------------------------------------------------------------------
Config();
//----------------------------------------------------------------------------
//! \brief Read the plugin configuration from a file.
//!
//! \todo Think of an infrastructure how this can effectively and
//! modularly parse only parts of a config file.
//----------------------------------------------------------------------------
void read_from_file(const std::string& cfgFile);
//----------------------------------------------------------------------------
//! \brief Save the plugin configuration to a file.
//!
//! \todo This should take a file stream, and append to it.
//----------------------------------------------------------------------------
void save_to_file(const std::string& cfgFile);
//----------------------------------------------------------------------------
//! \brief Returns the full path of a library file if one was configured.
//!
//! \return the full path of the library file that contains the requested
//! plugin class. If non was registerd for the particular class an empty
//! path will be returned.
//----------------------------------------------------------------------------
boost::filesystem::path full_library_path(const std::string& pluginName) const;
//----------------------------------------------------------------------------
//! \brief Retruns the base name of the library file
//!
//! The base name is the filename without platform specific embellishments.
//! \sa Plugin::Library
//! \return the base name of the library file that contains the requested
//! plugin class. If non was registerd for the particular class the
//! class name will be returned.
//----------------------------------------------------------------------------
std::string library_base_name(const std::string& pluginName) const;
//----------------------------------------------------------------------------
//! \brief Register the connection of a library filename which
//! contains a plugin class.
//!
//! \param[in] pluginName Must exactly match the registered plugin name.
//! \param[in] inLibrary Can be either be a library base name or
//! a full path.
//----------------------------------------------------------------------------
void register_plugin(const std::string& pluginName, const std::string& inLibrary);
//----------------------------------------------------------------------------
//! \brief true if the default system library path should be searched.
//----------------------------------------------------------------------------
bool search_system_path() const;
//----------------------------------------------------------------------------
//! \brief Set wether the system path should be searched. (Default = true)
//----------------------------------------------------------------------------
void set_search_system_path(bool use = true);
//----------------------------------------------------------------------------
//! \brief Returns the custom search path object.
//----------------------------------------------------------------------------
const SearchPath& search_path() const;
//----------------------------------------------------------------------------
//! \brief Add a path to the custom search paths.
//----------------------------------------------------------------------------
void add_search_path(const boost::filesystem::path& path);
private:
typedef std::map<std::string, std::string> PluginLibraryMap;
PluginLibraryMap m_pluginLibraryMap;
SearchPath m_searchPath;
bool m_useSystemPath;
};
}
}
#endif //openOR_Plugin_Config_hpp
| [
"avinfinity@gmail.com"
] | avinfinity@gmail.com |
5486139ae814f24664a0c15a87912e59a681d25b | 1b526bc0482d068e47b9e7e6c4abbb5dd1d9bfa2 | /devel/include/intera_motion_msgs/Trajectory.h | c64fb317dcd9debcd6a9ea9d99493753bf7258f0 | [] | no_license | ahadrauf2020/ee290_final_project | df7d6b5f53d36a588d204cd65cea83c2f7b29bc0 | 3a2cd3b10c39d2bcb46d9f504bdfebcf0de9195d | refs/heads/master | 2022-06-29T03:25:32.670331 | 2020-05-01T17:52:28 | 2020-05-01T17:52:28 | 257,447,031 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,844 | h | // Generated by gencpp from file intera_motion_msgs/Trajectory.msg
// DO NOT EDIT!
#ifndef INTERA_MOTION_MSGS_MESSAGE_TRAJECTORY_H
#define INTERA_MOTION_MSGS_MESSAGE_TRAJECTORY_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>
#include <intera_motion_msgs/Waypoint.h>
#include <intera_motion_msgs/TrajectoryOptions.h>
namespace intera_motion_msgs
{
template <class ContainerAllocator>
struct Trajectory_
{
typedef Trajectory_<ContainerAllocator> Type;
Trajectory_()
: label()
, joint_names()
, waypoints()
, trajectory_options() {
}
Trajectory_(const ContainerAllocator& _alloc)
: label(_alloc)
, joint_names(_alloc)
, waypoints(_alloc)
, trajectory_options(_alloc) {
(void)_alloc;
}
typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _label_type;
_label_type label;
typedef std::vector<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > , typename ContainerAllocator::template rebind<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::other > _joint_names_type;
_joint_names_type joint_names;
typedef std::vector< ::intera_motion_msgs::Waypoint_<ContainerAllocator> , typename ContainerAllocator::template rebind< ::intera_motion_msgs::Waypoint_<ContainerAllocator> >::other > _waypoints_type;
_waypoints_type waypoints;
typedef ::intera_motion_msgs::TrajectoryOptions_<ContainerAllocator> _trajectory_options_type;
_trajectory_options_type trajectory_options;
typedef boost::shared_ptr< ::intera_motion_msgs::Trajectory_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::intera_motion_msgs::Trajectory_<ContainerAllocator> const> ConstPtr;
}; // struct Trajectory_
typedef ::intera_motion_msgs::Trajectory_<std::allocator<void> > Trajectory;
typedef boost::shared_ptr< ::intera_motion_msgs::Trajectory > TrajectoryPtr;
typedef boost::shared_ptr< ::intera_motion_msgs::Trajectory const> TrajectoryConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::intera_motion_msgs::Trajectory_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::intera_motion_msgs::Trajectory_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace intera_motion_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'intera_core_msgs': ['/home/ee290/ee290_final_project/src/intera_common/intera_core_msgs/msg', '/home/ee290/ee290_final_project/devel/share/intera_core_msgs/msg'], 'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'intera_motion_msgs': ['/home/ee290/ee290_final_project/src/intera_common/intera_motion_msgs/msg', '/home/ee290/ee290_final_project/devel/share/intera_motion_msgs/msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::intera_motion_msgs::Trajectory_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::intera_motion_msgs::Trajectory_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::intera_motion_msgs::Trajectory_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::intera_motion_msgs::Trajectory_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::intera_motion_msgs::Trajectory_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::intera_motion_msgs::Trajectory_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::intera_motion_msgs::Trajectory_<ContainerAllocator> >
{
static const char* value()
{
return "9ab7e6d17ba67f0a6b00ab5f35f6d93e";
}
static const char* value(const ::intera_motion_msgs::Trajectory_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x9ab7e6d17ba67f0aULL;
static const uint64_t static_value2 = 0x6b00ab5f35f6d93eULL;
};
template<class ContainerAllocator>
struct DataType< ::intera_motion_msgs::Trajectory_<ContainerAllocator> >
{
static const char* value()
{
return "intera_motion_msgs/Trajectory";
}
static const char* value(const ::intera_motion_msgs::Trajectory_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::intera_motion_msgs::Trajectory_<ContainerAllocator> >
{
static const char* value()
{
return "# Representation of a trajectory used by the engine and motion controller.\n\
\n\
# optional label\n\
string label\n\
\n\
# Array of joint names that correspond to the waypoint joint_positions\n\
string[] joint_names\n\
\n\
# Array of waypoints that comprise the trajectory\n\
Waypoint[] waypoints\n\
\n\
# Trajectory level options\n\
TrajectoryOptions trajectory_options\n\
================================================================================\n\
MSG: intera_motion_msgs/Waypoint\n\
# Representation of a waypoint used by the motion controller\n\
\n\
# Desired joint positions\n\
# For Cartesian segments, the joint positions are used as nullspace biases\n\
float64[] joint_positions\n\
\n\
# Name of the endpoint that is currently active\n\
string active_endpoint\n\
\n\
# Cartesian pose\n\
# This is not used in trajectories using joint interpolation\n\
geometry_msgs/PoseStamped pose\n\
\n\
# Waypoint specific options\n\
# Default values will be used if not set\n\
# All waypoint options are applied to the segment moving to that waypoint\n\
WaypointOptions options\n\
\n\
================================================================================\n\
MSG: geometry_msgs/PoseStamped\n\
# A Pose with reference coordinate frame and timestamp\n\
Header header\n\
Pose pose\n\
\n\
================================================================================\n\
MSG: std_msgs/Header\n\
# Standard metadata for higher-level stamped data types.\n\
# This is generally used to communicate timestamped data \n\
# in a particular coordinate frame.\n\
# \n\
# sequence ID: consecutively increasing ID \n\
uint32 seq\n\
#Two-integer timestamp that is expressed as:\n\
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\
# time-handling sugar is provided by the client library\n\
time stamp\n\
#Frame this data is associated with\n\
# 0: no frame\n\
# 1: global frame\n\
string frame_id\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Pose\n\
# A representation of pose in free space, composed of position and orientation. \n\
Point position\n\
Quaternion orientation\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Point\n\
# This contains the position of a point in free space\n\
float64 x\n\
float64 y\n\
float64 z\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Quaternion\n\
# This represents an orientation in free space in quaternion form.\n\
\n\
float64 x\n\
float64 y\n\
float64 z\n\
float64 w\n\
\n\
================================================================================\n\
MSG: intera_motion_msgs/WaypointOptions\n\
# Optional waypoint label\n\
string label\n\
\n\
# Ratio of max allowed joint speed : max planned joint speed (from 0.0 to 1.0)\n\
float64 max_joint_speed_ratio\n\
\n\
# Slowdown heuristic is triggered if tracking error exceeds tolerances - radians\n\
float64[] joint_tolerances\n\
\n\
# Maximum accelerations for each joint (only for joint paths) - rad/s^2.\n\
float64[] max_joint_accel\n\
\n\
\n\
###########################################################\n\
# The remaining parameters only apply to Cartesian paths\n\
\n\
# Maximum linear speed of endpoint - m/s\n\
float64 max_linear_speed\n\
\n\
# Maximum linear acceleration of endpoint - m/s^2\n\
float64 max_linear_accel\n\
\n\
# Maximum rotational speed of endpoint - rad/s\n\
float64 max_rotational_speed\n\
\n\
# Maximum rotational acceleration of endpoint - rad/s^2\n\
float64 max_rotational_accel\n\
\n\
# Used for smoothing corners for continuous motion - m\n\
# The distance from the waypoint to where the curve starts while blending from\n\
# one straight line segment to the next.\n\
# Larger distance: trajectory passes farther from the waypoint at a higher speed\n\
# Smaller distance: trajectory passes closer to the waypoint at a lower speed\n\
# Zero distance: trajectory passes through the waypoint at zero speed\n\
float64 corner_distance\n\
\n\
================================================================================\n\
MSG: intera_motion_msgs/TrajectoryOptions\n\
# Trajectory interpolation type\n\
string CARTESIAN=CARTESIAN\n\
string JOINT=JOINT\n\
string interpolation_type\n\
\n\
# True if the trajectory uses interaction control, false for position control.\n\
bool interaction_control\n\
\n\
# Interaction control parameters\n\
intera_core_msgs/InteractionControlCommand interaction_params\n\
\n\
# Allow small joint adjustments at the beginning of Cartesian trajectories.\n\
# Set to false for 'small' motions.\n\
bool nso_start_offset_allowed\n\
\n\
# Check the offset at the end of a Cartesian trajectory from the final waypoint nullspace goal.\n\
bool nso_check_end_offset\n\
\n\
# Options for the tracking controller:\n\
TrackingOptions tracking_options\n\
\n\
# Desired trajectory end time, ROS timestamp\n\
time end_time\n\
\n\
# The rate in seconds that the path is interpolated and returned back to the user\n\
# No interpolation will happen if set to zero\n\
float64 path_interpolation_step\n\
\n\
================================================================================\n\
MSG: intera_core_msgs/InteractionControlCommand\n\
# Message sets the interaction (impedance/force) control on or off\n\
# It also contains desired cartesian stiffness K, damping D, and force values\n\
\n\
Header header\n\
bool interaction_control_active\n\
\n\
## Cartesian Impedance Control Parameters\n\
# Stiffness units are (N/m) for first 3 and (Nm/rad) for second 3 values\n\
float64[] K_impedance\n\
# Force certain directions to have maximum possible impedance for a given pose\n\
bool[] max_impedance\n\
# Damping units are (Ns/m) for first 3 and (Nms/rad) for the second 3 values\n\
float64[] D_impedance\n\
# Joint Nullspace stiffness units are in (Nm/rad) (length == number of joints)\n\
float64[] K_nullspace\n\
\n\
## Parameters for force control or impedance control with force limit\n\
# If in force mode, this is the vector of desired forces/torques\n\
# to be regulated in (N) and (Nm)\n\
# If in impedance with force limit mode, this vector specifies the\n\
# magnitude of forces/torques (N and Nm) that the command will not exceed.\n\
float64[] force_command\n\
\n\
## Desired frame\n\
geometry_msgs/Pose interaction_frame\n\
string endpoint_name\n\
# True if impedance and force commands are defined in endpoint frame\n\
bool in_endpoint_frame\n\
\n\
# Set to true to disable damping during force control. Damping is used\n\
# to slow down robot motion during force control in free space.\n\
# Option included for SDK users to disable damping in force control\n\
bool disable_damping_in_force_control\n\
\n\
# Set to true to disable reference resetting. Reference resetting is\n\
# used when interaction parameters change, in order to avoid jumps/jerks.\n\
# Option included for SDK users to disable reference resetting if the\n\
# intention is to change interaction parameters.\n\
bool disable_reference_resetting\n\
\n\
## Mode Selection Parameters\n\
# The possible interaction control modes are:\n\
# Impedance mode: implements desired endpoint stiffness and damping.\n\
uint8 IMPEDANCE_MODE=1\n\
# Force mode: applies force/torque in the specified dimensions.\n\
uint8 FORCE_MODE=2\n\
# Impedance with force limit: impedance control while ensuring the commanded\n\
# forces/torques do not exceed force_command.\n\
uint8 IMPEDANCE_WITH_FORCE_LIMIT_MODE=3\n\
# Force with motion bounds: force control while ensuring the current\n\
# pose/velocities do not exceed forceMotionThreshold (currenetly defined in yaml)\n\
uint8 FORCE_WITH_MOTION_LIMIT_MODE=4\n\
\n\
# Specifies the interaction control mode for each Cartesian dimension (6)\n\
uint8[] interaction_control_mode\n\
\n\
# All 6 values in force and impedance parameter vectors have to be filled,\n\
# If a control mode is not used in a Cartesian dimension,\n\
# the corresponding parameters will be ignored.\n\
\n\
## Parameters for Constrained Zero-G Behaviors\n\
# Allow for arbitrary rotational displacements from the current orientation\n\
# for constrained zero-G. Setting 'rotations_for_constrained_zeroG = True'\n\
# will disable the rotational stiffness field which limits rotational\n\
# displacements to +/- 82.5 degree.\n\
# NOTE: it will be only enabled for a stationary reference orientation\n\
bool rotations_for_constrained_zeroG\n\
\n\
================================================================================\n\
MSG: intera_motion_msgs/TrackingOptions\n\
# Minimum trajectory tracking time rate: (default = less than one)\n\
bool use_min_time_rate\n\
float64 min_time_rate\n\
\n\
# Maximum trajectory tracking time rate: (1.0 = real-time = default)\n\
bool use_max_time_rate\n\
float64 max_time_rate\n\
\n\
# Angular error tolerance at final point on trajectory (rad)\n\
float64[] goal_joint_tolerance\n\
\n\
# Time for the controller to settle within joint tolerances at the goal (sec)\n\
bool use_settling_time_at_goal\n\
float64 settling_time_at_goal\n\
";
}
static const char* value(const ::intera_motion_msgs::Trajectory_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::intera_motion_msgs::Trajectory_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.label);
stream.next(m.joint_names);
stream.next(m.waypoints);
stream.next(m.trajectory_options);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct Trajectory_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::intera_motion_msgs::Trajectory_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::intera_motion_msgs::Trajectory_<ContainerAllocator>& v)
{
s << indent << "label: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.label);
s << indent << "joint_names[]" << std::endl;
for (size_t i = 0; i < v.joint_names.size(); ++i)
{
s << indent << " joint_names[" << i << "]: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.joint_names[i]);
}
s << indent << "waypoints[]" << std::endl;
for (size_t i = 0; i < v.waypoints.size(); ++i)
{
s << indent << " waypoints[" << i << "]: ";
s << std::endl;
s << indent;
Printer< ::intera_motion_msgs::Waypoint_<ContainerAllocator> >::stream(s, indent + " ", v.waypoints[i]);
}
s << indent << "trajectory_options: ";
s << std::endl;
Printer< ::intera_motion_msgs::TrajectoryOptions_<ContainerAllocator> >::stream(s, indent + " ", v.trajectory_options);
}
};
} // namespace message_operations
} // namespace ros
#endif // INTERA_MOTION_MSGS_MESSAGE_TRAJECTORY_H
| [
"ahadrauf@berkeley.edu"
] | ahadrauf@berkeley.edu |
08f21c5f9f66973564777acdd1f81386ce9ec2e2 | bb9b83b2526d3ff8a932a1992885a3fac7ee064d | /src/modules/osg/generated_code/ActiveUniformMap.pypp.cpp | 81f99ef77e73f761581e3c7192d707993b28a0d8 | [] | no_license | JaneliaSciComp/osgpyplusplus | 4ceb65237772fe6686ddc0805b8c77d7b4b61b40 | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | refs/heads/master | 2021-01-10T19:12:31.756663 | 2015-09-09T19:10:16 | 2015-09-09T19:10:16 | 23,578,052 | 20 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 532 | cpp | // This file has been generated by Py++.
#include "boost/python.hpp"
#include "indexing_suite/container_suite.hpp"
#include "indexing_suite/map.hpp"
#include "wrap_osg.h"
#include "_ActiveVarInfo__value_traits.pypp.hpp"
#include "activeuniformmap.pypp.hpp"
namespace bp = boost::python;
void register_ActiveUniformMap_class(){
bp::class_< std::map< unsigned int, osg::Program::ActiveVarInfo > >( "ActiveUniformMap" )
.def( bp::indexing::map_suite< std::map< unsigned int, osg::Program::ActiveVarInfo > >() );
}
| [
"brunsc@janelia.hhmi.org"
] | brunsc@janelia.hhmi.org |
0a49c1216debb22abffffd2e98908aa71c61f823 | 5087884e0d7cab107e69a9fe7035ad5c338e7f77 | /include/TBLTree.h | 44b1b3c136499ad63430fba2f588e740886bd3ae | [
"LicenseRef-scancode-other-permissive"
] | permissive | jimregan/fnTBL | f62aec69064310f62e4ea2ebc73b8cc707f5c364 | df5be398eeec9590149d59c439fcea7743527182 | refs/heads/master | 2020-05-18T09:50:13.033335 | 2015-09-07T11:28:46 | 2015-09-07T11:28:46 | 42,048,391 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,443 | h | // -*- C++ -*-
/*
Implements the probabilistic tree needed for computing the probabilities
associated with the rules.
This file is part of the fnTBL distribution.
Copyright (c) 2001 Johns Hopkins University and Radu Florian and Grace Ngai.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software, fnTBL version 1.0, 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.
*/
#ifndef __TBLTree_h__
#define __TBLTree_h__
#include "Node.h"
#include "Rule.h"
#include <vector>
#include "hash_wrapper.h"
class TBLTree {
public:
typedef Node* PNode;
typedef TBLTree self;
typedef std::vector<PNode> pnode_vector;
typedef pnode_vector::iterator frontier_iterator;
typedef pnode_vector::const_iterator frontier_const_iterator;
typedef HASH_NAMESPACE::hash_map<Rule,int> rule_map_type;
typedef Node::example_index example_index;
TBLTree() {
root = new Node;
}
TBLTree(const string& file);
void readInTextFormat(const string& file);
void readClasses(const string& file);
frontier_iterator frontier_begin() {
return frontier1.begin();
}
frontier_iterator frontier_end() {
return frontier1.end();
}
frontier_const_iterator frontier_begin() const {
return frontier1.begin();
}
frontier_const_iterator frontier_end() const {
return frontier1.end();
}
void move_to_next_level() {
frontier1.swap(frontier2);
frontier2.clear();
}
void push_node_in_frontier(Node* p) {
frontier2.push_back(p);
}
const Node* findClassOfSample(const example_index& example) const {
return root->findClassOfSample(example);
}
void updateCounts() {
root->updateCounts();
}
void computeProbs(const example_index& example, const float2D& hypothesis) {
root->computeProbs(example, hypothesis);
}
void initialize(const vector<Rule>& rules);
const float1D& probs() const {
return root->probs;
}
void construct_tree();
void gather_leaves();
friend ostream& operator << (ostream& ostr, const self&);
friend istream& operator >> (istream& istr, self&);
static int GetRuleIndex(const Rule& rule) {
rule_map_type::iterator i = rule_index.find(rule);
int index;
if(i==rule_index.end()) {
index = rule_index[rule] = rules.size();
rules.push_back(rule);
} else
index = i->second;
return index;
}
protected:
Node * root;
pnode_vector frontier1, frontier2;
public:
static vector<Rule> rules;
static rule_map_type rule_index;
};
#endif
| [
"joregan@gmail.com"
] | joregan@gmail.com |
dab3888eafcc66d8f73e5ecd93e0211e1cb3be0a | 9259f0e6387e85f4198931f0c489beea8e580bf9 | /10.0.15063.0/winrt/internal/Windows.Networking.Connectivity.3.h | 8b208a687d714ad356440c2e8f9898cf61bf63a1 | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | part-machine/cppwinrt | 68fdd6ff4be685b9626451e94a113a7c1827fc23 | 5086290db972a5ed15d1a3e3438b57ce2f6eecd2 | refs/heads/master | 2021-01-16T18:39:49.206730 | 2017-07-29T17:54:09 | 2017-07-29T17:54:09 | 100,108,083 | 0 | 0 | null | 2017-08-12T11:28:45 | 2017-08-12T11:28:45 | null | UTF-8 | C++ | false | false | 7,470 | h | // C++ for the Windows Runtime v1.0.170406.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Networking.Connectivity.2.h"
WINRT_EXPORT namespace winrt {
namespace Windows::Networking::Connectivity {
template <typename H> struct impl_NetworkStatusChangedEventHandler : implements<impl_NetworkStatusChangedEventHandler<H>, abi<NetworkStatusChangedEventHandler>>, H
{
impl_NetworkStatusChangedEventHandler(H && handler) : H(std::forward<H>(handler)) {}
HRESULT __stdcall abi_Invoke(impl::abi_arg_in<Windows::Foundation::IInspectable> sender) noexcept override
{
try
{
(*this)(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&sender));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
}
namespace Windows::Networking::Connectivity {
struct WINRT_EBO AttributedNetworkUsage :
Windows::Networking::Connectivity::IAttributedNetworkUsage
{
AttributedNetworkUsage(std::nullptr_t) noexcept {}
};
struct WINRT_EBO CellularApnContext :
Windows::Networking::Connectivity::ICellularApnContext
{
CellularApnContext(std::nullptr_t) noexcept {}
CellularApnContext();
};
struct WINRT_EBO ConnectionCost :
Windows::Networking::Connectivity::IConnectionCost,
impl::require<ConnectionCost, Windows::Networking::Connectivity::IConnectionCost2>
{
ConnectionCost(std::nullptr_t) noexcept {}
};
struct WINRT_EBO ConnectionProfile :
Windows::Networking::Connectivity::IConnectionProfile,
impl::require<ConnectionProfile, Windows::Networking::Connectivity::IConnectionProfile2, Windows::Networking::Connectivity::IConnectionProfile3>
{
ConnectionProfile(std::nullptr_t) noexcept {}
};
struct WINRT_EBO ConnectionProfileFilter :
Windows::Networking::Connectivity::IConnectionProfileFilter,
impl::require<ConnectionProfileFilter, Windows::Networking::Connectivity::IConnectionProfileFilter2>
{
ConnectionProfileFilter(std::nullptr_t) noexcept {}
ConnectionProfileFilter();
};
struct WINRT_EBO ConnectionSession :
Windows::Networking::Connectivity::IConnectionSession
{
ConnectionSession(std::nullptr_t) noexcept {}
};
struct WINRT_EBO ConnectivityInterval :
Windows::Networking::Connectivity::IConnectivityInterval
{
ConnectivityInterval(std::nullptr_t) noexcept {}
};
struct ConnectivityManager
{
ConnectivityManager() = delete;
static Windows::Foundation::IAsyncOperation<Windows::Networking::Connectivity::ConnectionSession> AcquireConnectionAsync(const Windows::Networking::Connectivity::CellularApnContext & cellularApnContext);
static void AddHttpRoutePolicy(const Windows::Networking::Connectivity::RoutePolicy & routePolicy);
static void RemoveHttpRoutePolicy(const Windows::Networking::Connectivity::RoutePolicy & routePolicy);
};
struct WINRT_EBO DataPlanStatus :
Windows::Networking::Connectivity::IDataPlanStatus
{
DataPlanStatus(std::nullptr_t) noexcept {}
};
struct WINRT_EBO DataPlanUsage :
Windows::Networking::Connectivity::IDataPlanUsage
{
DataPlanUsage(std::nullptr_t) noexcept {}
};
struct WINRT_EBO DataUsage :
Windows::Networking::Connectivity::IDataUsage
{
DataUsage(std::nullptr_t) noexcept {}
};
struct [[deprecated("DataUsage may be altered or unavailable for releases after Windows 8.1. Instead, use NetworkUsage.")]] DataUsage;
struct WINRT_EBO IPInformation :
Windows::Networking::Connectivity::IIPInformation
{
IPInformation(std::nullptr_t) noexcept {}
};
struct WINRT_EBO LanIdentifier :
Windows::Networking::Connectivity::ILanIdentifier
{
LanIdentifier(std::nullptr_t) noexcept {}
};
struct WINRT_EBO LanIdentifierData :
Windows::Networking::Connectivity::ILanIdentifierData
{
LanIdentifierData(std::nullptr_t) noexcept {}
};
struct WINRT_EBO NetworkAdapter :
Windows::Networking::Connectivity::INetworkAdapter
{
NetworkAdapter(std::nullptr_t) noexcept {}
};
struct NetworkInformation
{
NetworkInformation() = delete;
static Windows::Foundation::Collections::IVectorView<Windows::Networking::Connectivity::ConnectionProfile> GetConnectionProfiles();
static Windows::Networking::Connectivity::ConnectionProfile GetInternetConnectionProfile();
static Windows::Foundation::Collections::IVectorView<Windows::Networking::Connectivity::LanIdentifier> GetLanIdentifiers();
static Windows::Foundation::Collections::IVectorView<Windows::Networking::HostName> GetHostNames();
static Windows::Foundation::IAsyncOperation<Windows::Networking::Connectivity::ProxyConfiguration> GetProxyConfigurationAsync(const Windows::Foundation::Uri & uri);
static Windows::Foundation::Collections::IVectorView<Windows::Networking::EndpointPair> GetSortedEndpointPairs(iterable<Windows::Networking::EndpointPair> destinationList, Windows::Networking::HostNameSortOptions sortOptions);
static event_token NetworkStatusChanged(const Windows::Networking::Connectivity::NetworkStatusChangedEventHandler & networkStatusHandler);
using NetworkStatusChanged_revoker = factory_event_revoker<INetworkInformationStatics>;
static NetworkStatusChanged_revoker NetworkStatusChanged(auto_revoke_t, const Windows::Networking::Connectivity::NetworkStatusChangedEventHandler & networkStatusHandler);
static void NetworkStatusChanged(event_token eventCookie);
static Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Networking::Connectivity::ConnectionProfile>> FindConnectionProfilesAsync(const Windows::Networking::Connectivity::ConnectionProfileFilter & pProfileFilter);
};
struct WINRT_EBO NetworkItem :
Windows::Networking::Connectivity::INetworkItem
{
NetworkItem(std::nullptr_t) noexcept {}
};
struct WINRT_EBO NetworkSecuritySettings :
Windows::Networking::Connectivity::INetworkSecuritySettings
{
NetworkSecuritySettings(std::nullptr_t) noexcept {}
};
struct WINRT_EBO NetworkStateChangeEventDetails :
Windows::Networking::Connectivity::INetworkStateChangeEventDetails,
impl::require<NetworkStateChangeEventDetails, Windows::Networking::Connectivity::INetworkStateChangeEventDetails2>
{
NetworkStateChangeEventDetails(std::nullptr_t) noexcept {}
};
struct WINRT_EBO NetworkUsage :
Windows::Networking::Connectivity::INetworkUsage
{
NetworkUsage(std::nullptr_t) noexcept {}
};
struct WINRT_EBO ProxyConfiguration :
Windows::Networking::Connectivity::IProxyConfiguration
{
ProxyConfiguration(std::nullptr_t) noexcept {}
};
struct WINRT_EBO RoutePolicy :
Windows::Networking::Connectivity::IRoutePolicy
{
RoutePolicy(std::nullptr_t) noexcept {}
RoutePolicy(const Windows::Networking::Connectivity::ConnectionProfile & connectionProfile, const Windows::Networking::HostName & hostName, Windows::Networking::DomainNameType type);
};
struct WINRT_EBO WlanConnectionProfileDetails :
Windows::Networking::Connectivity::IWlanConnectionProfileDetails
{
WlanConnectionProfileDetails(std::nullptr_t) noexcept {}
};
struct WINRT_EBO WwanConnectionProfileDetails :
Windows::Networking::Connectivity::IWwanConnectionProfileDetails
{
WwanConnectionProfileDetails(std::nullptr_t) noexcept {}
};
}
}
| [
"kwelton@microsoft.com"
] | kwelton@microsoft.com |
518b4aeca42c2d082472ddfd63bb56fdb21d1fec | 7c78a9ca4f343c358c99397830a12888b3876ff7 | /MultiplicacionMemoria.cpp | 1541965c414e9b86759b0a588c21de38a28f05ae | [] | no_license | fryzito/Concurrente-y-Paralelo | 058f7e1b6d3bd4e4bcff3bd3f52f20a2c6d03287 | d84748a33361e6df3dec5c16841f63b44acbbd27 | refs/heads/master | 2022-05-17T05:45:59.865724 | 2022-04-28T19:57:15 | 2022-04-28T19:57:15 | 59,216,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,016 | cpp | #include <bits/stdc++.h>
#define CLOCK print("clock %lf\n",(double)clock()/CLOCKS_PER_SEC);
using namespace std;
int main(){
int N;
scanf("%d\n",&N);
int A[N][N];int B[N][N]; int res[N][N];
//leendo matrices
for(int i=0;i<N;i++){
for(int j=0;j<N;j++) {
scanf("%d",&A[i][j]);
}
scanf("\n");
}
//Multiplicando matrices
clock_t start1=clock(); // <-- Tomando Tiempo
int i,j,k;
double tmp[N][N];
for (i = 0; i < N; ++i)
for (j = 0; j < N; ++j)
tmp[i][j] = A[j][i];
for (i = 0; i < N; ++i)
for (j = 0; j < N; ++j)
for (k = 0; k < N; ++k)
res[i][j] += A[i][k] * tmp[j][k];
printf("Tiempo trascurrido: %f\n",((double)clock()-start1)/CLOCKS_PER_SEC);
//Escribiendo matrices
for(int i=0;i<N;i++){
for(int j=0;j<N;j++) {
printf(" %d",res[i][j]);
}
printf("\n");
}
return 0;
}
// hacer conclusiones
// hacer un informe
// medir las estadis accesos a cache
// y nro de operaciones del procesador
// Utilizar Valgrind
| [
"fryzito@gmail.com"
] | fryzito@gmail.com |
6d0b96e2f0c6c4f2033a464a8784561fe8c78c0f | bb74da541406a89d49f270f841060e48e780c1a2 | /RedisStudio/DBClient.h | 0613950555a37355c0b11b8e50dca58b229a091b | [] | no_license | xiejiulong/RedisStudio | f063ceb526d71a7ccd6e03b8fac18a2d14bf92ed | 4b18d96dd8aa3b1967ad822d06bd84db89ae76ac | refs/heads/master | 2021-06-14T15:09:27.567167 | 2021-05-11T06:51:33 | 2021-05-11T06:51:33 | 185,119,402 | 1 | 0 | null | 2019-05-06T03:45:15 | 2019-05-06T03:45:15 | null | UTF-8 | C++ | false | false | 1,847 | h | #pragma once
#include <string>
#include <list>
#include <map>
class RedisResult;
class DBClient {
public:
typedef std::list<std::string> TSeqArrayResults;
typedef std::map<std::string, std::string> TDicConfig;
public:
virtual ~DBClient() {};
static DBClient* Create(const std::string& ip, int port, const std::string& auth);
void SetDBType(const std::string& dbtype);
std::string DBType();
virtual bool Connect(const std::string& ip, int port, const std::string& auth) = 0;
virtual bool Ping() = 0;
virtual bool IsConnected() = 0;
virtual void Quit() = 0;
virtual bool Info(std::string& results) = 0;
virtual bool keys(const std::string &, TSeqArrayResults& results) = 0;
virtual bool Exists(const std::string& key) = 0;
virtual bool Type(const std::string& key, string& type) = 0;
virtual long long TTL(const std::string& key) = 0;
virtual bool DatabasesNum(int& num);
virtual int DatabasesNum();
virtual bool SelectDB(int dbindex);
virtual long long DbSize() = 0;
virtual bool GetConfig(TDicConfig& dicConfig);
virtual bool SetConfig(const TDicConfig& dicConfig);
virtual bool ReWriteConfig();
virtual bool GetData(const std::string& key, std::string& type, RedisResult& results) = 0;
virtual bool UpdateData(const std::string& key,
const std::string& oldValue,
const std::string& newValue,
int idx,
const std::string& field="") = 0;
virtual bool DelKey(const std::string& key) = 0;
void SetLastError(const std::string& err);
std::string GetLastError();
protected:
std::string m_IP;
int m_Port;
std::string m_Auth;
private:
std::string m_Error;
std::string m_DBType;
};
| [
"cinience@qq.com"
] | cinience@qq.com |
09fcf00db42641044e02bfa72bc4d474e74a65b8 | 54dad81c9a5890ac6d7c3bedf1aff4b8f4d86f3c | /_junkPlugins/BatchRenderer/Source/BatchRenderer/Public/BatchRenderer.h | 576d182fd0f99327162064ed6927d9a5979816e6 | [
"MIT"
] | permissive | DodgeeSoftware/MichaelsPluginTest | 67f20b98e83323e8742ffaf71072d7abd1ee6346 | da52ae782df77e540c17d6602eeae141d8a8b329 | refs/heads/master | 2022-04-14T13:21:41.383306 | 2020-04-16T11:01:35 | 2020-04-16T11:01:35 | 256,189,317 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,433 | h | // Copyright 2018 Dodgee Software, Inc. All Rights Reserved.
#pragma once
// UNREAL ENGINE INCLUDES
#include <CoreMinimal.h>
#include <ModuleManager.h>
class FToolBarBuilder;
class FMenuBuilder;
static FName BatchRendererTabName = FName("BatchRenderer");
/* The FBatchRendererModule Implments the IModuleInterface and
* is the module class driving our BatchRenderer Plugin */
class FBatchRendererModule : public IModuleInterface
{
// ********************
// * IMODULEINTERFACE *
// ********************
public:
//! StartupModule (Called at Startup)
virtual void StartupModule() override;
//! ShutdownModule (Called at Shutdown)
virtual void ShutdownModule() override;
protected:
// BatchRendererTabName
FName BatchRendererTabName;
// *****************
// * GUI CALLBACKS *
// *****************
public:
// OnSpawnPluginTab
TSharedRef<class SDockTab> OnSpawnPluginTab(const class FSpawnTabArgs& SpawnTabArgs);
protected:
// This function will be bound to Command (by default it will bring up plugin window)
void PluginButtonClicked();
// AddToolbarExtension
void AddToolbarExtension(FToolBarBuilder& Builder);
// AddMenuExtension
void AddMenuExtension(FMenuBuilder& Builder);
// OnButtonClicked
FReply OnButtonClicked();
// *******
// * ??? *
// *******
public:
// Members and Methods
protected:
// PluginCommands
TSharedPtr<class FUICommandList> PluginCommands;
}; | [
"DodgeeSoftware@gmail.com"
] | DodgeeSoftware@gmail.com |
e1675f3b0117cf0ff19819058be7bbf98512cad1 | 357c68d24389b7708d0d11f920340c9b283c824e | /ida_build/windows/apps/DatCopy/Aspiscsi.h | 616b02d39027b2de5db427e3080062528bcb6c98 | [] | no_license | joeledwards/asl-station-processor | 80361a786ee277999b30d87ac1497c0bdc47d119 | d73f5167baf01e2d7455b180f8757b0988c78d45 | refs/heads/master | 2020-05-31T10:06:58.948122 | 2012-10-29T16:38:27 | 2012-10-29T16:38:27 | 6,052,634 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,868 | h | #ifndef __aspiscsi__
#define __aspiscsi__ 1
#include "win32/wnaspi32.h"
#include "win32/scsidefs.h"
#include "win32/scsitape.h"
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//extern LPSENDASPI32COMMAND lpfnSendASPI32Command;
typedef struct
{
int adapter;
int lun;
int target;
PVOID pNext;
int device;
char descr[100];
}DEVLIST, *PDEVLIST;
typedef struct scsi_handle {
int adapter;
int target_id;
int lun;
unsigned char buf[32768];
int nRead;
int nQty;
} SCSI, *PSCSI;
/////////////////////////////////////////////////////////////////////////////
// CDatCopyDlg dialog
class CAspiscsi
{
// Construction
public:
CAspiscsi(); // standard constructor
~CAspiscsi(); // standard distructor
bool InitASPI();
bool GetDeviceInfo( int target_id, int adapter_id, int lun_id, PUCHAR lpBuff, int nBuffSize);
PDEVLIST ScanSCSI(HWND hwnd);
void AddAdapter(int n=1)
{m_NumAdapters += n;};
BYTE GetNumAdapters()
{return m_NumAdapters; };
PSCSI Open(LPCSTR dev);
void Close(PSCSI pSCSI);
int Read(PSCSI , PUCHAR buffer, int count);
int Write(PSCSI , PUCHAR buffer, int count);
int Reset(PSCSI tp);
int Rewind(PSCSI tp);
int ScsiIoError
(
int aspi_status,
int adapter_status,
int target_status,
BYTE *sense
);
int SCSIRead(int adapter, int target_id, int lun, PUCHAR buf, int len);
int SCSIWrite(int adapter, int target_id, int lun, PUCHAR buf, int len);
int Eject(PSCSI);
int Abort(PSCSI);
int ReadError(){
return m_ReadError;};
private:
bool m_bInitSuccess;
SRB_ExecSCSICmd m_SCSICmd;
HANDLE m_ASPICompletionEvent;
DWORD m_ASPIEventStatus;
BYTE m_NumAdapters;
PDEVLIST m_pDevList;
HINSTANCE m_hlibAPI;
LPSENDASPI32COMMAND m_lpfnSendASPI32Command;
LPGETASPI32SUPPORTINFO m_lpfnGetASPI32SupportInfo;
int m_ReadError;
};
#endif | [
"maint@SLATE1.(none)"
] | maint@SLATE1.(none) |
bca8db447b4aa804589ab79331146ddf67886fbc | 9b4372792eb1b315dd1e7cb98156f5001b762dcf | /mainwindow.h | 71b9046a95f62b72382534012fe8b41211cfe721 | [] | no_license | Morolem/Pyramid-image-processing- | e035680a4a44e8599c17f0a5b82d8e9502234bac | 7d37455377b2eff558c6604fc4ccf38855334eb9 | refs/heads/master | 2020-07-30T08:26:21.336054 | 2019-11-21T06:13:34 | 2019-11-21T06:13:34 | 210,154,853 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,473 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private :
struct Images
{
QString fileName;
QImage imageData;
};
std::vector<Images> images;
QString path = "C:\\";
bool image_to_fit_window = false;
/// возвращает индекс вектора images, для найденного имени
int find_by_name(const QString &);
/// функция сортировки изображений по размеру диагонали
void combobox_quick_sort(const int &left,const int &right);
/// размер диагонали изображения (т. Пифагора)
double diag_images(const QImage &image);
/// поиск дубликатов в массиве изображений images
bool duplicate_search(const std::vector<Images> &v,const QImage &value);
/// заполнение combobox отсортированным массивом изображений
void insert_images_into_combobox();
private slots:
void on_pushButton_clicked();
void on_comboBox_activated(int index);
void on_doubleSpinBox_valueChanged(double arg1);
void on_pushButton_3_clicked();
void on_pushButton_2_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"www.andrei.97@mail.ru"
] | www.andrei.97@mail.ru |
f2efd47335a8ac7d25003001ec6ddf8faea22055 | ebc39e7af2fd97dc3dafd2ee1e58d594d4f97fb7 | /src/TDOA/Matrix.h | c5e8088fd03042b57c8fdb4f045626d7e2ff027e | [] | no_license | ridolph/pps_TDOA | 57d960ade2ec8a726abe0f22bbaff24852ca5673 | a8ecd37e8ae3a733f735eb57d673453aae8d3612 | refs/heads/master | 2022-11-24T00:01:00.619073 | 2020-07-28T05:37:01 | 2020-07-28T05:37:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,218 | h | #pragma once
#ifndef MATRIX_FILE
#define MATRIX_FILE
/*Matrix.h*/
#include <vector>
using namespace std;
enum DIM
{
ROW = 0,
COL,
BUTT
};
class MAT
{
public:
MAT(){}
MAT(int row,int col)
{resizeMat(row,col);}
MAT(const MAT& inMat)
{mMat = inMat.getMyMat();}
void operator =(vector<vector<double>> value);
~MAT(){}
int getRowSize()
{return mMat.size();}
vector<vector<double>> getMyMat()const
{return mMat;}
void push(vector<double> inVec)
{mMat.push_back(inVec);}
int getColSize()
{return mMat[0].size();}
void setValue(int row,int col,double value)
{mMat[row][col] = value;}
void resizeMat(int row,int col);
double at(int row,int col);
MAT MyMatrixDiffConstValue (double conValue);
MAT MyMatTanspose();
MAT MyMatDivide(double value);
MAT MyInv ();
MAT MyGetCol(int colNum);
MAT MyGetRow(int rowNum);
double MyMean(DIM inDim,int index);
MAT operator -(MAT &matRight);
MAT operator -(double value);
MAT operator *(MAT &matRight);
MAT operator *(double multiValue);
bool MyMatMatch_DimEqual(MAT &matRight);
bool MyMatMatch_DimMulti(MAT &matRight);
void ArrayToMat_Constructor(double *inArray,int rowSize,int colSize);
private:
vector<vector<double>> mMat;
};
#endif | [
"yfpps@headquarters.com"
] | yfpps@headquarters.com |
c50b5dd15860911c22b0cf149238ae62d55aaed7 | 7ef33fe1a49ea76c1132235b864790d82f595014 | /src/indigo.h | 299d270e1f2df421625fda01c569e3a6342dad67 | [
"BSD-3-Clause"
] | permissive | gear-genomics/tracy | 91ae9891b4fc4a1931279e913f46d04ce26b9c8c | 970bb5b51e25f8f592a3dcd19dd38a4e9bdc0662 | refs/heads/main | 2023-04-14T02:16:09.872971 | 2023-04-12T07:13:28 | 2023-04-12T07:13:28 | 137,339,828 | 91 | 17 | BSD-3-Clause | 2023-04-07T11:38:13 | 2018-06-14T09:54:24 | C++ | UTF-8 | C++ | false | false | 17,127 | h | #ifndef INDIGO_H
#define INDIGO_H
#define BOOST_DISABLE_ASSERTS
#include <boost/multi_array.hpp>
#include "decompose.h"
#include "trim.h"
#include "web.h"
#include "variants.h"
#include "fmindex.h"
using namespace sdsl;
namespace tracy {
struct IndigoConfig {
bool callvariants;
bool annotatevariants;
uint16_t linelimit;
uint16_t trimLeft;
uint16_t trimRight;
uint16_t kmer;
uint16_t maxindel;
uint16_t madc;
uint16_t minKmerSupport;
uint16_t qualCut;
int32_t gapopen;
int32_t gapext;
int32_t match;
int32_t mismatch;
float pratio;
float trimStringency;
std::string annotate;
std::string host;
std::string outprefix;
DnaScore<int32_t> aliscore;
boost::filesystem::path outfile;
boost::filesystem::path ab;
boost::filesystem::path genome;
};
int indigo(int argc, char** argv) {
IndigoConfig c;
// Parameter
boost::program_options::options_description generic("Generic options");
generic.add_options()
("help,?", "show help message")
("genome,r", boost::program_options::value<boost::filesystem::path>(&c.genome), "(gzipped) fasta or wildtype ab1 file")
("pratio,p", boost::program_options::value<float>(&c.pratio)->default_value(0.33), "peak ratio to call base")
("kmer,k", boost::program_options::value<uint16_t>(&c.kmer)->default_value(15), "kmer size")
("support,s", boost::program_options::value<uint16_t>(&c.minKmerSupport)->default_value(3), "min. kmer support")
("maxindel,i", boost::program_options::value<uint16_t>(&c.maxindel)->default_value(1000), "max. indel size in Sanger trace")
("annotate,a", boost::program_options::value<std::string>(&c.annotate), "annotate variants [homo_sapiens|homo_sapiens_hg19|mus_musculus|danio_rerio|...]")
("callVariants,v", "call variants in trace")
;
boost::program_options::options_description alignment("Alignment options");
alignment.add_options()
("gapopen,g", boost::program_options::value<int32_t>(&c.gapopen)->default_value(-10), "gap open")
("gapext,e", boost::program_options::value<int32_t>(&c.gapext)->default_value(-4), "gap extension")
("match,m", boost::program_options::value<int32_t>(&c.match)->default_value(3), "match")
("mismatch,n", boost::program_options::value<int32_t>(&c.mismatch)->default_value(-5), "mismatch")
;
boost::program_options::options_description tro("Trimming options");
tro.add_options()
("trim,t", boost::program_options::value<float>(&c.trimStringency)->default_value(0), "trimming stringency [1:9], 0: use trimLeft and trimRight")
("trimLeft,q", boost::program_options::value<uint16_t>(&c.trimLeft)->default_value(50), "trim size left")
("trimRight,u", boost::program_options::value<uint16_t>(&c.trimRight)->default_value(50), "trim size right")
;
boost::program_options::options_description otp("Output options");
otp.add_options()
("linelimit,l", boost::program_options::value<uint16_t>(&c.linelimit)->default_value(60), "alignment line length")
("outprefix,o", boost::program_options::value<std::string>(&c.outprefix)->default_value("out"), "output prefix")
;
boost::program_options::options_description hidden("Hidden options");
hidden.add_options()
("madc,c", boost::program_options::value<uint16_t>(&c.madc)->default_value(5), "MAD cutoff")
("qualCut,z", boost::program_options::value<uint16_t>(&c.qualCut)->default_value(45), "variant calling quality threshold")
("input-file", boost::program_options::value<boost::filesystem::path>(&c.ab), "ab1")
;
boost::program_options::positional_options_description pos_args;
pos_args.add("input-file", -1);
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic).add(alignment).add(tro).add(otp).add(hidden);
boost::program_options::options_description visible_options;
visible_options.add(generic).add(alignment).add(tro).add(otp);
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(pos_args).run(), vm);
boost::program_options::notify(vm);
// Check command line arguments
if ((vm.count("help")) || (!vm.count("input-file"))) {
std::cout << "Usage: tracy " << argv[0] << " [OPTIONS] trace.ab1" << std::endl;
std::cout << visible_options << "\n";
return -1;
}
if (c.maxindel < 1) c.maxindel = 1;
// Check trimming parameters
if (c.trimStringency > 9) c.trimStringency = 9;
// Variant calling
if (vm.count("callVariants")) c.callvariants = true;
else c.callvariants = false;
if (vm.count("annotate")) {
c.annotatevariants = true;
c.callvariants = true;
c.host = "rest.ensembl.org";
c.annotate = fixSpeciesName(c.annotate);
// hg19 workaround
if (c.annotate == "homo_sapiens_hg19") {
c.host = "grch37.rest.ensembl.org";
c.annotate = "homo_sapiens";
}
if (!speciesExist(c.annotate)) c.annotatevariants = false;
} else c.annotatevariants = false;
// Check ab1
if (!(boost::filesystem::exists(c.ab) && boost::filesystem::is_regular_file(c.ab) && boost::filesystem::file_size(c.ab))) {
std::cerr << "Trace file is missing: " << c.ab.string() << std::endl;
return 1;
}
// Check reference
if (!(boost::filesystem::exists(c.genome) && boost::filesystem::is_regular_file(c.genome) && boost::filesystem::file_size(c.genome))) {
std::cerr << "Reference file is missing: " << c.genome.filename().string() << std::endl;
return 1;
}
// Show cmd
boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
std::cout << '[' << boost::posix_time::to_simple_string(now) << "] ";
std::cout << "tracy ";
for(int i=0; i<argc; ++i) { std::cout << argv[i] << ' '; }
std::cout << std::endl;
// Load *.ab1 file
now = boost::posix_time::second_clock::local_time();
std::cout << '[' << boost::posix_time::to_simple_string(now) << "] " << "Load ab1 file" << std::endl;
Trace tr;
int32_t ft = traceFormat(c.ab.string());
if (ft == 0) {
if (!readab(c.ab.string(), tr)) return -1;
} else if (ft == 1) {
if (!readscf(c.ab.string(), tr)) return -1;
} else {
std::cerr << "Unknown trace file type!" << std::endl;
return -1;
}
// Any basecalls
if (!tr.basecallpos.size()) {
std::cerr << "Trace file lacks basecalls!" << std::endl;
return -1;
}
// Alignment options
AlignConfig<true, false> semiglobal;
c.aliscore = DnaScore<int32_t>(c.match, c.mismatch, c.gapopen, c.gapext);
// Call bases
BaseCalls bc;
basecall(tr, bc, c.pratio);
// Get trim sizes
if (c.trimStringency >= 1) {
uint32_t trimLeft = 0;
uint32_t trimRight = 0;
trimTrace(c, bc, trimLeft, trimRight);
c.trimLeft = trimLeft;
c.trimRight = trimRight;
}
// Check trim sizes
if (c.trimLeft + c.trimRight >= bc.bcPos.size()) {
std::cerr << "The sum of the left and right trim size is larger than the trace!" << std::endl;
return -1;
}
// Output trace information
traceTxtOut(c.outprefix + ".abif", bc, tr, c.trimLeft, c.trimRight);
// Create trimmed trace profile
typedef boost::multi_array<float, 2> TProfile;
TProfile trimmedtrace;
createProfile(tr, bc, trimmedtrace, c.trimLeft, c.trimRight);
// Identify position of indel shift in Sanger trace
TraceBreakpoint bp;
findBreakpoint(trimmedtrace, bp);
// Load reference
ReferenceSlice rs;
TProfile referenceprofile;
rs.filetype = genomeType(c.genome.string());
if (rs.filetype == -1) {
std::cerr << "Unknown reference file format!" << std::endl;
return -1;
}
// Find reference match
now = boost::posix_time::second_clock::local_time();
std::cout << '[' << boost::posix_time::to_simple_string(now) << "] " << "Find Reference Match" << std::endl;
TProfile prefslice;
if ((rs.filetype == 0) || (rs.filetype == 1)) {
if (rs.filetype == 0) {
// Indexed genome
csa_wt<> fm_index;
if (!loadFMIdx(c, rs, fm_index)) return -1;
if (!getReferenceSlice(c, fm_index, bc, rs)) return -1;
createProfile(c, rs, prefslice);
} else {
// Single FASTA
std::string faname = "";
std::string seq = "";
if (!loadSingleFasta(c.genome.string(), faname, seq)) return -1;
if (seq.size() > MAX_SINGLE_FASTA_SIZE) {
std::cerr << "Reference is larger than 50Kbp. Please use a smaller reference slice or an indexed genome!" << std::endl;
return -1;
}
// Profile
TProfile fwdprofile;
_createProfile(seq, fwdprofile);
TProfile revprofile;
reverseComplementProfile(fwdprofile, revprofile);
// Alignment scores
int32_t gsFwd = gotohScore(trimmedtrace, fwdprofile, semiglobal, c.aliscore);
int32_t gsRev = gotohScore(trimmedtrace, revprofile, semiglobal, c.aliscore);
// Forward or reverse?
rs.kmersupport = 0;
rs.pos = 0;
rs.chr = faname;
rs.refslice = seq;
if (gsFwd > gsRev) {
rs.forward = true;
copyProfile(fwdprofile, prefslice);
} else {
rs.forward = false;
reverseComplement(rs.refslice);
copyProfile(revprofile, prefslice);
}
}
} else if (rs.filetype == 2) {
// Wildtype trace
Trace gtr;
int32_t gft = traceFormat(c.genome.string());
if (gft == 0) {
if (!readab(c.genome.string(), gtr)) return -1;
} else if (gft == 1) {
if (!readscf(c.genome.string(), gtr)) return -1;
} else {
std::cerr << "Unknown trace file type!" << std::endl;
return -1;
}
// Basecalling and reference profile
BaseCalls gbc;
basecall(gtr, gbc, c.pratio);
// Figure out if fwd or rev
TProfile fwdprofile;
createProfile(gtr, gbc, fwdprofile);
TProfile revprofile;
reverseComplementProfile(fwdprofile, revprofile);
// Alignment scores
int32_t gsFwd = gotohScore(trimmedtrace, fwdprofile, semiglobal, c.aliscore);
int32_t gsRev = gotohScore(trimmedtrace, revprofile, semiglobal, c.aliscore);
// Forward or reverse?
rs.kmersupport = 0;
rs.pos = 0;
rs.chr = "wildtype";
rs.refslice = gbc.primary;
if (gsFwd > gsRev) {
rs.forward = true;
copyProfile(fwdprofile, prefslice);
} else {
rs.forward = false;
reverseComplement(rs.refslice);
copyProfile(revprofile, prefslice);
}
} else {
std::cerr << "Unknown reference file type!" << std::endl;
return - 1;
}
// Align trimmed trace to profile
typedef boost::multi_array<char, 2> TAlign;
TAlign align;
now = boost::posix_time::second_clock::local_time();
std::cout << '[' << boost::posix_time::to_simple_string(now) << "] " << "Alignment" << std::endl;
int32_t aliTrimScore = gotoh(trimmedtrace, prefslice, align, semiglobal, c.aliscore);
double seqsize = trimmedtrace.shape()[1];
double matchFraction = 0.35;
double scoreThreshold = seqsize * matchFraction * c.aliscore.match + seqsize * (1 - matchFraction) * c.aliscore.mismatch;
if (aliTrimScore <= scoreThreshold) {
std::cerr << "Alignment of trace to reference failed!" << std::endl;
return -1;
}
// Hom. InDel search
now = boost::posix_time::second_clock::local_time();
std::cout << '[' << boost::posix_time::to_simple_string(now) << "] " << "InDel Search" << std::endl;
if (!bp.indelshift) {
// Find breakpoint for hom. indels
if (!findHomozygousBreakpoint(align, bp)) return -1;
}
// Debug Breakpoint & Alignment
//std::cerr << "Breakpoint: " << bp.indelshift << ',' << bp.traceleft << ',' << bp.breakpoint << ',' << bp.bestDiff << std::endl;
//for(uint32_t i = 0; i<align.shape()[0]; ++i) {
//uint32_t alignedNuc = 0;
//for(uint32_t j = 0; j<align.shape()[1]; ++j) {
//if (align[0][j] != '-') {
//++alignedNuc;
//if (alignedNuc == bp.breakpoint) std::cerr << "#####";
//}
//std::cerr << align[i][j];
//}
//std::cerr << std::endl;
//}
now = boost::posix_time::second_clock::local_time();
std::cout << '[' << boost::posix_time::to_simple_string(now) << "] " << "Decompose Chromatogram" << std::endl;
// Decompose alleles
typedef std::pair<int32_t, int32_t> TIndelError;
typedef std::vector<TIndelError> TDecomposition;
TDecomposition dcp;
if (!decomposeAlleles(c, align, bc, bp, rs, dcp)) return -1;
writeDecomposition(c.outprefix + ".decomp", dcp);
// Generate plain nucleotide sequence for second allele
generateSecondaryDecomposed(tr, bc);
// Estimate allelic fractions
now = boost::posix_time::second_clock::local_time();
std::cout << '[' << boost::posix_time::to_simple_string(now) << "] " << "Estimate allelic fractions" << std::endl;
typedef std::pair<double, double> TFractions;
TFractions a1a2 = allelicFraction(c, tr, bc);
now = boost::posix_time::second_clock::local_time();
std::cout << '[' << boost::posix_time::to_simple_string(now) << "] " << "Allele-specific alignments" << std::endl;
// Allele1
typedef boost::multi_array<char, 2> TAlign;
TAlign alignPrimary;
std::string pri = trimmedSeq(bc.primary, c.trimLeft, c.trimRight);
gotoh(pri, rs.refslice, alignPrimary, semiglobal, c.aliscore);
// Trim initial reference slice
ReferenceSlice allele1(rs);
trimReferenceSlice(c, alignPrimary, allele1);
typedef boost::multi_array<char, 2> TAlign;
TAlign final1;
int32_t a1Score = gotoh(pri, allele1.refslice, final1, semiglobal, c.aliscore);
plotAlignment(c.outprefix + ".align1", final1, allele1, 1, a1Score, a1a2, c.linelimit);
// Allele2
TAlign alignSecondary;
std::string sec = trimmedSeq(bc.secDecompose, c.trimLeft, c.trimRight);
gotoh(sec, rs.refslice, alignSecondary, semiglobal, c.aliscore);
// Trim initial reference slice
ReferenceSlice allele2(rs);
trimReferenceSlice(c, alignSecondary, allele2);
TAlign final2;
int32_t a2Score = gotoh(sec, allele2.refslice, final2, semiglobal, c.aliscore);
plotAlignment(c.outprefix + ".align2", final2, allele2, 2, a2Score, a1a2, c.linelimit);
// Allele1 vs. Allele2
TAlign final3;
AlignConfig<false, false> global;
ReferenceSlice secrs;
secrs.refslice = sec;
secrs.forward = 1;
secrs.pos = 0;
secrs.chr = "Alt2";
int32_t a3Score = gotoh(pri, secrs.refslice, final3, global, c.aliscore);
plotAlignment(c.outprefix + ".align3", final3, secrs, 3, a3Score, a1a2, c.linelimit);
// Any het. InDel
if (!bp.indelshift) {
// Center on first SNP
uint32_t reliableTracePos = findBestTraceSection(bc);
bp.breakpoint = nearestSNP(c, bc, reliableTracePos);
}
// Variant Calling
typedef std::vector<Variant> TVariants;
TVariants var;
if (c.callvariants) {
now = boost::posix_time::second_clock::local_time();
std::cout << '[' << boost::posix_time::to_simple_string(now) << "] " << "Variant Calling" << std::endl;
if (rs.forward) {
callVariants(final1, allele1, var);
callVariants(final2, allele2, var);
} else {
// Reverse complement
std::string revPri(pri);
reverseComplement(revPri);
ReferenceSlice allele1Rev;
_reverseReferenceSlize(allele1, allele1Rev);
TAlign final1Rev;
gotoh(revPri, allele1Rev.refslice, final1Rev, semiglobal, c.aliscore);
callVariants(final1Rev, allele1Rev, var);
std::string revSec(sec);
reverseComplement(revSec);
ReferenceSlice allele2Rev;
_reverseReferenceSlize(allele2, allele2Rev);
TAlign final2Rev;
gotoh(revSec, allele2Rev.refslice, final2Rev, semiglobal, c.aliscore);
callVariants(final2Rev, allele2Rev, var);
}
if ((c.annotatevariants) && (rs.filetype == 0)) {
now = boost::posix_time::second_clock::local_time();
std::cout << '[' << boost::posix_time::to_simple_string(now) << "] " << "Variant Annotation (" << c.annotate << ")" << std::endl;
std::string region = rs.chr + ":" + boost::lexical_cast<std::string>(rs.pos) + "-" + boost::lexical_cast<std::string>(rs.pos + rs.refslice.size());
std::string response;
if (!variantsInRegion(c, region, response)) {
std::vector<KnownVariation> kv;
int32_t numVar = parseKnownVariants(response, kv);
if (numVar > 0) {
annotateVariants(kv, var);
}
} else {
std::cerr << "Warning: Variant annotation failed." << std::endl;
c.annotatevariants = false;
}
}
// Sort variants
std::sort(var.begin(), var.end(), SortVariant<Variant>());
// VCF output
vcfOutput(c, bc, var, rs);
}
// Json output
traceAlleleAlignJsonOut(c, bc, tr, var, allele1, allele2, secrs, final1, final2, final3, dcp, a1Score, a2Score, a3Score, bp, a1a2);
now = boost::posix_time::second_clock::local_time();
std::cout << '[' << boost::posix_time::to_simple_string(now) << "] " << "Done." << std::endl;
return 0;
}
}
#endif
| [
"rauschtobi@gmail.com"
] | rauschtobi@gmail.com |
0c82f09385fe57fde373bdd0183464182211815d | a1a1619972fea1e08c5bebb5c1e7ba1678b726a4 | /Verbalizer/src/BTUtil.cpp | ec937c605b8883c995e41712575992627bfc2544 | [] | no_license | itdonline/Verbalizer | 1eb9803f3fea87dab80c3813dca526da72ebd9d4 | 0a55f5ab8b477a04cfffce9a1e991aeee49d7e5c | refs/heads/master | 2021-05-26T12:19:23.834824 | 2011-07-13T18:56:21 | 2011-07-13T18:56:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,093 | cpp | /*
* BTUtil.cpp
*
* Copyright (c) 2011, BREAKFAST LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the BREAKFAST LLC 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 BREAKFAST LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "BTUtil.h"
//-------------------------------------------------------------------
// STATIC CALLBACK FUNCTIONS
//-------------------------------------------------------------------
// Callback for disconnects
void bluetoothDisconnect_c(void *userRefCon, IOBluetoothUserNotificationRef inRef, IOBluetoothObjectRef objectRef) {
// Stop listening to BT disconnects
IOBluetoothUserNotificationUnregister(inRef);
BTUtil * btutil = static_cast <BTUtil *>(userRefCon);
ofNotifyEvent(btutil->disconnectEvent, objectRef);
}
// Callback function for connections
void bluetoothConnect_c(void *userRefCon, IOBluetoothUserNotificationRef inRef, IOBluetoothObjectRef objectRef) {
BTUtil * btutil = static_cast <BTUtil *>(userRefCon);
// Start listening to BT disconnects
IOBluetoothDeviceRegisterForDisconnectNotification(objectRef, &bluetoothDisconnect_c, btutil);
ofNotifyEvent(btutil->connectEvent, objectRef);
}
// Callback function create-connection
void bluetoothCreateConnection_c(void *userRefCon, IOBluetoothDeviceRef deviceRef, IOReturn status) {
BTUtil * btutil = static_cast <BTUtil *>(userRefCon);
// Start listening to BT disconnects
//IOBluetoothDeviceRegisterForDisconnectNotification(objectRef, &bluetoothDisconnect_c, btutil);
//ofNotifyEvent(btutil->connectEvent, deviceRef);
bool success;
success = (status == kIOReturnSuccess);
ofNotifyEvent(btutil->createConnectionEvent, success, deviceRef);
}
// Callback for RFCOMM events
void rfcommEventListener_c (IOBluetoothRFCOMMChannelRef channel_ref, void *userRefCon, IOBluetoothRFCOMMChannelEvent *event) {
BTUtil * btutil = static_cast <BTUtil *>(userRefCon);
switch (event->eventType) {
case kIOBluetoothRFCOMMNewDataEvent: // we have new client data.
ofNotifyEvent(btutil->serialDataEvent, event->u.newData, &channel_ref);
break;
case kIOBluetoothRFCOMMFlowControlChangedEvent:
ofNotifyEvent(btutil->serialFlowEvent, event->u.flowStatus, &channel_ref);
break;
case kIOBluetoothRFCOMMChannelTerminatedEvent:
ofNotifyEvent(btutil->serialCloseEvent, event->u.terminatedChannel);
break;
}
}
//-------------------------------------------------------------------
// MEMBER FUNCTIONS
//-------------------------------------------------------------------
// Show's a list of BT devices that the user can pick from
IOBluetoothObjectRef BTUtil::selectBTDevice() {
IOBluetoothDeviceRef dev = NULL;
IOBluetoothDeviceSelectorControllerRef device_selector = IOBluetoothGetDeviceSelectorController();
CFArrayRef arr = IOBluetoothDeviceSelectorRunPanelWithAttributes(device_selector, NULL);
if (arr == NULL) { return dev; }
void* arr_value = const_cast <void *>(CFArrayGetValueAtIndex(arr, 0));
dev = reinterpret_cast<IOBluetoothDeviceRef>(arr_value);
return dev;
}
bool BTUtil::connect(IOBluetoothObjectRef dev) {
return IOBluetoothDeviceOpenConnection(dev, &bluetoothCreateConnection_c, this) == kIOReturnSuccess;
}
// Start listening to connections from devices.
void BTUtil::registerListenConnect(){
IOBluetoothRegisterForDeviceConnectNotifications(&bluetoothConnect_c, this);
}
bool BTUtil::isConnected(IOBluetoothObjectRef dev) {
return IOBluetoothDeviceIsConnected(dev);
}
// Establish new RFCOMM/SPP connection channel
IOBluetoothRFCOMMChannelRef BTUtil::openRFCOMMChannel(IOBluetoothObjectRef dev) {
//printf("in openRFCOMMChannel\n");
CFArrayRef device_services = IOBluetoothDeviceGetServices(dev);
//printf("Getting SDP service record\n");
IOBluetoothSDPServiceRecordRef service_record = (IOBluetoothSDPServiceRecordRef) CFArrayGetValueAtIndex(device_services, 0);
UInt8 channel_id;
IOBluetoothRFCOMMChannelRef channel_ref;
//printf("Finding channel ID\n");
IOBluetoothSDPServiceRecordGetRFCOMMChannelID(service_record, &channel_id);
// Open channel and listen for RFCOMM data
IOBluetoothDeviceOpenRFCOMMChannelAsync(dev, &channel_ref, channel_id, &rfcommEventListener_c, this);
// printf("Releasing service record\n");
//IOBluetoothObjectRelease(service_record);
return channel_ref;
}
bool BTUtil::sendRFCOMMData(IOBluetoothRFCOMMChannelRef channel_ref, void* buf, UInt32 length) {
return (IOBluetoothRFCOMMChannelWriteAsync(channel_ref, buf, length, this) == kIOReturnSuccess);
}
// Close the channel..
void BTUtil::closeChannel(IOBluetoothRFCOMMChannelRef channel_ref) {
IOBluetoothRFCOMMChannelCloseChannel(channel_ref);
IOBluetoothObjectRelease(channel_ref);
}
// and BT connection.
void BTUtil::closeConnection(IOBluetoothObjectRef dev) {
IOBluetoothDeviceCloseConnection(dev);
}
// Get the name for the device
char *BTUtil::deviceName(IOBluetoothObjectRef dev) {
CFStringRef dev_name = IOBluetoothDeviceGetName(dev);
char *buf = const_cast<char *>(CFStringGetCStringPtr(dev_name, kCFStringEncodingMacRoman));
return buf;
}
char *BTUtil::deviceAddress(IOBluetoothObjectRef dev) {
CFStringRef dev_address = IOBluetoothDeviceGetAddressString(dev);
char *buf = const_cast<char *>(CFStringGetCStringPtr(dev_address, kCFStringEncodingMacRoman));
return buf;
}
// Returns a Bluetooth device object for the c string address.
IOBluetoothObjectRef BTUtil::deviceForAddress(const char *address) {
CFStringRef btAddressString = CFStringCreateWithCString(kCFAllocatorDefault, address, kCFStringEncodingUTF8);
BluetoothDeviceAddress *btAddressPtr;
IOBluetoothCFStringToDeviceAddress(btAddressString, btAddressPtr);
CFRelease(btAddressString);
IOBluetoothDeviceRef device = IOBluetoothDeviceCreateWithAddress(btAddressPtr);
}
| [
"mattias@breakfastny.com"
] | mattias@breakfastny.com |
204fa10bd80c243dc23b086260353e683438dec1 | 089ed0fb513f66e9b20d400b491258c99a26a429 | /sicsProject/include/sics/forwardchecking_bitset_degreesequenceprune_ac1_ind.h | 1d20b51758e5874e14eb224e2bdabe308ed4a17b | [] | no_license | bi4528/sicsProject | 95885735ce502a764d2f2854792b2cbf1a4539df | 58cc27d4a1b59e21264bd779e888b54f61e17f75 | refs/heads/master | 2023-08-24T21:35:00.638424 | 2021-10-05T20:55:26 | 2021-10-05T20:55:26 | 391,051,372 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,622 | h | #ifndef SICS_FORWARDCHECKING_BITSET_DEGREESEQUENCEPRUNE_AC1_IND_H_
#define SICS_FORWARDCHECKING_BITSET_DEGREESEQUENCEPRUNE_AC1_IND_H_
#include <iterator>
#include <utility>
#include <numeric>
#include <vector>
#include <stack>
#include <boost/dynamic_bitset.hpp>
#include "adjacency_degreesortedlistmat.h"
#include "graph_traits.h"
#include "label_equivalence.h"
#include "consistency_utilities.h"
#include "stats.h"
namespace sics {
template <
typename G,
typename H,
typename Callback,
typename IndexOrderG,
typename VertexEquiv = default_vertex_label_equiv<G, H>,
typename EdgeEquiv = default_edge_label_equiv<G, H>>
void forwardchecking_bitset_degreesequenceprune_ac1_ind(
G const & g,
H const & h,
Callback const & callback,
IndexOrderG const & index_order_g,
VertexEquiv const & vertex_equiv = VertexEquiv(),
EdgeEquiv const & edge_equiv = EdgeEquiv()) {
using IndexG = typename G::index_type;
using IndexH = typename H::index_type;
struct explorer {
adjacency_degreesortedlistmat<
IndexG,
typename G::directed_category,
typename G::vertex_label_type,
typename G::edge_label_type> g;
adjacency_degreesortedlistmat<
IndexH,
typename H::directed_category,
typename H::vertex_label_type,
typename H::edge_label_type> h;
Callback callback;
std::vector<IndexG> index_order_g;
vertex_equiv_helper<VertexEquiv> vertex_equiv;
edge_equiv_helper<EdgeEquiv> edge_equiv;
IndexG m;
IndexH n;
using bits_type = std::conditional_t<
is_directed_v<H>,
std::tuple<boost::dynamic_bitset<>, boost::dynamic_bitset<>>,
std::tuple<boost::dynamic_bitset<>>>;
std::vector<bits_type> h_bits;
std::vector<bits_type> h_c_bits;
void build_h_bits() {
for (IndexH i=0; i<n; ++i) {
std::get<0>(h_bits[i]).resize(n);
std::get<0>(h_c_bits[i]).resize(n);
if constexpr (is_directed_v<H>) {
std::get<1>(h_bits[i]).resize(n);
std::get<1>(h_c_bits[i]).resize(n);
}
}
for (IndexH i=0; i<n; ++i) {
for (IndexH j=0; j<n; ++j) {
if (h.edge(i, j)) {
std::get<0>(h_bits[i]).set(j);
if constexpr (is_directed_v<H>) {
std::get<1>(h_bits[j]).set(i);
}
} else {
std::get<0>(h_c_bits[i]).set(j);
if constexpr (is_directed_v<H>) {
std::get<1>(h_c_bits[j]).set(i);
}
}
}
}
}
IndexG level;
std::vector<IndexH> map;
std::vector<boost::dynamic_bitset<>> M;
void build_M() {
for (IndexG u=0; u<m; ++u) {
for (IndexH v=0; v<n; ++v) {
if (vertex_equiv(g, u, h, v) &&
degree_condition(g, u, h, v) &&
degree_sequence_condition(g, u, h, v)) {
M[u].set(v);
}
}
}
ac1();
}
std::stack<std::vector<boost::dynamic_bitset<>>> M_st;
explorer(
G const & g,
H const & h,
Callback const & callback,
IndexOrderG const & index_order_g,
VertexEquiv const & vertex_equiv,
EdgeEquiv const & edge_equiv)
: g{g},
h{h},
callback{callback},
index_order_g{index_order_g},
vertex_equiv{vertex_equiv},
edge_equiv{edge_equiv},
m{g.num_vertices()},
n{h.num_vertices()},
h_bits(n),
h_c_bits(n),
level{0},
map(m, n),
M(m, boost::dynamic_bitset<>(n)) {
build_h_bits();
build_M();
}
bool explore() {
SICS_STATS_STATE;
if (level == m) {
return callback(std::as_const(*this));
} else {
auto x = index_order_g[level];
bool proceed = true;
for (auto y=M[x].find_first(); y!=boost::dynamic_bitset<>::npos; y=M[x].find_next(y)) {
M_st.push(M);
if (forward_check(y) && ac1()) {
map[x] = y;
++level;
proceed = explore();
--level;
map[x] = n;
}
M = M_st.top();
M_st.pop();
if (!proceed) {
break;
}
}
return proceed;
}
}
bool forward_check(IndexH y) {
auto x = index_order_g[level];
bool not_empty = true;
for (IndexG i=level+1; i<m && not_empty; ++i) {
auto u = index_order_g[i];
M[u].reset(y);
if (g.edge(x, u)) {
M[u] &= std::get<0>(h_bits[y]);
} else {
M[u] &= std::get<0>(h_c_bits[y]);
}
if constexpr (is_directed_v<G>) {
if (g.edge(u, x)) {
M[u] &= std::get<1>(h_bits[y]);
} else {
M[u] &= std::get<1>(h_c_bits[y]);
}
}
not_empty = M[u].any();
}
return not_empty;
}
bool ac1() {
bool change;
do {
change = false;
for (IndexG i0=level+1; i0<m; ++i0) {
auto u0 = index_order_g[i0];
for (auto v0=M[u0].find_first(); v0!=boost::dynamic_bitset<>::npos; v0=M[u0].find_next(v0)) {
for (IndexG u1=0; u1<m; ++u1) {
if (u1 != u0) {
bool exists = false;
for (auto v1=M[u1].find_first(); v1!=boost::dynamic_bitset<>::npos; v1=M[u1].find_next(v1)) {
if constexpr (is_directed_v<G>) {
if (v0 != v1 &&
(g.edge(u0, u1) == h.edge(v0, v1)) && (!g.edge(u0, u1) || edge_equiv(g, u0, u1, h, v0, v1)) &&
(g.edge(u1, u0) == h.edge(v1, v0)) && (!g.edge(u1, u0) || edge_equiv(g, u1, u0, g, v1, v0))) {
exists = true;
break;
}
} else {
if (v0 != v1 &&
g.edge(u0, u1) == h.edge(v0, v1) && (!g.edge(u0, u1) || edge_equiv(g, u0, u1, h, v0, v1))) {
exists = true;
break;
}
}
}
if (!exists) {
M[u0].reset(v0);
change = true;
break;
}
}
}
}
if (!M[u0].any()) {
return false;
}
}
} while (change);
return true;
}
} e(g, h, callback, index_order_g, vertex_equiv, edge_equiv);
e.explore();
}
} // namespace sics
#endif // SICS_FORWARDCHECKING_BITSET_DEGREESEQUENCEPRUNE_AC1_IND_H_
| [
"36712965+bi4528@users.noreply.github.com"
] | 36712965+bi4528@users.noreply.github.com |
ce01aca281cdea0a1218278e73dca565d034527c | 8f11b828a75180161963f082a772e410ad1d95c6 | /packages/vehicle/include/device/SBSonar.h | 4ec0d08eb41af8adf5f80dee086243f27aa1f9d5 | [] | no_license | venkatarajasekhar/tortuga | c0d61703d90a6f4e84d57f6750c01786ad21d214 | f6336fb4d58b11ddfda62ce114097703340e9abd | refs/heads/master | 2020-12-25T23:57:25.036347 | 2017-02-17T05:01:47 | 2017-02-17T05:01:47 | 43,284,285 | 0 | 0 | null | 2017-02-17T05:01:48 | 2015-09-28T06:39:21 | C++ | UTF-8 | C++ | false | false | 2,430 | h | /*
* Copyright (C) 2008 Robotics at Maryland
* Copyright (C) 2008 Joseph Lisee <jlisee@umd.edu>
* All rights reserved.
*
* Author: Joseph Lisee <jlisee@umd.edu>
* File: packages/vision/include/device/SBSonar.h
*/
#ifndef RAM_VEHICLE_DEVICE_SBPOWER_07_19_2008
#define RAM_VEHICLE_DEVICE_SBPOWER_07_19_2008
// STD Includes
#include <string>
// Project Includes
#include "vehicle/include/device/Device.h"
#include "vehicle/include/device/ISonar.h"
#include "core/include/ConfigNode.h"
#include "core/include/ReadWriteMutex.h"
// Must Be Included last
#include "vehicle/include/Export.h"
namespace ram {
namespace vehicle {
namespace device {
class RAM_EXPORT SBSonar :
public Device,
public ISonar
// boost::noncopyable
{
public:
/** Generated when we get a new ping */
static const core::Event::EventType UPDATE;
SBSonar(core::ConfigNode config,
core::EventHubPtr eventHub = core::EventHubPtr(),
IVehiclePtr vehicle = IVehiclePtr());
virtual ~SBSonar();
virtual math::Vector3 getDirection();
virtual double getRange();
virtual core::TimeVal getPingTime();
// Not used updatable stuff
virtual std::string getName() { return Device::getName(); }
virtual void update(double timestep) {}
virtual void setPriority(core::IUpdatable::Priority) {}
virtual core::IUpdatable::Priority getPriority() {
return IUpdatable::NORMAL_PRIORITY;
}
virtual void setAffinity(size_t) {};
virtual int getAffinity() {
return -1;
};
virtual void background(int interval) {
//Updatable::background(interval);
};
virtual void unbackground(bool join = false) {
//Updatable::unbackground(join);
};
virtual bool backgrounded() {
return true;
//return Updatable::backgrounded();
};
private:
/** SensorBoard::TEMPSENSOR_UPDATE event handler */
void onSonarUpdate(core::EventPtr event);
core::ReadWriteMutex m_mutex;
math::Vector3 m_direction;
double m_range;
core::TimeVal m_pingTime;
/** Sensor Board from which to access the hardware */
SensorBoardPtr m_sensorBoard;
/** SONAR_UPDATE event connection */
core::EventConnectionPtr m_connection;
};
} // namespace device
} // namespace vehicle
} // namespace ram
#endif // RAM_VEHICLE_DEVICE_SBPOWER_07_19_2008
| [
"dhakimdahakim@gmail.com"
] | dhakimdahakim@gmail.com |
012259e0f8bb9e690c1112add7a1fa206d0224b7 | be4737ec5e569506a3beea5cdfedafdd778e32e1 | /Array/frequenciesranges.cpp | 893b072b38496b65c3be6efbeba78d0cb408a8b5 | [] | no_license | Samykakkar/DSA-practice | 8fd49c690f9c6af56437cb09475e7796538df77b | d10938f34e9467688f178b6570ccc740d3cc4dff | refs/heads/master | 2023-07-24T22:10:26.953125 | 2021-09-06T09:26:00 | 2021-09-06T09:26:00 | 392,998,137 | 0 | 1 | null | 2021-08-13T10:46:25 | 2021-08-05T10:21:28 | C++ | UTF-8 | C++ | false | false | 128 | cpp | #include <iostream>
using namespace std;
void frequencyCount(vector<int> &arr, int N, int P)
int main()
{
return 0;
} | [
"sam8377984375@gmail.com"
] | sam8377984375@gmail.com |
ebeb22cb43dda3a7dad62506e38f64a734e6dc5a | 09cf8c90c4bbcc27a7a7c64fa7907d759f4bf2e9 | /week-04/day-02/01-PostIt/post_it.cpp | 063537f63cb8442d49f64f99a5d5dc68cd650361 | [] | no_license | green-fox-academy/FanniTakax | b52a4d03cb6b884779c8d3585be7086e33b0c5ae | 541f08ea3a13c5d2ce79acbe64b73b3c35019973 | refs/heads/master | 2020-04-02T00:50:06.685417 | 2019-01-28T10:52:11 | 2019-01-28T10:52:11 | 153,823,928 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 432 | cpp | //
// Created by malajabi on 11/13/2018.
//
#include "post_it.h"
PostIt::PostIt(std::string backgroundColor, std::string text, std::string textColor)
{
_backgroundColor = backgroundColor;
_text = text;
_textColor = textColor;
}
std::string PostIt::getBackgroundColor()
{
return _backgroundColor;
}
std::string PostIt::getText()
{
return _text;
}
std::string PostIt::getTextColor()
{
return _textColor;
} | [
"tkcsfni@gmail.com"
] | tkcsfni@gmail.com |
d956a9f4e41008f147950f9e83c56f15d303e9f6 | b3c64bd7b1997afeaa0b847d80e9d8bbbbe4ed7e | /scripts/kalimdor/maraudon/boss_noxxion.cpp | 29ae76b25f48545c406e5c9a99d2d38dd2fcf322 | [] | no_license | Corsol/ScriptDev3 | 3d7f34d6c3689c12d53165b9bfaf4ee8d969e705 | 7700e5ec4f9f79aa4e63e9e6e74c60d84d428602 | refs/heads/master | 2021-01-15T20:33:37.635689 | 2015-07-31T21:34:53 | 2015-07-31T21:34:53 | 40,475,601 | 1 | 0 | null | 2015-08-10T09:55:40 | 2015-08-10T09:55:40 | null | UTF-8 | C++ | false | false | 4,845 | cpp | /**
* ScriptDev3 is an extension for mangos providing enhanced features for
* area triggers, creatures, game objects, instances, items, and spells beyond
* the default database scripting in mangos.
*
* Copyright (C) 2006-2013 ScriptDev2 <http://www.scriptdev2.com/>
* Copyright (C) 2014-2015 MaNGOS <https://getmangos.eu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
/**
* ScriptData
* SDName: Boss_Noxxion
* SD%Complete: 100
* SDComment: None
* SDCategory: Maraudon
* EndScriptData
*/
#include "precompiled.h"
enum
{
SPELL_TOXICVOLLEY = 21687,
SPELL_UPPERCUT = 22916,
SPELL_NOXXION_SPAWNS_AURA = 21708,
SPELL_NOXXION_SPAWNS_SUMMON = 21707,
};
struct boss_noxxion : public CreatureScript
{
boss_noxxion() : CreatureScript("boss_noxxion") {}
struct boss_noxxionAI : public ScriptedAI
{
boss_noxxionAI(Creature* pCreature) : ScriptedAI(pCreature) { }
uint32 m_uiToxicVolleyTimer;
uint32 m_uiUppercutTimer;
uint32 m_uiSummonTimer;
void Reset() override
{
m_uiToxicVolleyTimer = 7000;
m_uiUppercutTimer = 16000;
m_uiSummonTimer = 19000;
}
void JustSummoned(Creature* pSummoned) override
{
if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0))
{
pSummoned->AI()->AttackStart(pTarget);
}
}
void UpdateAI(const uint32 diff) override
{
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
{
return;
}
if (m_uiToxicVolleyTimer < diff)
{
if (DoCastSpellIfCan(m_creature, SPELL_TOXICVOLLEY) == CAST_OK)
{
m_uiToxicVolleyTimer = 9000;
}
}
else
{
m_uiToxicVolleyTimer -= diff;
}
if (m_uiUppercutTimer < diff)
{
if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_UPPERCUT) == CAST_OK)
{
m_uiUppercutTimer = 12000;
}
}
else
{
m_uiUppercutTimer -= diff;
}
if (m_uiSummonTimer < diff)
{
if (DoCastSpellIfCan(m_creature, SPELL_NOXXION_SPAWNS_AURA) == CAST_OK)
{
m_uiSummonTimer = 40000;
}
}
else
{
m_uiSummonTimer -= diff;
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* pCreature) override
{
return new boss_noxxionAI(pCreature);
}
};
struct aura_dummy_noxxion_spawns : public AuraScript
{
aura_dummy_noxxion_spawns() : AuraScript("aura_dummy_noxxion_spawns") {}
bool OnDummyApply(const Aura* pAura, bool bApply) override
{
if (pAura->GetId() == SPELL_NOXXION_SPAWNS_AURA && pAura->GetEffIndex() == EFFECT_INDEX_0)
{
if (Creature* pTarget = (Creature*)pAura->GetTarget())
{
if (bApply)
{
pTarget->CastSpell(pTarget, SPELL_NOXXION_SPAWNS_SUMMON, true);
pTarget->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
}
else
{
pTarget->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
}
}
}
return true;
}
};
void AddSC_boss_noxxion()
{
Script* s;
s = new boss_noxxion();
s->RegisterSelf();
s = new aura_dummy_noxxion_spawns();
s->RegisterSelf();
//pNewScript = new Script;
//pNewScript->Name = "boss_noxxion";
//pNewScript->GetAI = &GetAI_boss_noxxion;
//pNewScript->pEffectAuraDummy = &EffectAuraDummy_spell_aura_dummy_noxxion_spawns;
//pNewScript->RegisterSelf();
}
| [
"Antz@getMaNGOS.co.uk"
] | Antz@getMaNGOS.co.uk |
ea558f947cd432263809d1e60bf06dabc49efc43 | 3c069491ee0fd844f65abff525902cb9f8b95544 | /tests/test_twounitschanger.cpp | ee459a63893c9845200199c658ac635cd24484eb | [] | no_license | 3dcl/osghimmel | 5a8f20dc8be8d7e609703baf9cce2ebfcc6cabfc | 4d51e954d1f94a7ea7599ce12fdca5f44d0f2bf3 | refs/heads/master | 2021-01-25T07:11:47.935307 | 2015-01-16T10:23:37 | 2015-01-16T10:23:37 | 23,115,750 | 1 | 0 | null | 2015-01-16T10:23:37 | 2014-08-19T15:40:11 | C++ | ISO-8859-3 | C++ | false | false | 3,038 | cpp |
// Copyright (c) 2011-2012, Daniel Müller <dm@g4t3.de>
// Computer Graphics Systems Group at the Hasso-Plattner-Institute, Germany
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Computer Graphics Systems Group at the
// Hasso-Plattner-Institute (HPI), Germany 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.
#include "test_twounitschanger.h"
#include "test.h"
#include "osgHimmel/twounitschanger.h"
using namespace osgHimmel;
void test_twounitschanger()
{
TwoUnitsChanger tuc;
// Test case shown in documentation on wiki.
tuc.setTransitionDuration(0.4f);
tuc.pushUnit(0, 0.0f);
tuc.pushUnit(1, 0.5f);
ASSERT_EQ(int, 0, tuc.getSrcUnit(0.0f));
ASSERT_EQ(int, 0, tuc.getSrcUnit(0.8f));
ASSERT_EQ(int, 1, tuc.getSrcUnit(0.2f));
ASSERT_EQ(int, 1, tuc.getSrcUnit(0.5f));
ASSERT_EQ(int, 1, tuc.getSrcUnit(0.3f));
ASSERT_EQ(int, 0, tuc.getSrcUnit(0.7f));
ASSERT_AB(float, 0.00, tuc.getSrcAlpha(0.8f), 0.0001);
ASSERT_AB(float, 0.25, tuc.getSrcAlpha(0.9f), 0.0001);
ASSERT_AB(float, 0.50, tuc.getSrcAlpha(0.0f), 0.0001);
ASSERT_AB(float, 0.75, tuc.getSrcAlpha(0.1f), 0.0001);
ASSERT_AB(float, 0.00, tuc.getSrcAlpha(0.2f), 0.0001);
ASSERT_AB(float, 0.00, tuc.getSrcAlpha(0.3f), 0.0001);
ASSERT_AB(float, 0.25, tuc.getSrcAlpha(0.4f), 0.0001);
ASSERT_AB(float, 0.50, tuc.getSrcAlpha(0.5f), 0.0001);
ASSERT_AB(float, 0.75, tuc.getSrcAlpha(0.6f), 0.0001);
ASSERT_AB(float, 0.00, tuc.getSrcAlpha(0.7f), 0.0001);
TEST_REPORT();
}
| [
"jan.klimke@hpi.uni-potsdam.de"
] | jan.klimke@hpi.uni-potsdam.de |
c7449c09fb51488295a3380070ac4abd71d82329 | 68e0727b9692f7491e9a1daa9fc0f550a0ea6637 | /inc/core/Application.hpp | 551eab888acf29a2c7297a8ef811cf31e68234ad | [] | no_license | ConnorHeidema/EmmoriaV2 | b3ea1fb4266362137677d96d00b2996e5d074e84 | 982d941e8713e0106a60ac9f7e4adb0e10477268 | refs/heads/master | 2023-02-16T20:48:02.393694 | 2021-01-15T02:54:22 | 2021-01-15T02:54:22 | 282,720,526 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | hpp | #ifndef __APPLICATION__
#define __APPLICATION__
#include <entt/entt.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
class Application
{
public:
Application();
bool Start();
private:
void Initialize_();
void RunLoop_();
void CheckForEvents_();
bool UpdateWhenNotFocused_();
entt::registry m_reg;
sf::RenderWindow m_renderWindow;
std::string const m_kOnlyWhenFocused;
};
#endif | [
"heidema.connor@gmail.com"
] | heidema.connor@gmail.com |
83db6bf04ba6f360170e9b7ee837acc4fc98c5b5 | 2809a20e2b8a6cbe39abf94fe0d74d05567c43f7 | /include/MatchVirtualCallee.h | a713b479e9e370eee39feb4466144974d6fd4301 | [
"MIT"
] | permissive | shakhand/CodingAssistant-Clang | 00daab03121874d503b388c15d20dd5fcdc4c0ae | 89346ddf7100feb6a09d02b79143deb7b824d6c3 | refs/heads/master | 2020-06-21T01:20:01.574974 | 2015-01-04T04:40:27 | 2015-01-04T04:40:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 418 | h | #ifndef _MATCH_VIRTUAL_CALLEE_H
#define _MATCH_VIRTUAL_CALLEE_H
#include "ASTUtility.h"
namespace EffectiveCPP {
using namespace clang::ast_matchers;
extern StatementMatcher ctorCallVtlMatcherEC;
extern StatementMatcher dtorCallVtlMatcherEC;
class CtorCallVtlPrinter : public MatchFinder::MatchCallback {
public:
virtual void run(const MatchFinder::MatchResult &Result);
};
}
#endif
| [
"ji.taoran@hotmail.com"
] | ji.taoran@hotmail.com |
c44a779746bf104aaa0515d94a5a9bb07e1c9c40 | 92c16d7ade01a5622669f47d10c9fb872d22adbb | /CT/Project1/pBall.h | 12270f67af6728a395f5270ab836a77c702a00b1 | [] | no_license | sonlechiht/DA2-LTHDT-TH | e1937cdede3bdc7064fbbe3f36b588474432dc39 | d57a699e1cbf123f6eebebd82cfc8a773bcc552d | refs/heads/master | 2022-12-11T04:55:55.537062 | 2019-12-13T14:36:44 | 2019-12-13T14:36:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 632 | h | #pragma once
#include"iostream"
#include"time.h"
#include"conio.h"
using namespace std;
enum Dir { STOP = 0, LEFT = 1, RIGHT = 2, UPLEFT = 3, UPRIGHT = 4, DOWNLEFT = 5, DOWNRIGHT = 6 };
class pBall
{
private:
int x, y;//TOA DO HIEN TAI CUA QUA BONG'
int defaultX, defaultY;//TOA DO. MAC. DINH. CUA QUA BONG'
Dir direction;//HUONG' DI CHUYEN CUA QUA BONG'
public:
pBall(int posX, int posY);
void reset();
void changeDir(Dir d);
void RandomDir();
void move();
friend ostream& operator<<(ostream& out, pBall c);
inline int getX() { return x; };
inline int getY() { return y; };
inline int getDir() { return direction; };
}; | [
"55779483+lechisonht@users.noreply.github.com"
] | 55779483+lechisonht@users.noreply.github.com |
19d29bd59b823b1c4c54d78b928c2a6598f2f9f3 | 717badf182457b194274cd58bc7d9f647ebe02ec | /FariaLib/SkyWorld.cpp | c7fe18a504e730a2256db1e72e49f8cbcfcc2044 | [
"MIT"
] | permissive | dennisjenkins75/FariaRomEditor | e319545563a2f7b071192141fd547b62124dc5be | 5050ce9a498ecb4ad5f7ffc76503cce258961cba | refs/heads/master | 2020-12-24T14:44:44.747900 | 2013-10-23T04:22:12 | 2013-10-23T04:22:12 | 13,792,651 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,418 | cpp | /* Skyworld.cpp */
static const int SKY_WORLD_WIDTH = 64;
static const int SKY_WORLD_HEIGHT = 64;
void FL_DecompressSkyworld
(
const unsigned char *rom, // [IN] Pointer to 256K Faria ROM image.
unsigned char *buffer // [OUT] Pointer to 4K (64x64 @1byte/tile).
)
{
const unsigned char *pSrc = rom + 0xf8e9;
unsigned char *pDest = buffer;
int i;
// One byte of SRC becomes 4 tiles. We just hack out the bits,
// in the form aabbccdd for the 4 tiles.
for (i = 0; i < SKY_WORLD_HEIGHT * SKY_WORLD_WIDTH / 4; i++)
{
*(pDest++) = (*pSrc >> 6) & 0x03;
*(pDest++) = (*pSrc >> 4) & 0x03;
*(pDest++) = (*pSrc >> 2) & 0x03;
*(pDest++) = (*pSrc >> 0) & 0x03;
pSrc++;
}
}
static const int CAVE_WORLD_WIDTH = 80;
static const int CAVE_WORLD_HEIGHT = 80;
void FL_DecompressCaveworld
(
const unsigned char *rom, // [IN] Pointer to 256K Faria ROM image.
unsigned char *buffer // [OUT] Pointer to 1600 bytes (80x80 @ 4 tiles / byte).
)
{
const unsigned char *pSrc = rom + 0x59a2;
unsigned char *pDest = buffer;
int i;
// One byte of SRC becomes 4 tiles. We just hack out the bits,
// in the form aabbccdd for the 4 tiles.
for (i = 0; i < CAVE_WORLD_HEIGHT * CAVE_WORLD_WIDTH / 4; i++)
{
*(pDest++) = (*pSrc >> 6) & 0x03;
*(pDest++) = (*pSrc >> 4) & 0x03;
*(pDest++) = (*pSrc >> 2) & 0x03;
*(pDest++) = (*pSrc >> 0) & 0x03;
pSrc++;
}
}
| [
"dennis.jenkins.75@gmail.com"
] | dennis.jenkins.75@gmail.com |
f11ae16a0c1dda52d33051a375b3b205a345386e | b4753c423c149c3448ed84b111b068de2bbfe9b5 | /src/tools/jetVetoMaps.cpp | b16ff7f557e1de49ec56621c10f94f8f23d35826 | [] | no_license | dmeuser/top_analysis | 8773667dfcf0c55ee849bec5a80f8a497f970220 | 6084cea81d2c662b93043d6bcf920fca24bf9a3d | refs/heads/master | 2023-04-06T00:26:42.129989 | 2023-03-16T12:22:53 | 2023-03-16T12:22:53 | 179,239,380 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,445 | cpp | #include "jetVetoMaps.hpp"
#include "Config.hpp"
#include <iostream>
JetVetoMaps::JetVetoMaps(const std::string& map_fileName, const std::string& map_histName, const std::string& map_histName_MC16, const Systematic::Systematic& systematic, const int year_int, const bool is2016) :
systematic_(systematic),
vetoMap_hist_(0),
vetoMap_hist_MC16_(0),
is2016_(is2016)
{
std::cout << "--- Beginning preparation of jet veto maps\n";
// Check existence of input files
if(!io::fileExists(map_fileName)){
std::cerr<<"ERROR in constructor of JetVetoMaps! "
<<"VetoMap file does not exist\n...break\n"<<std::endl;
exit(220);
}
// ~HEM1516only = (systematic.type()==Systematic::applyJetVetoMaps_HEM1516);
HEM1516only = (year_int==3); //apply HEM1516 only if UL18 is used
// Read required histogram
this->prepareHists(map_fileName,map_histName,map_histName_MC16,vetoMap_hist_,vetoMap_hist_MC16_);
}
void JetVetoMaps::prepareHists(const std::string& map_fileName, const std::string& map_histName, const std::string& map_histName_MC16,TH2* &vetoMap_hist_, TH2* &vetoMap_hist_MC16_)
{
io::RootFileReader vetoMap_file(map_fileName.c_str(),"",false);
// Access histograms
vetoMap_hist_ = (TH2*)(vetoMap_file.read<TH2F>(map_histName));
if (is2016_) vetoMap_hist_MC16_ = (TH2*)(vetoMap_file.read<TH2F>(map_histName_MC16));
if(!vetoMap_hist_ || (is2016_ && !vetoMap_hist_MC16_)){
std::cerr<<"Error in JetVetoMaps::prepareHists()! TH2 not found in: "<<map_fileName
<<"\n...break\n"<<std::endl;
exit(221);
}
// Store histogram in memory
vetoMap_hist_->SetDirectory(0);
if (is2016_) vetoMap_hist_MC16_->SetDirectory(0);
}
const bool JetVetoMaps::checkVetoMap(const std::vector<tree::Jet>& jets)
{
for(size_t iJet=0; iJet<jets.size(); ++iJet){
if(HEM1516only){
if (jets.at(iJet).p.Eta()>0 || jets.at(iJet).p.Phi()>0) continue; // Dirty fix to take only the part of the vetomaps, where HEM1516 is shown
}
if (vetoMap_hist_->GetBinContent(vetoMap_hist_->GetXaxis()->FindBin(jets.at(iJet).p.Eta()),vetoMap_hist_->GetYaxis()->FindBin(jets.at(iJet).p.Phi()))>0) return false;
if (is2016_){
if (vetoMap_hist_MC16_->GetBinContent(vetoMap_hist_MC16_->GetXaxis()->FindBin(jets.at(iJet).p.Eta()),vetoMap_hist_MC16_->GetYaxis()->FindBin(jets.at(iJet).p.Phi()))>0) return false;
}
}
return true;
}
| [
"danilo.meuser@rwth-aachen.de"
] | danilo.meuser@rwth-aachen.de |
3ec031ddc6075813ed44a34ab705021d3dd46e9c | 622371322a152750ae23eb8ba93454e2e5f28208 | /src/rule_bounding.cpp | e4f7fbeb2f4ef6b6bf512bb7e537f8dde4077d71 | [
"MIT"
] | permissive | foopod/gba-boids | 1c5255b530cfc9824ee21afb13432ed05c3f3a97 | ad8877f7630f8a2667955d8cdc8a53afba9adb63 | refs/heads/main | 2023-04-29T06:30:22.414447 | 2021-05-25T05:05:13 | 2021-05-25T05:05:13 | 370,298,840 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 758 | cpp | #include "rule_bounding.h"
#include "boid.h"
#include "bn_log.h"
#include "bn_math.h"
void BoundingRule::execute(bn::vector<Boid, 32>& boids_ptr){
bn::vector<Boid, 32>* boids = &boids_ptr;
// for each boid
for(int i = 0; i < boids->size(); i++){
Boid boid = boids->at(i);
if(boid.pos().x() < -80){
boids->at(i).add_vel(bn::fixed_point(_bounding_force, 0));
} else if(boid.pos().x() > 80){
boids->at(i).add_vel(bn::fixed_point(-_bounding_force, 0));
}
if(boid.pos().y() < -50){
boids->at(i).add_vel(bn::fixed_point(0, _bounding_force));
} else if(boid.pos().y() > 50){
boids->at(i).add_vel(bn::fixed_point(0, -_bounding_force));
}
}
}
| [
"jonathonshields@gmail.com"
] | jonathonshields@gmail.com |
1cc0f0ef3baf3e6311e893f3d7b20d3837a5072a | 9602e36990888087b0d3405218e5b0a850c00315 | /project/src/matroids/src/transversal_matroid.h | 6156f221af6b6fd3900b4fd3271c29b43f30b536 | [
"MIT"
] | permissive | fafianie/multiway_cut | e6360f3e48f4ac6b666cae0b135e638fe76e06d6 | 52355c9a754287545c060b3ae97b4e11aacd0bfb | refs/heads/master | 2021-06-02T13:20:55.710095 | 2020-08-15T15:40:14 | 2020-08-15T15:40:14 | 133,058,079 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 188 | h | #pragma once
#include "matroid.h"
#include "graph.h"
#include "galois.h"
class TransversalMatroid {
public:
static Matroid generate(Graph&, Galois*, std::vector<int>&);
}; | [
"stefan.fafianie@asml.com"
] | stefan.fafianie@asml.com |
f5c753c52c8deb9ddd21d375fe46cafa3a3d8ef0 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/thread/barrier.hpp | fad457dbc98bdbbf2bd3d94e25b2ddac4b30e238 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,008 | hpp | // Copyright (C) 2002-2003
// David Moore, William E. Kempf
//
// 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)
#ifndef BOOST_BARRIER_JDM030602_HPP
#define BOOST_BARRIER_JDM030602_HPP
#include <boost/thread/detail/config.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
namespace boost {
class BOOST_THREAD_DECL barrier
{
public:
barrier(unsigned int count);
~barrier();
bool wait();
private:
mutex m_mutex;
// disable warnings about non dll import
// see: http://www.boost.org/more/separate_compilation.html#dlls
#ifdef BOOST_MSVC
# pragma warning(push)
# pragma warning(disable: 4251 4231 4660 4275)
#endif
condition m_cond;
#ifdef BOOST_MSVC
# pragma warning(pop)
#endif
unsigned int m_threshold;
unsigned int m_count;
unsigned int m_generation;
};
} // namespace boost
#endif
| [
"66430417@qq.com@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | 66430417@qq.com@e2c90bd7-ee55-cca0-76d2-bbf4e3699278 |
6c6b249918e5381b1f0940928ca5fef98b5bfec9 | 706b18780794944774b4a29244c1867610a896a0 | /src/protocol/KeyValueResponseParser.h | 01b8ed20ae3448610e6ee46c848a59bce98ed594 | [
"Apache-2.0",
"BSD-3-Clause",
"curl",
"Zlib"
] | permissive | dlopes7/openkit-native | cb5daf7c2ad858f195d02884e840445b96a2369d | 669871b0f48d85534c3ecfdfca2c9fb6de5811f9 | refs/heads/master | 2020-09-17T06:10:52.992923 | 2020-03-23T00:50:15 | 2020-03-23T00:50:15 | 224,014,912 | 0 | 0 | NOASSERTION | 2020-03-23T00:50:17 | 2019-11-25T18:27:39 | null | UTF-8 | C++ | false | false | 2,512 | h | /**
* Copyright 2018-2019 Dynatrace LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _PROTOCOL_KEYVALUERESPONSEPARSER_H
#define _PROTOCOL_KEYVALUERESPONSEPARSER_H
#include "IResponseAttributes.h"
#include "ResponseAttributes.h"
#include "core/UTF8String.h"
#include <memory>
#include <unordered_map>
namespace protocol
{
class KeyValueResponseParser
{
public:
static const std::string RESPONSE_KEY_MAX_BEACON_SIZE_IN_KB;
static const std::string RESPONSE_KEY_SEND_INTERVAL_IN_SEC;
static const std::string RESPONSE_KEY_CAPTURE;
static const std::string RESPONSE_KEY_REPORT_CRASHES;
static const std::string RESPONSE_KEY_REPORT_ERRORS;
static const std::string RESPONSE_KEY_SERVER_ID;
static const std::string RESPONSE_KEY_MULTIPLICITY;
static std::shared_ptr<IResponseAttributes> parse(const core::UTF8String& keyValuePairResponse);
private:
KeyValueResponseParser() {}
static void applyBeaconSizeInKb(
protocol::ResponseAttributes::Builder& builder,
std::unordered_map<std::string, std::string>& keyValuePairs
);
static void applySendIntervalInSec(
protocol::ResponseAttributes::Builder& builder,
std::unordered_map<std::string, std::string>& keyValuePairs
);
static void applyCapture(
protocol::ResponseAttributes::Builder& builder,
std::unordered_map<std::string, std::string>& keyValuePairs
);
static void applyReportCrashes(
protocol::ResponseAttributes::Builder& builder,
std::unordered_map<std::string, std::string>& keyValuePairs
);
static void applyReportErrors(
protocol::ResponseAttributes::Builder& builder,
std::unordered_map<std::string, std::string>& keyValuePairs
);
static void applyServerId(
protocol::ResponseAttributes::Builder& builder,
std::unordered_map<std::string, std::string>& keyValuePairs
);
static void applyMultiplicity(
protocol::ResponseAttributes::Builder& builder,
std::unordered_map<std::string, std::string>& keyValuePairs
);
};
}
#endif
| [
"openkit@dynatrace.com"
] | openkit@dynatrace.com |
7cbe7e327f5510b68a195291affab399d1cc37b4 | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-iot-jobs-data/source/model/DescribeJobExecutionRequest.cpp | 6fd54339dbb6deee11fdc9f02856355f62253f22 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 1,275 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iot-jobs-data/model/DescribeJobExecutionRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/http/URI.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::IoTJobsDataPlane::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws::Http;
DescribeJobExecutionRequest::DescribeJobExecutionRequest() :
m_jobIdHasBeenSet(false),
m_thingNameHasBeenSet(false),
m_includeJobDocument(false),
m_includeJobDocumentHasBeenSet(false),
m_executionNumber(0),
m_executionNumberHasBeenSet(false)
{
}
Aws::String DescribeJobExecutionRequest::SerializePayload() const
{
return {};
}
void DescribeJobExecutionRequest::AddQueryStringParameters(URI& uri) const
{
Aws::StringStream ss;
if(m_includeJobDocumentHasBeenSet)
{
ss << m_includeJobDocument;
uri.AddQueryStringParameter("includeJobDocument", ss.str());
ss.str("");
}
if(m_executionNumberHasBeenSet)
{
ss << m_executionNumber;
uri.AddQueryStringParameter("executionNumber", ss.str());
ss.str("");
}
}
| [
"sdavtaker@users.noreply.github.com"
] | sdavtaker@users.noreply.github.com |
ba7a546518fa37e3220e147d463b65d2f694512b | 87fab40520223f50e865b5b0fbdde5a635773978 | /Bulb/bulb_settings.cpp | 10c0804c89146b373397100c1db126ed3d404506 | [] | no_license | JBarrada/Bulb | 765ea906e20c0ba9ae5726ead330c2dca242a170 | 5acc66a2e11987280647e0e5cd55e8ffc9874aef | refs/heads/master | 2022-12-19T06:46:26.082846 | 2020-10-01T20:55:42 | 2020-10-01T20:55:42 | 98,884,608 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,146 | cpp | #include "bulb_settings.h"
BulbSave::BulbSave() {
file_name = "";
image = BMP(256, 256);
}
bool BulbSave::load(string save_file_name) {
file_name = save_file_name;
image.load(file_name);
ifstream save_file(file_name);
char verify_string[10];
memset(verify_string, 0, 10);
save_file.seekg(image.bmp_file_size, ios::beg);
save_file.read(verify_string, 8);
save_file.close();
if (string(verify_string) == "BULBSAVE") {
vector<string> file_name_split = split_string(file_name, "\\");
clean_name = file_name_split.back().substr(0, file_name_split.back().size() - 4);
glGenTextures(1, &tex_id);
glBindTexture(GL_TEXTURE_2D, tex_id);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image.image_data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
return true;
} else {
return false;
}
}
BulbSettings::BulbSettings(BulbShader *bulb_shader, BulbControlSettings *control_settings, DrawingTools *drawing_tools) {
this->bulb_shader = bulb_shader;
this->control_settings = control_settings;
this->drawing_tools = drawing_tools;
settings_open = false;
menu_open = 0;
info_text = "";
settings_font = GLUT_BITMAP_HELVETICA_12;
font_height = 20;
load_menu_item_highlight = 0;
load_menu_item_selected = false;
load_menu_item_sub_highlight = 0;
load_menu_delete_hold = 0;
save_menu_item_highlight = 0;
save_menu_item_selected = false;
save_menu_item_sub_highlight = 0;
save_menu_overwrite_hold = 0;
save_menu_current_save_name = "";
control_menu_item_highlight = 0;
control_menu_item_selected = false;
control_menu_item_sub_highlight = 0;
shader_menu_item_highlight = 0;
shader_menu_item_selected = false;
shader_menu_item_sub_highlight = 0;
shader_menu_item_sub_selected = false;
shader_menu_item_sub_animate_highlight = 0;
shader_menu_category = 0;
main_menu_item_highlight = 0;
main_menu_item_selected = false;
}
float BulbSettings::settings_expo(float value) {
int power = 2;
if (value < 0 && (power % 2 == 0)) {
return -1.0f * pow(value, power);
} else {
return pow(value, power);
}
}
void BulbSettings::draw_bulb_variable(BulbVariable *variable, int sub_highlight, int sub_animate_highlight, bool sub_selected) {
int bar_width = 500;
int bar_height = font_height;
glColor3f(0.2f,0.2f,0.2f);
drawing_tools->rectangle_filled(0, 0, bar_width, bar_height + 5);
glColor3f(0.6f,0.6f,0.6f);
drawing_tools->text(5, 5, settings_font, variable->category + " : " + variable->name);
float var_bg_normal_color = (sub_selected) ? 0.1f : 0.3f;
float var_bg_selected_color = (sub_selected) ? 0.2f : 0.4f;
float var_fg_animate_color = (sub_selected) ? 0.3f : 0.5f;
float var_fg_color = (sub_selected) ? 0.6f : 1.0f;
for (int i = 0; i < BULB_VAR_SIZE[variable->var_type]; i++) {
int x = 0;
int y = (bar_height * (i+1)) + 5;
float var_bg_color = (i == sub_highlight) ? var_bg_selected_color : var_bg_normal_color;
glColor3f(var_bg_color,var_bg_color,var_bg_color);
drawing_tools->rectangle_filled(x, y, bar_width, bar_height);
// draw animate stuff
if (variable->animate_enable[i]) {
float var_fg_anmiate_color = (i == sub_highlight) ? var_bg_selected_color : var_bg_normal_color;
glColor3f(var_fg_animate_color,var_fg_animate_color,var_fg_animate_color);
int a_scale = (int)(variable->animate_values[i][1] * bar_width);
int a_offset = (int)(((variable->animate_values[i][2] + 1.0f) / 2.0f) * bar_width);
drawing_tools->rectangle_filled(x + a_offset - (a_scale / 2), y + (bar_height / 2) - 2, a_scale, 4);
}
// draw slider
if (variable->var_type != VAR_SAMP2D) {
glColor3f(var_fg_color,var_fg_color,var_fg_color);
int pos = (int)(((variable->value[0][i] - variable->value[1][i]) / variable->value[3][i]) * bar_width);
drawing_tools->rectangle_filled(x + pos - 2, y, 4, bar_height);
}
// draw text
glColor3f(var_fg_color,var_fg_color,var_fg_color);
drawing_tools->text(x + 5, y + 5, settings_font, variable->get_string(i));
}
// draw color bar
if (variable->is_color) {
glm::vec4 variable_color = variable->get_color();
glColor3f(variable_color.r, variable_color.g, variable_color.b);
drawing_tools->rectangle_filled(0, (bar_height*(BULB_VAR_SIZE[variable->var_type] + 1)) + 5, bar_width, bar_height);
}
// animate
if (variable->animate_enable[sub_highlight]) {
int animate_sliders_offset = BULB_VAR_SIZE[variable->var_type] + ((variable->is_color) ? 1 : 0);
float var_bg_normal_color = (!sub_selected) ? 0.1f : 0.3f;
float var_bg_selected_color = (!sub_selected) ? 0.2f : 0.4f;
float var_fg_color = (!sub_selected) ? 0.6f : 1.0f;
float mins[3] = {0.0f, 0.0f, -1.0f};
float ranges[3] = {1.0f, 1.0f, 2.0f};
for (int i = 0; i < 3; i++) {
int x = 0;
int y = (bar_height * (i+1+animate_sliders_offset)) + 5;
float var_bg_color = (i == sub_animate_highlight) ? var_bg_selected_color : var_bg_normal_color;
glColor3f(var_bg_color,var_bg_color,var_bg_color);
drawing_tools->rectangle_filled(x, y, bar_width, bar_height);
// draw slider
glColor3f(var_fg_color,var_fg_color,var_fg_color);
int pos = (int)(((variable->animate_values[sub_highlight][i] - mins[i]) / ranges[i]) * bar_width);
drawing_tools->rectangle_filled(x + pos - 2, y, 4, bar_height);
// draw text
glColor3f(var_fg_color,var_fg_color,var_fg_color);
drawing_tools->text(x + 5, y + 5, settings_font, variable->get_string_animate(sub_highlight, i));
}
}
}
void BulbSettings::control_menu_draw() {
if (control_menu_item_selected) {
draw_bulb_variable(control_settings->control_variables[control_menu_item_highlight], control_menu_item_sub_highlight, 0, false);
} else {
int category_size = (int)control_settings->control_variables.size();
glColor4f(0.2f,0.2f,0.2f,1.0f);
drawing_tools->rectangle_filled(0, 0, 250, (category_size + 1) * font_height + 5);
glColor4f(0.3f,0.3f,0.3f,1.0f);
drawing_tools->rectangle_filled(250, 0, 200, (category_size + 1) * font_height + 5);
glColor4f(0.4f,0.4f,0.4f,1.0f);
drawing_tools->rectangle_filled(0, (control_menu_item_highlight + 1) * font_height, 250, font_height);
glColor4f(0.6f,0.6f,0.6f,1.0f);
drawing_tools->text(5, 0 * font_height + 5, settings_font, "Control Settings");
for (int i = 0; i < category_size; i++) {
BulbVariable *current_variable = control_settings->control_variables[i];
string variable_string = current_variable->category + " : " + current_variable->name;
if (current_variable->is_color) {
glm::vec4 variable_color = current_variable->get_color();
glColor3f(variable_color.r, variable_color.g, variable_color.b);
drawing_tools->rectangle_filled(250, (i + 1) * font_height, 200, font_height);
}
glColor3f(1.0f,1.0f,1.0f);
drawing_tools->text(5, (i + 1) * font_height + 5, settings_font, variable_string);
if (current_variable->is_bright()) {
glColor3f(0.0f,0.0f,0.0f);
}
drawing_tools->text(255, (i + 1) * font_height + 5, settings_font, current_variable->get_string());
}
}
}
void BulbSettings::control_menu_input_update(GamePadState *gamepad_state, KeyboardState *keyboard_state) {
if (control_menu_item_selected) {
info_text = "[TRIGGERS]/[ARROW KEYS] to change value.";
if (gamepad_state->pressed(GamePad_Button_B) || keyboard_state->pressed_keyboard(27)) {
control_menu_item_selected = false;
}
int dpad_step = 0;
dpad_step += (gamepad_state->pressed(GamePad_Button_DPAD_RIGHT) - gamepad_state->pressed(GamePad_Button_DPAD_LEFT));
dpad_step += (keyboard_state->pressed_special(GLUT_KEY_RIGHT) - keyboard_state->pressed_special(GLUT_KEY_LEFT));
float trigger_step = (settings_expo(gamepad_state->rt) - settings_expo(gamepad_state->lt));
if (gamepad_state->pressed(GamePad_Button_DPAD_UP) || keyboard_state->pressed_special(GLUT_KEY_UP)) control_menu_item_sub_highlight++;
if (gamepad_state->pressed(GamePad_Button_DPAD_DOWN) || keyboard_state->pressed_special(GLUT_KEY_DOWN)) control_menu_item_sub_highlight--;
control_settings->control_variables[control_menu_item_highlight]->adjust_variable(trigger_step, dpad_step, control_menu_item_sub_highlight);
} else {
info_text = "[A]/[ENTER] to edit.";
if (gamepad_state->pressed(GamePad_Button_A) || keyboard_state->pressed_keyboard(13)) {
control_menu_item_selected = true;
control_menu_item_sub_highlight = 0;
}
if (gamepad_state->pressed(GamePad_Button_B) || keyboard_state->pressed_keyboard(27)) {
menu_open = 0; // main menu
}
if (gamepad_state->pressed(GamePad_Button_DPAD_UP) || keyboard_state->pressed_special(GLUT_KEY_UP)) control_menu_item_highlight++;
if (gamepad_state->pressed(GamePad_Button_DPAD_DOWN) || keyboard_state->pressed_special(GLUT_KEY_DOWN)) control_menu_item_highlight--;
int category_size = (int)control_settings->control_variables.size();
control_menu_item_highlight = glm::clamp(control_menu_item_highlight, 0, category_size-1);
}
}
void BulbSettings::shader_menu_draw() {
if (shader_menu_item_selected) {
int actual_highlight_index = bulb_shader->shader_categories_indexes[shader_menu_category][shader_menu_item_highlight];
BulbVariable *selected_variable = &bulb_shader->shader_variables[actual_highlight_index];
draw_bulb_variable(selected_variable, shader_menu_item_sub_highlight, shader_menu_item_sub_animate_highlight, shader_menu_item_sub_selected);
} else {
int category_size = (int)bulb_shader->shader_categories_indexes[shader_menu_category].size();
glColor4f(0.2f,0.2f,0.2f,1.0f);
drawing_tools->rectangle_filled(0, 0, 250, (category_size + 1) * font_height + 5);
glColor4f(0.3f,0.3f,0.3f,1.0f);
drawing_tools->rectangle_filled(250, 0, 200, (category_size + 1) * font_height + 5);
glColor4f(0.4f,0.4f,0.4f,1.0f);
drawing_tools->rectangle_filled(0, (shader_menu_item_highlight + 1) * font_height, 250, font_height);
glColor4f(0.6f,0.6f,0.6f,1.0f);
drawing_tools->text(5, 0 * font_height + 5, settings_font, "< " + bulb_shader->shader_categories[shader_menu_category] + " >");
for (int i = 0; i < category_size; i++) {
int actual_index = bulb_shader->shader_categories_indexes[shader_menu_category][i];
BulbVariable *current_variable = &bulb_shader->shader_variables[actual_index];
string variable_string = current_variable->category + " : " + current_variable->name;
if (current_variable->is_color) {
glm::vec4 variable_color = current_variable->get_color();
glColor3f(variable_color.r, variable_color.g, variable_color.b);
drawing_tools->rectangle_filled(250, (i + 1) * font_height, 200, font_height);
}
glColor3f(1.0f,1.0f,1.0f);
drawing_tools->text(5, (i + 1) * font_height + 5, settings_font, variable_string);
if (current_variable->is_bright()) {
glColor3f(0.0f,0.0f,0.0f);
}
drawing_tools->text(255, (i + 1) * font_height + 5, settings_font, current_variable->get_string());
}
}
}
void BulbSettings::shader_menu_input_update(GamePadState *gamepad_state, KeyboardState *keyboard_state) {
if (shader_menu_item_selected) {
info_text = "[TRIGGERS]/[ARROW KEYS] to change value. [X] to toggle animate. [Y] to toggle HSV on colors.";
int actual_highlight_index = bulb_shader->shader_categories_indexes[shader_menu_category][shader_menu_item_highlight];
BulbVariable *selected_variable = &bulb_shader->shader_variables[actual_highlight_index];
if (gamepad_state->pressed(GamePad_Button_X) || keyboard_state->pressed_keyboard('x')) {
if (selected_variable->var_type != VAR_SAMP2D) {
selected_variable->animate_enable[shader_menu_item_sub_highlight] = !selected_variable->animate_enable[shader_menu_item_sub_highlight];
shader_menu_item_sub_selected = selected_variable->animate_enable[shader_menu_item_sub_highlight]; // auto enter menu
}
}
int dpad_step = 0;
dpad_step += (gamepad_state->pressed(GamePad_Button_DPAD_RIGHT) - gamepad_state->pressed(GamePad_Button_DPAD_LEFT));
dpad_step += (keyboard_state->pressed_special(GLUT_KEY_RIGHT) - keyboard_state->pressed_special(GLUT_KEY_LEFT));
float trigger_step = (settings_expo(gamepad_state->rt) - settings_expo(gamepad_state->lt));
if (shader_menu_item_sub_selected) {
if (gamepad_state->pressed(GamePad_Button_B) || keyboard_state->pressed_keyboard(27)) {
shader_menu_item_sub_selected = false;
}
if (gamepad_state->pressed(GamePad_Button_DPAD_UP) || keyboard_state->pressed_special(GLUT_KEY_UP)) shader_menu_item_sub_animate_highlight++;
if (gamepad_state->pressed(GamePad_Button_DPAD_DOWN) || keyboard_state->pressed_special(GLUT_KEY_DOWN)) shader_menu_item_sub_animate_highlight--;
selected_variable->adjust_animate(dpad_step + trigger_step, shader_menu_item_sub_highlight, shader_menu_item_sub_animate_highlight);
} else {
if ((gamepad_state->pressed(GamePad_Button_A) || keyboard_state->pressed_keyboard(13)) && selected_variable->animate_enable[shader_menu_item_sub_highlight]) {
shader_menu_item_sub_selected = true;
}
if (gamepad_state->pressed(GamePad_Button_B) || keyboard_state->pressed_keyboard(27)) {
shader_menu_item_selected = false;
}
if (gamepad_state->pressed(GamePad_Button_Y) || keyboard_state->pressed_keyboard('y')) {
selected_variable->set_hsv_mode(!selected_variable->hsv_mode);
}
if (gamepad_state->pressed(GamePad_Button_DPAD_UP) || keyboard_state->pressed_special(GLUT_KEY_UP)) shader_menu_item_sub_highlight++;
if (gamepad_state->pressed(GamePad_Button_DPAD_DOWN) || keyboard_state->pressed_special(GLUT_KEY_DOWN)) shader_menu_item_sub_highlight--;
selected_variable->adjust_variable(trigger_step, dpad_step, shader_menu_item_sub_highlight);
}
} else {
info_text = "[DPAD]/[ARROW KEYS] to change category. [A]/[ENTER] to edit.";
if (gamepad_state->pressed(GamePad_Button_A) || keyboard_state->pressed_keyboard(13)) {
shader_menu_item_selected = true;
shader_menu_item_sub_highlight = 0;
}
if (gamepad_state->pressed(GamePad_Button_B) || keyboard_state->pressed_keyboard(27)) {
menu_open = 0; // main menu
}
if (gamepad_state->pressed(GamePad_Button_DPAD_RIGHT) || keyboard_state->pressed_special(GLUT_KEY_RIGHT)) shader_menu_category++;
if (gamepad_state->pressed(GamePad_Button_DPAD_LEFT) || keyboard_state->pressed_special(GLUT_KEY_LEFT)) shader_menu_category--;
shader_menu_category = glm::clamp(shader_menu_category, 0, (int)bulb_shader->shader_categories.size() - 1);
if (gamepad_state->pressed(GamePad_Button_DPAD_UP) || keyboard_state->pressed_special(GLUT_KEY_UP)) shader_menu_item_highlight++;
if (gamepad_state->pressed(GamePad_Button_DPAD_DOWN) || keyboard_state->pressed_special(GLUT_KEY_DOWN)) shader_menu_item_highlight--;
int category_size = (int)bulb_shader->shader_categories_indexes[shader_menu_category].size();
shader_menu_item_highlight = glm::clamp(shader_menu_item_highlight, 0, category_size-1);
}
}
void BulbSettings::main_menu_draw() {
string menu_items[] = {"Shader Settings", "Control Settings", "Load", "Save"};
int menu_items_size = 4;
glColor4f(0.2f,0.2f,0.2f,1.0f);
drawing_tools->rectangle_filled(0, 0, 250, (menu_items_size) * font_height + 5);
glColor4f(0.4f,0.4f,0.4f,1.0f);
drawing_tools->rectangle_filled(0, main_menu_item_highlight * font_height, 250, font_height);
glColor4f(1.0f,1.0f,1.0f,1.0f);
for (int i = 0; i < menu_items_size; i++) {
drawing_tools->text(5, i * font_height + 5, settings_font, menu_items[i]);
}
}
void BulbSettings::main_menu_input_update(GamePadState *gamepad_state, KeyboardState *keyboard_state) {
info_text = "";
int menu_items_size = 4;
if (gamepad_state->pressed(GamePad_Button_A) || keyboard_state->pressed_keyboard(13)) {
main_menu_item_selected = true;
menu_open = main_menu_item_highlight + 1;
if (menu_open == 4) save_menu_current_save_name = random_name(8);
}
if (gamepad_state->pressed(GamePad_Button_B) || keyboard_state->pressed_keyboard(27)) {
settings_open = false;
}
if (gamepad_state->pressed(GamePad_Button_DPAD_UP) || keyboard_state->pressed_special(GLUT_KEY_UP)) main_menu_item_highlight++;
if (gamepad_state->pressed(GamePad_Button_DPAD_DOWN) || keyboard_state->pressed_special(GLUT_KEY_DOWN)) main_menu_item_highlight--;
main_menu_item_highlight = glm::clamp(main_menu_item_highlight, 0, menu_items_size - 1);
}
void BulbSettings::save_menu_draw() {
if (!save_menu_item_selected) {
string menu_items[] = {"New \"" + save_menu_current_save_name + "\"", "Overwrite"};
int menu_items_size = 2;
glColor4f(0.2f,0.2f,0.2f,1.0f);
drawing_tools->rectangle_filled(0, 0, 250, (menu_items_size) * font_height + 5);
glColor4f(0.4f,0.4f,0.4f,1.0f);
drawing_tools->rectangle_filled(0, save_menu_item_highlight * font_height, 250, font_height);
glColor4f(1.0f,1.0f,1.0f,1.0f);
for (int i = 0; i < menu_items_size; i++) {
drawing_tools->text(5, i * font_height + 5, settings_font, menu_items[i]);
}
} else if (save_menu_item_highlight == 0) {
// new save should be handled in input update
} else if (save_menu_item_highlight == 1) {
int menu_items_size = (int)save_files.size();
glColor4f(0.2f,0.2f,0.2f,1.0f);
drawing_tools->rectangle_filled(0, 0, 250, (menu_items_size + 1) * font_height + 5);
glColor4f(0.4f,0.4f,0.4f,1.0f);
drawing_tools->rectangle_filled(0, (save_menu_item_sub_highlight + 1) * font_height, 250, font_height);
if (save_menu_overwrite_hold > 0) {
glColor4f(0.6f,0.4f,0.4f,1.0f);
drawing_tools->rectangle_filled(0, (save_menu_item_sub_highlight + 1) * font_height, (250 * save_menu_overwrite_hold) / 100, font_height);
}
glColor4f(0.6f,0.6f,0.6f,1.0f);
drawing_tools->text(5, 0 * font_height + 5, settings_font, "Save\\Overwrite");
glColor4f(1.0f,1.0f,1.0f,1.0f);
for (int i = 0; i < menu_items_size; i++) {
string file_text = save_files[i].clean_name;
drawing_tools->text(5, (i + 1) * font_height + 5, settings_font, file_text);
}
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, save_files[save_menu_item_sub_highlight].tex_id);
drawing_tools->rectangle_tex(250, 0, 256, 256);
glDisable(GL_TEXTURE_2D);
}
}
void BulbSettings::save_menu_input_update(GamePadState *gamepad_state, KeyboardState *keyboard_state) {
if (!save_menu_item_selected) {
info_text = "";
int menu_items_size = 2;
if (gamepad_state->pressed(GamePad_Button_A) || keyboard_state->pressed_keyboard(13)) {
save_menu_item_selected = true;
save_menu_item_sub_highlight = 0;
if (save_menu_item_highlight == 0) {
save_menu_item_selected = false;
save_save_file("BulbSaves\\" + save_menu_current_save_name + ".bmp");
save_menu_current_save_name = random_name(8);
} else if (save_menu_item_highlight == 1) {
update_save_files();
}
}
if (gamepad_state->pressed(GamePad_Button_B) || keyboard_state->pressed_keyboard(27)) {
menu_open = 0; // main menu
}
if (gamepad_state->pressed(GamePad_Button_DPAD_UP) || keyboard_state->pressed_special(GLUT_KEY_UP)) save_menu_item_highlight++;
if (gamepad_state->pressed(GamePad_Button_DPAD_DOWN) || keyboard_state->pressed_special(GLUT_KEY_DOWN)) save_menu_item_highlight--;
save_menu_item_highlight = glm::clamp(save_menu_item_highlight, 0, menu_items_size - 1);
} else {
if (gamepad_state->pressed(GamePad_Button_B) || keyboard_state->pressed_keyboard(27)) {
save_menu_item_selected = false;
}
if (gamepad_state->pressed(GamePad_Button_DPAD_UP) || keyboard_state->pressed_special(GLUT_KEY_UP)) {save_menu_item_sub_highlight++; save_menu_overwrite_hold = -1;}
if (gamepad_state->pressed(GamePad_Button_DPAD_DOWN) || keyboard_state->pressed_special(GLUT_KEY_DOWN)) {save_menu_item_sub_highlight--; save_menu_overwrite_hold = -1;}
if (save_menu_item_highlight == 0) {
// should not happen
} else if (save_menu_item_highlight == 1) {
info_text = "Hold [A]/[ENTER] to overwrite with new save.";
save_menu_item_sub_highlight = glm::clamp(save_menu_item_sub_highlight, 0, (int)save_files.size() - 1);
if (gamepad_state->buttons[GamePad_Button_A] || keyboard_state->keyboard[13]) {
if (save_menu_overwrite_hold != -1) {
save_menu_overwrite_hold += 1;
if (save_menu_overwrite_hold >= 100) {
save_menu_overwrite_hold = -1;
save_save_file(save_files[save_menu_item_sub_highlight].file_name);
update_save_files();
}
}
} else {
save_menu_overwrite_hold = 0;
}
}
}
}
void BulbSettings::load_menu_draw() {
if (!load_menu_item_selected) {
string menu_items[] = {"Fractals", "Saves"};
int menu_items_size = 2;
glColor4f(0.2f,0.2f,0.2f,1.0f);
drawing_tools->rectangle_filled(0, 0, 250, (menu_items_size) * font_height + 5);
glColor4f(0.4f,0.4f,0.4f,1.0f);
drawing_tools->rectangle_filled(0, load_menu_item_highlight * font_height, 250, font_height);
glColor4f(1.0f,1.0f,1.0f,1.0f);
for (int i = 0; i < menu_items_size; i++) {
drawing_tools->text(5, i * font_height + 5, settings_font, menu_items[i]);
}
} else if (load_menu_item_highlight == 0) {
int menu_items_size = (int)bulb_shader->fractal_files.size();
glColor4f(0.2f,0.2f,0.2f,1.0f);
drawing_tools->rectangle_filled(0, 0, 250, (menu_items_size + 1) * font_height + 5);
glColor4f(0.4f,0.4f,0.4f,1.0f);
drawing_tools->rectangle_filled(0, (load_menu_item_sub_highlight + 1) * font_height, 250, font_height);
glColor4f(0.6f,0.6f,0.6f,1.0f);
drawing_tools->text(5, 0 * font_height + 5, settings_font, "Load\\Fractals");
glColor4f(1.0f,1.0f,1.0f,1.0f);
for (int i = 0; i < menu_items_size; i++) {
string file_text = bulb_shader->fractal_files[i];
if (bulb_shader->fractal_files[i] == bulb_shader->fractal_file) {
file_text += " (Loaded)";
}
drawing_tools->text(5, (i + 1) * font_height + 5, settings_font, file_text);
}
} else if (load_menu_item_highlight == 1) {
int menu_items_size = (int)save_files.size();
glColor4f(0.2f,0.2f,0.2f,1.0f);
drawing_tools->rectangle_filled(0, 0, 250, (menu_items_size + 1) * font_height + 5);
glColor4f(0.4f,0.4f,0.4f,1.0f);
drawing_tools->rectangle_filled(0, (load_menu_item_sub_highlight + 1) * font_height, 250, font_height);
if (load_menu_delete_hold > 0) {
glColor4f(0.6f,0.4f,0.4f,1.0f);
drawing_tools->rectangle_filled(0, (load_menu_item_sub_highlight + 1) * font_height, (250 * load_menu_delete_hold) / 100, font_height);
}
glColor4f(0.6f,0.6f,0.6f,1.0f);
drawing_tools->text(5, 0 * font_height + 5, settings_font, "Load\\Saves");
glColor4f(1.0f,1.0f,1.0f,1.0f);
for (int i = 0; i < menu_items_size; i++) {
string file_text = save_files[i].clean_name;
drawing_tools->text(5, (i + 1) * font_height + 5, settings_font, file_text);
}
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, save_files[load_menu_item_sub_highlight].tex_id);
drawing_tools->rectangle_tex(250, 0, 256, 256);
glDisable(GL_TEXTURE_2D);
}
}
void BulbSettings::load_menu_input_update(GamePadState *gamepad_state, KeyboardState *keyboard_state) {
if (!load_menu_item_selected) {
info_text = "";
int menu_items_size = 2;
if (gamepad_state->pressed(GamePad_Button_A) || keyboard_state->pressed_keyboard(13)) {
load_menu_item_selected = true;
load_menu_item_sub_highlight = 0;
if (load_menu_item_highlight == 1) {
update_save_files();
}
}
if (gamepad_state->pressed(GamePad_Button_B) || keyboard_state->pressed_keyboard(27)) {
menu_open = 0; // main menu
}
if (gamepad_state->pressed(GamePad_Button_DPAD_UP) || keyboard_state->pressed_special(GLUT_KEY_UP)) load_menu_item_highlight++;
if (gamepad_state->pressed(GamePad_Button_DPAD_DOWN) || keyboard_state->pressed_special(GLUT_KEY_DOWN)) load_menu_item_highlight--;
load_menu_item_highlight = glm::clamp(load_menu_item_highlight, 0, menu_items_size - 1);
} else {
info_text = "[A]/[ENTER] to load.";
if (gamepad_state->pressed(GamePad_Button_B) || keyboard_state->pressed_keyboard(27)) {
load_menu_item_selected = false;
}
if (gamepad_state->pressed(GamePad_Button_DPAD_UP) || keyboard_state->pressed_special(GLUT_KEY_UP)) {load_menu_item_sub_highlight++; load_menu_delete_hold = -1;}
if (gamepad_state->pressed(GamePad_Button_DPAD_DOWN) || keyboard_state->pressed_special(GLUT_KEY_DOWN)) {load_menu_item_sub_highlight--; load_menu_delete_hold = -1;}
if (load_menu_item_highlight == 0) {
load_menu_item_sub_highlight = glm::clamp(load_menu_item_sub_highlight, 0, (int)bulb_shader->fractal_files.size() - 1);
if (gamepad_state->pressed(GamePad_Button_A) || keyboard_state->pressed_keyboard(13)) {
bulb_shader->fractal_file = bulb_shader->fractal_files[load_menu_item_sub_highlight];
bulb_shader->load();
}
} else if (load_menu_item_highlight == 1) {
info_text = "[A]/[ENTER] to load. Hold [X] to delete a save.";
load_menu_item_sub_highlight = glm::clamp(load_menu_item_sub_highlight, 0, (int)save_files.size() - 1);
if (gamepad_state->buttons[GamePad_Button_X] || keyboard_state->keyboard['x']) {
if (load_menu_delete_hold != -1) {
load_menu_delete_hold += 1;
if (load_menu_delete_hold >= 100) {
load_menu_delete_hold = -1;
remove(save_files[load_menu_item_sub_highlight].file_name.c_str());
update_save_files();
load_menu_item_sub_highlight = glm::clamp(load_menu_item_sub_highlight, 0, (int)save_files.size() - 1);
return;
}
}
} else {
load_menu_delete_hold = 0;
}
if (gamepad_state->pressed(GamePad_Button_A) || keyboard_state->pressed_keyboard(13)) {
load_save_file(save_files[load_menu_item_sub_highlight].file_name);
}
}
}
}
void BulbSettings::update_save_files() {
for (int i = 0; i < (int)save_files.size(); i++) {
glDeleteTextures(1, &save_files[i].tex_id);
}
save_files.clear();
string directory = "BulbSaves\\*";
WIN32_FIND_DATA fileData;
HANDLE hFind;
if ( !((hFind = FindFirstFile(directory.c_str(), &fileData)) == INVALID_HANDLE_VALUE) ) {
while(FindNextFile(hFind, &fileData)) {
vector<string> file_name_split = split_string(fileData.cFileName, ".");
if (to_upper(file_name_split[1]) == "BMP") {
string save_file_name = "BulbSaves\\" + string(fileData.cFileName);
BulbSave current_save;
if (current_save.load(save_file_name)) {
save_files.push_back(current_save);
}
}
}
}
FindClose(hFind);
}
void BulbSettings::draw() {
glUseProgram(0);
if (menu_open == 0) {
main_menu_draw();
} else if (menu_open == 1) {
shader_menu_draw();
} else if (menu_open == 2) {
control_menu_draw();
} else if (menu_open == 3) {
load_menu_draw();
} else if (menu_open == 4) {
save_menu_draw();
}
if (info_text.length() != 0) {
int text_width = drawing_tools->text_width(settings_font, info_text);
glColor3f(0.2f,0.2f,0.2f);
drawing_tools->rectangle_filled(0, (int)drawing_tools->SCREEN_H - font_height, text_width + 10, font_height);
glColor3f(1,1,1);
drawing_tools->text(5, (int)drawing_tools->SCREEN_H - font_height + 5, settings_font, info_text);
}
}
void BulbSettings::load_save_file(string save_file_name) {
ifstream save_file;
save_file.open(save_file_name, ios::in);
BMP save_image;
save_image.load(save_file_name);
bulb_shader->read_from_save_file(save_file, save_image.bmp_file_size);
control_settings->read_from_save_file(save_file, save_image.bmp_file_size);
save_file.close();
}
void BulbSettings::save_save_file(string save_file_name) {
// capture and save thumbnail
glClear(GL_COLOR_BUFFER_BIT);
bulb_shader->draw();
glutSwapBuffers();
int screen_w = (int)drawing_tools->SCREEN_W, screen_h = (int)drawing_tools->SCREEN_H;
int capture_res = 256, screen_res = min(screen_w, screen_h);
screen_res -= (screen_res % 4);
unsigned char *data = new unsigned char[screen_res * screen_res * 3];
glReadPixels((screen_w / 2) - (screen_res / 2), (screen_h / 2) - (screen_res / 2), screen_res, screen_res, GL_RGB, GL_UNSIGNED_BYTE, data);
BMP save_image(capture_res, capture_res);
for (int y = 0; y < capture_res; y++) {
for (int x = 0; x < capture_res; x++) {
int screen_x = (x * screen_res) / capture_res;
int screen_y = ((capture_res - y - 1) * screen_res) / capture_res;
save_image.set_pixel(x, y, &data[(screen_y * 3 * screen_res) + (screen_x * 3)]);
}
}
save_image.save(save_file_name);
ofstream save_file;
save_file.open(save_file_name, ios::app);
save_file.seekp(save_image.bmp_file_size, ios::beg);
save_file << "BULBSAVE" << endl;
bulb_shader->write_to_save_file(save_file);
control_settings->write_to_save_file(save_file);
save_file.close();
}
void BulbSettings::input_update(GamePadXbox *gamepad, KeyboardState *keyboard) {
if (gamepad->State.pressed(GamePad_Button_START)) {
settings_open = false;
info_text = "";
}
if (menu_open == 0) {
main_menu_input_update(&gamepad->State, keyboard);
} else if (menu_open == 1) {
shader_menu_input_update(&gamepad->State, keyboard);
} else if (menu_open == 2) {
control_menu_input_update(&gamepad->State, keyboard);
} else if (menu_open == 3) {
load_menu_input_update(&gamepad->State, keyboard);
} else if (menu_open == 4) {
save_menu_input_update(&gamepad->State, keyboard);
}
} | [
"xeerogravity@aim.com"
] | xeerogravity@aim.com |
032645e0b36da5b739a1613c085469f2242394fc | 3e14bfc4a7c2c29214928f7a805f62ba487c36ff | /Common/StateMapDlg.cpp | b2e34a162a5d3202553ce6387b0f8df931e77c17 | [] | no_license | chinarustin/RadarSim | bef6464c220a38cc7c512d26b4398aba30872033 | 1b33f3bcf20c9da36cb8eb382a39afefbfe1930d | refs/heads/master | 2020-12-26T01:48:39.860994 | 2014-05-14T18:17:17 | 2014-05-14T18:17:17 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,422 | cpp | // StateMapDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "StateMapDlg.h"
// CStateMapDlg 对话框
IMPLEMENT_DYNAMIC(CStateMapDlg, CDialog)
CStateMapDlg::CStateMapDlg(LPCWSTR title, StateMap &stateMap, CCommonDlg *dlg, CWnd* pParent /*=NULL*/)
: CDialog(CStateMapDlg::IDD, pParent)
, m_Title(title)
, m_StateMap(stateMap)
, m_Dlg(dlg)
, m_Initialized(false)
, m_Ctrl(stateMap)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
CStateMapDlg::~CStateMapDlg()
{
}
void CStateMapDlg::CreateDlg(CStateMapDlg &dlg)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
dlg.Create(IDD_STATEMAP_DLG, GetDesktopWindow());
}
void CStateMapDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_STATEMAP, m_Ctrl);
DDX_Check(pDX, IDC_STATEMAP_SHOW_TRACK, m_StateMap.m_ShowTrack);
DDX_Check(pDX, IDC_STATEMAP_SHOW_THETA_RANGE, m_StateMap.m_ShowThetaRange);
DDX_Control(pDX, IDC_STATEMAP_BACKGROUND, m_Background);
DDX_Control(pDX, IDC_STATEMAP_PLANE_TYPE, m_PlaneType);
DDX_Control(pDX, IDC_STATEMAP_PLANE_COLOR, m_PlaneColor);
DDX_Control(pDX, IDC_STATEMAP_TARGET_ID, m_TargetId);
DDX_Control(pDX, IDC_STATEMAP_TARGET_TYPE, m_TargetType);
DDX_Control(pDX, IDC_STATEMAP_TARGET_COLOR, m_TargetColor);
DDX_Control(pDX, IDC_STATEMAP_PLANE_ID, m_PlaneId);
}
BEGIN_MESSAGE_MAP(CStateMapDlg, CDialog)
ON_WM_CLOSE()
ON_WM_SIZE()
ON_BN_CLICKED(IDC_STATEMAP_SHOW_TRACK, &CStateMapDlg::OnBnClickedStatemapShowTrack)
ON_BN_CLICKED(IDC_STATEMAP_SHOW_THETA_RANGE, &CStateMapDlg::OnBnClickedStatemapShowThetaRange)
ON_CBN_SELCHANGE(IDC_STATEMAP_BACKGROUND, &CStateMapDlg::OnCbnSelchangeStatemapBackground)
ON_CBN_SELCHANGE(IDC_STATEMAP_PLANE_TYPE, &CStateMapDlg::OnCbnSelchangeStatemapPlaneType)
ON_CBN_SELCHANGE(IDC_STATEMAP_PLANE_COLOR, &CStateMapDlg::OnCbnSelchangeStatemapPlaneColor)
ON_CBN_SELCHANGE(IDC_STATEMAP_TARGET_ID, &CStateMapDlg::OnCbnSelchangeStatemapTargetId)
ON_CBN_SELCHANGE(IDC_STATEMAP_TARGET_TYPE, &CStateMapDlg::OnCbnSelchangeStatemapTargetType)
ON_CBN_SELCHANGE(IDC_STATEMAP_TARGET_COLOR, &CStateMapDlg::OnCbnSelchangeStatemapTargetColor)
ON_CBN_SELCHANGE(IDC_STATEMAP_PLANE_ID, &CStateMapDlg::OnCbnSelchangeStatemapPlaneId)
END_MESSAGE_MAP()
// CStateMapDlg 消息处理程序
BOOL CStateMapDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
m_Initialized = true;
SetWindowTextW(m_Title);
GetDlgItem(IDC_STATEMAP_GRP)->SetWindowTextW(m_Title);
for (int i = 0; i < StateMapBackgroundLast; ++i)
{
m_Background.InsertString(i, StateMapBackgroundNames[i]);
}
m_Background.SetCurSel(m_StateMap.m_Background);
for (int i = 0; i < TargetTypeLast; ++i)
{
m_PlaneType.InsertString(i, TargetTypeNames[i]);
}
// m_PlaneType.SetCurSel(m_StateMap.m_PlaneType);
for (int i = 0; i < TargetColorLast; ++i)
{
m_PlaneColor.InsertString(i, TargetColorNames[i]);
}
// m_PlaneColor.SetCurSel(m_StateMap.m_PlaneColor);
for (int i = 0; i < TargetTypeLast; ++i)
{
m_TargetType.InsertString(i, TargetTypeNames[i]);
}
for (int i = 0; i < TargetColorLast; ++i)
{
m_TargetColor.InsertString(i, TargetColorNames[i]);
}
Resize();
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CStateMapDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CStateMapDlg::OnClose()
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
// CDialog::OnClose();
m_Dlg->OnSubDlgClose(this);
}
void CStateMapDlg::Resize()
{
RECT rect;
GetClientRect(&rect);
int left = rect.left + PAD, width = 2 * (80 + PAD), top = rect.top + PAD, height = rect.bottom - rect.top - PAD * 2;
int left2 = left + width + PAD, width2 = rect.right - PAD - left2, top2 = top, height2 = height;
GetDlgItem(IDC_STATEMAP_PARAM_GRP)->MoveWindow(left, top, width, height);
left = left + PAD;
width = 80;
top = top + PAD * 2;
height = 20;
GetDlgItem(IDC_STATEMAP_SHOW_TRACK)->MoveWindow(left, top, width, height);
top = top + height + PAD;
GetDlgItem(IDC_STATEMAP_SHOW_THETA_RANGE)->MoveWindow(left, top, width * 2, height);
top = top + height + PAD;
GetDlgItem(IDC_STATEMAP_BACKGROUND_STATIC)->MoveWindow(left, top, width, height);
GetDlgItem(IDC_STATEMAP_BACKGROUND)->MoveWindow(left + width, top, width, height);
top = top + height + PAD;
GetDlgItem(IDC_STATEMAP_PLANE_ID_STATIC)->MoveWindow(left, top, width, height);
GetDlgItem(IDC_STATEMAP_PLANE_ID)->MoveWindow(left + width, top, width, height);
top = top + height + PAD;
GetDlgItem(IDC_STATEMAP_PLANE_TYPE_STATIC)->MoveWindow(left, top, width, height);
GetDlgItem(IDC_STATEMAP_PLANE_TYPE)->MoveWindow(left + width, top, width, height);
top = top + height + PAD;
GetDlgItem(IDC_STATEMAP_PLANE_COLOR_STATIC)->MoveWindow(left, top, width, height);
GetDlgItem(IDC_STATEMAP_PLANE_COLOR)->MoveWindow(left + width, top, width, height);
top = top + height + PAD;
GetDlgItem(IDC_STATEMAP_TARGET_ID_STATIC)->MoveWindow(left, top, width, height);
GetDlgItem(IDC_STATEMAP_TARGET_ID)->MoveWindow(left + width, top, width, height);
top = top + height + PAD;
GetDlgItem(IDC_STATEMAP_TARGET_TYPE_STATIC)->MoveWindow(left, top, width, height);
GetDlgItem(IDC_STATEMAP_TARGET_TYPE)->MoveWindow(left + width, top, width, height);
top = top + height + PAD;
GetDlgItem(IDC_STATEMAP_TARGET_COLOR_STATIC)->MoveWindow(left, top, width, height);
GetDlgItem(IDC_STATEMAP_TARGET_COLOR)->MoveWindow(left + width, top, width, height);
GetDlgItem(IDC_STATEMAP_GRP)->MoveWindow(left2, top2, width2, height2);
GetDlgItem(IDC_STATEMAP)->MoveWindow(left2 + PAD, top2 + PAD * 2, width2 - PAD * 2, height2 - PAD * 3);
}
void CStateMapDlg::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
// TODO: 在此处添加消息处理程序代码
if (m_Initialized)
{
Resize();
}
}
void CStateMapDlg::Reset()
{
m_Ctrl.Reset();
m_Background.SetCurSel(m_StateMap.m_Background);
m_PlaneId.ResetContent();
m_PlaneType.SetCurSel(CB_ERR);
m_PlaneColor.SetCurSel(CB_ERR);
m_TargetId.ResetContent();
m_TargetType.SetCurSel(CB_ERR);
m_TargetColor.SetCurSel(CB_ERR);
UpdateData(FALSE);
}
void CStateMapDlg::AddPlane(Plane &plane)
{
CString str;
str.AppendFormat(TEXT("%d"), plane.m_Id);
m_PlaneId.InsertString(m_PlaneId.GetCount(), str);
}
void CStateMapDlg::AddTarget(Target &target)
{
CString str;
str.AppendFormat(TEXT("%d"), target.m_Id);
m_TargetId.InsertString(m_TargetId.GetCount(), str);
}
void CStateMapDlg::OnBnClickedStatemapShowTrack()
{
// TODO: 在此添加控件通知处理程序代码
m_StateMap.m_ShowTrack = !m_StateMap.m_ShowTrack;
m_Ctrl.DrawTargets();
m_Ctrl.BlendAll();
m_Ctrl.Invalidate();
}
void CStateMapDlg::OnBnClickedStatemapShowThetaRange()
{
// TODO: 在此添加控件通知处理程序代码
m_StateMap.m_ShowThetaRange = !m_StateMap.m_ShowThetaRange;
m_Ctrl.DrawTargets();
m_Ctrl.BlendAll();
m_Ctrl.Invalidate();
}
void CStateMapDlg::OnCbnSelchangeStatemapBackground()
{
// TODO: 在此添加控件通知处理程序代码
int index = m_Background.GetCurSel();
int count = m_Background.GetCount();
if ((index != CB_ERR) && (count >= 1))
{
m_StateMap.m_Background = (StateMapBackground)index;
m_Ctrl.DrawBackground();
m_Ctrl.BlendAll();
m_Ctrl.Invalidate();
}
}
void CStateMapDlg::OnCbnSelchangeStatemapPlaneId()
{
// TODO: Add your control notification handler code here
int index = m_PlaneId.GetCurSel();
int count = m_PlaneId.GetCount();
if ((index != CB_ERR) && (count >= 1))
{
m_PlaneType.SetCurSel(m_StateMap.m_PlaneTypes[index]);
m_PlaneColor.SetCurSel(m_StateMap.m_PlaneColors[index]);
}
}
void CStateMapDlg::OnCbnSelchangeStatemapPlaneType()
{
// TODO: 在此添加控件通知处理程序代码
int index = m_PlaneId.GetCurSel();
int count = m_PlaneId.GetCount();
if ((index != CB_ERR) && (count >= 1))
{
m_StateMap.m_PlaneTypes[index] = (TargetType)m_PlaneType.GetCurSel();
m_Ctrl.DrawTargets();
m_Ctrl.BlendAll();
m_Ctrl.Invalidate();
}
}
void CStateMapDlg::OnCbnSelchangeStatemapPlaneColor()
{
// TODO: 在此添加控件通知处理程序代码
int index = m_PlaneId.GetCurSel();
int count = m_PlaneId.GetCount();
if ((index != CB_ERR) && (count >= 1))
{
m_StateMap.m_PlaneColors[index] = (TargetColor)m_PlaneColor.GetCurSel();
m_Ctrl.DrawTargets();
m_Ctrl.BlendAll();
m_Ctrl.Invalidate();
}
}
void CStateMapDlg::OnCbnSelchangeStatemapTargetId()
{
// TODO: 在此添加控件通知处理程序代码
int index = m_TargetId.GetCurSel();
int count = m_TargetId.GetCount();
if ((index != CB_ERR) && (count >= 1))
{
m_TargetType.SetCurSel(m_StateMap.m_TargetTypes[index]);
m_TargetColor.SetCurSel(m_StateMap.m_TargetColors[index]);
}
}
void CStateMapDlg::OnCbnSelchangeStatemapTargetType()
{
// TODO: 在此添加控件通知处理程序代码
int index = m_TargetId.GetCurSel();
int count = m_TargetId.GetCount();
if ((index != CB_ERR) && (count >= 1))
{
m_StateMap.m_TargetTypes[index] = (TargetType)m_TargetType.GetCurSel();
m_Ctrl.DrawTargets();
m_Ctrl.BlendAll();
m_Ctrl.Invalidate();
}
}
void CStateMapDlg::OnCbnSelchangeStatemapTargetColor()
{
// TODO: 在此添加控件通知处理程序代码
int index = m_TargetId.GetCurSel();
int count = m_TargetId.GetCount();
if ((index != CB_ERR) && (count >= 1))
{
m_StateMap.m_TargetColors[index] = (TargetColor)m_TargetColor.GetCurSel();
m_Ctrl.DrawTargets();
m_Ctrl.BlendAll();
m_Ctrl.Invalidate();
}
}
| [
"zanmato1984@gmail.com"
] | zanmato1984@gmail.com |
1808b8ac2247f7034049b680a70d21e76664078d | aefdfc265ce14f80e2def183ed54be1866cf609b | /Snake/Classes/Native/UnityEngine_ArrayTypes.h | 7e317fd9a6d598bb82ce856a682c986b5546b5e3 | [] | no_license | labdogg1003/Snake | 5865b464a9e10f13cb2603a2c1356280f9f38afd | d91017ccbf433761898de90e3763ffaf50020f5f | refs/heads/master | 2021-01-11T04:29:12.852507 | 2016-10-24T16:01:33 | 2016-10-24T16:01:33 | 71,182,749 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,126 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
// UnityEngine.Object
struct Object_t3071478659;
// UnityEngine.SocialPlatforms.IAchievementDescription
struct IAchievementDescription_t655461400;
// UnityEngine.SocialPlatforms.IAchievement
struct IAchievement_t2957812780;
// UnityEngine.SocialPlatforms.IScore
struct IScore_t4279057999;
// UnityEngine.SocialPlatforms.IUserProfile
struct IUserProfile_t598900827;
// UnityEngine.SocialPlatforms.Impl.AchievementDescription
struct AchievementDescription_t2116066607;
// UnityEngine.SocialPlatforms.Impl.UserProfile
struct UserProfile_t2280656072;
// UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard
struct GcLeaderboard_t1820874799;
// UnityEngine.SocialPlatforms.Impl.Achievement
struct Achievement_t344600729;
// UnityEngine.SocialPlatforms.Impl.Score
struct Score_t3396031228;
// UnityEngine.Camera
struct Camera_t2727095145;
// UnityEngine.Behaviour
struct Behaviour_t200106419;
// UnityEngine.Component
struct Component_t3501516275;
// UnityEngine.Display
struct Display_t1321072632;
// UnityEngine.Rigidbody2D
struct Rigidbody2D_t1743771669;
// UnityEngine.GUILayoutOption
struct GUILayoutOption_t331591504;
// UnityEngine.GUILayoutUtility/LayoutCache
struct LayoutCache_t879908455;
// UnityEngine.GUILayoutEntry
struct GUILayoutEntry_t1336615025;
// UnityEngine.GUIStyle
struct GUIStyle_t2990928826;
// UnityEngine.Networking.IMultipartFormSection
struct IMultipartFormSection_t2606995300;
// UnityEngine.DisallowMultipleComponent
struct DisallowMultipleComponent_t62111112;
// UnityEngine.ExecuteInEditMode
struct ExecuteInEditMode_t3132250205;
// UnityEngine.RequireComponent
struct RequireComponent_t1687166108;
// UnityEngine.Events.PersistentCall
struct PersistentCall_t2972625667;
// UnityEngine.Events.BaseInvokableCall
struct BaseInvokableCall_t1559630662;
// UnityEngine.Transform
struct Transform_t1659122786;
// UnityEngine.GameObject
struct GameObject_t3674682005;
// UnityEngine.Sprite
struct Sprite_t3199167241;
// UnityEngine.Canvas
struct Canvas_t2727140764;
// UnityEngine.Font
struct Font_t4241557075;
// UnityEngine.CanvasGroup
struct CanvasGroup_t3702418109;
// UnityEngine.RectTransform
struct RectTransform_t972643934;
// UnityEngine.MonoBehaviour
struct MonoBehaviour_t667441552;
// UnityEngine.RenderTexture
struct RenderTexture_t1963041563;
// UnityEngine.Texture
struct Texture_t2526458961;
// UnityEngine.Mesh
struct Mesh_t4241756145;
#include "mscorlib_System_Array1146569071.h"
#include "UnityEngine_UnityEngine_Object3071478659.h"
#include "UnityEngine_UnityEngine_SocialPlatforms_Impl_Achie2116066607.h"
#include "UnityEngine_UnityEngine_SocialPlatforms_Impl_UserP2280656072.h"
#include "UnityEngine_UnityEngine_SocialPlatforms_GameCenter1820874799.h"
#include "UnityEngine_UnityEngine_SocialPlatforms_GameCenter3481375915.h"
#include "UnityEngine_UnityEngine_SocialPlatforms_Impl_Achiev344600729.h"
#include "UnityEngine_UnityEngine_SocialPlatforms_GameCenter2181296590.h"
#include "UnityEngine_UnityEngine_SocialPlatforms_Impl_Score3396031228.h"
#include "UnityEngine_UnityEngine_Vector24282066565.h"
#include "UnityEngine_UnityEngine_Color4194546905.h"
#include "UnityEngine_UnityEngine_Keyframe4079056114.h"
#include "UnityEngine_UnityEngine_Vector34282066566.h"
#include "UnityEngine_UnityEngine_Vector44282066567.h"
#include "UnityEngine_UnityEngine_Color32598853688.h"
#include "UnityEngine_UnityEngine_Camera2727095145.h"
#include "UnityEngine_UnityEngine_Behaviour200106419.h"
#include "UnityEngine_UnityEngine_Component3501516275.h"
#include "UnityEngine_UnityEngine_Display1321072632.h"
#include "UnityEngine_UnityEngine_Touch4210255029.h"
#include "UnityEngine_UnityEngine_Experimental_Director_Playab70832698.h"
#include "UnityEngine_UnityEngine_ContactPoint243083348.h"
#include "UnityEngine_UnityEngine_RaycastHit4003175726.h"
#include "UnityEngine_UnityEngine_Rigidbody2D1743771669.h"
#include "UnityEngine_UnityEngine_RaycastHit2D1374744384.h"
#include "UnityEngine_UnityEngine_ContactPoint2D4288432358.h"
#include "UnityEngine_UnityEngine_UIVertex4244065212.h"
#include "UnityEngine_UnityEngine_UICharInfo65807484.h"
#include "UnityEngine_UnityEngine_UILineInfo4113875482.h"
#include "UnityEngine_UnityEngine_GUILayoutOption331591504.h"
#include "UnityEngine_UnityEngine_GUILayoutUtility_LayoutCach879908455.h"
#include "UnityEngine_UnityEngine_GUILayoutEntry1336615025.h"
#include "UnityEngine_UnityEngine_GUIStyle2990928826.h"
#include "UnityEngine_UnityEngine_DisallowMultipleComponent62111112.h"
#include "UnityEngine_UnityEngine_ExecuteInEditMode3132250205.h"
#include "UnityEngine_UnityEngine_RequireComponent1687166108.h"
#include "UnityEngine_UnityEngine_SendMouseEvents_HitInfo3209134097.h"
#include "UnityEngine_UnityEngine_Events_PersistentCall2972625667.h"
#include "UnityEngine_UnityEngine_Events_BaseInvokableCall1559630662.h"
#include "UnityEngine_UnityEngine_Transform1659122786.h"
#include "UnityEngine_UnityEngine_GameObject3674682005.h"
#include "UnityEngine_UnityEngine_Sprite3199167241.h"
#include "UnityEngine_UnityEngine_Canvas2727140764.h"
#include "UnityEngine_UnityEngine_Font4241557075.h"
#include "UnityEngine_UnityEngine_CanvasGroup3702418109.h"
#include "UnityEngine_UnityEngine_RectTransform972643934.h"
#include "UnityEngine_UnityEngine_MonoBehaviour667441552.h"
#include "UnityEngine_UnityEngine_RenderTexture1963041563.h"
#include "UnityEngine_UnityEngine_Texture2526458961.h"
#include "UnityEngine_UnityEngine_Mesh4241756145.h"
#pragma once
// UnityEngine.Object[]
struct ObjectU5BU5D_t1015136018 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Object_t3071478659 * m_Items[1];
public:
inline Object_t3071478659 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Object_t3071478659 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Object_t3071478659 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.SocialPlatforms.IAchievementDescription[]
struct IAchievementDescriptionU5BU5D_t4128901257 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Il2CppObject * m_Items[1];
public:
inline Il2CppObject * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Il2CppObject ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Il2CppObject * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.SocialPlatforms.IAchievement[]
struct IAchievementU5BU5D_t1953253797 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Il2CppObject * m_Items[1];
public:
inline Il2CppObject * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Il2CppObject ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Il2CppObject * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.SocialPlatforms.IScore[]
struct IScoreU5BU5D_t250104726 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Il2CppObject * m_Items[1];
public:
inline Il2CppObject * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Il2CppObject ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Il2CppObject * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.SocialPlatforms.IUserProfile[]
struct IUserProfileU5BU5D_t3419104218 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Il2CppObject * m_Items[1];
public:
inline Il2CppObject * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Il2CppObject ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Il2CppObject * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.SocialPlatforms.Impl.AchievementDescription[]
struct AchievementDescriptionU5BU5D_t759444790 : public Il2CppArray
{
public:
ALIGN_FIELD (8) AchievementDescription_t2116066607 * m_Items[1];
public:
inline AchievementDescription_t2116066607 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline AchievementDescription_t2116066607 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, AchievementDescription_t2116066607 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.SocialPlatforms.Impl.UserProfile[]
struct UserProfileU5BU5D_t2378268441 : public Il2CppArray
{
public:
ALIGN_FIELD (8) UserProfile_t2280656072 * m_Items[1];
public:
inline UserProfile_t2280656072 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline UserProfile_t2280656072 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, UserProfile_t2280656072 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard[]
struct GcLeaderboardU5BU5D_t1649880630 : public Il2CppArray
{
public:
ALIGN_FIELD (8) GcLeaderboard_t1820874799 * m_Items[1];
public:
inline GcLeaderboard_t1820874799 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline GcLeaderboard_t1820874799 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, GcLeaderboard_t1820874799 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.SocialPlatforms.GameCenter.GcAchievementData[]
struct GcAchievementDataU5BU5D_t1726768202 : public Il2CppArray
{
public:
ALIGN_FIELD (8) GcAchievementData_t3481375915 m_Items[1];
public:
inline GcAchievementData_t3481375915 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline GcAchievementData_t3481375915 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, GcAchievementData_t3481375915 value)
{
m_Items[index] = value;
}
};
// UnityEngine.SocialPlatforms.Impl.Achievement[]
struct AchievementU5BU5D_t912418020 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Achievement_t344600729 * m_Items[1];
public:
inline Achievement_t344600729 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Achievement_t344600729 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Achievement_t344600729 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.SocialPlatforms.GameCenter.GcScoreData[]
struct GcScoreDataU5BU5D_t1670395707 : public Il2CppArray
{
public:
ALIGN_FIELD (8) GcScoreData_t2181296590 m_Items[1];
public:
inline GcScoreData_t2181296590 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline GcScoreData_t2181296590 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, GcScoreData_t2181296590 value)
{
m_Items[index] = value;
}
};
// UnityEngine.SocialPlatforms.Impl.Score[]
struct ScoreU5BU5D_t2926278037 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Score_t3396031228 * m_Items[1];
public:
inline Score_t3396031228 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Score_t3396031228 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Score_t3396031228 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.Vector2[]
struct Vector2U5BU5D_t4024180168 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Vector2_t4282066565 m_Items[1];
public:
inline Vector2_t4282066565 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Vector2_t4282066565 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Vector2_t4282066565 value)
{
m_Items[index] = value;
}
};
// UnityEngine.Color[]
struct ColorU5BU5D_t2441545636 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Color_t4194546905 m_Items[1];
public:
inline Color_t4194546905 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Color_t4194546905 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Color_t4194546905 value)
{
m_Items[index] = value;
}
};
// UnityEngine.Keyframe[]
struct KeyframeU5BU5D_t3589549831 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Keyframe_t4079056114 m_Items[1];
public:
inline Keyframe_t4079056114 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Keyframe_t4079056114 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Keyframe_t4079056114 value)
{
m_Items[index] = value;
}
};
// UnityEngine.Vector3[]
struct Vector3U5BU5D_t215400611 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Vector3_t4282066566 m_Items[1];
public:
inline Vector3_t4282066566 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Vector3_t4282066566 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Vector3_t4282066566 value)
{
m_Items[index] = value;
}
};
// UnityEngine.Vector4[]
struct Vector4U5BU5D_t701588350 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Vector4_t4282066567 m_Items[1];
public:
inline Vector4_t4282066567 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Vector4_t4282066567 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Vector4_t4282066567 value)
{
m_Items[index] = value;
}
};
// UnityEngine.Color32[]
struct Color32U5BU5D_t2960766953 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Color32_t598853688 m_Items[1];
public:
inline Color32_t598853688 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Color32_t598853688 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Color32_t598853688 value)
{
m_Items[index] = value;
}
};
// UnityEngine.Camera[]
struct CameraU5BU5D_t2716570836 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Camera_t2727095145 * m_Items[1];
public:
inline Camera_t2727095145 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Camera_t2727095145 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Camera_t2727095145 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.Behaviour[]
struct BehaviourU5BU5D_t1756617250 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Behaviour_t200106419 * m_Items[1];
public:
inline Behaviour_t200106419 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Behaviour_t200106419 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Behaviour_t200106419 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.Component[]
struct ComponentU5BU5D_t663911650 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Component_t3501516275 * m_Items[1];
public:
inline Component_t3501516275 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Component_t3501516275 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Component_t3501516275 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.Display[]
struct DisplayU5BU5D_t3684569385 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Display_t1321072632 * m_Items[1];
public:
inline Display_t1321072632 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Display_t1321072632 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Display_t1321072632 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.Touch[]
struct TouchU5BU5D_t3635654872 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Touch_t4210255029 m_Items[1];
public:
inline Touch_t4210255029 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Touch_t4210255029 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Touch_t4210255029 value)
{
m_Items[index] = value;
}
};
// UnityEngine.Experimental.Director.Playable[]
struct PlayableU5BU5D_t910723999 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Playable_t70832698 m_Items[1];
public:
inline Playable_t70832698 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Playable_t70832698 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Playable_t70832698 value)
{
m_Items[index] = value;
}
};
// UnityEngine.ContactPoint[]
struct ContactPointU5BU5D_t715040733 : public Il2CppArray
{
public:
ALIGN_FIELD (8) ContactPoint_t243083348 m_Items[1];
public:
inline ContactPoint_t243083348 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline ContactPoint_t243083348 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, ContactPoint_t243083348 value)
{
m_Items[index] = value;
}
};
// UnityEngine.RaycastHit[]
struct RaycastHitU5BU5D_t528650843 : public Il2CppArray
{
public:
ALIGN_FIELD (8) RaycastHit_t4003175726 m_Items[1];
public:
inline RaycastHit_t4003175726 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline RaycastHit_t4003175726 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, RaycastHit_t4003175726 value)
{
m_Items[index] = value;
}
};
// UnityEngine.Rigidbody2D[]
struct Rigidbody2DU5BU5D_t23929848 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Rigidbody2D_t1743771669 * m_Items[1];
public:
inline Rigidbody2D_t1743771669 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Rigidbody2D_t1743771669 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Rigidbody2D_t1743771669 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.RaycastHit2D[]
struct RaycastHit2DU5BU5D_t889400257 : public Il2CppArray
{
public:
ALIGN_FIELD (8) RaycastHit2D_t1374744384 m_Items[1];
public:
inline RaycastHit2D_t1374744384 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline RaycastHit2D_t1374744384 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, RaycastHit2D_t1374744384 value)
{
m_Items[index] = value;
}
};
// UnityEngine.ContactPoint2D[]
struct ContactPoint2DU5BU5D_t3916425411 : public Il2CppArray
{
public:
ALIGN_FIELD (8) ContactPoint2D_t4288432358 m_Items[1];
public:
inline ContactPoint2D_t4288432358 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline ContactPoint2D_t4288432358 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, ContactPoint2D_t4288432358 value)
{
m_Items[index] = value;
}
};
// UnityEngine.UIVertex[]
struct UIVertexU5BU5D_t1796391381 : public Il2CppArray
{
public:
ALIGN_FIELD (8) UIVertex_t4244065212 m_Items[1];
public:
inline UIVertex_t4244065212 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline UIVertex_t4244065212 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, UIVertex_t4244065212 value)
{
m_Items[index] = value;
}
};
// UnityEngine.UICharInfo[]
struct UICharInfoU5BU5D_t4214337045 : public Il2CppArray
{
public:
ALIGN_FIELD (8) UICharInfo_t65807484 m_Items[1];
public:
inline UICharInfo_t65807484 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline UICharInfo_t65807484 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, UICharInfo_t65807484 value)
{
m_Items[index] = value;
}
};
// UnityEngine.UILineInfo[]
struct UILineInfoU5BU5D_t2354741311 : public Il2CppArray
{
public:
ALIGN_FIELD (8) UILineInfo_t4113875482 m_Items[1];
public:
inline UILineInfo_t4113875482 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline UILineInfo_t4113875482 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, UILineInfo_t4113875482 value)
{
m_Items[index] = value;
}
};
// UnityEngine.GUILayoutOption[]
struct GUILayoutOptionU5BU5D_t2977405297 : public Il2CppArray
{
public:
ALIGN_FIELD (8) GUILayoutOption_t331591504 * m_Items[1];
public:
inline GUILayoutOption_t331591504 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline GUILayoutOption_t331591504 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, GUILayoutOption_t331591504 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.GUILayoutUtility/LayoutCache[]
struct LayoutCacheU5BU5D_t3709016094 : public Il2CppArray
{
public:
ALIGN_FIELD (8) LayoutCache_t879908455 * m_Items[1];
public:
inline LayoutCache_t879908455 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline LayoutCache_t879908455 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, LayoutCache_t879908455 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.GUILayoutEntry[]
struct GUILayoutEntryU5BU5D_t2084979372 : public Il2CppArray
{
public:
ALIGN_FIELD (8) GUILayoutEntry_t1336615025 * m_Items[1];
public:
inline GUILayoutEntry_t1336615025 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline GUILayoutEntry_t1336615025 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, GUILayoutEntry_t1336615025 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.GUIStyle[]
struct GUIStyleU5BU5D_t565654559 : public Il2CppArray
{
public:
ALIGN_FIELD (8) GUIStyle_t2990928826 * m_Items[1];
public:
inline GUIStyle_t2990928826 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline GUIStyle_t2990928826 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, GUIStyle_t2990928826 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.Networking.IMultipartFormSection[]
struct IMultipartFormSectionU5BU5D_t3148335757 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Il2CppObject * m_Items[1];
public:
inline Il2CppObject * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Il2CppObject ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Il2CppObject * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.DisallowMultipleComponent[]
struct DisallowMultipleComponentU5BU5D_t3749917529 : public Il2CppArray
{
public:
ALIGN_FIELD (8) DisallowMultipleComponent_t62111112 * m_Items[1];
public:
inline DisallowMultipleComponent_t62111112 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline DisallowMultipleComponent_t62111112 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, DisallowMultipleComponent_t62111112 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.ExecuteInEditMode[]
struct ExecuteInEditModeU5BU5D_t156135824 : public Il2CppArray
{
public:
ALIGN_FIELD (8) ExecuteInEditMode_t3132250205 * m_Items[1];
public:
inline ExecuteInEditMode_t3132250205 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline ExecuteInEditMode_t3132250205 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, ExecuteInEditMode_t3132250205 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.RequireComponent[]
struct RequireComponentU5BU5D_t968569205 : public Il2CppArray
{
public:
ALIGN_FIELD (8) RequireComponent_t1687166108 * m_Items[1];
public:
inline RequireComponent_t1687166108 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline RequireComponent_t1687166108 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, RequireComponent_t1687166108 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.SendMouseEvents/HitInfo[]
struct HitInfoU5BU5D_t3452915852 : public Il2CppArray
{
public:
ALIGN_FIELD (8) HitInfo_t3209134097 m_Items[1];
public:
inline HitInfo_t3209134097 GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline HitInfo_t3209134097 * GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, HitInfo_t3209134097 value)
{
m_Items[index] = value;
}
};
// UnityEngine.Events.PersistentCall[]
struct PersistentCallU5BU5D_t1880240530 : public Il2CppArray
{
public:
ALIGN_FIELD (8) PersistentCall_t2972625667 * m_Items[1];
public:
inline PersistentCall_t2972625667 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline PersistentCall_t2972625667 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, PersistentCall_t2972625667 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.Events.BaseInvokableCall[]
struct BaseInvokableCallU5BU5D_t3104884963 : public Il2CppArray
{
public:
ALIGN_FIELD (8) BaseInvokableCall_t1559630662 * m_Items[1];
public:
inline BaseInvokableCall_t1559630662 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline BaseInvokableCall_t1559630662 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, BaseInvokableCall_t1559630662 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.Transform[]
struct TransformU5BU5D_t3792884695 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Transform_t1659122786 * m_Items[1];
public:
inline Transform_t1659122786 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Transform_t1659122786 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Transform_t1659122786 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.GameObject[]
struct GameObjectU5BU5D_t2662109048 : public Il2CppArray
{
public:
ALIGN_FIELD (8) GameObject_t3674682005 * m_Items[1];
public:
inline GameObject_t3674682005 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline GameObject_t3674682005 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, GameObject_t3674682005 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.Sprite[]
struct SpriteU5BU5D_t2761310900 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Sprite_t3199167241 * m_Items[1];
public:
inline Sprite_t3199167241 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Sprite_t3199167241 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Sprite_t3199167241 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.Canvas[]
struct CanvasU5BU5D_t2903919733 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Canvas_t2727140764 * m_Items[1];
public:
inline Canvas_t2727140764 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Canvas_t2727140764 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Canvas_t2727140764 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.Font[]
struct FontU5BU5D_t3453939458 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Font_t4241557075 * m_Items[1];
public:
inline Font_t4241557075 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Font_t4241557075 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Font_t4241557075 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.CanvasGroup[]
struct CanvasGroupU5BU5D_t290646448 : public Il2CppArray
{
public:
ALIGN_FIELD (8) CanvasGroup_t3702418109 * m_Items[1];
public:
inline CanvasGroup_t3702418109 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline CanvasGroup_t3702418109 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, CanvasGroup_t3702418109 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.RectTransform[]
struct RectTransformU5BU5D_t3587651179 : public Il2CppArray
{
public:
ALIGN_FIELD (8) RectTransform_t972643934 * m_Items[1];
public:
inline RectTransform_t972643934 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline RectTransform_t972643934 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, RectTransform_t972643934 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.MonoBehaviour[]
struct MonoBehaviourU5BU5D_t129089073 : public Il2CppArray
{
public:
ALIGN_FIELD (8) MonoBehaviour_t667441552 * m_Items[1];
public:
inline MonoBehaviour_t667441552 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline MonoBehaviour_t667441552 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, MonoBehaviour_t667441552 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.RenderTexture[]
struct RenderTextureU5BU5D_t1576771098 : public Il2CppArray
{
public:
ALIGN_FIELD (8) RenderTexture_t1963041563 * m_Items[1];
public:
inline RenderTexture_t1963041563 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline RenderTexture_t1963041563 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, RenderTexture_t1963041563 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.Texture[]
struct TextureU5BU5D_t606176076 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Texture_t2526458961 * m_Items[1];
public:
inline Texture_t2526458961 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Texture_t2526458961 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Texture_t2526458961 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
// UnityEngine.Mesh[]
struct MeshU5BU5D_t1759126828 : public Il2CppArray
{
public:
ALIGN_FIELD (8) Mesh_t4241756145 * m_Items[1];
public:
inline Mesh_t4241756145 * GetAt(il2cpp_array_size_t index) const { return m_Items[index]; }
inline Mesh_t4241756145 ** GetAddressAt(il2cpp_array_size_t index) { return m_Items + index; }
inline void SetAt(il2cpp_array_size_t index, Mesh_t4241756145 * value)
{
m_Items[index] = value;
Il2CppCodeGenWriteBarrier(m_Items + index, value);
}
};
| [
"labguitar1003@gmail.com"
] | labguitar1003@gmail.com |
7a82c016a27a3b500892ed0eb11132907695dfdd | 8492f5c968ec3bd60c7e184ea1b9ef0a108c1aa2 | /2D_Lines/line_structs.cpp | 87f06d9c4342c9175c825d23594454e6bea524ff | [] | no_license | MrMounir19/Comp_Graph_Engine | 97ebcc5bcbe06ec2f54d57af223cbea6ab165222 | 2bbdcbcb941f28c05b8f8f7e18b153eb1f13f293 | refs/heads/master | 2022-09-25T22:17:51.964689 | 2020-05-31T15:14:39 | 2020-05-31T15:14:39 | 242,787,035 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,131 | cpp |
#ifndef ENGINE_LINESTRUCTS
#define ENGINE_LINESTRUCTS
#include <vector>
#include <limits>
struct Color {
double red;
double green;
double blue;
Color (double R, double G, double B):red(R), green(G), blue(B) {}
Color (std::vector<double> color) {
red = color[0];
green = color[1];
blue = color[2];
}
};
struct Point2D {
double x;
double y;
Point2D (double X, double Y):x(X), y(Y) {}
};
struct Line2D {
Point2D p1;
Point2D p2;
Color color;
Line2D (Point2D P1, Point2D P2, Color c, double Z1, double Z2):p1(P1), p2(P2), color(c), z1(Z1), z2(Z2) {}
double z1;
double z2;
};
struct ZBuffer {
std::vector<std::vector<double>> buffer;
ZBuffer(unsigned int width, unsigned int height ) {
double posInf = std::numeric_limits<double>::infinity();
std::vector<double> rij;
for (unsigned int w = 0; w < width; w++) {
rij.push_back(posInf);
}
for (unsigned int h = 0; h < height; h++) {
buffer.push_back(rij);
}
}
};
using Lines2D = std::vector<Line2D>;
#endif
| [
"mounirvillaverde@gmail.com"
] | mounirvillaverde@gmail.com |
52b939af5e1daad911cd112ddf63744591577db3 | c173d7387b44e86d74e83472f428479c56bce58f | /hardware/MPU6050.cpp | 8a715987117d1220e0af64ba768f57706a7afba4 | [
"MIT"
] | permissive | rise0chen/lib-mcu-stm32f1 | e604ba0470fe8aea17a1ae303c4531e18be2cfec | 203ea6564d1e8821e6e2ab991056bad9fa9da2e1 | refs/heads/master | 2021-05-05T15:52:13.726459 | 2019-09-30T08:39:34 | 2019-09-30T08:39:34 | 117,324,381 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,816 | cpp | /*************************************************
Copyright (C), 2018-2028, Crise Tech. Co., Ltd.
File name: Mpu6050.cpp
Author: rise0chen
Version: 1.0
Date: 2018.4.26
Description: Mpu6050陀螺仪芯片
Usage:
#include "Mpu6050.h"
Mpu6050 mpu6050(&i2c2, 0x68);
mpu6050.init();
mpu6050.getGYRO();
mpu6050.getACCEL();
usart1.printf("GYRO_X:%d;\r\n",Mpu6050::GYRO[0]);
usart1.printf("GYRO_Y:%d;\r\n",Mpu6050::GYRO[1]);
usart1.printf("GYRO_Z:%d;\r\n",Mpu6050::GYRO[2]);
usart1.printf("ACCEL_X:%d;\r\n",Mpu6050::ACCEL[0]);
usart1.printf("ACCEL_Y:%d;\r\n",Mpu6050::ACCEL[1]);
usart1.printf("ACCEL_Z:%d;\r\n",Mpu6050::ACCEL[2]);
History:
rise0chen 2018.4.26 编写注释
*************************************************/
#include "Mpu6050.h"
/*************************************************
Function: Mpu6050::Mpu6050
Description: Mpu6050构造函数
Input:
i2c_com I2C外设
i2c_addr I2C地址
Return: DS18B20类
*************************************************/
Mpu6050::Mpu6050(I2c* i2c_com, uint8_t i2c_addr) {
com = i2c_com;
addr = i2c_addr;
}
/*************************************************
Function: Mpu6050::init
Description: 初始化Mpu6050
Input: void
Return: void
*************************************************/
void Mpu6050::init(void) {
writeByte(MPU_PWR_MGMT1_REG, 0X80); //复位Mpu6050
delay_ms(100);
writeByte(MPU_PWR_MGMT1_REG, 0X00); //唤醒Mpu6050
writeByte(MPU_GYRO_CFG_REG, 3 << 3); //陀螺仪满量程范围 ±2000dps 16.384=1°/s
writeByte(MPU_ACCEL_CFG_REG, 0 << 3); //加速度满量程范围 ±2g 16384=1g
writeByte(MPU_USER_CTRL_REG, 0X00); // I2C主模式关闭
writeByte(MPU_FIFO_EN_REG, 0X00); //关闭FIFO
if (readByte(MPU_DEVICE_ID_REG) == addr) { //器件ID正确
writeByte(MPU_PWR_MGMT1_REG, 0X09); //禁用温度传感器,PLL X轴为参考
writeByte(MPU_PWR_MGMT2_REG, 0X00); //加速度与陀螺仪都工作
writeByte(MPU_SAMPLE_RATE_REG, (1000 / 50 - 1)); //采样率 50Hz
writeByte(MPU_CFG_REG, 4); //数字低通滤波器 25Hz
writeByte(MPU_INT_EN_REG, 0X40); //开启运动中断
writeByte(MPU_INTBP_CFG_REG, 0XF0); // INT引脚开漏输出,中断时低电平
writeByte(MPU_MOTION_DET_REG, 0x01); //运动阈值
writeByte(MPU_MOTION_DUR_REG, 0x14); //计数器阈值
writeByte(MPU_MDETECT_CTRL_REG, 0xC8);
}
}
/*************************************************
Function: Mpu6050::getGYRO
Description: 读取倾斜角,输出到GYRO[]
Input: void
Return: void
*************************************************/
void Mpu6050::getGYRO(void) {
uint8_t buf[2];
buf[0] = readByte(MPU_GYRO_XOUTH_REG);
buf[1] = readByte(MPU_GYRO_XOUTL_REG);
GYRO[0] = (buf[0] << 8) | buf[1];
buf[0] = readByte(MPU_GYRO_YOUTH_REG);
buf[1] = readByte(MPU_GYRO_YOUTL_REG);
GYRO[1] = (buf[0] << 8) | buf[1];
buf[0] = readByte(MPU_GYRO_ZOUTH_REG);
buf[1] = readByte(MPU_GYRO_ZOUTL_REG);
GYRO[2] = (buf[0] << 8) | buf[1];
}
/*************************************************
Function: Mpu6050::getACCEL
Description: 读取加速度,输出到ACCEL[]
Input: void
Return: void
*************************************************/
void Mpu6050::getACCEL(void) {
uint8_t buf[2];
buf[0] = readByte(MPU_ACCEL_XOUTH_REG);
buf[1] = readByte(MPU_ACCEL_XOUTL_REG);
ACCEL[0] = (buf[0] << 8) | buf[1];
buf[0] = readByte(MPU_ACCEL_YOUTH_REG);
buf[1] = readByte(MPU_ACCEL_YOUTL_REG);
ACCEL[1] = (buf[0] << 8) | buf[1];
buf[0] = readByte(MPU_ACCEL_ZOUTH_REG);
buf[1] = readByte(MPU_ACCEL_ZOUTL_REG);
ACCEL[2] = (buf[0] << 8) | buf[1];
}
/*************************************************
Function: Mpu6050::writeByte
Description: 向寄存器写单字节
Input:
reg 寄存器地址
data 单字节数据
Return: void
*************************************************/
void Mpu6050::writeByte(uint8_t reg, uint8_t data) {
com->start();
com->write((addr << 1) | 0); //发送器件地址+写命令
com->write(reg); //写寄存器地址
com->write(data); //发送数据
com->stop();
}
/*************************************************
Function: Mpu6050::readByte
Description: 从寄存器读单字节
Input:
reg 寄存器地址
Return: 单字节数据
*************************************************/
uint8_t Mpu6050::readByte(uint8_t reg) {
uint8_t res;
com->start();
com->write((addr << 1) | 0); //发送器件地址+写命令
com->write(reg); //写寄存器地址
com->start();
com->write((addr << 1) | 1); //发送器件地址+读命令
res = com->read(0); //读取数据,发送nACK
com->stop(); //产生一个停止条件
return res;
}
| [
"1034018425@qq.com"
] | 1034018425@qq.com |
11708a8d7a7954c4e25be57d83018a87c922d9c7 | 129b17409003e825e01ee3b74b6b2b462d1cbf55 | /HrCommon/HrResource/HrAssetLoadManager.cpp | 45e7003d7fa9bb7191c527f7a5b7947ca1ea4411 | [] | no_license | nincool/Cocos2d | f868203601a89cd89c8835aaf6d5f190982885eb | 555dea1a4b6e2f07ec825cbe26ae8e1a8b7645ac | refs/heads/master | 2016-09-05T17:46:26.555853 | 2015-07-25T07:37:10 | 2015-07-25T07:37:10 | 32,519,367 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 938 | cpp | #include "HrAssetLoadManager.h"
#include "IAssetLoad.h"
using namespace HrCCBase;
HrCCBase::CHrAssetLoadManager::CHrAssetLoadManager()
{
m_nCurLoadAssetNum = 0;
m_nTotalAssetNum = 0;
m_nCurLoadAssetIndex = 0;
m_pAssetLoadEvent = nullptr;
}
HrCCBase::CHrAssetLoadManager::~CHrAssetLoadManager()
{
}
void CHrAssetLoadManager::ScanResource()
{
for (auto item : m_vecAssetLoad)
{
m_nTotalAssetNum += item->GetTotalAssetNum();
}
}
void CHrAssetLoadManager::UpdateLoadResource()
{
if (m_vecAssetLoad.size() > 0)
{
m_vecAssetLoad[m_nCurLoadAssetIndex]->LoadOneResource();
}
}
void CHrAssetLoadManager::SetCurrentProcess(int nTotalNum, int nCurrentNum)
{
++m_nCurLoadAssetNum;
m_pAssetLoadEvent->SetCurrentProcess(m_nTotalAssetNum, m_nCurLoadAssetNum + 1 );
}
void CHrAssetLoadManager::LoadAssetFinal()
{
++m_nCurLoadAssetIndex;
if (m_nCurLoadAssetNum >= m_nTotalAssetNum)
{
m_pAssetLoadEvent->LoadAssetFinal();
}
}
| [
"howieren@163.com"
] | howieren@163.com |
654dd0141a2b4390498ca2541770a2bb768208f4 | e8ebf2696611e5c4bd58d6d81ac0bbd54864ff6d | /QGoogleMap.cpp | ede0ff86eec76a953c1a52b2acde2922ead92fe6 | [
"MIT"
] | permissive | fedormex/QGoogleMap | 7ed23dad11564e97de6241f2e135e40b11242b6e | f6b10a5191888018d99ba78ca43271a38cad8e25 | refs/heads/master | 2020-03-17T14:42:55.361775 | 2018-05-31T19:41:32 | 2018-05-31T19:41:32 | 133,683,785 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 29,962 | cpp | #include <sys/stat.h>
#include <sys/types.h>
#include <utime.h>
#include <signal.h>
#include "QGoogleMap.h"
const int MEM_CACHE_SIZE = 200; // In chunks
const int DISK_CACHE_SIZE = 10000; // In chunks
const int HISTORY_SIZE = 1000; // maximum history (track) size
const int ZOOM_MAX = 19; // maximum zoom value
const int ZOOM_MIN = 10; // minimum zoom value
const double EPSILON = 1e-8;
const double DEG_LENGTH_ARRAY[] = {
0, // Zoom level 0
0, // Zoom level 1
0, // Zoom level 2
0, // Zoom level 3
0, // Zoom level 4
22.8, // Zoom level 5
0, // Zoom level 6
0, // Zoom level 7
0, // Zoom level 8
0, // Zoom level 9
727.142857, // Zoom level 10
1454.285714, // Zoom level 11
2908.571428, // Zoom level 12
0, // Zoom level 13
0, // Zoom level 14
0, // Zoom level 15
46625.0, // Zoom level 16
93250.0, // Zoom level 17
186500.0, // Zoom level 18
373000.0, // Zoom level 19
0 }; // Zoom level 20
const QString FFMPEG = "ffmpeg";
StdinReader::StdinReader(QObject* parent)
: QThread ( parent )
, mStream ( stdin, QIODevice::ReadOnly )
{
setTerminationEnabled(true);
}
void StdinReader::run()
{
while (true)
{
QString line = mStream.readLine();
if (line.isEmpty())
{
usleep(100000);
continue;
}
emit readLine(line);
}
}
CacheCleaner::CacheCleaner(const QString& cacheDir, QObject* parent)
: QThread ( parent )
, mCacheDir ( cacheDir )
{
setTerminationEnabled(true);
}
void CacheCleaner::run()
{
while (true)
{
QDir dir(mCacheDir);
QStringList fileList = dir.entryList(QStringList() << "*.png", QDir::Files, QDir::Time);
if (fileList.size() > DISK_CACHE_SIZE)
{
while (fileList.size() > DISK_CACHE_SIZE / 2)
{
qDebug() << "Removing file" << fileList.last();
dir.remove(fileList.last());
fileList.removeLast();
}
}
usleep(60000000);
}
}
QGoogleMap::QGoogleMap(const QString& apiKey, QWidget* parent)
: QWidget ( parent )
, mApiKey ( apiKey )
, mHomeDir ( "/var/tmp/QGoogleMap" )
, mMapType ( "roadmap" )
, mMapZoom ( 18 )
, mDegLength ( DEG_LENGTH_ARRAY[mMapZoom] )
, mLatitude ( 42.531 )
, mLongitude ( -71.149 )
, mTargetLatitude ( 0.0 )
, mTargetLongitude ( 0.0 )
, mTargetAccuracy ( 0.0 )
, mAdjustTime ( QDateTime::currentDateTime() )
, mGpsTime ( QDateTime::currentDateTime() )
, mRecordProcess ( 0 )
{
mkdir(qPrintable(mHomeDir), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
mkdir(qPrintable(mHomeDir + "/cache"), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
mkdir(qPrintable(mHomeDir + "/video"), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
mkdir(qPrintable(mHomeDir + "/logs"), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
mNetworkManager = new QNetworkAccessManager(this);
connect(mNetworkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onRequestFinished(QNetworkReply*)));
mNetworkTimeoutSignalMapper = new QSignalMapper(this);
connect(mNetworkTimeoutSignalMapper, SIGNAL(mapped(QObject*)),
this, SLOT(onRequestTimeout(QObject*)));
QTimer* refreshTimer = new QTimer(this);
refreshTimer->setInterval(250);
refreshTimer->setSingleShot(false);
refreshTimer->start();
connect(refreshTimer, SIGNAL(timeout()), this, SLOT(refresh()));
mReader = new StdinReader(this);
connect(mReader, SIGNAL(readLine(QString)), this, SLOT(onReadLine(QString)));
mReader->start();
mCacheCleaner = new CacheCleaner(mHomeDir + "/cache", this);
mCacheCleaner->start();
mZoomInButton = new QToolButton(this);
mZoomInButton->setStyleSheet("background-color: rgba(200,200,200,200); border-style: solid; border-radius: 30px;");
mZoomInButton->setIcon(QIcon(":/icons/zoom_in"));
mZoomInButton->setFixedSize(60, 60);
mZoomInButton->setEnabled(mMapZoom < ZOOM_MAX);
connect(mZoomInButton, SIGNAL(clicked()), this, SLOT(onZoomIn()));
mZoomOutButton = new QToolButton(this);
mZoomOutButton->setStyleSheet("background-color: rgba(200,200,200,200); border-style: solid; border-radius: 30px;");
mZoomOutButton->setIcon(QIcon(":/icons/zoom_out"));
mZoomOutButton->setFixedSize(60, 60);
mZoomOutButton->setEnabled(mMapZoom > ZOOM_MIN);
connect(mZoomOutButton, SIGNAL(clicked()), this, SLOT(onZoomOut()));
mAdjustButton = new QToolButton(this);
mAdjustButton->setStyleSheet("QToolButton { background-color: rgba(200,200,200,200); border-style: solid; border-radius: 30px; } "
"QToolButton:checked { background-color: rgba(150,150,150,200); border-style: solid; border-radius: 30px; } ");
mAdjustButton->setCheckable(true);
mAdjustButton->setChecked(false);
mAdjustButton->setFixedSize(60, 60);
connect(mAdjustButton, SIGNAL(toggled(bool)), this, SLOT(onAdjustModeToggle()));
QTimer::singleShot(0, mAdjustButton, SLOT(toggle()));
mRecordButton = new QToolButton(this);
mRecordButton->setIcon(QIcon(":/icons/record_start"));
mRecordButton->setStyleSheet("QToolButton { background-color: rgba(200,200,200,200); border-style: solid; border-radius: 30px; } "
"QToolButton:checked { background-color: rgba(150,150,150,200); border-style: solid; border-radius: 30px; } ");
mRecordButton->setCheckable(true);
mRecordButton->setChecked(false);
mRecordButton->setFixedSize(60, 60);
connect(mRecordButton, SIGNAL(toggled(bool)), this, SLOT(onRecordToggle()));
}
void QGoogleMap::setTarget(double latitude, double longitude, double accuracy, double azimuth)
{
mTargetLatitude = latitude;
mTargetLongitude = longitude;
mTargetAccuracy = accuracy;
mTargetAzimuth = azimuth;
if (hasTarget())
{
mTargetHistory.append(qMakePair(mTargetLatitude, mTargetLongitude));
if (mTargetHistory.size() > HISTORY_SIZE)
mTargetHistory.removeFirst();
}
refresh();
update();
}
void QGoogleMap::setInfoText(const QString& text)
{
mInfoText = text;
update();
}
void QGoogleMap::cancelTarget()
{
mTargetLatitude = 0.0;
mTargetLongitude = 0.0;
mTargetAccuracy = 0.0;
mTargetHistory.clear();
}
bool QGoogleMap::hasTarget()const
{
return (qAbs(mTargetLatitude) > EPSILON || qAbs(mTargetLongitude) > EPSILON) &&
qAbs(mTargetLatitude) <= 89.0 &&
qAbs(mTargetLongitude) <= 180.0;
}
void QGoogleMap::keyPressEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_Plus || event->key() == Qt::Key_Equal)
onZoomIn();
else if (event->key() == Qt::Key_Minus)
onZoomOut();
else if (event->key() == Qt::Key_Q)
close();
}
void QGoogleMap::resizeEvent(QResizeEvent* event)
{
const int buttonWidth = mZoomInButton->width();
const int buttonHeight = mZoomInButton->height();
const int padding = 10;
mZoomInButton -> move(width() - buttonWidth - 10, height() / 2 - 3 * padding / 2 - 2 * buttonHeight);
mZoomOutButton -> move(width() - buttonWidth - 10, height() / 2 - padding / 2 - buttonHeight);
mAdjustButton -> move(width() - buttonWidth - 10, height() / 2 + padding / 2);
mRecordButton -> move(width() - buttonWidth - 10, height() / 2 + 3 * padding / 2 + buttonHeight);
update();
}
void QGoogleMap::mousePressEvent(QMouseEvent* event)
{
if (event->buttons() == Qt::LeftButton)
{
mCursorPos = event->pos();
event->accept();
}
else
event->ignore();
}
void QGoogleMap::mouseReleaseEvent(QMouseEvent* event)
{
mCursorPos = QPoint();
event->accept();
}
void QGoogleMap::mouseMoveEvent(QMouseEvent* event)
{
if (event->buttons() == Qt::LeftButton)
{
const int px = event->pos().x() - mCursorPos.x();
const int py = event->pos().y() - mCursorPos.y();
mCursorPos = event->pos();
onScroll(px, py);
event->accept();
}
}
void QGoogleMap::paintEvent(QPaintEvent* event)
{
const double LATITUDE_COEF = 1.0 / cos(mLatitude * M_PI / 180);
const double PARALLEL_DEG_LENGTH = 40000000.0 / 360 / LATITUDE_COEF;
const QFont defaultFont = this->font();
QPainter p;
p.begin(this);
p.setRenderHints(QPainter::Antialiasing |
QPainter::TextAntialiasing |
QPainter::SmoothPixmapTransform |
QPainter::HighQualityAntialiasing |
QPainter::NonCosmeticDefaultPen,
true);
// Drawing gray background
p.fillRect(0, 0, width(), height(), QColor(Qt::gray));
// Drawing map chunks
for(auto chunk: mMapChunks)
{
if (chunk.zoom != mMapZoom)
continue;
double dx = (chunk.longitude - mLongitude);
double dy = (chunk.latitude - mLatitude);
qint64 px = width() / 2 + (qint64)round(dx * mDegLength) - chunk.image.width() / 2;
qint64 py = height() / 2 - (qint64)round(dy * mDegLength * LATITUDE_COEF) - chunk.image.height() / 2;
if (px > -chunk.image.width() && px < width() &&
py > -chunk.image.height() && py < height())
p.drawImage(px, py, chunk.image);
}
// Drawing target
if (hasTarget())
{
// Drawing track
if (!mTargetHistory.isEmpty())
{
QPainterPath path;
for(int i = 0; i < mTargetHistory.size(); ++i)
{
double dx = mTargetHistory[i].second - mLongitude;
double dy = mTargetHistory[i].first - mLatitude;
qint64 px = width() / 2 + (qint64)round(dx * mDegLength);
qint64 py = height() / 2 - (qint64)round(dy * mDegLength * LATITUDE_COEF);
if (i == 0)
path.moveTo(px, py);
else
path.lineTo(px, py);
}
p.setPen(QColor(255, 100, 0, 255));
p.drawPath(path);
}
double dx = mTargetLongitude - mLongitude;
double dy = mTargetLatitude - mLatitude;
qint64 px = width() / 2 + (qint64)round(dx * mDegLength);
qint64 py = height() / 2 - (qint64)round(dy * mDegLength * LATITUDE_COEF);
int radius = mTargetAccuracy * 10 * mDegLength / PARALLEL_DEG_LENGTH; // External radius: navigation-determined, transparent
int radius1 = 25; // Internal radius: fixed, solid
if (px >= -100 && px < width() + 100 &&
py >= -100 && py < height() + 100)
{
p.setPen ( QColor(255, 100, 0, 0) );
p.setBrush ( QColor(255, 100, 0, 80) );
p.drawEllipse(QPoint(px, py), radius, radius);
p.setPen ( QColor(255, 100, 0, 0) );
p.setBrush ( QColor(255, 100, 0, 255) );
p.drawEllipse(QPoint(px, py), radius1, radius1);
//p.setPen ( QColor(255, 0, 0, 160) );
//p.setBrush ( QColor(255, 0, 0, 160) );
//p.drawEllipse(QPoint(px, py), radiusMin, radiusMin);
double alpha = mTargetAzimuth * M_PI / 180;
double sinA = sin(alpha);
double cosA = cos(alpha);
//QPointF P(px, py);
//QPointF Q(px + radius * sinA, py - radius * cosA);
//QPointF R(px - radius * cosA * 0.66 - radius * sinA * 0.25, py - radius * sinA * 0.66 + radius * cosA * 0.25);
//QPointF S(px + radius * cosA * 0.66 - radius * sinA * 0.25, py + radius * sinA * 0.66 + radius * cosA * 0.25);
QPointF P(px - radius1 * sinA * 0.22, py + radius1 * cosA * 0.22);
QPointF Q(px + radius1 * sinA * 0.55, py - radius1 * cosA * 0.55);
QPointF R(px + radius1 * cosA * 0.44 - radius1 * sinA * 0.55, py + radius1 * sinA * 0.44 + radius1 * cosA * 0.55);
QPointF S(px - radius1 * cosA * 0.44 - radius1 * sinA * 0.55, py - radius1 * sinA * 0.44 + radius1 * cosA * 0.55);
QPainterPath path;
path.moveTo(Q);
path.lineTo(R);
path.lineTo(P);
path.lineTo(S);
path.lineTo(Q);
p.fillPath(path, QBrush(QColor(255, 255, 255, 255)));
}
}
// Drawing info panel
if (!mInfoText.isEmpty())
{
QStringList lines = mInfoText.split("\n");
QFont fixedFont = defaultFont;
fixedFont.setFamily("Courier New");
p.setFont(fixedFont);
QFontMetrics fm(p.font());
int fh = fm.height();
int rh = lines.size() * (fh + 1);
int rw = 0;
for(int i = 0; i < lines.size(); ++i)
rw = qMax(rw, fm.width(lines[i]) + 10);
int rw1 = rw + 50 - (rw % 50);
p.fillRect(0, 0, rw1, rh, QColor(255, 255, 255, 128));
p.setPen(QColor(Qt::black));
for(int i = 0; i < lines.size(); ++i)
p.drawText(5, (i + 1) * (fh + 1), lines[i]);
}
// Drawing scale
if (true)
{
const int minLen = 100; // minimum scale length
const int padding = 10; // padding from the bottom-left corner of the widget
const double a = PARALLEL_DEG_LENGTH / mDegLength; // number of meters in 1 pixel
QList<double> scales;
scales << 1e0 << 2e0 << 3e0 << 4e0 << 5e0 << 6e0 << 7e0 << 8e0 << 9e0
<< 1e1 << 2e1 << 3e1 << 4e1 << 5e1 << 6e1 << 7e1 << 8e1 << 9e1
<< 1e2 << 2e2 << 3e2 << 4e2 << 5e2 << 6e2 << 7e2 << 8e2 << 9e2
<< 1e3 << 2e3 << 3e3 << 4e3 << 5e3 << 6e3 << 7e3 << 8e3 << 9e3
<< 1e4 << 2e4 << 3e4 << 4e4 << 5e4 << 6e4 << 7e4 << 8e4 << 9e4
<< 1e5 << 2e5 << 3e5 << 4e5 << 5e5 << 6e5 << 7e5 << 8e5 << 9e5
<< 1e6 << 2e6 << 3e6 << 4e6 << 5e6 << 6e6 << 7e6 << 8e6 << 9e6;
double scale = scales.last();
for(int i = 0; i < scales.size(); ++i)
if (a * minLen < scales[i])
{
scale = scales[i];
break;
}
// Calculating scale length in pixels
int pxLen = qRound(scale / a);
p.setPen(QColor(0, 0, 0));
p.drawLine(padding, height() - padding, padding + pxLen, height() - padding);
p.drawLine(padding, height() - padding, padding, height() - padding - 5);
p.drawLine(padding + pxLen / 2, height() - padding, padding + pxLen / 2, height() - padding - 5);
p.drawLine(padding + pxLen, height() - padding, padding + pxLen, height() - padding - 5);
QString text0, text1, text2;
if (scale < 1000)
{
text0 = QString("%1").arg(scale, 0, 'f', 0);
text1 = text0 + " m";
text2 = QString("%1").arg(scale/2, 0, 'f', static_cast<int>(scale) % 2);
}
else
{
text0 = QString("%1").arg(scale/1000, 0, 'f', 0);
text1 = text0 + " km";
text2 = QString("%1").arg(scale/2000, 0, 'f', static_cast<int>(scale/1000) % 2);
}
QFont font(p.font());
QFont scaleFont = defaultFont;
scaleFont.setFamily("Courier New");
p.setFont(scaleFont);
QFontMetrics fm(scaleFont);
const int textY = height() - padding - fm.height() / 2;
p.drawText(padding + pxLen - fm.width(text0) / 2, textY, text1);
p.drawText(padding + pxLen / 2 - fm.width(text2) / 2, textY, text2);
}
p.end();
event->accept();
}
QList<QRectF> CheckRectCoverage(const QRectF& A, const QList<QRectF>& B)
{
QList<QRectF> queue;
queue.append(A);
for(int i = 0; i < B.size(); ++i)
{
if (queue.isEmpty())
break;
QList<QRectF> S;
for(int j = 0; j < queue.size(); ++j)
{
QRectF R = queue[j];
if (B[i].contains(R))
{
queue.removeAt(j--);
continue;
}
if (B[i].intersects(R))
{
queue.removeAt(j--);
if (B[i].top() > R.top() && B[i].top() < R.bottom())
{
QRectF R1(R);
R1.setBottom(B[i].top());
R.setTop(B[i].top());
S.append(R1);
}
if (B[i].left() > R.left() && B[i].left() < R.right())
{
QRectF R1(R);
R1.setRight(B[i].left());
R.setLeft(B[i].left());
S.append(R1);
}
if (B[i].right() > R.left() && B[i].right() < R.right())
{
QRectF R1(R);
R1.setLeft(B[i].right());
R.setRight(B[i].right());
S.append(R1);
}
if (B[i].bottom() > R.top() && B[i].bottom() < R.bottom())
{
QRectF R1(R);
R1.setTop(B[i].bottom());
R.setBottom(B[i].bottom());
S.append(R1);
}
}
}
queue.append(S);
}
return queue;
}
void QGoogleMap::refresh()
{
const double LATITUDE_COEF = 1.0 / cos(mLatitude * M_PI / 180);
// Searching for uncovered area
QList<QRectF> rects;
int paddingX = width() / 2;
int paddingY = height() / 2;
// Analysing map chunks
for(auto chunk: mMapChunks)
{
if (chunk.zoom != mMapZoom)
continue;
// Calculating pixel coordinates of the image center
double dx = (chunk.longitude - mLongitude);
double dy = (chunk.latitude - mLatitude);
qint64 px = width() / 2 + (qint64)round(dx * mDegLength) - chunk.image.width() / 2;
qint64 py = height() / 2 - (qint64)round(dy * mDegLength * LATITUDE_COEF) - chunk.image.height() / 2;
if (px > -paddingX - chunk.image.width() && px < width() + paddingX &&
py > -paddingY - chunk.image.height() && py < height() + paddingY)
rects.append(QRectF(px, py, chunk.image.width(), chunk.image.height()));
}
QList<QRectF> uncovered = CheckRectCoverage(QRectF(-paddingX, -paddingY, width() + 2 * paddingX, height() + 2 * paddingY), rects);
int maxWidth = 640;
int maxHeight = 560;
for(int i = 0; i < uncovered.size(); ++i)
{
QRectF R = uncovered[i];
if (R.width() > maxWidth)
{
QRectF R1 = R;
R1.setRight(R.left() + maxWidth);
R.setLeft(R.left() + maxWidth);
uncovered[i] = R;
uncovered.append(R1);
}
if (R.height() > maxHeight)
{
QRectF R1 = R;
R1.setBottom(R.top() + maxHeight);
R.setTop(R.left() + maxHeight);
uncovered[i] = R;
uncovered.append(R1);
}
}
for(int i = 0; i < uncovered.size(); ++i)
{
int px = uncovered[i].left();
int py = uncovered[i].top();
double dx = (px - width() / 2) / mDegLength;
double dy = (height() / 2 - py) / mDegLength / LATITUDE_COEF;
double longitude = dx + mLongitude;
double latitude = dy + mLatitude;
requestMap(latitude, longitude, mMapZoom);
}
if (mMapChunks.size() > MEM_CACHE_SIZE)
clearCache();
if (mAdjustButton->isChecked() && hasTarget())
{
QDateTime timeNow = QDateTime::currentDateTime();
if (timeNow > mAdjustTime)
{
mLatitude = mTargetLatitude;
mLongitude = mTargetLongitude;
}
}
}
void QGoogleMap::clearCache()
{
const double LATITUDE_COEF = 1.0 / cos(mLatitude * M_PI / 180);
const int paddingX = width() / 2;
const int paddingY = height() / 2;
// Analysing map chunks
for(auto iter = mMapChunks.begin(); iter != mMapChunks.end(); )
{
const MapChunk& chunk = iter.value();
if (chunk.zoom != mMapZoom)
{
mMapChunks.erase(iter++);
continue;
}
// Calculating pixel coordinates of the image center
double dx = (chunk.longitude - mLongitude);
double dy = (chunk.latitude - mLatitude);
qint64 px = width() / 2 + (qint64)round(dx * mDegLength) - chunk.image.width() / 2;
qint64 py = height() / 2 - (qint64)round(dy * mDegLength * LATITUDE_COEF) - chunk.image.height() / 2;
if (px <= -paddingX - chunk.image.width() || px >= width() + paddingX ||
py <= -paddingY - chunk.image.height() || py >= height() + paddingY)
{
mMapChunks.erase(iter++);
continue;
}
++iter;
}
}
void QGoogleMap::onZoomIn()
{
if (mMapZoom < ZOOM_MAX)
{
++mMapZoom;
mDegLength *= 2;
mZoomInButton ->setEnabled(mMapZoom < ZOOM_MAX);
mZoomOutButton->setEnabled(mMapZoom > ZOOM_MIN);
}
update();
}
void QGoogleMap::onZoomOut()
{
if (mMapZoom > ZOOM_MIN)
{
--mMapZoom;
mDegLength /= 2;
mZoomInButton ->setEnabled(mMapZoom < ZOOM_MAX);
mZoomOutButton->setEnabled(mMapZoom > ZOOM_MIN);
}
update();
}
void QGoogleMap::onScroll(int px, int py)
{
const double LATITUDE_COEF = 1.0 / cos(mLatitude * M_PI / 180);
mLatitude += py / mDegLength / LATITUDE_COEF;
mLongitude -= px / mDegLength;
update();
mAdjustTime = QDateTime::currentDateTime().addSecs(5);
}
void QGoogleMap::requestMap(double lat, double lon, int zoom)
{
// Rounding latitude and longitude to 0.001
lat = round(lat * 1000) / 1000;
lon = round(lon * 1000) / 1000;
QString hash("%1,%2,%3");
hash = hash.arg(zoom);
hash = hash.arg(lat, 0, 'f', 6);
hash = hash.arg(lon, 0, 'f', 6);
if (mMapChunks.contains(hash))
return;
// Requesting cache storage
QString fileName("%1/%2-%3.png");
fileName = fileName.arg(mHomeDir + "/cache");
fileName = fileName.arg(mMapType);
fileName = fileName.arg(hash);
QImage image;
if (image.load(fileName))
{
// Updating file timestamp
utime(qPrintable(fileName), 0);
MapChunk chunk;
chunk.type = mMapType;
chunk.zoom = zoom;
chunk.latitude = lat;
chunk.longitude = lon;
chunk.image = image.copy(0, 40, image.width(), image.height() - 80);
mMapChunks[hash] = chunk;
update();
return;
}
mMapChunks.insert(hash, MapChunk());
// Requesting google api service
QString url("https://maps.googleapis.com/maps/api/staticmap?center=%1,%2&zoom=%3&size=640x640&maptype=%4&key=%5");
url = url.arg(lat, 0, 'f', 6);
url = url.arg(lon, 0, 'f', 6);
url = url.arg(zoom);
url = url.arg(mMapType);
url = url.arg(mApiKey);
qDebug() << "Requesting " << hash << ", cached: " << mMapChunks.size();
QNetworkReply* reply = mNetworkManager->get(QNetworkRequest(QUrl(url)));
reply->setProperty("type", QString("request_map"));
reply->setProperty("hash", hash);
QTimer* requestTimer = new QTimer(reply);
requestTimer->setObjectName("request_timer");
requestTimer->setSingleShot(true);
requestTimer->setInterval(5000);
requestTimer->start();
connect(requestTimer, SIGNAL(timeout()), mNetworkTimeoutSignalMapper, SLOT(map()));
mNetworkTimeoutSignalMapper->setMapping(requestTimer, reply);
}
void QGoogleMap::onRequestFinished(QNetworkReply* reply)
{
const QString url = reply->url().toString();
const QString type = reply->property("type").toString();
const QString hash = reply->property("hash").toString();
const int errorCode = reply->error();
const int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
const QByteArray data = reply->readAll();
if (errorCode == QNetworkReply::NoError)
{
if (type == "request_map")
{
QStringList values = hash.split(",");
const int zoom = values[0].toInt();
const double latitude = values[1].toDouble();
const double longitude = values[2].toDouble();
// Caching file
QString fileName("%1/%2-%3.png");
fileName = fileName.arg(mHomeDir + "/cache");
fileName = fileName.arg(mMapType);
fileName = fileName.arg(hash);
QFile f(fileName);
if (f.open(QIODevice::WriteOnly))
{
f.write(data);
f.close();
}
//QDir dir(mHomeDir + "/cache");
//QStringList fileList = dir.entryList(QStringList() << "*.png", QDir::Files, QDir::Time);
//while (fileList.size() > DISK_CACHE_SIZE)
//{
// //qDebug() << "Removing" << fileList.back();
// //dir.remove(fileList.back());
// dir.rename(fileList.last(), fileList.last() + ".tmp");
// fileList.removeLast();
//}
QImage image;
if (image.loadFromData(data))
{
MapChunk chunk;
chunk.type = mMapType;
chunk.zoom = zoom;
chunk.latitude = latitude;
chunk.longitude = longitude;
chunk.image = image.copy(0, 40, image.width(), image.height() - 80);
mMapChunks[hash] = chunk;
update();
}
}
}
else
{
qDebug() << "Request " << type << ": FAILED with error " << reply->errorString();
if (type == "request_map")
mMapChunks.remove(hash);
}
QTimer* timer = reply->findChild<QTimer*>("request_timer");
if (timer)
timer->stop();
reply->deleteLater();
}
void QGoogleMap::onRequestTimeout(QObject* reply)
{
dynamic_cast<QNetworkReply*>(reply)->abort();
}
static double getTimeStamp()
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec * 1e-9;
}
void QGoogleMap::onReadLine(QString line)
{
QDateTime timeNow = QDateTime::currentDateTime();
QStringList parts = line.split(" ");
if (parts.size() == 17)
{
// Line format:
// time gx gy gz ax ay az odo_count odo_speed gps_count lat lon alt acc gprmc_count vel dir
double timestamp = parts[0].toDouble();
double latency = getTimeStamp() - timestamp;
double gx = parts[1].toDouble();
double gy = parts[2].toDouble();
double gz = parts[3].toDouble();
double ax = parts[4].toDouble();
double ay = parts[5].toDouble();
double az = parts[6].toDouble();
double odometer = parts[8].toDouble();
double latitude = parts[10].toDouble();
double longitude = parts[11].toDouble();
double altitude = parts[12].toDouble();
double accuracy = parts[13].toDouble();
double velocity = parts[15].toDouble();
double direction = parts[16].toDouble();
double gps_count = parts[9].toDouble();
if (gps_count > EPSILON)
mGpsTime = timeNow;
setTarget(latitude, longitude, accuracy, direction);
QMap<QString,QString> addressMap;
QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
for(int i = 0; i < interfaces.size(); ++i)
{
QList<QNetworkAddressEntry> addresses = interfaces[i].addressEntries();
for(int j = 0; j < addresses.size(); ++j)
if (addresses[j].ip().protocol() == QAbstractSocket::IPv4Protocol)
addressMap[interfaces[i].name()] = addresses[j].ip().toString();
}
QString text;
text += QString("IP address : %1\n").arg(addressMap.value("wlan0"));
text += QString("Latency : %1\n").arg(latency, 0, 'f', 3);
text += QString("Location : %1, %2, %3\n")
.arg(latitude, 0, 'f', 6)
.arg(longitude, 0, 'f', 6)
.arg(altitude, 0, 'f', 1);
text += QString("Direction : %1\n").arg(direction, 0, 'f', 2);
text += QString("Velocity : %1\n").arg(velocity, 0, 'f', 2);
text += QString("Odometer : %1\n").arg(odometer, 0, 'f', 2);
text += QString("Accel : %1, %2, %3\n").arg(ax, 0, 'f', 0).arg(ay, 0, 'f', 0).arg(az, 0, 'f', 0);
text += QString("Gyro : %1, %2, %3\n").arg(gx, 0, 'f', 0).arg(gy, 0, 'f', 0).arg(gz, 0, 'f', 0);
qint64 gpsDelta = mGpsTime.msecsTo(timeNow);
if (gpsDelta < 3000)
text += QString("GPS : on\n");
else
text += QString("GPS : off (%1 sec)\n").arg(gpsDelta / 1000);
setInfoText(text);
if (!mRecordLogFile.isEmpty())
{
QFile f(mRecordLogFile);
if (f.open(QIODevice::Append))
{
QString text("%1 %2 %3 %4\n");
text = text.arg(timeNow.toString("yyyy-MM-dd hh:mm:ss.zzz"));
text = text.arg(latitude, 0, 'f', 6);
text = text.arg(longitude, 0, 'f', 6);
text = text.arg(gpsDelta / 1000);
f.write(text.toUtf8());
f.close();
}
}
//qDebug() << qPrintable(text) << "\n";
}
}
void QGoogleMap::onAdjustModeToggle()
{
mAdjustTime = QDateTime::currentDateTime();
mAdjustButton->setIcon(mAdjustButton->isChecked() ? QIcon(":/icons/adjust_mode_on") : QIcon(":/icons/adjust_mode_off"));
}
void QGoogleMap::onRecordToggle()
{
mRecordButton->setIcon(mRecordButton->isChecked() ? QIcon(":/icons/record_stop") : QIcon(":/icons/record_start"));
if (!mRecordProcess)
{
QDateTime timeNow = QDateTime::currentDateTime();
// Creating new process
mRecordVideoFile = QString("%1/%2.mp4");
mRecordVideoFile = mRecordVideoFile.arg(mHomeDir + "/video");
mRecordVideoFile = mRecordVideoFile.arg(timeNow.toString("yyyyMMdd_hhmmss"));
mRecordLogFile = QString("%1/%2.log");
mRecordLogFile = mRecordLogFile.arg(mHomeDir + "/logs");
mRecordLogFile = mRecordLogFile.arg(timeNow.toString("yyyyMMdd_hhmmss"));
qDebug() << "Start recording video" << mRecordVideoFile;
qDebug() << "Start recording video" << mRecordVideoFile;
QPoint P = this->mapToGlobal(QPoint(0,0));
QString command("%1 -f x11grab -r 25 -s %2x%3 -i :0.0+%4,%5 -vcodec h264 %6");
command = command.arg(FFMPEG);
command = command.arg(width());
command = command.arg(height());
command = command.arg(P.x());
command = command.arg(P.y());
command = command.arg(mRecordVideoFile);
mRecordProcess = new QProcess(this);
mRecordProcess->start(command);
connect(mRecordProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(onRecordFinished()));
}
else
{
// Stopping existing process
qDebug() << "Stop recording video" << mRecordVideoFile;
kill(mRecordProcess->pid(), SIGINT);
mRecordButton->blockSignals(true);
mRecordVideoFile.clear();
mRecordLogFile.clear();
}
}
void QGoogleMap::onRecordFinished()
{
mRecordButton->blockSignals(false);
delete mRecordProcess;
mRecordProcess = 0;
}
int main(int argc, char** argv)
{
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
setlocale(LC_NUMERIC, "C");
if (argc < 2)
{
qCritical() << "Missing api-key file";
return -1;
}
QFile f(argv[1]);
if (!f.open(QIODevice::ReadOnly))
{
qCritical() << "Unable to read api-key file" << argv[1];
return -1;
}
QString apiKey = QString(f.readAll()).trimmed();
f.close();
QApplication app(argc, argv);
QGoogleMap* map = new QGoogleMap(apiKey);
map->setMinimumSize(800, 480);
map->show();
return app.exec();
}
| [
"Fedor.Puchkov@navigine.com"
] | Fedor.Puchkov@navigine.com |
ed99803c497a07484c898e8fa53276d323cc5756 | 0ff5c3178e87a28a82165bfa908d9319cf7a2323 | /04. Arrays/max_heap.cpp | a85031c3441ebbb9b10d6a53d284769bd1eb1c2d | [
"MIT"
] | permissive | SR-Sunny-Raj/Hacktoberfest2021-DSA | 40bf8385ed976fd81d27340514579b283c339c1f | 116526c093ed1ac7907483d001859df63c902cb3 | refs/heads/master | 2023-01-31T07:46:26.016367 | 2023-01-26T12:45:32 | 2023-01-26T12:45:32 | 262,236,251 | 261 | 963 | MIT | 2023-03-25T14:22:10 | 2020-05-08T05:36:07 | C++ | UTF-8 | C++ | false | false | 4,430 | cpp | // Max Heap implementation in C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
using namespace std;
// Data structure to store a max-heap node
struct PriorityQueue
{
private:
// vector to store heap elements
vector<int> A;
// return parent of `A[i]`
// don't call this function if `i` is already a root node
int PARENT(int i) {
return (i - 1) / 2;
}
// return left child of `A[i]`
int LEFT(int i) {
return (2*i + 1);
}
// return right child of `A[i]`
int RIGHT(int i) {
return (2*i + 2);
}
// Recursive heapify-down algorithm.
// The node at index `i` and its two direct children
// violates the heap property
void heapify_down(int i)
{
// get left and right child of node at index `i`
int left = LEFT(i);
int right = RIGHT(i);
int largest = i;
// compare `A[i]` with its left and right child
// and find the largest value
if (left < size() && A[left] > A[i]) {
largest = left;
}
if (right < size() && A[right] > A[largest]) {
largest = right;
}
// swap with a child having greater value and
// call heapify-down on the child
if (largest != i)
{
swap(A[i], A[largest]);
heapify_down(largest);
}
}
// Recursive heapify-up algorithm
void heapify_up(int i)
{
// check if the node at index `i` and its parent violate the heap property
if (i && A[PARENT(i)] < A[i])
{
// swap the two if heap property is violated
swap(A[i], A[PARENT(i)]);
// call heapify-up on the parent
heapify_up(PARENT(i));
}
}
public:
// return size of the heap
unsigned int size() {
return A.size();
}
// Function to check if the heap is empty or not
bool empty() {
return size() == 0;
}
// insert key into the heap
void push(int key)
{
// insert a new element at the end of the vector
A.push_back(key);
// get element index and call heapify-up procedure
int index = size() - 1;
heapify_up(index);
}
// Function to remove an element with the highest priority (present at the root)
void pop()
{
try {
// if the heap has no elements, throw an exception
if (size() == 0)
{
throw out_of_range("Vector<X>::at() : "
"index is out of range(Heap underflow)");
}
// replace the root of the heap with the last element
// of the vector
A[0] = A.back();
A.pop_back();
// call heapify-down on the root node
heapify_down(0);
}
// catch and print the exception
catch (const out_of_range &oor) {
cout << endl << oor.what();
}
}
// Function to return an element with the highest priority (present at the root)
int top()
{
try {
// if the heap has no elements, throw an exception
if (size() == 0)
{
throw out_of_range("Vector<X>::at() : "
"index is out of range(Heap underflow)");
}
// otherwise, return the top (first) element
return A.at(0); // or return A[0];
}
// catch and print the exception
catch (const out_of_range &oor) {
cout << endl << oor.what();
}
}
};
// Max Heap implementation in C++
int main()
{
PriorityQueue pq;
// Note: The element's value decides priority
pq.push(3);
pq.push(2);
pq.push(15);
cout << "Size is " << pq.size() << endl;
cout << pq.top() << " ";
pq.pop();
cout << pq.top() << " ";
pq.pop();
pq.push(5);
pq.push(4);
pq.push(45);
cout << endl << "Size is " << pq.size() << endl;
cout << pq.top() << " ";
pq.pop();
cout << pq.top() << " ";
pq.pop();
cout << pq.top() << " ";
pq.pop();
cout << pq.top() << " ";
pq.pop();
cout << endl << boolalpha << pq.empty();
pq.top(); // top operation on an empty heap
pq.pop(); // pop operation on an empty heap
return 0;
}
| [
"sanvisumanpathak@gmail.com"
] | sanvisumanpathak@gmail.com |
c25b4575dbc9d144e1a196108f739e28015d7973 | 4b7d5c2c86c5ab35e39c43262b740392c5e519df | /Top_Coder/BinaryCode.cpp | 0860464b33b969ee756ec51cbc509c4d6aeaf327 | [] | no_license | gjones1911/cs302 | 732b4b0bd53116038e56b32d80851c906c54af1e | 8a0a88d4032e214edaaed71f0a0b3bb106959845 | refs/heads/master | 2020-05-14T20:17:14.392321 | 2019-04-17T17:56:55 | 2019-04-17T17:56:55 | 181,942,009 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,445 | cpp | // BEGIN CUT HERE
// PROBLEM STATEMENT
// Let's say you have a binary string such as the following:
011100011
One way to encrypt this string is to add to each digit the sum of its adjacent digits. For example, the above string would become:
123210122
In particular, if P is the original string, and Q is the encrypted string, then Q[i] = P[i-1] + P[i] + P[i+1] for all digit positions i. Characters off the left and right edges of the string are treated as zeroes.
An encrypted string given to you in this format can be decoded as follows (using 123210122 as an example):
Assume P[0] = 0.
Because Q[0] = P[0] + P[1] = 0 + P[1] = 1, we know that P[1] = 1.
Because Q[1] = P[0] + P[1] + P[2] = 0 + 1 + P[2] = 2, we know that P[2] = 1.
Because Q[2] = P[1] + P[2] + P[3] = 1 + 1 + P[3] = 3, we know that P[3] = 1.
Repeating these steps gives us P[4] = 0, P[5] = 0, P[6] = 0, P[7] = 1, and P[8] = 1.
We check our work by noting that Q[8] = P[7] + P[8] = 1 + 1 = 2. Since this equation works out, we are finished, and we have recovered one possible original string.
Now we repeat the process, assuming the opposite about P[0]:
Assume P[0] = 1.
Because Q[0] = P[0] + P[1] = 1 + P[1] = 1, we know that P[1] = 0.
Because Q[1] = P[0] + P[1] + P[2] = 1 + 0 + P[2] = 2, we know that P[2] = 1.
Now note that Q[2] = P[1] + P[2] + P[3] = 0 + 1 + P[3] = 3, which leads us to the conclusion that P[3] = 2. However, this violates the fact that each character in the original string must be '0' or '1'. Therefore, there exists no such original string P where the first digit is '1'.
Note that this algorithm produces at most two decodings for any given encrypted string. There can never be more than one possible way to decode a string once the first binary digit is set.
Given a string message, containing the encrypted string, return a vector <string> with exactly two elements. The first element should contain the decrypted string assuming the first character is '0'; the second element should assume the first character is '1'. If one of the tests fails, return the string "NONE" in its place. For the above example, you should return {"011100011", "NONE"}.
DEFINITION
Class:BinaryCode
Method:decode
Parameters:string
Returns:vector <string>
Method signature:vector <string> decode(string message)
CONSTRAINTS
-message will contain between 1 and 50 characters, inclusive.
-Each character in message will be either '0', '1', '2', or '3'.
EXAMPLES
0)
"123210122"
Returns: { "011100011", "NONE" }
The example from above.
1)
"11"
Returns: { "01", "10" }
We know that one of the digits must be '1', and the other must be '0'. We return both cases.
2)
"22111"
Returns: { "NONE", "11001" }
Since the first digit of the encrypted string is '2', the first two digits of the original string must be '1'. Our test fails when we try to assume that P[0] = 0.
3)
"123210120"
Returns: { "NONE", "NONE" }
This is the same as the first example, but the rightmost digit has been changed to something inconsistent with the rest of the original string. No solutions are possible.
4)
"3"
Returns: { "NONE", "NONE" }
5)
"12221112222221112221111111112221111"
Returns: { "01101001101101001101001001001101001", "10110010110110010110010010010110010" }
// END CUT HERE
#line 88 "BinaryCode.cpp"
#include <string>
#include <vector>
using namspace std;
class BinaryCode
{
public:
vector <string> decode(string message)
{
}
};
| [
"gjones2@hydra25.eecs.utk.edu"
] | gjones2@hydra25.eecs.utk.edu |
4752c2a115821eac4d84d5904381b60e69de44b9 | e86c8116ab0542a6b7f6a551344a86139e39f9de | /Sample/SimpleVoxelization/Source/Public/SimpleVoxelizationTriMesh.h | 28b1ddb601aa32eeaefb359c1a92290b7b812b0f | [] | no_license | jazzboysc/RTGI | fb1b9eed9272ce48828e9a294529d70be3f61532 | 80290d4e1892948d81427569fb862267407e3c5a | refs/heads/master | 2020-04-14T05:23:38.219651 | 2015-07-17T07:12:48 | 2015-07-17T07:12:48 | 20,085,664 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,256 | h | #ifndef RTGI_SimpleVoxelizationTriMesh_H
#define RTGI_SimpleVoxelizationTriMesh_H
#include "TriangleMesh.h"
#include "Texture3D.h"
#include "AABB.h"
#include "ShaderUniform.h"
namespace RTGI
{
//----------------------------------------------------------------------------
// Author: Che Sun
// Date: 10/08/2014
//----------------------------------------------------------------------------
class SimpleVoxelizationTriMesh : public TriangleMesh
{
public:
SimpleVoxelizationTriMesh(Material* material, Camera* camera);
virtual ~SimpleVoxelizationTriMesh();
// Implement base class interface.
virtual void OnGetShaderConstants();
virtual void OnUpdateShaderConstants(int technique, int pass);
AABB* SceneBB;
vec3 MaterialColor;
private:
// pass 1.
ShaderUniform mSceneBBCenterLoc;
ShaderUniform mSceneBBExtensionLoc;
ShaderUniform mMaterialColorLoc;
ShaderUniform mDimLoc;
ShaderUniform mShowWorldPositionLoc;
ShaderUniform mInv2SceneBBExtensionLoc;
// pass 2.
ShaderUniform mWorldLoc2, mViewLoc2, mProjLoc2;
ShaderUniform mSceneBBCenterLoc2;
ShaderUniform mSceneBBExtensionLoc2;
ShaderUniform mDimLoc2;
};
typedef RefPointer<SimpleVoxelizationTriMesh> SimpleVoxelizationTriMeshPtr;
}
#endif | [
"S515380c"
] | S515380c |
ed2234d1791478833a8a4546f2ad2c19e072f094 | b677894966f2ae2d0585a31f163a362e41a3eae0 | /ns3/ns-3.26/src/flow-monitor/helper/flow-monitor-helper.cc | 0f2334fa353893d7c398c3ed79bbe3f5dadb4d94 | [
"LicenseRef-scancode-free-unknown",
"GPL-2.0-only",
"Apache-2.0"
] | permissive | cyliustack/clusim | 667a9eef2e1ea8dad1511fd405f3191d150a04a8 | cbedcf671ba19fded26e4776c0e068f81f068dfd | refs/heads/master | 2022-10-06T20:14:43.052930 | 2022-10-01T19:42:19 | 2022-10-01T19:42:19 | 99,692,344 | 7 | 3 | Apache-2.0 | 2018-07-04T10:09:24 | 2017-08-08T12:51:33 | Python | UTF-8 | C++ | false | false | 4,703 | cc | // -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*-
//
// Copyright (c) 2009 INESC Porto
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation;
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Author: Gustavo J. A. M. Carneiro <gjc@inescporto.pt> <gjcarneiro@gmail.com>
//
#include "flow-monitor-helper.h"
#include "ns3/flow-monitor.h"
#include "ns3/ipv4-flow-classifier.h"
#include "ns3/ipv4-flow-probe.h"
#include "ns3/ipv4-l3-protocol.h"
#include "ns3/ipv6-flow-classifier.h"
#include "ns3/ipv6-flow-probe.h"
#include "ns3/ipv6-l3-protocol.h"
#include "ns3/node.h"
#include "ns3/node-list.h"
namespace ns3 {
FlowMonitorHelper::FlowMonitorHelper ()
{
m_monitorFactory.SetTypeId ("ns3::FlowMonitor");
}
FlowMonitorHelper::~FlowMonitorHelper ()
{
if (m_flowMonitor)
{
m_flowMonitor->Dispose ();
m_flowMonitor = 0;
m_flowClassifier4 = 0;
m_flowClassifier6 = 0;
}
}
void
FlowMonitorHelper::SetMonitorAttribute (std::string n1, const AttributeValue &v1)
{
m_monitorFactory.Set (n1, v1);
}
Ptr<FlowMonitor>
FlowMonitorHelper::GetMonitor ()
{
if (!m_flowMonitor)
{
m_flowMonitor = m_monitorFactory.Create<FlowMonitor> ();
m_flowClassifier4 = Create<Ipv4FlowClassifier> ();
m_flowMonitor->AddFlowClassifier (m_flowClassifier4);
m_flowClassifier6 = Create<Ipv6FlowClassifier> ();
m_flowMonitor->AddFlowClassifier (m_flowClassifier6);
}
return m_flowMonitor;
}
Ptr<FlowClassifier>
FlowMonitorHelper::GetClassifier ()
{
if (!m_flowClassifier4)
{
m_flowClassifier4 = Create<Ipv4FlowClassifier> ();
}
return m_flowClassifier4;
}
Ptr<FlowClassifier>
FlowMonitorHelper::GetClassifier6 ()
{
if (!m_flowClassifier6)
{
m_flowClassifier6 = Create<Ipv6FlowClassifier> ();
}
return m_flowClassifier6;
}
Ptr<FlowMonitor>
FlowMonitorHelper::Install (Ptr<Node> node)
{
Ptr<FlowMonitor> monitor = GetMonitor ();
Ptr<FlowClassifier> classifier = GetClassifier ();
Ptr<Ipv4L3Protocol> ipv4 = node->GetObject<Ipv4L3Protocol> ();
if (ipv4)
{
Ptr<Ipv4FlowProbe> probe = Create<Ipv4FlowProbe> (monitor,
DynamicCast<Ipv4FlowClassifier> (classifier),
node);
}
Ptr<FlowClassifier> classifier6 = GetClassifier6 ();
Ptr<Ipv6L3Protocol> ipv6 = node->GetObject<Ipv6L3Protocol> ();
if (ipv6)
{
Ptr<Ipv6FlowProbe> probe6 = Create<Ipv6FlowProbe> (monitor,
DynamicCast<Ipv6FlowClassifier> (classifier6),
node);
}
return m_flowMonitor;
}
Ptr<FlowMonitor>
FlowMonitorHelper::Install (NodeContainer nodes)
{
for (NodeContainer::Iterator i = nodes.Begin (); i != nodes.End (); ++i)
{
Ptr<Node> node = *i;
if (node->GetObject<Ipv4L3Protocol> () || node->GetObject<Ipv6L3Protocol> ())
{
Install (node);
}
}
return m_flowMonitor;
}
Ptr<FlowMonitor>
FlowMonitorHelper::InstallAll ()
{
for (NodeList::Iterator i = NodeList::Begin (); i != NodeList::End (); ++i)
{
Ptr<Node> node = *i;
if (node->GetObject<Ipv4L3Protocol> () || node->GetObject<Ipv6L3Protocol> ())
{
Install (node);
}
}
return m_flowMonitor;
}
void
FlowMonitorHelper::SerializeToXmlStream (std::ostream &os, int indent, bool enableHistograms, bool enableProbes)
{
if (m_flowMonitor)
{
m_flowMonitor->SerializeToXmlStream (os, indent, enableHistograms, enableProbes);
}
}
std::string
FlowMonitorHelper::SerializeToXmlString (int indent, bool enableHistograms, bool enableProbes)
{
std::ostringstream os;
if (m_flowMonitor)
{
m_flowMonitor->SerializeToXmlStream (os, indent, enableHistograms, enableProbes);
}
return os.str ();
}
void
FlowMonitorHelper::SerializeToXmlFile (std::string fileName, bool enableHistograms, bool enableProbes)
{
if (m_flowMonitor)
{
m_flowMonitor->SerializeToXmlFile (fileName, enableHistograms, enableProbes);
}
}
} // namespace ns3
| [
"you@example.com"
] | you@example.com |
d606ccdacc5f050950b5634878c6bf926902887f | 77cba4e5adbd3bbb4c57cf2efb7dfcb0396e7f02 | /Computer Graphics/computer graphics practical/graphics practicals/DDA.CPP | 9c4bee4aa5c8d30dde9bdf8061dfc7c95b9ea7ee | [] | no_license | simran-pandey/Computer-Science-Resources | c8f9c77f8dd5bcaa57a3c2e5e5e07ce7102d9976 | d4ce7d021984a55f750fe1f93b0b9acbc0f22a8e | refs/heads/master | 2020-03-08T15:44:48.753555 | 2019-03-15T11:28:01 | 2019-03-15T11:28:01 | 128,220,222 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,517 | cpp | #include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include<iostream.h>
#include<math.h>
void main()
{
clrscr();
int x1,x2,y1,y2;
float dy,dx;
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int xmax, ymax;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
/* an error occurred */
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}
setcolor(getmaxcolor());
xmax = getmaxx();
ymax = getmaxy();
do
{
cout<<"Enter x1"<<endl;
cin>>x1;
cout<<"Enter x2"<<endl;
cin>>x2;
cout<<"Enter y1"<<endl;
cin>>y1;
cout<<"Enter y2"<<endl;
cin>>y2;
}while(!(x1<xmax) && !(x2<xmax) && !(y1<ymax) && !(y2<ymax));
line(x1,y1,x2,y2);
dy=y2-y1;
dx=x2-x1;
if(x1==x2)
{
if(y2<y1)
{
int z =y1;
y1=y2;
y2=z;
}
for(int i=y1;i<=y2;i++)
{
putpixel(x1,i,RED);
}
}
else
{
float m=dy/dx;
if(fabs(m)<1)
{
if(x1>x2)
{
int z=x1;
x1=x2;
x2=z;
z=y1;
y1=y2;
y2=z;
}
float y=y1;
for(int i=x1;i<=x2;i++,y+=m)
{
putpixel(i,float(floor(y+0.5)),RED);
}
}
else
{
if(y1>y2)
{
int z=y1;
y1=y2;
y2=z;
z=x1;
x1=x2;
x2=z;
}
float x=x1;
for(int i=y1;i<=y2;i++,x+=1/m)
{
putpixel(float(floor(x+0.5)),i,RED);
}
}
}
getch();
} | [
"pandeysimran97@gmail.com"
] | pandeysimran97@gmail.com |
ceb26cc17abc9c8c768d771f8944caaeba94eef7 | 7725332c392408ee1d49afe44ffcb1401dbb655f | /abc/abc077B.cpp | 98779f94cad77ea96efa6e7f523d57d0022765b3 | [] | no_license | moxlev/AtCoder | 8a95b58a99a773df4cb8fd0dcde6cc12aa1c5bd7 | 94375e589d2b74adb7190ad84c16fd541b5f495f | refs/heads/master | 2021-07-13T19:34:56.087640 | 2019-03-12T13:13:06 | 2019-03-12T13:13:06 | 152,913,053 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 383 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <numeric>
#include <functional>
#include <cmath>
#include <stdio.h>
int main(){
int n;
std::cin>>n;
int i = 1;
while(true){
if(i * i > n){
std::cout<<(i - 1) * (i - 1)<<std::endl;
break;
}
++i;
}
return 0;
}
| [
"moxglev@gmail.com"
] | moxglev@gmail.com |
843a7e0fa8c10bf6b8ff55bb8a1087d309e5ff71 | 5b41e312db8aeb5532ba59498c93e2ec1dccd4ff | /DM/DM_LF/DM_LF_Frame/CDM_LFSampleManager.h | 3cbfe738b15337025d636ad2b49eed21b19ee78e | [] | no_license | frankilfrancis/KPO_HMI_vs17 | 10d96c6cb4aebffb83254e6ca38fe6d1033eba79 | de49aa55eccd8a7abc165f6057088a28426a1ceb | refs/heads/master | 2020-04-15T16:40:14.366351 | 2019-11-14T15:33:25 | 2019-11-14T15:33:25 | 164,845,188 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 786 | h | // Copyright (C) 1991 - 1999 Rational Software Corporation
#if defined (_MSC_VER) && (_MSC_VER >= 1000)
#pragma once
#endif
#ifndef _INC_CDM_LFSAMPLEMANAGER_4164FDA9006D_INCLUDED
#define _INC_CDM_LFSAMPLEMANAGER_4164FDA9006D_INCLUDED
#include "CDM_SampleManager.h"
class CDM_LFProductManagementInterface_Impl;
class CEventMessage;
class CDM_LFSampleManager : public CDM_SampleManager
{
public:
virtual ~CDM_LFSampleManager();
CDM_LFSampleManager();
std::string createSampleCodeFromScratch(std::string& ProductID, long ActSampleType, const std::string ActPlantID, const std::string ActProcessStage, long ActSampleNo);
void initProductSampleInformation(const std::string& ProductID, const std::string& Plant);
};
#endif /* _INC_CDM_LFSAMPLEMANAGER_4164FDA9006D_INCLUDED */
| [
"52784069+FrankilPacha@users.noreply.github.com"
] | 52784069+FrankilPacha@users.noreply.github.com |
7154e500caae223dc380389646aec08cf3b97e6d | 16a95d35f44a9ee90aa3d2faaa3808931b7c008e | /Ke thua/sucsac_source.cpp | b0904322f69962de366e2e9f49f87e4ee56df5be | [] | no_license | hoangtuyenblogger/Phuong-Phap-Lap-Trinh-Huong-Doi-Tuong | 690e1ff65f98e83bd032bd355bd060614042daf2 | 53a742c122a22b0838ecb3da04749a0c0a324ab1 | refs/heads/master | 2022-12-18T13:04:14.578932 | 2020-09-17T09:31:51 | 2020-09-17T09:31:51 | 233,080,281 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 420 | cpp | #include <cstdlib>
#include <ctime>
#include<iostream>
using namespace std;
#include"sucsac_map.h"
game::game()
{
ten= "";
diem = 0;
}
void game::play()
{
int random =1 + rand() % 6; // suc sac co 6 mat, random 1 gia tri
diem +=random; // cong gia tri random vao diem
}
/* ---------- nguoi -----*/
gamer::gamer()
{
::game();
}
/*----------- may --------*/
computer::computer()
{
::game();
ten = "may";
}
| [
"34962881+hoangtuyenblogger@users.noreply.github.com"
] | 34962881+hoangtuyenblogger@users.noreply.github.com |
bcb9e97f6c35ee248a4a3b90e5452d880523e15b | d34da294ad925d881cfaeddaf6c25ec4a119f746 | /design/firmware/turbidoconc.ino | 5fb1aa7457858ac39ce6f52f505cc11c0c9d4b22 | [] | no_license | ingolia-lab/turbidostat | befb1192be53f5400203a0e8173dfcd5868c165e | f455666de056509f74e5096bf62489194f39e7c9 | refs/heads/master | 2021-07-04T22:03:02.942965 | 2020-08-04T03:10:08 | 2020-08-04T03:10:08 | 140,904,066 | 7 | 5 | null | 2020-08-04T03:10:09 | 2018-07-14T00:37:15 | C++ | UTF-8 | C++ | false | false | 5,028 | ino | #include "turbidoconc.h"
TurbidoConcBase::TurbidoConcBase(Supervisor &s) :
TurbidoMixBase(s),
_currentPpm1(1000000),
_fillSeconds(1000)
{
}
int TurbidoConcBase::begin(void)
{
int err = TurbidoMixBase::begin();
if (!err) {
_lastTotalMsec1 = pump1().totalOnMsec();
_lastTotalMsec2 = pump2().totalOnMsec();
}
return err;
}
#define DEBUG_PPM 0
int TurbidoConcBase::loop(void)
{
long currMsec1 = pump1().totalOnMsec();
long currMsec2 = pump2().totalOnMsec();
#if DEBUG_PPM
long oldPpm = _currentPpm1;
#endif
long newPpm = updatePpm1(currMsec1 - _lastTotalMsec1, currMsec2 - _lastTotalMsec2);
if (newPpm < 0) {
Serial.println("# ERROR updating ppm estimate!");
}
#if DEBUG_PPM
snprintf(Supervisor::outbuf, Supervisor::outbufLen,
"# _lastTotalMsec1 = %ld currMsec1 = %ld Diff = %ld\r\n",
_lastTotalMsec1, currMsec1, currMsec1 - _lastTotalMsec1);
snprintf(Supervisor::outbuf + strlen(Supervisor::outbuf),
Supervisor::outbufLen - strlen(Supervisor::outbuf),
"# _lastTotalMsec2 = %ld currMsec2 = %ld Diff = %ld\r\n",
_lastTotalMsec2, currMsec2, currMsec2 - _lastTotalMsec2);
snprintf(Supervisor::outbuf + strlen(Supervisor::outbuf),
Supervisor::outbufLen - strlen(Supervisor::outbuf),
"# oldPpm = %ld newPpm = %ld", oldPpm, newPpm);
Serial.println(Supervisor::outbuf);
#endif
_lastTotalMsec1 = currMsec1;
_lastTotalMsec2 = currMsec2;
return TurbidoMixBase::loop();
}
void TurbidoConcBase::setPumpOn(void)
{
if ( (currentPpm1() > targetPpm1()) || (targetPpm1() == 0) ) {
setPump2On();
} else {
setPump1On();
}
}
void TurbidoConcBase::formatHeader(char *buf, unsigned int buflen)
{
TurbidoMixBase::formatHeader(buf, buflen);
strncpy(buf + strlen(buf), "\tcurrPpm\ttargPpm", buflen - strlen(buf));
}
void TurbidoConcBase::formatLine(char *buf, unsigned int buflen, long currMeasure)
{
TurbidoMixBase::formatLine(buf, buflen, currMeasure);
snprintf(buf + strlen(buf), buflen - strlen(buf),
"\t%07lu\t%07lu",
currentPpm1(), targetPpm1());
}
void TurbidoConcBase::formatParams(char *buf, unsigned int buflen)
{
TurbidoMixBase::formatParams(buf, buflen);
snprintf(buf + strlen(buf), buflen - strlen(buf),
"# Fill time: %lu seconds (%07lu ppm per second)\r\n# Current fraction of media #1: %07lu ppm\r\n",
_fillSeconds, ppmPerSecond(), _currentPpm1);
}
void TurbidoConcBase::manualReadParams(void)
{
TurbidoMixBase::manualReadParams();
manualReadULong("fill time [seconds] ", _fillSeconds);
manualReadULong("current fraction media #1 (parts per million) ", _currentPpm1);
if (_currentPpm1 > 1000000) {
_currentPpm1 = 1000000;
}
}
// f = fraction per second [ in ppm / second ]
// f * t = fraction exchanged in t seconds [ in ppm; must be >2000 = 0.2%]
// cnew = cold * (1 - (f * (t1 + t2))) + 1 * f * t1 + 0 * f * t2
// = cold * (1 - (f * t1) - (f * t2)) + f * t1
// = cold - cold * f * t1 - cold * f * t2 + f * t1
// = cold + (1 - cold) * f * t1 - cold * f * t2
// e.g. ((conc * 1e6) / 20) * ((fract * 1e6) / 25) = (conc * 5e4) * (fract * 4e4) = conc * 2e9
long TurbidoConcBase::updatePpm1(unsigned int msec1, unsigned int msec2)
{
unsigned long ppmPerSec = ppmPerSecond();
if ((msec1 + msec2 > 2000) || (ppmPerSec > 1000000) || (_currentPpm1 > 1000000)) {
// ERROR -- MAY OVERFLOW
return -1;
}
// (f * 1e6) * (t * 1e3) / 1e3 = (f * t) * 1e6
unsigned long newPpmAdded = (msec1 * ppmPerSec) / 1000;
// (f * 1e6) * (t * 1e3) / 1e3 = (f * t) * 1e6
unsigned long oldFractRemovedPpm = ( (msec1 + msec2) * ppmPerSec ) / 1000;
// ( ( ( conc * 1e6) / 20 ) * ( ( fract * 1e6) / 25 ) ) ) = conc * 2e9 = ( conc * 1e6 ) * 2000
unsigned long oldPpmRemoved = ( (_currentPpm1 / 20) * (oldFractRemovedPpm / 25) ) / 2000;
if (_currentPpm1 + newPpmAdded < oldPpmRemoved) {
_currentPpm1 = 0;
} else {
_currentPpm1 = (_currentPpm1 + newPpmAdded) - oldPpmRemoved;
if (_currentPpm1 > 1000000) {
_currentPpm1 = 1000000;
}
}
return (long) _currentPpm1;
}
TurbidoConcFixed::TurbidoConcFixed(Supervisor &s):
TurbidoConcBase(s),
_targetPpm1(500000)
{
}
void TurbidoConcFixed::formatHeader(char *buf, unsigned int buflen)
{
buf[0] = 'C';
TurbidoConcBase::formatHeader(buf + 1, buflen - 1);
}
void TurbidoConcFixed::formatLine(char *buf, unsigned int buflen, long m)
{
buf[0] = 'C';
TurbidoConcBase::formatLine(buf + 1, buflen - 1, m);
}
void TurbidoConcFixed::formatParams(char *buf, unsigned int buflen)
{
TurbidoConcBase::formatParams(buf, buflen);
snprintf(buf + strlen(buf), buflen - strlen(buf),
"# Target fraction media #1 %07lu ppm\r\n",
_targetPpm1);
}
void TurbidoConcFixed::manualReadParams(void)
{
TurbidoConcBase::manualReadParams();
manualReadULong("Target fraction media #1 (parts per million) ", _targetPpm1);
if (_targetPpm1 > 1000000) {
_targetPpm1 = 1000000;
}
}
| [
"nick@ingolia.org"
] | nick@ingolia.org |
e899c930dee44b76feffe23c8f90b6391117c2af | 42f0c87e7c7369c61638cc06c62c20f8a6b80215 | /tmp/Distinct_Subsequences.cpp | bfc53ae87e30de5dfa27eed6a1a87a9452b11376 | [] | no_license | utwodownson/leetcode_old | d07d63b065fadb52b1b6a0e1c5aba3482b9d9771 | fb6eebe29d17360b0eef9fa25cf8d4853e345ef0 | refs/heads/master | 2021-05-01T00:37:47.970764 | 2014-02-19T05:27:40 | 2014-02-19T05:27:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 851 | cpp | /* Given a string S and a string T, count the number of distinct subsequences of T in S.
* A subsequence of a string is a new string which is formed from the original string by deleting some
* (can be none) of the characters without disturbing the relative positions of the remaining characters.
* (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
* Here is an example:
* S = "rabbbit", T = "rabbit"
* Return 3.
*/
class Solution {
public:
int numDistinct(string S, string T) {
int ss = S.length(), st = T.length();
vector<int> count(st + 1, 0);
count[0] = 1;
for (int i = 0; i < ss; ++i)
for (int j = st; j >= 0; --j)
if (S[i] == T[j - 1])
count[j] += count[j - 1];
return count[st];
}
};
| [
"utwodownson@gmail.com"
] | utwodownson@gmail.com |
c87b019c04c7e84454f7c39d7e34f1506d21b957 | 3d88116aa52d2ec4d3a581e2918503ead4d21b02 | /Src/KLuaQuestInfo.cpp | c3578c3e046a390e026466084a19eadde6f30c9d | [] | no_license | zhengguo85938406/GameWorld | 59f63bfd871d05a503f03d315a618a45f400cac9 | 8af713954c96ba3b0b5f7f96f5cdb5b313783f30 | refs/heads/master | 2021-01-25T08:37:47.103500 | 2015-07-31T09:56:03 | 2015-07-31T09:56:03 | 39,997,701 | 4 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,365 | cpp | #include "stdafx.h"
#include "KQuestInfoList.h"
#include "KSO3World.h"
DEFINE_LUA_CLASS_BEGIN(KQuestInfo)
REGISTER_LUA_STRING_READONLY(KQuestInfo, QuestName) // 任务名称
REGISTER_LUA_BOOL(KQuestInfo, Repeat) //是否可重复
REGISTER_LUA_BOOL(KQuestInfo, Accept) //是否先接才能交
REGISTER_LUA_DWORD(KQuestInfo, CoolDownID) //CoolDown计时器ID
REGISTER_LUA_DWORD(KQuestInfo, PrequestID) //前置任务ID
REGISTER_LUA_INTEGER(KQuestInfo, StartTime) //开始时间
REGISTER_LUA_INTEGER(KQuestInfo, EndTime) //结束时间
REGISTER_LUA_DWORD(KQuestInfo, SubsequenceID) //直接后继任务ID
REGISTER_LUA_INTEGER(KQuestInfo, QuestValue1) //任务变量
REGISTER_LUA_INTEGER(KQuestInfo, QuestValue2) //任务变量
REGISTER_LUA_INTEGER(KQuestInfo, QuestValue3) //任务变量
REGISTER_LUA_INTEGER(KQuestInfo, QuestValue4) //任务变量
REGISTER_LUA_INTEGER(KQuestInfo, QuestEvent1) //任务事件
REGISTER_LUA_INTEGER(KQuestInfo, QuestEvent2) //任务事件
REGISTER_LUA_INTEGER(KQuestInfo, QuestEvent3) //任务事件
REGISTER_LUA_INTEGER(KQuestInfo, QuestEvent4) //任务事件
REGISTER_LUA_INTEGER(KQuestInfo, PresentExp) //交任务时奖励的经验
REGISTER_LUA_INTEGER(KQuestInfo, PresentMoney) //交任务时奖励的金钱数量
DEFINE_LUA_CLASS_END(KQuestInfo)
| [
"85938406@qq.com"
] | 85938406@qq.com |
633ca0be2a10b44d112142a3d54cd4cb39fb3614 | 74ea903c078ff7f70ea04111937c06046dae990a | /TestCases.cpp | 7778d8ce7fc898d9b7d3d853f4a23b5fcd6493a2 | [] | no_license | jimmybeer/MapGenerator | 65eaac72eecce451bcdc04e468de59a42264b459 | 5d4fabfd1fb18edf95f8371b5224ed767c4523aa | refs/heads/master | 2020-05-19T10:22:33.368384 | 2015-05-10T21:38:59 | 2015-05-10T21:38:59 | 35,388,306 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,895 | cpp | #include "TestCase.h"
#include "IPoint.h"
#include "IRect.h"
#include "Helper.h"
#include <iostream>
void TestCase::Run()
{
std::cout << "Running Point Test Cases:\n";
TestCase::RunPointTests();
std::cout << "Running Rectangle Test Cases:\n";
TestCase::RunRectTests();
}
void TestCase::RunPointTests()
{
int count = 0;
int pass = 0;
IPoint p1(10,5);
IPoint p2(p1);
// Copy Constructor
count++;
std::cout << "Copy Constructor: ";
if(p2.X == p1.X && p2.Y == p1.Y)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << p2.toString() << "\n";
}
IPoint p3(35, 25);
p2 = p3;
// Assignment operator
count++;
std::cout << "Assignment operator: ";
if(p2.X == p3.X && p2.Y == p3.Y)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << p2.toString() << "\n";
}
// Addition and Subtraction
IPoint p4;
p4 = p1 + p2;
count++;
std::cout << "Addition operator: ";
if(p4.X == 45 && p4.Y == 30)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << p4.toString() << "\n";
}
p4 = p2 - p1;
count++;
std::cout << "Subtraction operator: ";
if(p4.X == 25 && p4.Y == 20)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << p4.toString() << "\n";
}
// Multiplation and Divide
p4 = p1 * 5;
count++;
std::cout << "Multiplation operator: ";
if(p4.X == 50 && p4.Y == 25)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << p4.toString() << "\n";
}
p4 = p2 / 5;
count++;
std::cout << "Divide operator: ";
if(p4.X == 7 && p4.Y == 5)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << p4.toString() << "\n";
}
// Zero and IsNull
count++;
std::cout << "!IsNull: ";
if(p2.IsNull() == false)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << p2.toString() << "\n";
}
count++;
std::cout << "Zero().IsNull: ";
if(p2.Zero().IsNull() == true)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << p2.toString() << "\n";
}
std::cout << "Completed (" + std::to_string(pass) + "/" + std::to_string(count) + ")\n\n";
}
void TestCase::RunRectTests()
{
int count = 0;
int pass = 0;
IRect r1;
// IsNull
count++;
std::cout << "IsNull: ";
if(r1.IsNull() == true)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r1.toString() << "\n";
}
IRect r2(10, 20, 40, 40);
IRect r3(r2);
// Copy Constructor
count++;
std::cout << "Copy Constructor: ";
if((r3.Position.X == r2.Position.X) && (r3.Position.Y == r2.Position.Y)
&& (r3.Width == r2.Width) && (r3.Height == r2.Height))
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r3.toString() << "\n";
}
r1 = r3;
// Assignment operator
count++;
std::cout << "Assignment operator: ";
if((r1.Position.X == r3.Position.X) && (r1.Position.Y == r3.Position.Y)
&& (r1.Width == r3.Width) && (r1.Height == r3.Height))
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r1.toString() << "\n";
}
r2.Position.X = 30;
r2.Position.Y = 40;
r2.Height = 60;
r3.Position.X = 20;
r3.Position.Y = 65;
r3.Width = 20;
r3.Height = 20;
// Positional tests
count++;
std::cout << "Half Width: ";
if(r2.HalfWidth() == 20)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r2.toString() << "\n";
}
count++;
std::cout << "Half Height: ";
if(r2.HalfHeight() == 30)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r2.toString() << "\n";
}
count++;
std::cout << "CenterX: ";
if(r2.CenterX() == 50)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r2.toString() << "\n";
}
count++;
std::cout << "CenterY: ";
if(r2.CenterY() == 70)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r2.toString() << "\n";
}
count++;
std::cout << "Left: ";
if(r3.Left() == 20)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r3.toString() << "\n";
}
count++;
std::cout << "Right: ";
if(r3.Right() == 40)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r3.toString() << "\n";
}
count++;
std::cout << "Top: ";
if(r3.Top() == 65)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r3.toString() << "\n";
}
count++;
std::cout << "Bottom: ";
if(r3.Bottom() == 85)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r3.toString() << "\n";
}
count++;
std::cout << "Contains: ";
if(r1.Contains(20, 30))
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r1.toString() << "\n";
}
IPoint p(60, 50);
count++;
std::cout << "!Contains: ";
if(r1.Contains(p) == false)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r1.toString() << "\n";
}
count++;
std::cout << "IsIntersecting: ";
if(r1.IsIntersecting(r2) && r2.IsIntersecting(r1))
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r1.toString() << "<>" << r2.toString() << "\n";
}
count++;
std::cout << "!IsIntersecting: ";
if(r1.IsIntersecting(r3) == false && r3.IsIntersecting(r1) == false)
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r1.toString() << "<>" << r3.toString() << "\n";
}
count++;
std::cout << "Intersect: ";
IRect* r4 = r2.Intersect(r1);
if(r4)
{
if((r4->Position.X == 30) && (r4->Position.Y == 40)
&& (r4->Width == 20) && (r4->Height == 20))
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r4->toString() << "\n";
}
}
else
{
std::cout << "FAIL - Intersect returned NULL\n";
}
delete r4;
count++;
std::cout << "IntersectWith: ";
r3.IntersectWith(r2);
if((r3.Position.X == 30) && (r3.Position.Y == 65)
&& (r3.Width == 10) && (r3.Height == 20))
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r3.toString() << "\n";
}
count++;
std::cout << "United: ";
r4 = r1.United(r2);
if(r4)
{
if((r4->Position.X == 10) && (r4->Position.Y == 20)
&& (r4->Width == 60) && (r4->Height == 80))
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << r4->toString() << "\n";
}
}
else
{
std::cout << "FAIL - United returned NULL\n";
}
delete r4;
count++;
std::cout << "Penetration: ";
IPoint* penetration = r1.Penetration(r2);
if(penetration)
{
if((penetration->X == -20) && (penetration->Y == -20))
{
pass++;
std::cout << "PASS\n";
}
else
{
std::cout << "FAIL - " << p.toString() << "\n";
}
}
else
{
std::cout << "FAIL - penetration returned NULL\n";
}
delete penetration;
std::cout << "Completed (" + std::to_string(pass) + "/" + std::to_string(count) + ")\n\n";
}
| [
"james-young@live.com"
] | james-young@live.com |
5b5203dabbebdefdc384e49f21421f98dce7e878 | 87cb1d34fce13656de340c6e61a1ed85748b6f81 | /ch4/example/213.cpp | 524cb7271d21429b50b01f1ea2f4570f6da06aa5 | [] | no_license | Visualsf/aoapc | 9ccfd5c82990ecdee9505e8ccd32c4689bd3fefb | fe7e58cfaad29e8b18636ac4f18b9418f72dca18 | refs/heads/master | 2020-03-10T20:52:44.145281 | 2018-11-23T10:25:45 | 2018-11-23T10:25:45 | 129,579,633 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,650 | cpp | /**
* 1.readchar处理读入时可能会遇到编码文本由多行组成的问题,因此用这种方法一直读到不为换行字符为止;
* 2.readint用来读取确定位数后的编码文本;
* 3.readcode主要是将编码文本对应到code[len][value]数组当中。读到EOF表示文件读取完毕;读到换行符表示当前编码本读取完毕。
** /
/**/
#include <stdio.h>
#include <string.h>
/*一直读取到非换行符为止*/
int readchar(){
for(;;){
int ch = getchar();
if(ch != '\n' && ch != '\r')
return ch;
}
}
/*读取c位的字符并求出其对应的值*/
int readint(int c){
int v = 0;
while(c--) {
v = v * 2 + readchar() - '0';
}
return v;
}
/*将初始字符对应到相应的位置,code[length][value]*/
int code[8][1<<8];
int readcodes(){
memset(code, 0, sizeof(code)); //清空数组
code[1][0] = readchar();
for(int len = 2; len <= 7; len++) {
for(int i = 0; i < (1 << len) - 1; i++) {
int ch = getchar();
if(ch == EOF) return 0; //读到EOF表示没有编码数据
if(ch == '\n' || ch == '\r') return 1; //读到换行表示编码数据录入结束
code[len][i] = ch;
}
}
return 1;
}
int main(int argc, char const *argv[])
{
while(readcodes()){
for(;;){
int len = readint(3);
if(len == 0) break;
for(;;) {
int v = readint(len);
if(v == (1 << len) - 1) break;
putchar(code[len][v]);
}
}
putchar('\n');
}
return 0;
} | [
"740782940@qq.com"
] | 740782940@qq.com |
e0c613827be7f0965b9b7be58888257ddcee6bb9 | 4da66ea2be83b62a46d77bf53f690b5146ac996d | /modules/theoraplayer/native/theoraplayer/src/YUV/libyuv/include/libyuv/convert_argb.h | 360c6d359396c0b7d8c21eea7fad597d56aac85c | [
"Zlib",
"LicenseRef-scancode-unknown",
"BSD-3-Clause"
] | permissive | blitz-research/monkey2 | 620855b08b6f41b40ff328da71d2e0d05d943855 | 3f6be81d73388b800a39ee53acaa7f4a0c6a9f42 | refs/heads/develop | 2021-04-09T17:13:34.240441 | 2020-06-28T04:26:30 | 2020-06-28T04:26:30 | 53,753,109 | 146 | 76 | Zlib | 2019-09-07T21:28:05 | 2016-03-12T20:59:51 | Monkey | UTF-8 | C++ | false | false | 8,340 | h | /*
* Copyright 2012 The LibYuv Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef INCLUDE_LIBYUV_CONVERT_ARGB_H_ // NOLINT
#define INCLUDE_LIBYUV_CONVERT_ARGB_H_
#include "libyuv/basic_types.h"
// TODO(fbarchard): Remove the following headers includes
#include "libyuv/convert_from.h"
#include "libyuv/planar_functions.h"
#include "libyuv/rotate.h"
// TODO(fbarchard): This set of functions should exactly match convert.h
// TODO(fbarchard): Add tests. Create random content of right size and convert
// with C vs Opt and or to I420 and compare.
// TODO(fbarchard): Some of these functions lack parameter setting.
#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif
// Alias.
#define ARGBToARGB ARGBCopy
// Copy ARGB to ARGB.
LIBYUV_API
int ARGBCopy(const uint8* src_argb, int src_stride_argb,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert I420 to ARGB.
LIBYUV_API
int I420ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert I422 to ARGB.
LIBYUV_API
int I422ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert I444 to ARGB.
LIBYUV_API
int I444ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert I411 to ARGB.
LIBYUV_API
int I411ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert I400 (grey) to ARGB. Reverse of ARGBToI400.
LIBYUV_API
int I400ToARGB(const uint8* src_y, int src_stride_y,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert J400 (jpeg grey) to ARGB.
LIBYUV_API
int J400ToARGB(const uint8* src_y, int src_stride_y,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Alias.
#define YToARGB I400ToARGB
// Convert NV12 to ARGB.
LIBYUV_API
int NV12ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_uv, int src_stride_uv,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert NV21 to ARGB.
LIBYUV_API
int NV21ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_vu, int src_stride_vu,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert M420 to ARGB.
LIBYUV_API
int M420ToARGB(const uint8* src_m420, int src_stride_m420,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert YUY2 to ARGB.
LIBYUV_API
int YUY2ToARGB(const uint8* src_yuy2, int src_stride_yuy2,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert UYVY to ARGB.
LIBYUV_API
int UYVYToARGB(const uint8* src_uyvy, int src_stride_uyvy,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert J420 to ARGB.
LIBYUV_API
int J420ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert J422 to ARGB.
LIBYUV_API
int J422ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// BGRA little endian (argb in memory) to ARGB.
LIBYUV_API
int BGRAToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// ABGR little endian (rgba in memory) to ARGB.
LIBYUV_API
int ABGRToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// RGBA little endian (abgr in memory) to ARGB.
LIBYUV_API
int RGBAToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Deprecated function name.
#define BG24ToARGB RGB24ToARGB
// RGB little endian (bgr in memory) to ARGB.
LIBYUV_API
int RGB24ToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// RGB big endian (rgb in memory) to ARGB.
LIBYUV_API
int RAWToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// RGB16 (RGBP fourcc) little endian to ARGB.
LIBYUV_API
int RGB565ToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// RGB15 (RGBO fourcc) little endian to ARGB.
LIBYUV_API
int ARGB1555ToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// RGB12 (R444 fourcc) little endian to ARGB.
LIBYUV_API
int ARGB4444ToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
#ifdef HAVE_JPEG
// src_width/height provided by capture
// dst_width/height for clipping determine final size.
LIBYUV_API
int MJPGToARGB(const uint8* sample, size_t sample_size,
uint8* dst_argb, int dst_stride_argb,
int src_width, int src_height,
int dst_width, int dst_height);
#endif
// Convert camera sample to ARGB with cropping, rotation and vertical flip.
// "src_size" is needed to parse MJPG.
// "dst_stride_argb" number of bytes in a row of the dst_argb plane.
// Normally this would be the same as dst_width, with recommended alignment
// to 16 bytes for better efficiency.
// If rotation of 90 or 270 is used, stride is affected. The caller should
// allocate the I420 buffer according to rotation.
// "dst_stride_u" number of bytes in a row of the dst_u plane.
// Normally this would be the same as (dst_width + 1) / 2, with
// recommended alignment to 16 bytes for better efficiency.
// If rotation of 90 or 270 is used, stride is affected.
// "crop_x" and "crop_y" are starting position for cropping.
// To center, crop_x = (src_width - dst_width) / 2
// crop_y = (src_height - dst_height) / 2
// "src_width" / "src_height" is size of src_frame in pixels.
// "src_height" can be negative indicating a vertically flipped image source.
// "crop_width" / "crop_height" is the size to crop the src to.
// Must be less than or equal to src_width/src_height
// Cropping parameters are pre-rotation.
// "rotation" can be 0, 90, 180 or 270.
// "format" is a fourcc. ie 'I420', 'YUY2'
// Returns 0 for successful; -1 for invalid parameter. Non-zero for failure.
LIBYUV_API
int ConvertToARGB(const uint8* src_frame, size_t src_size,
uint8* dst_argb, int dst_stride_argb,
int crop_x, int crop_y,
int src_width, int src_height,
int crop_width, int crop_height,
enum RotationMode rotation,
uint32 format);
#ifdef __cplusplus
} // extern "C"
} // namespace libyuv
#endif
#endif // INCLUDE_LIBYUV_CONVERT_ARGB_H_ NOLINT
| [
"blitzmunter@gmail.com"
] | blitzmunter@gmail.com |
b20ae5a37dfd651c5b7560a63d7d2d8e9b0f62ac | 3960aae83906764d80a045154eed9c79b00b20bd | /try.cpp | acfb411349ca5a1181085d1cf5a954565bc5173e | [] | no_license | davidwangd/pinyin-Introduction-to-AI-homework | cf1a6ce788343b1bcb87d2ae9e440e429051dc25 | b9b468bae1d6b600ff163fe61336db80b8d8a606 | refs/heads/master | 2021-01-22T21:45:44.788621 | 2017-03-31T15:23:43 | 2017-03-31T15:23:43 | 85,473,468 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 423 | cpp | #include "jsoncpp/json.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <fstream>
#include <algorithm>
using namespace std;
int main(){
ifstream fin("sina_news/2016-01.txt");
ofstream fout("test.txt");
string str;
for (int i = 0;i < 3;i++){
getline(fin, str);
Json::Reader reader;
Json::Value input;
reader.parse(str, input);
fout << input["html"].asString() << endl;
}
} | [
"david wang"
] | david wang |
0649da288e146326b45319cd216312b1825dd414 | 5d6d99d9af43de26935bad3e593018b872f25d2b | /src/gdlibrary.cpp | 45297ae25f51bdd1f3402871a4949beccd8085c2 | [
"MIT"
] | permissive | portaloffreedom/godot_entt_net_example | 0b91b97f18c2554faae864647e132182c7a84a21 | fae7b359dc42988f3afb4c1bb6247aa191d30fa3 | refs/heads/master | 2021-08-28T03:39:11.018483 | 2021-08-17T10:19:39 | 2021-08-17T10:19:39 | 209,872,723 | 23 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 690 | cpp | #include <Godot.hpp>
#include "Entity.h"
#include "EntityManager.h"
extern "C" void GDN_EXPORT godot_gdnative_init(godot_gdnative_init_options *o)
{
std::cout << "godot_gdnative_init()" << std::endl;
godot::Godot::gdnative_init(o);
}
extern "C" void GDN_EXPORT godot_gdnative_terminate(godot_gdnative_terminate_options *o)
{
std::cout << "godot_gdnative_terminate()" << std::endl;
godot::Godot::gdnative_terminate(o);
}
extern "C" void GDN_EXPORT godot_nativescript_init(void *handle)
{
std::cout << "godot_nativescript_init()" << std::endl;
godot::Godot::nativescript_init(handle);
godot::register_class<godot::Entity>();
godot::register_class<godot::EntityManager>();
}
| [
"matteo.dek@gmail.com"
] | matteo.dek@gmail.com |
dc01771861a12001df0c9ab777c33dbf5b6006aa | c62001313d731f5a1b090b7dcf6b35ebc27c8014 | /source/MyGlobal.cpp | 3ff23b73ac8431cb6c61ca4281ff5a9d1df25d05 | [] | no_license | ZHHJemotion/Face_Verification_UI | c6ed5fe77fdb384acdbef378dd4d242637479d79 | b575e3e1b825bc5662eaa6c4b77d20c10c20cb5a | refs/heads/master | 2021-04-26T23:36:06.570751 | 2018-09-15T22:43:13 | 2018-09-15T22:43:13 | 123,825,383 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,040 | cpp | #include <QDebug>
#include <QLibrary>
#include "MyGlobal.h"
QString MyGlobal::pathOriginalImage = NULL;
QString MyGlobal::pathFaceLandmarkImage = NULL;
QString MyGlobal::pathFaceAlignmentImage = NULL;
MyGlobal::MyGlobal(QObject *parent):QObject(parent)
{
}
MyGlobal::~MyGlobal()
{
}
bool MyGlobal::init()
{
// 1. define the paths of data
// -----------------------------------------------
pathOriginalImage = PathManage::makePathStr("/Users/Desktop/Programming/C++/Face_Verification_UI/data/originalFace/");
pathFaceLandmarkImage = PathManage::makePathStr("/Users/Desktop/Programming/C++/Face_Verification_UI/data/faceLandmarkDetection/");
pathFaceAlignmentImage = PathManage::makePathStr("/Users/Desktop/Programming/C++/Face_Verification_UI/data/faceAlignment/");
// 2. create the paths of data
// -----------------------------------------------
PathManage::mkPath(pathOriginalImage);
PathManage::mkPath(pathFaceLandmarkImage);
PathManage::mkPath(pathFaceAlignmentImage);
return true;
}
| [
"zhhjemotion@hotmail.com"
] | zhhjemotion@hotmail.com |
38ad9d34a7d22a472ef5a7d7e0e56f2c644a70fb | 1346a61bccb11d41e36ae7dfc613dafbe56ddb29 | /GeometricTools/GTEngine/Include/GteConvexHull2.inl | 5d15b8e7a0aae78289783114b3d5bbad80ab7698 | [] | no_license | cnsuhao/GeometricToolsEngine1p0 | c9a5845e3eb3a44733445c02bfa57c8ed286a499 | d4f2b7fda351917d4bfc3db1c6f8090f211f63d1 | refs/heads/master | 2021-05-28T02:00:50.566024 | 2014-08-14T07:28:23 | 2014-08-14T07:28:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,793 | inl | // Geometric Tools LLC, Redmond WA 98052
// Copyright (c) 1998-2014
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 1.0.0 (2014/08/11)
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
ConvexHull2<InputType, ComputeType>::ConvexHull2()
:
mEpsilon((InputType)0),
mDimension(0),
mLine(Vector2<InputType>::Zero(), Vector2<InputType>::Zero()),
mNumPoints(0),
mNumUniquePoints(0),
mPoints(nullptr)
{
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType>
bool ConvexHull2<InputType, ComputeType>::operator()(int numPoints,
Vector2<InputType> const* points, InputType epsilon)
{
mEpsilon = std::max(epsilon, (InputType)0);
mDimension = 0;
mLine.origin = Vector2<InputType>::Zero();
mLine.direction = Vector2<InputType>::Zero();
mNumPoints = numPoints;
mNumUniquePoints = 0;
mPoints = points;
mMerged.clear();
mHull.clear();
int i, j;
if (mNumPoints < 3)
{
// ConvexHull2 should be called with at least three points.
return false;
}
IntrinsicsVector2<InputType> info(mNumPoints, mPoints, mEpsilon);
if (info.dimension == 0)
{
// mDimension is 0
return false;
}
if (info.dimension == 1)
{
// The set is (nearly) collinear.
mDimension = 1;
mLine = Line2<InputType>(info.origin, info.direction[0]);
return false;
}
mDimension = 2;
// Compute the points for the queries.
mComputePoints.resize(mNumPoints);
mQuery.Set(mNumPoints, &mComputePoints[0]);
for (i = 0; i < mNumPoints; ++i)
{
for (j = 0; j < 2; ++j)
{
mComputePoints[i][j] = points[i][j];
}
}
// Sort the points.
mHull.resize(mNumPoints);
for (int i = 0; i < mNumPoints; ++i)
{
mHull[i] = i;
}
std::sort(mHull.begin(), mHull.end(),
[points](int i0, int i1)
{
if (points[i0][0] < points[i1][0]) { return true; }
if (points[i0][0] > points[i1][0]) { return false; }
return points[i0][1] < points[i1][1];
}
);
// Remove duplicates.
auto newEnd = std::unique(mHull.begin(), mHull.end(),
[points](int i0, int i1)
{
return points[i0] == points[i1];
}
);
mHull.erase(newEnd, mHull.end());
mNumUniquePoints = static_cast<int>(mHull.size());
// Use a divide-and-conquer algorithm. The merge step computes the
// convex hull of two convex polygons.
mMerged.resize(mNumUniquePoints);
int i0 = 0, i1 = mNumUniquePoints - 1;
GetHull(i0, i1);
mHull.resize(i1 - i0 + 1);
return true;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
InputType ConvexHull2<InputType, ComputeType>::GetEpsilon() const
{
return mEpsilon;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
int ConvexHull2<InputType, ComputeType>::GetDimension() const
{
return mDimension;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
Line2<InputType> const& ConvexHull2<InputType, ComputeType>::GetLine() const
{
return mLine;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
int ConvexHull2<InputType, ComputeType>::GetNumPoints() const
{
return mNumPoints;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
int ConvexHull2<InputType, ComputeType>::GetNumUniquePoints() const
{
return mNumUniquePoints;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
Vector2<InputType> const* ConvexHull2<InputType, ComputeType>::GetPoints()
const
{
return mPoints;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
PrimalQuery2<ComputeType> const&
ConvexHull2<InputType, ComputeType>::GetQuery() const
{
return mQuery;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
std::vector<int> const& ConvexHull2<InputType, ComputeType>::GetHull() const
{
return mHull;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
void ConvexHull2<InputType, ComputeType>::GetHull(int& i0, int& i1)
{
int numVertices = i1 - i0 + 1;
if (numVertices > 1)
{
// Compute the middle index of input range.
int mid = (i0 + i1)/2;
// Compute the hull of subsets (mid-i0+1 >= i1-mid).
int j0 = i0, j1 = mid, j2 = mid + 1, j3 = i1;
GetHull(j0, j1);
GetHull(j2, j3);
// Merge the convex hulls into a single convex hull.
Merge(j0, j1, j2, j3, i0, i1);
}
// else: The convex hull is a single point.
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
void ConvexHull2<InputType, ComputeType>::Merge(int j0, int j1, int j2,
int j3, int& i0, int& i1)
{
// Subhull0 is to the left of subhull1 because of the initial sorting of
// the points by x-components. We need to find two mutually visible
// points, one on the left subhull and one on the right subhull.
int size0 = j1 - j0 + 1;
int size1 = j3 - j2 + 1;
int i;
Vector2<ComputeType> p;
// Find the right-most point of the left subhull.
Vector2<ComputeType> pmax0 = mComputePoints[mHull[j0]];
int imax0 = j0;
for (i = j0 + 1; i <= j1; ++i)
{
p = mComputePoints[mHull[i]];
if (pmax0 < p)
{
pmax0 = p;
imax0 = i;
}
}
// Find the left-most point of the right subhull.
Vector2<ComputeType> pmin1 = mComputePoints[mHull[j2]];
int imin1 = j2;
for (i = j2 + 1; i <= j3; ++i)
{
p = mComputePoints[mHull[i]];
if (p < pmin1)
{
pmin1 = p;
imin1 = i;
}
}
// Get the lower tangent to hulls (LL = lower-left, LR = lower-right).
int iLL = imax0, iLR = imin1;
GetTangent(j0, j1, j2, j3, iLL, iLR);
// Get the upper tangent to hulls (UL = upper-left, UR = upper-right).
int iUL = imax0, iUR = imin1;
GetTangent(j2, j3, j0, j1, iUR, iUL);
// Construct the counterclockwise-ordered merged-hull vertices.
int k;
int numMerged = 0;
i = iUL;
for (k = 0; k < size0; ++k)
{
mMerged[numMerged++] = mHull[i];
if (i == iLL)
{
break;
}
i = (i < j1 ? i + 1 : j0);
}
LogAssert(k < size0, "Unexpected condition.");
i = iLR;
for (k = 0; k < size1; ++k)
{
mMerged[numMerged++] = mHull[i];
if (i == iUR)
{
break;
}
i = (i < j3 ? i + 1 : j2);
}
LogAssert(k < size1, "Unexpected condition.");
int next = j0;
for (k = 0; k < numMerged; ++k)
{
mHull[next] = mMerged[k];
++next;
}
i0 = j0;
i1 = next - 1;
}
//----------------------------------------------------------------------------
template <typename InputType, typename ComputeType> inline
void ConvexHull2<InputType, ComputeType>::GetTangent(int j0, int j1, int j2,
int j3, int& i0, int& i1)
{
// In theory the loop terminates in a finite number of steps, but the
// upper bound for the loop variable is used to trap problems caused by
// floating point roundoff errors that might lead to an infinite loop.
int size0 = j1 - j0 + 1;
int size1 = j3 - j2 + 1;
int const imax = size0 + size1;
int i, iLm1, iRp1;
Vector2<ComputeType> L0, L1, R0, R1;
for (i = 0; i < imax; i++)
{
// Get the endpoints of the potential tangent.
L1 = mComputePoints[mHull[i0]];
R0 = mComputePoints[mHull[i1]];
// Walk along the left hull to find the point of tangency.
if (size0 > 1)
{
iLm1 = (i0 > j0 ? i0 - 1 : j1);
L0 = mComputePoints[mHull[iLm1]];
auto order = mQuery.ToLineExtended(R0, L0, L1);
if (order == PrimalQuery2<ComputeType>::ORDER_NEGATIVE
|| order == PrimalQuery2<ComputeType>::ORDER_COLLINEAR_RIGHT)
{
i0 = iLm1;
continue;
}
}
// Walk along right hull to find the point of tangency.
if (size1 > 1)
{
iRp1 = (i1 < j3 ? i1 + 1 : j2);
R1 = mComputePoints[mHull[iRp1]];
auto order = mQuery.ToLineExtended(L1, R0, R1);
if (order == PrimalQuery2<ComputeType>::ORDER_NEGATIVE
|| order == PrimalQuery2<ComputeType>::ORDER_COLLINEAR_LEFT)
{
i1 = iRp1;
continue;
}
}
// The tangent segment has been found.
break;
}
// Detect an "infinite loop" caused by floating point round-off errors.
LogAssert(i < imax, "Unexpected condition.");
}
//----------------------------------------------------------------------------
| [
"qloach@foxmail.com"
] | qloach@foxmail.com |
518b173c8b78649fcfd795adee7a20e7f42360b5 | 046355f0dbfa7e677c4885466e683432a4c62bac | /build-MyNotepad-Desktop_Qt_5_12_0_MSVC2017_64bit-Release/ui_aboutdialog.h | 38ebdc89ec319bf260ff9a6cf0b54db7768aaa1a | [] | no_license | Sears-Tian/Qt-Toolkit | fc32828089f07cf86fe3f86e7748c9a34a0651d9 | 2419a78cb4c001d5b7d30370ff412d5e1cda2779 | refs/heads/master | 2020-05-17T07:41:33.456290 | 2019-04-26T09:05:55 | 2019-04-26T09:05:55 | 183,427,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,498 | h | /********************************************************************************
** Form generated from reading UI file 'aboutdialog.ui'
**
** Created by: Qt User Interface Compiler version 5.12.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_ABOUTDIALOG_H
#define UI_ABOUTDIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QDialog>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_AboutDialog
{
public:
QLabel *labelInfo;
QLabel *labelMovie;
QWidget *horizontalLayoutWidget;
QHBoxLayout *horizontalLayout;
QPushButton *pushButtonStop;
QSpacerItem *horizontalSpacer;
QPushButton *pushButtonStart;
void setupUi(QDialog *AboutDialog)
{
if (AboutDialog->objectName().isEmpty())
AboutDialog->setObjectName(QString::fromUtf8("AboutDialog"));
AboutDialog->resize(400, 497);
labelInfo = new QLabel(AboutDialog);
labelInfo->setObjectName(QString::fromUtf8("labelInfo"));
labelInfo->setGeometry(QRect(10, 10, 371, 91));
labelMovie = new QLabel(AboutDialog);
labelMovie->setObjectName(QString::fromUtf8("labelMovie"));
labelMovie->setGeometry(QRect(20, 120, 361, 291));
horizontalLayoutWidget = new QWidget(AboutDialog);
horizontalLayoutWidget->setObjectName(QString::fromUtf8("horizontalLayoutWidget"));
horizontalLayoutWidget->setGeometry(QRect(60, 420, 251, 61));
horizontalLayout = new QHBoxLayout(horizontalLayoutWidget);
horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
horizontalLayout->setContentsMargins(0, 0, 0, 0);
pushButtonStop = new QPushButton(horizontalLayoutWidget);
pushButtonStop->setObjectName(QString::fromUtf8("pushButtonStop"));
horizontalLayout->addWidget(pushButtonStop);
horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout->addItem(horizontalSpacer);
pushButtonStart = new QPushButton(horizontalLayoutWidget);
pushButtonStart->setObjectName(QString::fromUtf8("pushButtonStart"));
horizontalLayout->addWidget(pushButtonStart);
retranslateUi(AboutDialog);
QMetaObject::connectSlotsByName(AboutDialog);
} // setupUi
void retranslateUi(QDialog *AboutDialog)
{
AboutDialog->setWindowTitle(QApplication::translate("AboutDialog", "Dialog", nullptr));
labelInfo->setText(QApplication::translate("AboutDialog", "<html><head/><body><p><span style=\" font-size:14pt; font-weight:600; color:#ff007f;\">\347\211\210\346\235\203\346\211\200\346\234\211\302\2512019 </span></p><p><span style=\" font-size:14pt; font-weight:600; color:#ff007f;\">Snowflake All rights reserved.</span></p></body></html>", nullptr));
labelMovie->setText(QString());
pushButtonStop->setText(QApplication::translate("AboutDialog", "\345\201\234\346\255\242", nullptr));
pushButtonStart->setText(QApplication::translate("AboutDialog", "\345\274\200\345\247\213", nullptr));
} // retranslateUi
};
namespace Ui {
class AboutDialog: public Ui_AboutDialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_ABOUTDIALOG_H
| [
"worldtjh@hotmail.com"
] | worldtjh@hotmail.com |
0e093694e558ec9e20b7da8d285441de52a0be34 | ed412f1b35df1abc96c821e00345c2cefa2ba986 | /Projekt/Projekt/GameInteractionController.h | 92a11fb82b644a1d52b15e87a19cbcf00b62e011 | [] | no_license | andrzejg123/ProjektPK4 | 5919a14210d02d086796569995b2c299c9f65c0e | 722fd5d343627f980c6fa0d61a7dc11b5fca6ce9 | refs/heads/master | 2020-04-28T12:34:10.002902 | 2019-04-03T07:53:23 | 2019-04-03T07:53:23 | 175,280,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 528 | h | #pragma once
#include "GameObjectsHolder.h"
#include "GameView.h"
#include "PendingActionsController.h"
class GameInteractionController
{
GameObjectsHolder* gameObjectsHolder;
Interactive* possibleInteractionObject;
PendingActionsController* pendingActionsController;
GameView* gameView;
public:
void checkInteractions();
GameInteractionController(GameObjectsHolder* gameObjectsHolder, GameView* gameView, PendingActionsController* pendingActionsController);
~GameInteractionController();
void handleInteraction();
};
| [
"a"
] | a |
c789c2ac81d8370e3cd143ec481fd7367d4a8fb4 | 128774befeda73b0e27317f46c8f3cf94668071e | /special-practice/数论/prime.cpp | 43bd2617e8a5bfc2ae997d0a702780ae376bf3b2 | [] | no_license | toFindMore/oj-pratice | 5932903284d9d0c583f09aa62950aa911e0236ad | 9a714aeb6a117250a622d3efebbeb39b2737355f | refs/heads/master | 2023-04-13T19:35:14.302216 | 2021-04-09T13:49:58 | 2021-04-09T13:49:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 929 | cpp | //
// Created by 周健 on 2020-02-02.
//
#include <stdio.h>
#include <string.h>
const int MAXN = 10001;
int prime[MAXN];
bool isPrime[MAXN];
void init1() {
int cnt = -1;
memset(isPrime, true, sizeof(isPrime));
isPrime[0] = isPrime[1] = false;
for (int i = 2; i < MAXN; i++) {
if (isPrime[i]) {
prime[++cnt] = i;
}
for (int j = i * 2; j < MAXN; j += i) {
isPrime[j] = false;
}
}
}
// 优化后的筛法
void init2() {
int cnt = -1;
memset(isPrime, true, sizeof(isPrime));
isPrime[0] = isPrime[1] = false;
for (int i = 2; i < MAXN; i++) {
if (isPrime[i]) {
prime[++cnt] = i;
}
for (int j = 1; j <=cnt && prime[j] * i < MAXN; ++j) {
isPrime[prime[j] * i] = false;
}
}
}
int main() {
init2();
for (int i = 0; i < 20; i++) {
printf("%d\n", prime[i]);
}
}
| [
"17855824057@163.com"
] | 17855824057@163.com |
2c3de1ae3e8940bad187b6c2e4f3c2ecd613edec | d508027427b9a11a6bab0722479ee8d7b7eda72b | /3rd/include/maya2012sdk/tbb/task.h | 2ed69ecb72f60acd25d4eec3ffa56405db0779de | [] | no_license | gaoyakun/atom3d | 421bc029ee005f501e0adb6daed778662eb73bac | 129adf3ceca175faa8acf715c05e3c8f099399fe | refs/heads/master | 2021-01-10T18:28:50.562540 | 2019-12-06T13:17:00 | 2019-12-06T13:17:00 | 56,327,530 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,773 | h | /*
Copyright 2005-2010 Intel Corporation. All Rights Reserved.
The source code contained or described herein and all documents related
to the source code ("Material") are owned by Intel Corporation or its
suppliers or licensors. Title to the Material remains with Intel
Corporation or its suppliers and licensors. The Material is protected
by worldwide copyright laws and treaty provisions. No part of the
Material may be used, copied, reproduced, modified, published, uploaded,
posted, transmitted, distributed, or disclosed in any way without
Intel's prior express written permission.
No license under any patent, copyright, trade secret or other
intellectual property right is granted to or conferred upon you by
disclosure or delivery of the Materials, either expressly, by
implication, inducement, estoppel or otherwise. Any license under such
intellectual property rights must be express and approved by Intel in
writing.
*/
#ifndef __TBB_task_H
#define __TBB_task_H
#include "tbb_stddef.h"
#include "tbb_machine.h"
typedef struct ___itt_caller *__itt_caller;
namespace tbb {
class task;
class task_list;
#if __TBB_TASK_GROUP_CONTEXT
class task_group_context;
#endif /* __TBB_TASK_GROUP_CONTEXT */
// MSVC does not allow taking the address of a member that was defined
// privately in task_base and made public in class task via a using declaration.
#if _MSC_VER || (__GNUC__==3 && __GNUC_MINOR__<3)
#define __TBB_TASK_BASE_ACCESS public
#else
#define __TBB_TASK_BASE_ACCESS private
#endif
namespace internal {
class allocate_additional_child_of_proxy: no_assign {
//! No longer used, but retained for binary layout compatibility. Always NULL.
task* self;
task& parent;
public:
explicit allocate_additional_child_of_proxy( task& parent_ ) : self(NULL), parent(parent_) {}
task& __TBB_EXPORTED_METHOD allocate( size_t size ) const;
void __TBB_EXPORTED_METHOD free( task& ) const;
};
}
namespace interface5 {
namespace internal {
//! Base class for methods that became static in TBB 3.0.
/** TBB's evolution caused the "this" argument for several methods to become obsolete.
However, for backwards binary compatibility, the new methods need distinct names,
otherwise the One Definition Rule would be broken. Hence the new methods are
defined in this private base class, and then exposed in class task via
using declarations. */
class task_base: tbb::internal::no_copy {
__TBB_TASK_BASE_ACCESS:
friend class tbb::task;
//! Schedule task for execution when a worker becomes available.
static void spawn( task& t );
//! Spawn multiple tasks and clear list.
static void spawn( task_list& list );
//! Like allocate_child, except that task's parent becomes "t", not this.
/** Typically used in conjunction with schedule_to_reexecute to implement while loops.
Atomically increments the reference count of t.parent() */
static tbb::internal::allocate_additional_child_of_proxy allocate_additional_child_of( task& t ) {
return tbb::internal::allocate_additional_child_of_proxy(t);
}
//! Destroy a task.
/** Usually, calling this method is unnecessary, because a task is
implicitly deleted after its execute() method runs. However,
sometimes a task needs to be explicitly deallocated, such as
when a root task is used as the parent in spawn_and_wait_for_all. */
static void __TBB_EXPORTED_FUNC destroy( task& victim );
};
} // internal
} // interface5
//! @cond INTERNAL
namespace internal {
class scheduler: no_copy {
public:
//! For internal use only
virtual void spawn( task& first, task*& next ) = 0;
//! For internal use only
virtual void wait_for_all( task& parent, task* child ) = 0;
//! For internal use only
virtual void spawn_root_and_wait( task& first, task*& next ) = 0;
//! Pure virtual destructor;
// Have to have it just to shut up overzealous compilation warnings
virtual ~scheduler() = 0;
#if __TBB_ARENA_PER_MASTER
//! For internal use only
virtual void enqueue( task& t, void* reserved ) = 0;
#endif /* __TBB_ARENA_PER_MASTER */
};
//! A reference count
/** Should always be non-negative. A signed type is used so that underflow can be detected. */
typedef intptr_t reference_count;
//! An id as used for specifying affinity.
typedef unsigned short affinity_id;
#if __TBB_TASK_GROUP_CONTEXT
struct context_list_node_t {
context_list_node_t *my_prev,
*my_next;
};
class allocate_root_with_context_proxy: no_assign {
task_group_context& my_context;
public:
allocate_root_with_context_proxy ( task_group_context& ctx ) : my_context(ctx) {}
task& __TBB_EXPORTED_METHOD allocate( size_t size ) const;
void __TBB_EXPORTED_METHOD free( task& ) const;
};
#endif /* __TBB_TASK_GROUP_CONTEXT */
class allocate_root_proxy: no_assign {
public:
static task& __TBB_EXPORTED_FUNC allocate( size_t size );
static void __TBB_EXPORTED_FUNC free( task& );
};
class allocate_continuation_proxy: no_assign {
public:
task& __TBB_EXPORTED_METHOD allocate( size_t size ) const;
void __TBB_EXPORTED_METHOD free( task& ) const;
};
class allocate_child_proxy: no_assign {
public:
task& __TBB_EXPORTED_METHOD allocate( size_t size ) const;
void __TBB_EXPORTED_METHOD free( task& ) const;
};
//! Memory prefix to a task object.
/** This class is internal to the library.
Do not reference it directly, except within the library itself.
Fields are ordered in way that preserves backwards compatibility and yields
good packing on typical 32-bit and 64-bit platforms.
@ingroup task_scheduling */
class task_prefix {
private:
friend class tbb::task;
friend class tbb::interface5::internal::task_base;
friend class tbb::task_list;
friend class internal::scheduler;
friend class internal::allocate_root_proxy;
friend class internal::allocate_child_proxy;
friend class internal::allocate_continuation_proxy;
friend class internal::allocate_additional_child_of_proxy;
#if __TBB_TASK_GROUP_CONTEXT
//! Shared context that is used to communicate asynchronous state changes
/** Currently it is used to broadcast cancellation requests generated both
by users and as the result of unhandled exceptions in the task::execute()
methods. */
task_group_context *context;
#endif /* __TBB_TASK_GROUP_CONTEXT */
//! The scheduler that allocated the task, or NULL if the task is big.
/** Small tasks are pooled by the scheduler that allocated the task.
If a scheduler needs to free a small task allocated by another scheduler,
it returns the task to that other scheduler. This policy avoids
memory space blowup issues for memory allocators that allocate from
thread-specific pools. */
scheduler* origin;
//! Obsolete. The scheduler that owns the task.
/** Retained only for the sake of backward binary compatibility.
Still used by inline methods in the task.h header. **/
scheduler* owner;
//! The task whose reference count includes me.
/** In the "blocking style" of programming, this field points to the parent task.
In the "continuation-passing style" of programming, this field points to the
continuation of the parent. */
tbb::task* parent;
//! Reference count used for synchronization.
/** In the "continuation-passing style" of programming, this field is
the difference of the number of allocated children minus the
number of children that have completed.
In the "blocking style" of programming, this field is one more than the difference. */
reference_count ref_count;
//! Obsolete. Used to be scheduling depth before TBB 2.2
/** Retained only for the sake of backward binary compatibility.
Not used by TBB anymore. **/
int depth;
//! A task::state_type, stored as a byte for compactness.
/** This state is exposed to users via method task::state(). */
unsigned char state;
//! Miscellaneous state that is not directly visible to users, stored as a byte for compactness.
/** 0x0 -> version 1.0 task
0x1 -> version >=2.1 task
0x20 -> task_proxy
0x40 -> task has live ref_count
0x80 -> a stolen task */
unsigned char extra_state;
affinity_id affinity;
//! "next" field for list of task
tbb::task* next;
//! The task corresponding to this task_prefix.
tbb::task& task() {return *reinterpret_cast<tbb::task*>(this+1);}
};
} // namespace internal
//! @endcond
#if __TBB_TASK_GROUP_CONTEXT
#if TBB_USE_CAPTURED_EXCEPTION
class tbb_exception;
#else
namespace internal {
class tbb_exception_ptr;
}
#endif /* !TBB_USE_CAPTURED_EXCEPTION */
//! Used to form groups of tasks
/** @ingroup task_scheduling
The context services explicit cancellation requests from user code, and unhandled
exceptions intercepted during tasks execution. Intercepting an exception results
in generating internal cancellation requests (which is processed in exactly the
same way as external ones).
The context is associated with one or more root tasks and defines the cancellation
group that includes all the descendants of the corresponding root task(s). Association
is established when a context object is passed as an argument to the task::allocate_root()
method. See task_group_context::task_group_context for more details.
The context can be bound to another one, and other contexts can be bound to it,
forming a tree-like structure: parent -> this -> children. Arrows here designate
cancellation propagation direction. If a task in a cancellation group is canceled
all the other tasks in this group and groups bound to it (as children) get canceled too.
IMPLEMENTATION NOTE:
When adding new members to task_group_context or changing types of existing ones,
update the size of both padding buffers (_leading_padding and _trailing_padding)
appropriately. See also VERSIONING NOTE at the constructor definition below. **/
class task_group_context : internal::no_copy {
private:
#if TBB_USE_CAPTURED_EXCEPTION
typedef tbb_exception exception_container_type;
#else
typedef internal::tbb_exception_ptr exception_container_type;
#endif
enum version_traits_word_layout {
traits_offset = 16,
version_mask = 0xFFFF,
traits_mask = 0xFFFFul << traits_offset
};
public:
enum kind_type {
isolated,
bound
};
enum traits_type {
exact_exception = 0x0001ul << traits_offset,
concurrent_wait = 0x0004ul << traits_offset,
#if TBB_USE_CAPTURED_EXCEPTION
default_traits = 0
#else
default_traits = exact_exception
#endif /* !TBB_USE_CAPTURED_EXCEPTION */
};
private:
union {
//! Flavor of this context: bound or isolated.
kind_type my_kind;
uintptr_t _my_kind_aligner;
};
//! Pointer to the context of the parent cancellation group. NULL for isolated contexts.
task_group_context *my_parent;
//! Used to form the thread specific list of contexts without additional memory allocation.
/** A context is included into the list of the current thread when its binding to
its parent happens. Any context can be present in the list of one thread only. **/
internal::context_list_node_t my_node;
//! Used to set and maintain stack stitching point for Intel Performance Tools.
__itt_caller itt_caller;
//! Leading padding protecting accesses to frequently used members from false sharing.
/** Read accesses to the field my_cancellation_requested are on the hot path inside
the scheduler. This padding ensures that this field never shares the same cache
line with a local variable that is frequently written to. **/
char _leading_padding[internal::NFS_MaxLineSize -
2 * sizeof(uintptr_t)- sizeof(void*) - sizeof(internal::context_list_node_t)
- sizeof(__itt_caller)];
//! Specifies whether cancellation was request for this task group.
uintptr_t my_cancellation_requested;
//! Version for run-time checks and behavioral traits of the context.
/** Version occupies low 16 bits, and traits (zero or more ORed enumerators
from the traits_type enumerations) take the next 16 bits.
Original (zeroth) version of the context did not support any traits. **/
uintptr_t my_version_and_traits;
//! Pointer to the container storing exception being propagated across this task group.
exception_container_type *my_exception;
//! Scheduler that registered this context in its thread specific list.
/** This field is not terribly necessary, but it allows to get a small performance
benefit by getting us rid of using thread local storage. We do not care
about extra memory it takes since this data structure is excessively padded anyway. **/
void *my_owner;
//! Trailing padding protecting accesses to frequently used members from false sharing
/** \sa _leading_padding **/
char _trailing_padding[internal::NFS_MaxLineSize - sizeof(intptr_t) - 2 * sizeof(void*)];
public:
//! Default & binding constructor.
/** By default a bound context is created. That is this context will be bound
(as child) to the context of the task calling task::allocate_root(this_context)
method. Cancellation requests passed to the parent context are propagated
to all the contexts bound to it.
If task_group_context::isolated is used as the argument, then the tasks associated
with this context will never be affected by events in any other context.
Creating isolated contexts involve much less overhead, but they have limited
utility. Normally when an exception occurs in an algorithm that has nested
ones running, it is desirably to have all the nested algorithms canceled
as well. Such a behavior requires nested algorithms to use bound contexts.
There is one good place where using isolated algorithms is beneficial. It is
a master thread. That is if a particular algorithm is invoked directly from
the master thread (not from a TBB task), supplying it with explicitly
created isolated context will result in a faster algorithm startup.
VERSIONING NOTE:
Implementation(s) of task_group_context constructor(s) cannot be made
entirely out-of-line because the run-time version must be set by the user
code. This will become critically important for binary compatibility, if
we ever have to change the size of the context object.
Boosting the runtime version will also be necessary if new data fields are
introduced in the currently unused padding areas and these fields are updated
by inline methods. **/
task_group_context ( kind_type relation_with_parent = bound,
uintptr_t traits = default_traits )
: my_kind(relation_with_parent)
, my_version_and_traits(1 | traits)
{
init();
}
__TBB_EXPORTED_METHOD ~task_group_context ();
//! Forcefully reinitializes the context after the task tree it was associated with is completed.
/** Because the method assumes that all the tasks that used to be associated with
this context have already finished, calling it while the context is still
in use somewhere in the task hierarchy leads to undefined behavior.
IMPORTANT: This method is not thread safe!
The method does not change the context's parent if it is set. **/
void __TBB_EXPORTED_METHOD reset ();
//! Initiates cancellation of all tasks in this cancellation group and its subordinate groups.
/** \return false if cancellation has already been requested, true otherwise.
Note that canceling never fails. When false is returned, it just means that
another thread (or this one) has already sent cancellation request to this
context or to one of its ancestors (if this context is bound). It is guaranteed
that when this method is concurrently called on the same not yet cancelled
context, true will be returned by one and only one invocation. **/
bool __TBB_EXPORTED_METHOD cancel_group_execution ();
//! Returns true if the context received cancellation request.
bool __TBB_EXPORTED_METHOD is_group_execution_cancelled () const;
//! Records the pending exception, and cancels the task group.
/** May be called only from inside a catch-block. If the context is already
canceled, does nothing.
The method brings the task group associated with this context exactly into
the state it would be in, if one of its tasks threw the currently pending
exception during its execution. In other words, it emulates the actions
of the scheduler's dispatch loop exception handler. **/
void __TBB_EXPORTED_METHOD register_pending_exception ();
protected:
//! Out-of-line part of the constructor.
/** Singled out to ensure backward binary compatibility of the future versions. **/
void __TBB_EXPORTED_METHOD init ();
private:
friend class task;
friend class internal::allocate_root_with_context_proxy;
static const kind_type binding_required = bound;
static const kind_type binding_completed = kind_type(bound+1);
static const kind_type detached = kind_type(binding_completed+1);
static const kind_type dying = kind_type(detached+1);
//! Checks if any of the ancestors has a cancellation request outstanding,
//! and propagates it back to descendants.
void propagate_cancellation_from_ancestors ();
}; // class task_group_context
#endif /* __TBB_TASK_GROUP_CONTEXT */
//! Base class for user-defined tasks.
/** @ingroup task_scheduling */
class task: __TBB_TASK_BASE_ACCESS interface5::internal::task_base {
//! Set reference count
void __TBB_EXPORTED_METHOD internal_set_ref_count( int count );
//! Decrement reference count and return its new value.
internal::reference_count __TBB_EXPORTED_METHOD internal_decrement_ref_count();
protected:
//! Default constructor.
task() {prefix().extra_state=1;}
public:
//! Destructor.
virtual ~task() {}
//! Should be overridden by derived classes.
virtual task* execute() = 0;
//! Enumeration of task states that the scheduler considers.
enum state_type {
//! task is running, and will be destroyed after method execute() completes.
executing,
//! task to be rescheduled.
reexecute,
//! task is in ready pool, or is going to be put there, or was just taken off.
ready,
//! task object is freshly allocated or recycled.
allocated,
//! task object is on free list, or is going to be put there, or was just taken off.
freed,
//! task to be recycled as continuation
recycle
};
//------------------------------------------------------------------------
// Allocating tasks
//------------------------------------------------------------------------
//! Returns proxy for overloaded new that allocates a root task.
static internal::allocate_root_proxy allocate_root() {
return internal::allocate_root_proxy();
}
#if __TBB_TASK_GROUP_CONTEXT
//! Returns proxy for overloaded new that allocates a root task associated with user supplied context.
static internal::allocate_root_with_context_proxy allocate_root( task_group_context& ctx ) {
return internal::allocate_root_with_context_proxy(ctx);
}
#endif /* __TBB_TASK_GROUP_CONTEXT */
//! Returns proxy for overloaded new that allocates a continuation task of *this.
/** The continuation's parent becomes the parent of *this. */
internal::allocate_continuation_proxy& allocate_continuation() {
return *reinterpret_cast<internal::allocate_continuation_proxy*>(this);
}
//! Returns proxy for overloaded new that allocates a child task of *this.
internal::allocate_child_proxy& allocate_child() {
return *reinterpret_cast<internal::allocate_child_proxy*>(this);
}
//! Define recommended static form via import from base class.
using task_base::allocate_additional_child_of;
#if __TBB_DEPRECATED_TASK_INTERFACE
//! Destroy a task.
/** Usually, calling this method is unnecessary, because a task is
implicitly deleted after its execute() method runs. However,
sometimes a task needs to be explicitly deallocated, such as
when a root task is used as the parent in spawn_and_wait_for_all. */
void __TBB_EXPORTED_METHOD destroy( task& t );
#else /* !__TBB_DEPRECATED_TASK_INTERFACE */
//! Define recommended static form via import from base class.
using task_base::destroy;
#endif /* !__TBB_DEPRECATED_TASK_INTERFACE */
//------------------------------------------------------------------------
// Recycling of tasks
//------------------------------------------------------------------------
//! Change this to be a continuation of its former self.
/** The caller must guarantee that the task's refcount does not become zero until
after the method execute() returns. Typically, this is done by having
method execute() return a pointer to a child of the task. If the guarantee
cannot be made, use method recycle_as_safe_continuation instead.
Because of the hazard, this method may be deprecated in the future. */
void recycle_as_continuation() {
__TBB_ASSERT( prefix().state==executing, "execute not running?" );
prefix().state = allocated;
}
//! Recommended to use, safe variant of recycle_as_continuation
/** For safety, it requires additional increment of ref_count.
With no decendants and ref_count of 1, it has the semantics of recycle_to_reexecute. */
void recycle_as_safe_continuation() {
__TBB_ASSERT( prefix().state==executing, "execute not running?" );
prefix().state = recycle;
}
//! Change this to be a child of new_parent.
void recycle_as_child_of( task& new_parent ) {
internal::task_prefix& p = prefix();
__TBB_ASSERT( prefix().state==executing||prefix().state==allocated, "execute not running, or already recycled" );
__TBB_ASSERT( prefix().ref_count==0, "no child tasks allowed when recycled as a child" );
__TBB_ASSERT( p.parent==NULL, "parent must be null" );
__TBB_ASSERT( new_parent.prefix().state<=recycle, "corrupt parent's state" );
__TBB_ASSERT( new_parent.prefix().state!=freed, "parent already freed" );
p.state = allocated;
p.parent = &new_parent;
#if __TBB_TASK_GROUP_CONTEXT
p.context = new_parent.prefix().context;
#endif /* __TBB_TASK_GROUP_CONTEXT */
}
//! Schedule this for reexecution after current execute() returns.
/** Made obsolete by recycle_as_safe_continuation; may become deprecated. */
void recycle_to_reexecute() {
__TBB_ASSERT( prefix().state==executing, "execute not running, or already recycled" );
__TBB_ASSERT( prefix().ref_count==0, "no child tasks allowed when recycled for reexecution" );
prefix().state = reexecute;
}
// All depth-related methods are obsolete, and are retained for the sake
// of backward source compatibility only
intptr_t depth() const {return 0;}
void set_depth( intptr_t ) {}
void add_to_depth( int ) {}
//------------------------------------------------------------------------
// Spawning and blocking
//------------------------------------------------------------------------
//! Set reference count
void set_ref_count( int count ) {
#if TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT
internal_set_ref_count(count);
#else
prefix().ref_count = count;
#endif /* TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT */
}
//! Atomically increment reference count and returns its old value.
/** Has acquire semantics */
void increment_ref_count() {
__TBB_FetchAndIncrementWacquire( &prefix().ref_count );
}
//! Atomically decrement reference count and returns its new value.
/** Has release semantics. */
int decrement_ref_count() {
#if TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT
return int(internal_decrement_ref_count());
#else
return int(__TBB_FetchAndDecrementWrelease( &prefix().ref_count ))-1;
#endif /* TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT */
}
//! Define recommended static forms via import from base class.
using task_base::spawn;
//! Similar to spawn followed by wait_for_all, but more efficient.
void spawn_and_wait_for_all( task& child ) {
prefix().owner->wait_for_all( *this, &child );
}
//! Similar to spawn followed by wait_for_all, but more efficient.
void __TBB_EXPORTED_METHOD spawn_and_wait_for_all( task_list& list );
//! Spawn task allocated by allocate_root, wait for it to complete, and deallocate it.
static void spawn_root_and_wait( task& root ) {
root.prefix().owner->spawn_root_and_wait( root, root.prefix().next );
}
//! Spawn root tasks on list and wait for all of them to finish.
/** If there are more tasks than worker threads, the tasks are spawned in
order of front to back. */
static void spawn_root_and_wait( task_list& root_list );
//! Wait for reference count to become one, and set reference count to zero.
/** Works on tasks while waiting. */
void wait_for_all() {
prefix().owner->wait_for_all( *this, NULL );
}
#if __TBB_ARENA_PER_MASTER
//! Enqueue task for starvation-resistant execution.
static void enqueue( task& t ) {
t.prefix().owner->enqueue( t, NULL );
}
#endif /* __TBB_ARENA_PER_MASTER */
//! The innermost task being executed or destroyed by the current thread at the moment.
static task& __TBB_EXPORTED_FUNC self();
//! task on whose behalf this task is working, or NULL if this is a root.
task* parent() const {return prefix().parent;}
#if __TBB_TASK_GROUP_CONTEXT
//! Shared context that is used to communicate asynchronous state changes
task_group_context* context() {return prefix().context;}
#endif /* __TBB_TASK_GROUP_CONTEXT */
//! True if task was stolen from the task pool of another thread.
bool is_stolen_task() const {
return (prefix().extra_state & 0x80)!=0;
}
//------------------------------------------------------------------------
// Debugging
//------------------------------------------------------------------------
//! Current execution state
state_type state() const {return state_type(prefix().state);}
//! The internal reference count.
int ref_count() const {
#if TBB_USE_ASSERT
internal::reference_count ref_count_ = prefix().ref_count;
__TBB_ASSERT( ref_count_==int(ref_count_), "integer overflow error");
#endif
return int(prefix().ref_count);
}
//! Obsolete, and only retained for the sake of backward compatibility. Always returns true.
bool __TBB_EXPORTED_METHOD is_owned_by_current_thread() const;
//------------------------------------------------------------------------
// Affinity
//------------------------------------------------------------------------
//! An id as used for specifying affinity.
/** Guaranteed to be integral type. Value of 0 means no affinity. */
typedef internal::affinity_id affinity_id;
//! Set affinity for this task.
void set_affinity( affinity_id id ) {prefix().affinity = id;}
//! Current affinity of this task
affinity_id affinity() const {return prefix().affinity;}
//! Invoked by scheduler to notify task that it ran on unexpected thread.
/** Invoked before method execute() runs, if task is stolen, or task has
affinity but will be executed on another thread.
The default action does nothing. */
virtual void __TBB_EXPORTED_METHOD note_affinity( affinity_id id );
#if __TBB_TASK_GROUP_CONTEXT
//! Initiates cancellation of all tasks in this cancellation group and its subordinate groups.
/** \return false if cancellation has already been requested, true otherwise. **/
bool cancel_group_execution () { return prefix().context->cancel_group_execution(); }
//! Returns true if the context received cancellation request.
bool is_cancelled () const { return prefix().context->is_group_execution_cancelled(); }
#endif /* __TBB_TASK_GROUP_CONTEXT */
private:
friend class interface5::internal::task_base;
friend class task_list;
friend class internal::scheduler;
friend class internal::allocate_root_proxy;
#if __TBB_TASK_GROUP_CONTEXT
friend class internal::allocate_root_with_context_proxy;
#endif /* __TBB_TASK_GROUP_CONTEXT */
friend class internal::allocate_continuation_proxy;
friend class internal::allocate_child_proxy;
friend class internal::allocate_additional_child_of_proxy;
//! Get reference to corresponding task_prefix.
/** Version tag prevents loader on Linux from using the wrong symbol in debug builds. **/
internal::task_prefix& prefix( internal::version_tag* = NULL ) const {
return reinterpret_cast<internal::task_prefix*>(const_cast<task*>(this))[-1];
}
}; // class task
//! task that does nothing. Useful for synchronization.
/** @ingroup task_scheduling */
class empty_task: public task {
/*override*/ task* execute() {
return NULL;
}
};
//! A list of children.
/** Used for method task::spawn_children
@ingroup task_scheduling */
class task_list: internal::no_copy {
private:
task* first;
task** next_ptr;
friend class task;
friend class interface5::internal::task_base;
public:
//! Construct empty list
task_list() : first(NULL), next_ptr(&first) {}
//! Destroys the list, but does not destroy the task objects.
~task_list() {}
//! True if list if empty; false otherwise.
bool empty() const {return !first;}
//! Push task onto back of list.
void push_back( task& task ) {
task.prefix().next = NULL;
*next_ptr = &task;
next_ptr = &task.prefix().next;
}
//! Pop the front task from the list.
task& pop_front() {
__TBB_ASSERT( !empty(), "attempt to pop item from empty task_list" );
task* result = first;
first = result->prefix().next;
if( !first ) next_ptr = &first;
return *result;
}
//! Clear the list
void clear() {
first=NULL;
next_ptr=&first;
}
};
inline void interface5::internal::task_base::spawn( task& t ) {
t.prefix().owner->spawn( t, t.prefix().next );
}
inline void interface5::internal::task_base::spawn( task_list& list ) {
if( task* t = list.first ) {
t->prefix().owner->spawn( *t, *list.next_ptr );
list.clear();
}
}
inline void task::spawn_root_and_wait( task_list& root_list ) {
if( task* t = root_list.first ) {
t->prefix().owner->spawn_root_and_wait( *t, *root_list.next_ptr );
root_list.clear();
}
}
} // namespace tbb
inline void *operator new( size_t bytes, const tbb::internal::allocate_root_proxy& ) {
return &tbb::internal::allocate_root_proxy::allocate(bytes);
}
inline void operator delete( void* task, const tbb::internal::allocate_root_proxy& ) {
tbb::internal::allocate_root_proxy::free( *static_cast<tbb::task*>(task) );
}
#if __TBB_TASK_GROUP_CONTEXT
inline void *operator new( size_t bytes, const tbb::internal::allocate_root_with_context_proxy& p ) {
return &p.allocate(bytes);
}
inline void operator delete( void* task, const tbb::internal::allocate_root_with_context_proxy& p ) {
p.free( *static_cast<tbb::task*>(task) );
}
#endif /* __TBB_TASK_GROUP_CONTEXT */
inline void *operator new( size_t bytes, const tbb::internal::allocate_continuation_proxy& p ) {
return &p.allocate(bytes);
}
inline void operator delete( void* task, const tbb::internal::allocate_continuation_proxy& p ) {
p.free( *static_cast<tbb::task*>(task) );
}
inline void *operator new( size_t bytes, const tbb::internal::allocate_child_proxy& p ) {
return &p.allocate(bytes);
}
inline void operator delete( void* task, const tbb::internal::allocate_child_proxy& p ) {
p.free( *static_cast<tbb::task*>(task) );
}
inline void *operator new( size_t bytes, const tbb::internal::allocate_additional_child_of_proxy& p ) {
return &p.allocate(bytes);
}
inline void operator delete( void* task, const tbb::internal::allocate_additional_child_of_proxy& p ) {
p.free( *static_cast<tbb::task*>(task) );
}
#endif /* __TBB_task_H */
| [
"80844871@qq.com"
] | 80844871@qq.com |
ecaae615017b21f6409ea13bcc73e648b6d064ec | 3e70eda6819fec5bf5ba2299573b333a3a610131 | /c/library/newbench/trunk/src/test/stub-server/include/c_auto_ptr.h | a7ba18a4bc1a53591a3ffe93a3c7083085c26078 | [] | no_license | dawnbreaks/taomee | cdd4f9cecaf659d134d207ae8c9dd2247bef97a1 | f21b3633680456b09a40036d919bf9f58c9cd6d7 | refs/heads/master | 2021-01-17T10:45:31.240038 | 2013-03-14T08:10:27 | 2013-03-14T08:10:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,993 | h | /*
* =====================================================================================
* @file c_auto_ptr.h
* @brief 提供相关自动管理指针类,这些类会自动释放传入的资源
*
* Detailed description starts here.
*
* @internal
* Created 01/22/2010 01:53:21 PM
* Revision 1.0.0.0
* Compiler gcc/g++
* Company TaoMee.Inc, ShangHai.
* Copyright Copyright (c) 2010, TaoMee.Inc, ShangHai.
*
* @author jasonwang (王国栋), jasonwang@taomee.com
* This source code was wrote for TaoMee,Inc. ShangHai CN.
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <mysql/mysql.h>
#include <sys/mman.h>
#include <semaphore.h>
#include <pthread.h>
/**
* @brief 将用户的MYSQL_RESULT指针交给类来处理,它会自动释放资源
*/
class c_mysql_res_auto_ptr
{
public:
/**
* @brief 将用户的MYSQL_RESULT指针传给类
*
* @param res MYSQL_RES结果集指针
*/
c_mysql_res_auto_ptr(MYSQL_RES* res);
/**
* @brief 自动释放MYSQL_RESULT指针
*/
~c_mysql_res_auto_ptr();
/**
* @brief 用户传入的指针与类脱离,不再由类来管理
*
* @return 成功返回0,失败返回-1
*/
int detach();
/**
* @brief 释放类管理的指针
*
* @return 成功返回0,失败返回-1
*/
int free();
/**
* @brief 将类管理的指针返回给用户
*
* @return 类管理的指针
*/
MYSQL_RES* get_ptr();
private:
c_mysql_res_auto_ptr(c_mysql_res_auto_ptr &c_ptr) {}
/**
* @brief 保存用户传入的指针
*/
MYSQL_RES* m_res;
};
/**
* @brief 将用户的文件描述符交给类来处理,它会自动释放资源
*/
class c_fd_auto_ptr
{
public:
/**
* @brief 将用户的文件描述符传给类
*
* @param fd 文件描述符
*/
c_fd_auto_ptr(int);
/**
* @brief 自动释放文件描述符
*/
~c_fd_auto_ptr();
/**
* @brief 用户传入的文件描述符与类脱离,不再由类来管理
*
* @return 成功返回0,失败返回-1
*/
int detach();
/**
* @brief 关闭类管理的文件描述符
*
* @return 成功返回0,失败返回-1
*/
int free();
/**
* @brief 获取类管理的文件描述符
*
* @return 文件描述符
*/
int get_fd();
private:
c_fd_auto_ptr(c_fd_auto_ptr &c_ptr) {}
/**
* @brief 保存用户传入的文件描述符
*/
int m_fd;
};
/**
* @brief 将用户的抽象数据类型指针交给类来处理,它会自动释放资源
*/
template<typename T>
class c_obj_auto_ptr
{
public:
/**
* @brief 将用户的抽象数据类型指针传给类
*
* @param ptr 抽象数据类型指针
*/
c_obj_auto_ptr(T* ptr)
{
m_ptr = ptr;
}
/**
* @brief 自动释放抽象数据类型指针
*/
~c_obj_auto_ptr()
{
free();
}
/**
* @brief 用户传入的指针与类脱离,不再由类来管理
*
* @return 成功返回0,失败返回-1
*/
int detach()
{
if (m_ptr != NULL) {
m_ptr = NULL;
return 0;
}
return -1;
}
/**
* @brief 释放类管理的指针
*
* @return 成功返回0,失败返回-1
*/
int free()
{
if (m_ptr != NULL) {
delete m_ptr;
m_ptr = NULL;
return 0;
}
return -1;
}
/**
* @brief 将类管理的指针返回给用户
*
* @return 类管理的指针
*/
T* get_ptr()
{
return m_ptr;
}
private:
c_obj_auto_ptr(c_obj_auto_ptr &c_ptr) {}
/**
* @brief 保存用户传入的指针
*/
T* m_ptr;
};
/**
* @brief 将用户的动态分配内存指针交给类来处理,它会自动释放资源
*/
class c_malloc_auto_ptr
{
public:
/**
* @brief 将用户的动态分配内存指针传给类
*
* @param ptr 用户动态分配内存指针
*/
c_malloc_auto_ptr(void* ptr);
/**
* @brief 自动释放用户动态分配内存指针
*/
~c_malloc_auto_ptr();
/**
* @brief 用户传入的指针与类脱离,不再由类来管理
*
* @return 成功返回0,失败返回-1
*/
int detach();
/**
* @brief 释放类管理的指针
*
* @return 成功返回0,失败返回-1
*/
int free();
/**
* @brief 将类管理的指针返回给用户
*
* @return 类管理的指针
*/
void* get_ptr();
private:
c_malloc_auto_ptr(c_malloc_auto_ptr &c_ptr) {}
/**
* @brief 保存用户传入的指针
*/
void* m_ptr;
};
/**
* @brief 将用户的内存映射指针交给类来处理,它会自动释放资源
*/
class c_mmap_auto_ptr
{
public:
/**
* @brief 将用户的内存映射指针传给类
*
* @param map 内存映射指针
*
* @param sz 内存映射的字节数
*/
c_mmap_auto_ptr(void* map, size_t sz);
/**
* @brief 自动释放内存映射指针
*/
~c_mmap_auto_ptr();
/**
* @brief 用户传入的指针与类脱离,不再由类来管理
*
* @return 成功返回0,失败返回-1
*/
int detach();
/**
* @brief 释放类管理的指针
*
* @return 成功返回0,失败返回-1
*/
int free();
/**
* @brief 将类管理的指针返回给用户
*
* @return 类管理的指针
*/
void* get_ptr();
private:
c_mmap_auto_ptr(c_mmap_auto_ptr &c_ptr) {}
/**
* @brief 保存用户传入的指针
*/
void* m_map;
/**
* @brief 保存内存映射的字节数
*/
size_t m_sz;
};
/**
* @brief 将用户的线程互斥锁指针交给类来处理,它会自动释放资源
*/
class c_pthread_mutex_auto_ptr
{
public:
/**
* @brief 将用户的线程互斥锁指针传给类
*
* @param mtx 线程互斥锁指针
*/
c_pthread_mutex_auto_ptr(pthread_mutex_t *mtx);
/**
* @brief 自动释放线程互斥锁指针
*/
~c_pthread_mutex_auto_ptr();
/**
* @brief 用户传入的指针与类脱离,不再由类来管理
*
* @return 成功返回0,失败返回-1
*/
int detach();
/**
* @brief 释放类管理的指针
*
* @return 成功返回0,失败返回-1
*/
int free();
/**
* @brief 将类管理的指针返回给用户
*
* @return 类管理的指针
*/
pthread_mutex_t *get_ptr();
private:
c_pthread_mutex_auto_ptr(c_pthread_mutex_auto_ptr &c_ptr) {}
/**
* @brief 保存用户传入的指针
*/
pthread_mutex_t *m_mtx;
};
/**
* @brief 将用户的信号量描述符指针交给类来处理,它会自动释放资源
*/
class c_semaphore_auto_ptr
{
public:
/**
* @brief 将用户的信号量描述指针传给类
*
* @param sem 信号量描述符指针
*/
c_semaphore_auto_ptr(sem_t *sem);
/**
* @brief 自动释放信号量
*/
~c_semaphore_auto_ptr();
/**
* @brief 用户传入的指针与类脱离,不再由类来管理
*
* @return 成功返回0,失败返回-1
*/
int detach();
/**
* @brief 释放类管理的指针
*
* @return 成功返回0,失败返回-1
*/
int free();
/**
* @brief 将类管理的指针返回给用户
*
* @return 类管理的指针
*/
sem_t *get_ptr();
private:
c_semaphore_auto_ptr(c_semaphore_auto_ptr &c_ptr) {}
/**
* @brief 保存用户传入的指针
*/
sem_t *m_sem;
};
| [
"smyang.ustc@gmail.com"
] | smyang.ustc@gmail.com |
531a1d188adf67e0c3f4142941f2519f4e1050f2 | 1f63dde39fcc5f8be29f2acb947c41f1b6f1683e | /Boss2D/addon/webrtc-jumpingyang001_for_boss/common_video/video_frame.cc | f93def599ff4fcf4404b7e779135069a4020f68c | [
"BSD-3-Clause",
"LicenseRef-scancode-google-patent-license-webm",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | koobonil/Boss2D | 09ca948823e0df5a5a53b64a10033c4f3665483a | e5eb355b57228a701495f2660f137bd05628c202 | refs/heads/master | 2022-10-20T09:02:51.341143 | 2019-07-18T02:13:44 | 2019-07-18T02:13:44 | 105,999,368 | 7 | 2 | MIT | 2022-10-04T23:31:12 | 2017-10-06T11:57:07 | C++ | UTF-8 | C++ | false | false | 1,836 | cc | /*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include BOSS_WEBRTC_U_common_video__include__video_frame_h //original-code:"common_video/include/video_frame.h"
#include <string.h>
#include <algorithm> // swap
#include BOSS_WEBRTC_U_rtc_base__bind_h //original-code:"rtc_base/bind.h"
#include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h"
namespace webrtc {
// FFmpeg's decoder, used by H264DecoderImpl, requires up to 8 bytes padding due
// to optimized bitstream readers. See avcodec_decode_video2.
const size_t EncodedImage::kBufferPaddingBytesH264 = 8;
size_t EncodedImage::GetBufferPaddingBytes(VideoCodecType codec_type) {
switch (codec_type) {
case kVideoCodecVP8:
case kVideoCodecVP9:
return 0;
case kVideoCodecH264:
return kBufferPaddingBytesH264;
case kVideoCodecI420:
case kVideoCodecGeneric:
case kVideoCodecMultiplex:
case kVideoCodecUnknown:
return 0;
}
RTC_NOTREACHED();
return 0;
}
EncodedImage::EncodedImage() : EncodedImage(nullptr, 0, 0) {}
EncodedImage::EncodedImage(const EncodedImage&) = default;
EncodedImage::EncodedImage(uint8_t* buffer, size_t length, size_t size)
: _buffer(buffer), _length(length), _size(size) {}
void EncodedImage::SetEncodeTime(int64_t encode_start_ms,
int64_t encode_finish_ms) {
timing_.encode_start_ms = encode_start_ms;
timing_.encode_finish_ms = encode_finish_ms;
}
} // namespace webrtc
| [
"slacealic@nate.com"
] | slacealic@nate.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.