blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 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
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a429e024b94c5f40a6e603f1790f881498fa66cd | 64cb5c0a368faf2b8d72b0d262137a3bedb7a814 | /test/test_buffer.cc | b1a2fbce5125f99bad50be767ca61d7188590e6c | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | fixdocker/kids | 2d9783268013ffc775b1c2ed53c061effeb5f265 | bee2a5fab27d90620910ab8c5a59e248688b4599 | refs/heads/master | 2022-11-20T12:49:05.071813 | 2020-07-22T13:41:32 | 2020-07-22T13:41:32 | 281,688,104 | 0 | 0 | NOASSERTION | 2020-07-22T13:40:35 | 2020-07-22T13:40:34 | null | UTF-8 | C++ | false | false | 3,502 | cc | #include <vector>
#include "gtest/gtest.h"
#include "buffer.h"
#include "util.h"
TEST(TestBuffer, TestConstruct) {
Buffer buf;
EXPECT_EQ(0, buf.size());
EXPECT_EQ(0, buf.capacity());
EXPECT_EQ(0, buf.blank_size());
Buffer *strs = new Buffer("abc def ghi");
EXPECT_TRUE(strs != NULL);
EXPECT_EQ(11, strs->size());
EXPECT_STREQ("abc def ghi", strs->data());
delete strs;
}
TEST(TestBuffer, TestAppend) {
Buffer buf;
buf.append("abc", 4);
EXPECT_EQ(4, buf.size());
EXPECT_STREQ("abc", buf.data());
EXPECT_EQ('b', buf[1]);
buf.append("def", 4);
EXPECT_EQ(8, buf.size());
EXPECT_EQ('a', buf[0]);
EXPECT_EQ('b', buf[1]);
EXPECT_EQ('c', buf[2]);
EXPECT_EQ('\0', buf[3]);
EXPECT_EQ('d', buf[4]);
EXPECT_EQ('e', buf[5]);
EXPECT_EQ('f', buf[6]);
EXPECT_EQ('\0', buf[7]);
}
TEST(TestBuffer, TestResize) {
Buffer buf;
buf.resize(10);
EXPECT_EQ(10, buf.capacity());
EXPECT_EQ('\0', buf.data()[10]);
}
TEST(TestBuffer, TestCopy) {
Buffer buf;
buf.resize(10);
EXPECT_EQ(10, buf.capacity());
Buffer buf2(buf);
EXPECT_EQ(0, buf2.size());
EXPECT_EQ(10, buf2.capacity());
buf2.append("abc", 4);
EXPECT_STREQ("abc", buf2.data());
EXPECT_EQ(10, buf2.capacity());
Buffer buf3(buf2);
EXPECT_EQ(4, buf3.size());
EXPECT_EQ(10, buf3.capacity());
EXPECT_STREQ("abc", buf3.data());
}
TEST(TestBuffer, TestPopFront) {
Buffer strs("abc def ghi");
EXPECT_STREQ("abc def ghi", strs.data());
Buffer *buf = strs.pop_front(4);
EXPECT_TRUE(buf != NULL);
EXPECT_STREQ("abc ", buf->data());
EXPECT_EQ(7, strs.size());
EXPECT_STREQ("def ghi", strs.data());
delete buf;
buf = strs.pop_front(strs.size());
EXPECT_EQ(0, strs.size());
EXPECT_STREQ("def ghi", buf->data());
}
TEST(TestBuffer, TestRemoveFront) {
Buffer strs("abc def ghi");
Buffer buf = strs.data();
EXPECT_STREQ("abc def ghi", buf.data());
buf.remove_front(4);
EXPECT_STREQ("def ghi", buf.data());
buf.remove_front(4);
EXPECT_STREQ("ghi", buf.data());
buf.remove_front(3);
EXPECT_STREQ("", buf.data());
}
TEST(TestBuffer, TestAssign) {
Buffer strs("abc def ghi");
strs = "jkl";
EXPECT_STREQ("jkl", strs.data());
std::vector<Buffer> v;
v.push_back(Buffer());
EXPECT_STREQ("", v.front().data());
}
TEST(TestBuffer, TestClear) {
Buffer strs("abc def ghi");
Buffer strs2 = strs;
EXPECT_EQ(2, strs.refcount());
strs2.clear();
EXPECT_EQ(11, strs.size());
EXPECT_EQ(1, strs.refcount());
EXPECT_EQ(1, strs2.refcount());
}
TEST(TestBuffer, TestHashset) {
std::unordered_set<Buffer, Buffer::Hasher> set;
Buffer buf("abc def ghi");
set.insert(buf);
EXPECT_EQ(1, set.size());
EXPECT_EQ(2, buf.refcount());
Buffer buf2("abc def ghi");
EXPECT_EQ(1, buf2.refcount());
std::unordered_set<Buffer, Buffer::Hasher>::iterator it = set.find(buf2);
EXPECT_EQ(2, it->refcount());
set.erase(it);
EXPECT_EQ(1, buf.refcount());
}
TEST(TestBuffer, TestHashmap) {
std::unordered_map<Buffer, int, Buffer::Hasher> int_by_topic;
std::unordered_set<Buffer, Buffer::Hasher> sub_topics;
Buffer *buf = new Buffer("abc");
EXPECT_EQ(1, buf->refcount());
Buffer& topic = *buf;
sub_topics.insert(topic);
EXPECT_EQ(2, topic.refcount());
int_by_topic[topic] = 1;
EXPECT_EQ(3, topic.refcount());
delete buf;
Buffer buf2("abc");
std::unordered_set<Buffer, Buffer::Hasher>::iterator it = sub_topics.find(buf2);
EXPECT_TRUE(it != sub_topics.end());
EXPECT_EQ(2, it->refcount());
//sub_topics.erase(it);
}
| [
"[email protected]"
] | |
3c5b26c205fd6ffa9bdcfc63390dda04829496e8 | 1994f421b057f39b9cfcfadda403a3bd9ae1fe8c | /poseidon/socket/abstract_socket.cpp | 92c82506f80ba887117bc80dbd63d941f3bfb9e7 | [
"BSD-3-Clause"
] | permissive | david123sw/poseidon | 29731c6e049b6fb0f026b3a53f8a52d834d61643 | 5edfe30ec99e373e11d76fc4386e564253edc587 | refs/heads/master | 2023-04-13T04:42:30.473976 | 2023-02-07T16:26:18 | 2023-02-07T16:28:21 | 70,473,560 | 1 | 0 | null | 2016-10-10T09:35:24 | 2016-10-10T09:35:24 | null | UTF-8 | C++ | false | false | 3,188 | cpp | // This file is part of Poseidon.
// Copyleft 2022 - 2023, LH_Mouse. All wrongs reserved.
#include "../precompiled.ipp"
#include "abstract_socket.hpp"
#include "../utils.hpp"
#include <sys/socket.h>
#include <fcntl.h>
namespace poseidon {
Abstract_Socket::
Abstract_Socket(unique_posix_fd&& fd)
{
// Take ownership the socket handle.
this->m_fd = ::std::move(fd);
if(!this->m_fd)
POSEIDON_THROW(("Null socket handle not valid"));
// Get the local address and address family.
::sockaddr_in6 addr;
::socklen_t addrlen = sizeof(addr);
if(::getsockname(this->fd(), (::sockaddr*) &addr, &addrlen) != 0)
POSEIDON_THROW((
"Could not get socket local address",
"[`getsockname()` failed: $1]"),
format_errno());
if((addr.sin6_family != AF_INET6) || (addrlen != sizeof(addr)))
POSEIDON_THROW((
"Addresss family unimplemented: family `$1`, addrlen `$2`"),
addr.sin6_family, addrlen);
this->m_sockname.set_addr(addr.sin6_addr);
this->m_sockname.set_port(be16toh(addr.sin6_port));
this->m_sockname_ready.store(true);
// Turn on non-blocking mode if it hasn't been enabled.
int fl_old = ::fcntl(this->fd(), F_GETFL);
if(fl_old == -1)
POSEIDON_THROW((
"Could not get socket flags",
"[`fcntl()` failed: $1]"),
format_errno());
int fl_new = fl_old | O_NONBLOCK;
if(fl_new != fl_old)
::fcntl(this->fd(), F_SETFL, fl_new);
this->m_state.store(socket_state_established);
}
Abstract_Socket::
Abstract_Socket(int type, int protocol)
{
// Create a non-blocking socket.
this->m_fd.reset(::socket(AF_INET6, type | SOCK_NONBLOCK, protocol));
if(!this->m_fd)
POSEIDON_THROW((
"Could not create IPv6 socket: type `$2`, protocol `$3`",
"[`socket()` failed: $1]"),
format_errno(), type, protocol);
this->m_state.store(socket_state_connecting);
}
Abstract_Socket::
~Abstract_Socket()
{
}
const Socket_Address&
Abstract_Socket::
local_address() const noexcept
{
if(this->m_sockname_ready.load())
return this->m_sockname;
// Try getting the address now.
static plain_mutex s_mutex;
plain_mutex::unique_lock lock(s_mutex);
if(this->m_sockname_ready.load())
return this->m_sockname;
::sockaddr_in6 addr;
::socklen_t addrlen = sizeof(addr);
if(::getsockname(this->fd(), (::sockaddr*) &addr, &addrlen) != 0)
return ipv6_unspecified;
ROCKET_ASSERT(addr.sin6_family == AF_INET6);
ROCKET_ASSERT(addrlen == sizeof(addr));
// Cache the address.
this->m_sockname.set_addr(addr.sin6_addr);
this->m_sockname.set_port(be16toh(addr.sin6_port));
this->m_sockname_ready.store(true);
return this->m_sockname;
}
bool
Abstract_Socket::
quick_shut_down() noexcept
{
this->m_state.store(socket_state_closed);
// Enable linger to request that any pending data be discarded.
::linger lng;
lng.l_onoff = 1;
lng.l_linger = 0;
::setsockopt(this->fd(), SOL_SOCKET, SO_LINGER, &lng, sizeof(lng));
return ::shutdown(this->fd(), SHUT_RDWR) == 0;
}
} // namespace poseidon
| [
"[email protected]"
] | |
81138c45e49df92ff57b148a9d565eef982f0801 | 72a3ce4880c23aa92f875f9f5cb4964dabb1cc96 | /stack/739.cpp | e8d52a5458b6216b3e3fbab66e88d09f589aa32e | [] | no_license | wzppengpeng/leetcode_solution | a06d9894b94c3598297ae8044cfe310fd30ce748 | 7c4b37b4bd224fea1ad42908592e8b2a01675d9a | refs/heads/master | 2021-06-06T01:11:36.165530 | 2019-12-08T15:37:28 | 2019-12-08T15:37:28 | 103,827,304 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,135 | cpp | /**
* Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
*/
/**
* 使用栈来保存目前最大的值,遍历到某个数时首先跟栈顶的元素比对,并更新结果
*/
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
vector<int> res(temperatures.size(), 0);
stack<pair<int, size_t>> st;
for(size_t i = 0; i < temperatures.size(); ++i) {
while(!st.empty() && temperatures[i] > st.top().first) {
auto& latest = st.top();
res[latest.second] = i - latest.second;
st.pop();
}
st.push({temperatures[i], i});
}
return res;
}
}; | [
"[email protected]"
] | |
7c306835d03f75bbcaccbea57568f0531ee00033 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_1482494_0/C++/Troy/b.cpp | 9b26d56ed7ff97755fcccda432047d0c11fdb791 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,721 | cpp | /*
* Author: Troy
* Created Time: 2012/4/28 10:05:51
* File Name: b.cpp
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <time.h>
#include <cctype>
#include <functional>
#include <deque>
#include <iomanip>
#include <bitset>
#include <assert.h>
#include <numeric>
#include <sstream>
#include <utility>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define all(a) (a).begin(),(a).end()
#define FOR(i,a,b) for (int i=(a);i<(b);i++)
#define FORD(i,a,b) for (int i=(a); i>=(b); i--)
#define REP(i,b) FOR(i,0,b)
#define sf scanf
#define pf printf
#define Maxn 1110
using namespace std;
const int maxint = -1u>>1;
const double pi = 3.14159265358979323;
const double eps = 1e-8;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<int>::iterator vit;
int n, now;
struct Level
{
int a, b, goal;
}d[Maxn];
int gettwo(int sum)
{
int mx = 0, ret = -1;
REP(i, n)
{
if (d[i].goal != 2 && d[i].b <= sum)
{
ret = i;
return ret;
}
}
return ret;
}
int getone(int sum)
{
int ret = -1, mx = 0;
REP(i, n)
if (d[i].goal == 0 && d[i].a <= sum)
{
//cout <<d[i].a <<" "<<mx <<" "<<ret <<endl;
if (d[i].b > mx)
{
ret = i;
mx = d[i].b;
}
}
return ret;
}
int main()
{
//freopen("B-small-attempt0.in", "r", stdin);
//freopen("B-small-attempt0.out", "w", stdout);
int T, ca = 0;
sf("%d", &T);
while (T--)
{
sf("%d", &n);
REP(i, n)
{
sf("%d%d", &d[i].a, &d[i].b);
d[i].goal = 0;
}
now = 0;
int ans = 0;
while (now < 2 * n)
{
int p1 = gettwo(now);
//cout <<p1 <<endl;
if (p1 != -1)
{
now += (d[p1].goal == 1 ? 1 : 2);
d[p1].goal = 2;
ans++;
continue;
}
int p2 = getone(now);
//cout <<p2 <<endl;
if (p2 == -1) break;
else
{
d[p2].goal = 1;
now++;
ans++;
continue;
}
}
if (now == 2 * n) pf("Case #%d: %d\n", ++ca, ans);
else pf("Case #%d: Too Bad\n", ++ca);
}
return 0;
}
| [
"[email protected]"
] | |
d2ac4479f2335fcb771f41646e48d1d70837edcc | 041dea11d127e81d6799976e5413600bba55e677 | /SimplyAUT_MotionController/SimplyAUT_MotionController/DialogFiles.cpp | 24de13ab1e41e27743656ef21bf7e40b44a1cc48 | [] | no_license | donkeithmitchell/SimplyAUT_MotionController | d5e5c7d3ca284fb28ac4c8db8a664dcb28e3ed7a | 43bc5fd8c45b2ae82931b83cc1f41e4b4ec3ea7c | refs/heads/master | 2022-09-06T17:31:08.183745 | 2020-05-25T18:33:24 | 2020-05-25T18:33:24 | 260,375,230 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,529 | cpp | // DialogStatus.cpp : implementation file
//
#include "pch.h"
#include "SimplyAUT_MotionController.h"
#include "DialogFiles.h"
#include "afxdialogex.h"
#include "resource.h"
const char* g_szTitle[] = { "#", "File", "Max Offset", "Avg Offset", NULL };
// CDialogFiles dialog
// this dialog is used to list the output files
IMPLEMENT_DYNAMIC(CDialogFiles, CDialogEx)
CDialogFiles::CDialogFiles(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_DIALOG_FILES, pParent)
{
m_pParent = NULL; // used to pass messagews to its parent
m_nMsg = 0;
m_bInit = FALSE;
m_bCheck = FALSE;
}
CDialogFiles::~CDialogFiles()
{
}
void CDialogFiles::Init(CWnd* pParent, UINT nMsg)
{
m_pParent = pParent;
m_nMsg = nMsg;
}
void CDialogFiles::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST_FILES, m_listFiles);
}
BEGIN_MESSAGE_MAP(CDialogFiles, CDialogEx)
ON_WM_SIZE()
END_MESSAGE_MAP()
// CDialogFiles message handlers
// CDialogFiles message handlers
BOOL CDialogFiles::OnInitDialog()
{
char buffer[MAX_PATH];
CRect rect;
CDialogEx::OnInitDialog();
// TODO: Add extra initialization here
m_bInit = TRUE;
// create a list control, and insert colums for the statistics of the files
LV_COLUMN listColumn;
listColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_SUBITEM;
listColumn.cx = 0;
listColumn.pszText = buffer;
for (int i = 0; g_szTitle[i] != NULL; ++i)
{
strncpy_s(buffer, g_szTitle[i], sizeof(buffer));
listColumn.iSubItem = i;
listColumn.fmt = (i == 0) ? LVCFMT_CENTER : LVCFMT_LEFT;
m_listFiles.InsertColumn(i, &listColumn);
}
PostMessage(WM_SIZE);
return TRUE; // return TRUE unless you set the focus to a control
}
// CDialogMotors message handlers
// this dialog is sized to a tab, and not the size that designed into
// thus, must locate the controls on Size
void CDialogFiles::OnSize(UINT nFlag, int cx, int cy)
{
CRect rect;
CDialogEx::OnSize(nFlag, cx, cy);
if (!m_bInit)
return;
GetClientRect(&rect);
cx = rect.Width();
cy = rect.Height();
m_listFiles.MoveWindow(2, 2, cx - 4, cy - 4);
m_listFiles.GetClientRect(&rect);
cx = rect.Width();
cy = rect.Height();
CDC* pDC = GetDC();
CSize sz1 = pDC->GetTextExtent("8888"); // assume that never exceeds 4 digits
CSize sz2 = pDC->GetTextExtent("Max Offset");
ReleaseDC(pDC);
m_listFiles.SetColumnWidth(0, sz1.cx);
m_listFiles.SetColumnWidth(1, cx - sz1.cx - 2*sz2.cx);
m_listFiles.SetColumnWidth(2, sz2.cx);
m_listFiles.SetColumnWidth(3, sz2.cx);
}
void CDialogFiles::Create(CWnd* pParent)
{
CDialogEx::Create(IDD_DIALOG_FILES, pParent);
ShowWindow(SW_HIDE);
}
// the files are File_XX.txt
// sort by XX
static int SortFileList(const void* e1, const void* e2)
{
const CString* file1 = (CString*)e1;
const CString* file2 = (CString*)e2;
int ind1 = file1->Find("_");
int ind2 = file2->Find("_");
int N1 = (ind1 == -1) ? 0 : atoi(file1->Mid(ind1 + 1));
int N2 = (ind2 == -1) ? 0 : atoi(file2->Mid(ind2 + 1));
return N1 - N2;
}
// get a list of all File_XX.txt files, and sort by XX
int CDialogFiles::GetFileList(CArray<CString, CString>& fileList)
{
char buffer[MAX_PATH];
CString path;
fileList.SetSize(0);
if (::SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, buffer) != S_OK)
return 0;
CFileFind find;
path.Format("%s\\SimplyAUTFiles\\*.txt", buffer);
if (!find.FindFile(path))
return 0;
int ret = 1;
for (int i = 0, j = 0; ret != 0; ++i)
{
ret = find.FindNextFileA();
CString szFile = find.GetFileName();
int ind = szFile.Find("File_");
if (ind != -1 )
fileList.Add(find.GetFilePath());
}
qsort(fileList.GetData(), fileList.GetSize(), sizeof(CString), ::SortFileList);
return (int)fileList.GetSize();
}
// for njow this is cheap and dirty
// on every new entry, remove all entries and build again
void CDialogFiles::UpdateFileList()
{
char buffer[MAX_PATH];
LV_ITEM listItem;
listItem.mask = LVIF_TEXT;
listItem.iSubItem = 0;
listItem.pszText = buffer;
listItem.cchTextMax = sizeof(buffer);
if (!IsWindow(m_listFiles.m_hWnd))
return;
CString szFile;
CArray<CString, CString> fileList;
char drive[_MAX_DRIVE];
char path[_MAX_PATH];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
m_listFiles.DeleteAllItems();
int len = GetFileList(fileList);
if (len == 0)
return;
for( int i = 0, j=0; i < len; ++i)
{
::_splitpath_s(fileList[i], drive, _MAX_DRIVE, path, _MAX_PATH, fname, _MAX_FNAME, ext, _MAX_EXT);
szFile.Format("%s%s", fname, ext);
int ind = szFile.Find("File_");
if (ind == -1)
continue;
int nFileNum = atoi(szFile.Mid(ind + 5));
listItem.iItem = j;
sprintf_s(buffer, sizeof(buffer), "%d", nFileNum);
m_listFiles.InsertItem(&listItem);
strncpy_s(buffer, szFile, sizeof(buffer));
m_listFiles.SetItemText(j, 1, buffer);
FILE* fp = NULL;
if (fopen_s(&fp, fileList[i], "r") == 0 && fp != NULL)
{
int pos;
double capH, capW, HiLo, offset;
fgets(buffer, sizeof(buffer), fp);
double maxOff = 0;
double sum = 0;
int cnt = 0;
while (fgets(buffer, sizeof(buffer), fp))
{
sscanf_s(buffer, "%d\t%lf\t%lf\t%lf\t%lf\n", &pos, &capH, &capW, &HiLo, &offset);
maxOff = max(maxOff, fabs(offset));
sum += fabs(offset);
cnt++;
}
sprintf_s(buffer, sizeof(buffer), "%5.1f", maxOff);
m_listFiles.SetItemText(j, 2, buffer);
sprintf_s(buffer, sizeof(buffer), "%5.2f", cnt ? sum/cnt : 0);
m_listFiles.SetItemText(j, 3, buffer);
j++;
fclose(fp);
}
}
}
void CDialogFiles::EnableControls()
{
UpdateFileList();
}
| [
"dmitchell@TDEWS123"
] | dmitchell@TDEWS123 |
d9c4aa457a56ed59764fc446a62bc6363d5ae2b3 | 8141ef14afe62f0d9d992726ef35b0cd713c47f4 | /boost-graph/boost-graph/Kruskal.h | 85c211e1b82434386a7d999d694352c0248c2df9 | [] | no_license | YBelikov/boost-graph | 05966c91c3e2e3f635aebf141f1da8781957dfdc | 42b24fc9fbacf5d96aea71739588ba363c4c5002 | refs/heads/master | 2023-08-03T09:12:27.949561 | 2023-07-21T15:27:52 | 2023-07-21T15:27:52 | 240,084,966 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 190 | h | #pragma once
template<typename Graph, typename OutputEdgeIterator, typename WeightMap>
void kruskalSpanningTree(const Graph& graph, OutputEdgeIterator outputIterator, WeightMap weights) {
} | [
"[email protected]"
] | |
e2c9a43ed8ddea520edb2b8d3bd7835d4f383cc0 | 187b9278a8122bd7ac0a26932e476b2cf7171492 | /TFMEngine/src/GPU/texture/GPUTexture1D.cpp | 70bac61ba1d33b200edaf94c071b2b0c6acc1c18 | [] | no_license | Graphics-Physics-Libraries/RenderLibrary | b0b7a1fe23b7d1553886d1a8783f49a2d83ed593 | 83cb99f269853f8311111c011face5c101eb6cd3 | refs/heads/master | 2020-07-14T16:53:18.939002 | 2019-01-31T09:12:23 | 2019-01-31T09:12:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 869 | cpp | #include "GPU/texture/GPUTexture1D.h"
namespace RenderLib
{
namespace GPU
{
namespace Texture
{
GPUTexture1D::GPUTexture1D() : GPUTexture()
{
}
GPUTexture1D::~GPUTexture1D()
{
}
GLenum
GPUTexture1D::getTexturType()
{
return GL_TEXTURE_1D;
}
void
GPUTexture1D::uploadMutable(void * data)
{
glTexImage1D(GL_TEXTURE_1D, 0, config.internalFormat, width, 0,
config.format, config.pixelType, data);
}
void
GPUTexture1D::uploadInmutable(void * data)
{
glTexStorage1D(GL_TEXTURE_1D, 1, config.internalFormat, width);
glTexSubImage1D(GL_TEXTURE_1D, 0, 0, width, config.format,
config.pixelType, data);
}
} // namespace Texture
} // namespace GPU
} // namespace RenderLib | [
"[email protected]"
] | |
a9e2dd352646413730507b538e22e5d83f1368a7 | 78f48025d3eea984744557704349ca3a2bc5c34b | /Week8_BinarySearch/Powxn.cpp | 748c8734df398157ab98a199252f75b4986d8b1b | [] | no_license | yyhe/CodingPractise | 33b7da5aa664837cb55e9aa92de2c1e47d3b889b | 0db49a85933e80b6215f494993a6994d82846d1a | refs/heads/master | 2020-09-12T12:48:15.326299 | 2020-01-06T16:18:48 | 2020-01-06T16:18:48 | 222,430,848 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 589 | cpp | class Solution {
public:
double myPow(double x, int n) {
if (n < 0)
{
return 1.0 / myPow(x, -(n + 1)) / x;
}
else if (n == 0)
{
return 1;
}
else if (n == 1)
{
return x;
}
else if (n == -1)
{
return 1 / x;
}
else if (n & 1)
{
double mid = myPow(x, n / 2);
return mid * mid * x;
}
else
{
double mid = myPow(x, n / 2);
return mid * mid;
}
}
};
| [
"[email protected]"
] | |
52522928f3947ece5af6e7451c504ed357d79d09 | 710f7d2951c7af722d8e8ea896c5e6733e155860 | /zGameServer_X/GameServer/MuLua.h | d060c039fbe2c22842d021002cb69c24142575fc | [] | no_license | lnsurgent/X-MU_Community_Server | 5cda542a5cbd6d73ade156ca8354eeab2909da91 | e576e30a0222789b2d02506569e5b435dd696e2f | refs/heads/master | 2016-09-06T07:50:10.870481 | 2016-02-11T06:56:20 | 2016-02-11T06:56:20 | 29,187,243 | 12 | 8 | null | 2015-01-18T15:23:14 | 2015-01-13T11:40:29 | C++ | UTF-8 | C++ | false | false | 579 | h | // ------------------------------
// Decompiled by Hybrid
// 1.01.00
// ------------------------------
#pragma once
#include "../Lua/include/lua.hpp"
class MULua
{
public:
MULua(void);
~MULua(void);
private:
bool Create();
public:
void Release();
bool DoFile(const char* szFileName);
bool DoFile(lua_State* L, const char* szFileName);
bool DoString(std::string kString);
lua_State* GetLua();
void Register(void* pLua);
void CreateWinConsole(HINSTANCE hInstance);
void DestroyWinConsole();
private:
lua_State* m_luaState;
};
extern MULua g_MuLuaQuestExp; | [
"[email protected]"
] | |
02e89b92f7ea9806316170ee159113cd90cf3af2 | 4c5786fbbd690250feb5372072f3341bcb39a49d | /NewPlatform/ServerModule/GameServer/InitParameter.cpp | 496df14dd50d033816866a5ff90b770cd4391918 | [] | no_license | toowind/CyzGitRepository | d96244139865ccc6fbf0db359ebf85f5d86a80e9 | bcdc1f69d7ac3e714771ae67aad37e780ef2dfc3 | refs/heads/master | 2021-01-21T12:20:44.205211 | 2017-04-01T03:55:41 | 2017-04-01T03:55:41 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,416 | cpp | #include "StdAfx.h"
#include "InitParameter.h"
//////////////////////////////////////////////////////////////////////////////////
//时间定义
#define TIME_CONNECT 30 //重连时间
#define TIME_COLLECT 30 //统计时间
//客户时间
#define TIME_INTERMIT 0 //中断时间
#define TIME_ONLINE_COUNT 600 //人数时间
//////////////////////////////////////////////////////////////////////////////////
//构造函数
CInitParameter::CInitParameter()
{
InitParameter();
}
//析构函数
CInitParameter::~CInitParameter()
{
}
//初始化
VOID CInitParameter::InitParameter()
{
//时间定义
m_wConnectTime=TIME_CONNECT;
m_wCollectTime=TIME_COLLECT;
//协调信息
m_wCorrespondPort=PORT_CENTER;
ZeroMemory(&m_CorrespondAddress,sizeof(m_CorrespondAddress));
//配置信息
ZeroMemory(m_szServerName,sizeof(m_szServerName));
ZeroMemory(&m_ServiceAddress,sizeof(m_ServiceAddress));
ZeroMemory(&m_TreasureDBParameter,sizeof(m_TreasureDBParameter));
ZeroMemory(&m_PlatformDBParameter,sizeof(m_PlatformDBParameter));
return;
}
//加载配置
VOID CInitParameter::LoadInitParameter()
{
//重置参数
InitParameter();
//获取路径
TCHAR szWorkDir[MAX_PATH]=TEXT("");
CWHService::GetWorkDirectory(szWorkDir,CountArray(szWorkDir));
//构造路径
TCHAR szIniFile[MAX_PATH]=TEXT("");
_sntprintf(szIniFile,CountArray(szIniFile),TEXT("%s\\ServerParameter.ini"),szWorkDir);
//读取配置
CWHIniData IniData;
IniData.SetIniFilePath(szIniFile);
//读取配置
IniData.ReadEncryptString(TEXT("ServerInfo"),TEXT("ServiceName"),NULL,m_szServerName,CountArray(m_szServerName));
IniData.ReadEncryptString(TEXT("ServerInfo"),TEXT("ServiceAddr"),NULL,m_ServiceAddress.szAddress,CountArray(m_ServiceAddress.szAddress));
//协调信息
m_wCorrespondPort=IniData.ReadInt(TEXT("Correspond"),TEXT("ServicePort"),m_wCorrespondPort);
IniData.ReadEncryptString(TEXT("ServerInfo"),TEXT("CorrespondAddr"),NULL,m_CorrespondAddress.szAddress,CountArray(m_CorrespondAddress.szAddress));
//连接信息
m_TreasureDBParameter.wDataBasePort=(WORD)IniData.ReadInt(TEXT("TreasureDB"),TEXT("DBPort"),1433);
IniData.ReadEncryptString(TEXT("TreasureDB"),TEXT("DBAddr"),NULL,m_TreasureDBParameter.szDataBaseAddr,CountArray(m_TreasureDBParameter.szDataBaseAddr));
IniData.ReadEncryptString(TEXT("TreasureDB"),TEXT("DBUser"),NULL,m_TreasureDBParameter.szDataBaseUser,CountArray(m_TreasureDBParameter.szDataBaseUser));
IniData.ReadEncryptString(TEXT("TreasureDB"),TEXT("DBPass"),NULL,m_TreasureDBParameter.szDataBasePass,CountArray(m_TreasureDBParameter.szDataBasePass));
IniData.ReadEncryptString(TEXT("TreasureDB"),TEXT("DBName"),szTreasureDB,m_TreasureDBParameter.szDataBaseName,CountArray(m_TreasureDBParameter.szDataBaseName));
//连接信息
m_PlatformDBParameter.wDataBasePort=(WORD)IniData.ReadInt(TEXT("PlatformDB"),TEXT("DBPort"),1433);
IniData.ReadEncryptString(TEXT("PlatformDB"),TEXT("DBAddr"),NULL,m_PlatformDBParameter.szDataBaseAddr,CountArray(m_PlatformDBParameter.szDataBaseAddr));
IniData.ReadEncryptString(TEXT("PlatformDB"),TEXT("DBUser"),NULL,m_PlatformDBParameter.szDataBaseUser,CountArray(m_PlatformDBParameter.szDataBaseUser));
IniData.ReadEncryptString(TEXT("PlatformDB"),TEXT("DBPass"),NULL,m_PlatformDBParameter.szDataBasePass,CountArray(m_PlatformDBParameter.szDataBasePass));
IniData.ReadEncryptString(TEXT("PlatformDB"),TEXT("DBName"),szPlatformDB,m_PlatformDBParameter.szDataBaseName,CountArray(m_PlatformDBParameter.szDataBaseName));
//连接信息
m_UserCustomDBParameter.wDataBasePort = (WORD)IniData.ReadInt(TEXT("UserCustomDB"), TEXT("DBPort"), 1433);
IniData.ReadEncryptString(TEXT("UserCustomDB"), TEXT("DBAddr"), NULL, m_UserCustomDBParameter.szDataBaseAddr, CountArray(m_UserCustomDBParameter.szDataBaseAddr));
IniData.ReadEncryptString(TEXT("UserCustomDB"), TEXT("DBUser"), NULL, m_UserCustomDBParameter.szDataBaseUser, CountArray(m_UserCustomDBParameter.szDataBaseUser));
IniData.ReadEncryptString(TEXT("UserCustomDB"), TEXT("DBPass"), NULL, m_UserCustomDBParameter.szDataBasePass, CountArray(m_UserCustomDBParameter.szDataBasePass));
IniData.ReadEncryptString(TEXT("UserCustomDB"), TEXT("DBName"), szUserCustomDB, m_UserCustomDBParameter.szDataBaseName, CountArray(m_UserCustomDBParameter.szDataBaseName));
return;
}
//////////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
] | |
9a5750ab9c339204e0012444f1f658d640d29396 | 0dbdf1fc2b207072da5887466f5da1a258722506 | /Laboratoriniai/S1 laborai/L1antra-22/L1antra-2/L1antra-2/L1antra-2.cpp | 9fd9eddc8cc273ca69c3a9a2443e210d3cc9d974 | [] | no_license | petkus09/KTU-Cplusplus | ff483c256c2a244fb04a75662e5023da634ce09b | 2a5b24d800a107c95d69285b1bcfedacfe82c3b3 | refs/heads/master | 2016-09-06T15:12:44.945986 | 2013-08-20T19:07:30 | 2013-08-20T19:07:30 | null | 0 | 0 | null | null | null | null | ISO-8859-13 | C++ | false | false | 423 | cpp | #include <iostream>
using namespace std;
int main()
{
setlocale (LC_ALL, "Lithuanian");
double pi = 3.1415;
double H;
double R, r;
double V;
cout << "Įveskite kūgio aukštinės reikšmę:" << endl;
cin >> H;
cout << "Įveskite kūgio pagrindų spindulių reikšmes:" << endl;
cin >> R >> r;
V = (1.0 / 3) * pi * H * (R * R + R * r + r * r);
cout << "Kūgio tūris = " << V << endl;
return 0;
} | [
"[email protected]#"
] | |
75fa7f28abd67166ce58a1e05fa532cae050a9f2 | bdcd0020d1159e23894a2e0f0fbb679ec14736d6 | /src/graphs/dijkstra-III.cpp | f6f2e227e1e6777b9045e54989288465b0e7e222 | [] | no_license | joseraulperezrodriguez/algorithms-and-datastructures | 6e9f8c1233c3e38477d92c6b615c0e7231a007b7 | e69503dcd41e2d82139726ea4e5bf974f0f6227b | refs/heads/master | 2020-03-26T20:13:08.506668 | 2019-09-14T21:58:28 | 2019-09-14T21:58:28 | 145,311,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,420 | cpp | /*
koder : melkor
TASK : Dijkstra's Single-Source Shortst-Paths Algorithm
Running time: O(E log V)
*/
#include <cstdio>
#include <set>
#include <bits/stdc++.h>
using namespace std;
#define MAXV 50000
#define MAXE 100000
#define oo 1000000000
typedef pair< int, int > pii;
struct edge {
int v, w, next;
} edges[MAXE];
int V, edge_count, source;
int u, v, w, dist;
int p[MAXV], d[MAXV];
int main() {
freopen( "in.txt", "r", stdin );
freopen( "out.txt", "w", stdout );
memset( p, -1, sizeof( p ) );
scanf( "%d %d %d", &V, &edge_count, &source );
for ( int i = 0; i < edge_count; i++ ) {
scanf( "%d %d %d", &u, &v, &w );
u--; v--;
edges[i] = ( edge ) { v, w, p[u] };
p[u] = i;
}
/* Dijkstra's Algorithm */
set< pii > S;
for ( int i = 0; i < V; i++ )
d[i] = oo;
d[ --source ] = 0;
S.insert( make_pair( 0, source ) );
for ( int i = 0; i < V; i++ ) {
pii top = *S.begin();
S.erase( S.begin() );
u = top.second;
dist = top.first;
for ( int i = p[u]; i != -1; i = edges[i].next ) {
v = edges[i].v; w = edges[i].w;
if ( d[u] + w < d[v] ) {
if ( d[v] != oo )
S.erase( S.find( make_pair( d[v], v ) ) );
d[v] = d[u] + w;
S.insert( make_pair( d[v], v ) );
}
}
}
return 0;
}//melkor
| [
"[email protected]"
] | |
6ef27bdb63581208e25b3c2564507481df2d5641 | b832bc78ebdc57f127ecc58c1ad1479a2244a603 | /include/core/Config.hpp | 18144a8dd0d2e5d98ca73d0048277bfc315135de | [
"MIT"
] | permissive | TerensTare/tnt | a25d3bda795b1693cae66ecc2ee785ae1aa9d541 | 916067a9bf697101afb1d0785112aa34014e8126 | refs/heads/master | 2023-04-08T23:06:53.972084 | 2021-04-20T12:56:23 | 2021-04-20T12:56:23 | 238,545,192 | 35 | 9 | MIT | 2020-09-03T03:14:33 | 2020-02-05T20:46:22 | C++ | UTF-8 | C++ | false | false | 718 | hpp | #ifndef CONFIG_HPP
#define CONFIG_HPP
#ifndef DOXYGEN_SHOULD_SKIP_THIS
// clang-format off
# if defined(_MSC_VER) && !defined(__clang__)
# ifdef TNT_BUILD
# define TNT_API __declspec(dllexport)
# define TNT_EXPORT
# else
//disable warnings on extern before template instantiation
# define TNT_API __declspec(dllimport)
# define TNT_EXPORT extern
# endif //!TNT_BUILD_DLL
# elif defined(__GNUC__) || (defined(__clang__) && !defined(_MSC_VER))
# ifdef TNT_BUILD
# define TNT_API __attribute__((visibility("default")))
# define TNT_EXPORT
# else
# define TNT_API
# define TNT_EXPORT
# endif
# endif //!_MSC_VER
// clang-format on
#endif
#endif //!CONFIG_HPP | [
"[email protected]"
] | |
28887d0027842d64e89670153dbcaafca7649c30 | 3802c1706af3287ace2351bee0d49689f1f3e362 | /AshIDE/SettingsWindow.h | dce5c76f4c1234066f1b145d76fd67ff0f2a1b4a | [] | no_license | bjackson/LC3Tools | 6114560fc3421184151e5ea25c6b41dbee38dc97 | ecf35b883e82891460d45264cdb3a1e4996c72d0 | refs/heads/master | 2021-01-16T20:55:56.899035 | 2016-04-22T21:28:00 | 2016-04-22T21:28:00 | 56,454,202 | 0 | 0 | null | 2016-04-17T19:25:35 | 2016-04-17T19:25:35 | null | UTF-8 | C++ | false | false | 3,206 | h | // Copyright 2003 Ashley Wise
// University Of Illinois Urbana-Champaign
// [email protected]
#ifndef SETTINGSWINDOW_H
#define SETTINGSWINDOW_H
#pragma warning (disable:4786)
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Return_Button.H>
#include <FL/Fl_Choice.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Input.H>
#include "../Assembler/Base.h"
#include "Project.h"
using namespace std;
using namespace JMT;
namespace AshIDE
{
class SettingsWindow : public Fl_Group
{
protected:
friend class MainWindow;
//Widgets for the project settings
Fl_Group *pSettings;
Fl_Group *pProjectSettings;
Fl_Check_Button *pProjectSetting[NUM_PROJECT_SETTINGS];
Fl_Group *pFileSettings;
Fl_Button *pDefineAddDlg, *pDefineRemove;
Fl_Choice *pDefines;
Fl_Button *pAssemble, *pBuild, *pSimulate;
//Widgets for the file settings
Fl_Check_Button *pFileSetting[NUM_PROJECT_FILE_SETTINGS];
Fl_Choice *pLanguage;
Fl_Choice *pSourceType;
Fl_Button *pAssembleFile;
//Widgets for the pre-processor define dialog
Fl_Window *pDefineDlg;
Fl_Input *pDefineIdentifier, *pDefineValue;
Fl_Return_Button *pDefineAdd;
Fl_Button *pDefineCancel;
public:
/**********************************************************************\
SettingsWindow( [in] x, [in] y, [in] width, [in] height )
Constructs the message window.
This window only displays text, there is no editing.
\******/
SettingsWindow(int, int, int, int);
/**********************************************************************\
~SettingsWindow( )
Destructor
\******/
virtual ~SettingsWindow();
//*** Project Settings Management Functions ***//
/**********************************************************************\
InitProjectSettings( )
Initializes the project settings based on the current project.
\******/
bool InitProjectSettings();
static void ProjectSettingCB(Fl_Widget *pW, void *pV) { TheProject.SetSetting((Project::SettingEnum)(unsigned int)pV, ((Fl_Button *)pW)->value() != 0); }
static void DefineAddDlgCB(Fl_Widget *pW, void *pV);
bool DefineAddDlg();
static void DefineRemoveCB(Fl_Widget *pW, void *pV) { ((SettingsWindow *)pV)->DefineRemove(); }
bool DefineRemove();
static void DefineAddCB(Fl_Widget *pW, void *pV) { ((SettingsWindow *)pV)->DefineAdd(); }
bool DefineAdd();
static void DefineCancelCB(Fl_Widget *pW, void *pV) { ((SettingsWindow *)pV)->DefineCancel(); }
bool DefineCancel();
//*** File Settings Management Functions ***//
/**********************************************************************\
InitFileSettings( )
Initializes the file settings based on the current file in the current project.
\******/
bool InitFileSettings();
static void FileSettingCB(Fl_Widget *pW, void *pV) { if(TheProject.pFile) TheProject.pFile->SetSetting((Project::FileData::FileSettingEnum)(unsigned int)pV, ((Fl_Button *)pW)->value() != 0); }
static void LanguageCB(Fl_Widget *pW, void *pV) { ((SettingsWindow *)pV)->Language(); }
bool Language();
static void SourceTypeCB(Fl_Widget *pW, void *pV) { ((SettingsWindow *)pV)->SourceType(); }
bool SourceType();
};
}
#endif
| [
"[email protected]"
] | |
1ae3a5272cb4ce56afbab00c8deee65962916adf | b4fe6f4a6e4059563d4e158eca4e2da46aca36ed | /Project_C/Project_C/Project_C.cpp | c548a9512af9a4c196c23ac89f0bda39737e78ac | [] | no_license | aliyazdi75/Cells_Life | 71da1b9591337238805783d8d04afda707f88f24 | 195eafe0d65410d60e9935a6547f7f75aefeab7e | refs/heads/master | 2021-01-11T19:29:46.158535 | 2017-01-18T20:02:51 | 2017-01-18T20:02:51 | 79,379,542 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,075 | cpp | unsigned char Energy_Cell_harif[100][100];
int psn_of_Cell_harif[15][15];
#include "Cells.h"
#include "Multi_Player.h"
void clrscr();
void gotoxy(int x, int y);
int randn(int m, int n);
void print_square(int x, int y, int k);
int Print_Screen(void);
int Update_Screen();
int Load_map();
int move_cell(int d, int b, int c);
int save_game();
int Allowed_block();
int split_cell();
int boost_energy();
int show_MoveMenu();
int show_MainMenu();
int select_cell();
int show_Menu();
int Load_menu_map();
int New_Game();
int Map_Editor();
int move_cell_harif(int d, int xm, int ym);
int boost_energy_in_multi();
int show_MoveMenu_in_multi();
int show_MainMenu_in_multi();
int select_cell_in_multi();
int show_Menu_in_multi();
int paly_multi_player();
int main(void) {
//Final Project
a: srand(time(NULL));
int i, j, k;
char c;
clrscr();
gotoxy(0, 0);
for (j = 0;j < 4 * fs.height + 6;j++) {
for (i = 0;i < 60;i++)
printf(" ");
printf("\n");
}
gotoxy(0, 0);
printf("[1] Load\n[2] New single player game\n[3] New Multiplayer game\n[4] Map Editor\n[5] Exit\n");
b: c = getch();
if (c == 49) { //Load
clrscr();
k = Load_menu_map();
clrscr();
if (k == -1)
goto a;
}
else if (c == 50) { //New single player game
clrscr();
printf("Enter cells number: ");
scanf("%d", &xn);
clrscr();
k = New_Game();
if (k == -1)
goto a;
}
else if (c == 51) { //New Multiplayer game
clrscr();
q++;
k = paly_multi_player();
clrscr();
if (k == -1)
goto a;
}
else if (c == 52) { //Map Editor
k = Map_Editor();
clrscr();
if (k == -1)
goto a;
}
else if (c == 53) {//Exit
exit(0);
}
else {
goto b;
}
return 0;
}
int Load_map() {
int i, j, k, a, b;
char c, inname[30];
FILE *fp;
clrscr();
gotoxy(0, 0);
printf("How:\n[1] Text\n[2] Binary");
a: c = getch();
if (c == 49) { //Text
clrscr();
gotoxy(0, 0);
printf("Enter Your Map Name To Open (WITH NO FORMAT): ");
scanf("%s", inname);
strcat(inname, ".txt");
fp = fopen(inname, "r+");
if (fp == NULL) {
clrscr();
printf("Cannot open file, Try again with Enter!\n");
getch();
return -1;
}
clrscr();
fgets(arr, 50, fp);
fscanf(fp, "[%d*%d]", &fs.width, &fs.height);
for (j = fs.height - 1;j >= 0;j--)
for (i = fs.width - 1;i >= 0;i--)
psn_of_Cell[j][i] = -1;
for (j = fs.height - 1;j >= 0;j--)
for (i = fs.width - 1;i >= 0;i--)
psn_of_Cell_harif[j][i] = -1;
fgets(arr, 50, fp);
fgets(arr, 50, fp);
fgets(arr, 50, fp);
for (i = 0;i < fs.width;i++) {
for (j = fs.height - 1;j >= 0;j--) {
for (k = 0;k < 10;k++)
arr2[k] = 0;
a = fs.height - j - 1;
fscanf(fp, "[(%d,%d) = %d, %s", &i, &j, &Energy_Cell[a][i * 4], arr2);
if (strcmp(arr2, "Source]") == 0)
Block_Cell[a][i] = '1';
else if (strcmp(arr2, "Split]") == 0)
Block_Cell[a][i] = '2';
else if (strcmp(arr2, "Wall]") == 0)
Block_Cell[a][i] = '3';
else if (strcmp(arr2, "Normal]") == 0)
Block_Cell[a][i] = '4';
fgets(arr, 50, fp);
}
}
fgets(arr, 50, fp);
fscanf(fp, "%d", &x1);
fgets(arr, 50, fp);
fgets(arr, 60, fp);
for (k = 0;k < x1;k++) {
fscanf(fp, "[(%d,%d", &i, &j);
fscanf(fp, ") = %d]", &psn_of_Cell[j][i]);
fgets(arr, 50, fp);
}
fclose(fp);
}
else if (c == 50) { //Binary
clrscr();
gotoxy(0, 0);
printf("Enter Your Map Name To Open (WITH NO FORMAT): ");
scanf("%s", inname);
strcat(inname, ".bin");
fp = fopen(inname, "r+b");
if (fp == NULL) {
clrscr();
printf("Cannot open file, Try again with Enter!\n");
getch();
return -1;
}
clrscr();
fread(&fs, sizeof(fs), 1, fp);
for (j = fs.height - 1;j >= 0;j--)
for (i = fs.width - 1;i >= 0;i--)
psn_of_Cell[j][i] = -1;
for (j = fs.height - 1;j >= 0;j--)
for (i = fs.width - 1;i >= 0;i--)
psn_of_Cell_harif[j][i] = -1;
for (i = 0;i < fs.width;i++) {
for (j = fs.height - 1;j >= 0;j--) {
a = fs.height - 1 - j;
fread(&Energy_Cell[a][i * 4], 4, 1, fp);
fread(&Block_Cell[a][i], 1, 1, fp);
}
}
fread(&x1, sizeof(int), 1, fp);
for (i = 0;i < fs.width;i++) {
for (j = fs.height - 1;j >= 0;j--) {
fread(&psn_of_Cell[j][i], sizeof(int), 1, fp);
}
}
fclose(fp);
}
else {
goto a;
}
if (xn < x1 && xn != 0) {
return -2;
}
if (x1 > 1 && xn == 0 && q == 1)
return 0;
Update_Screen();
return 0;
}
int show_Menu() {
a: char c;
int i, j;
gotoxy(0, fs.height * 4 + 4);
printf("[1] Select a cell\n[2] Save\n[3] Return\n");
b: c = getch();
if (c == 49) { //Select a cell
select_cell();
goto a;
}
else if (c == 50) { //Save
save_game();
goto a;
}
else if (c == 51) { //Return
return -1;
}
else {
goto b;
}
return 0;
}
int Load_menu_map() {
int k;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
k = Load_map();
if (k == -1)
return -1;
SetConsoleTextAttribute(hConsole, 15);
gotoxy(0, fs.height * 4 + 4);
k = show_Menu();
if (k == -1)
return -1;
return 0;
}
int New_Game() {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
int i, j, k, a, b;
char c;
clrscr();
gotoxy(0, 0);
printf("Which Map:\n[1] Defult Map\n[2] My Selction Map");
a: c = getch();
if (c == 49) {
fs.width = 4;
fs.height = 4;
for (j = fs.height - 1;j >= 0;j--)
for (i = fs.width - 1;i >= 0;i--)
psn_of_Cell[j][i] = -1;
Energy_Cell[0][0] = 30;
Energy_Cell[1][4] = 60;
Energy_Cell[2][8] = 90;
Energy_Cell[3][8] = 45;
Energy_Cell[3][12] = 20;
Block_Cell[0][0] = '1';
Block_Cell[0][1] = '4';
Block_Cell[0][2] = '4';
Block_Cell[0][3] = '2';
Block_Cell[1][0] = '2';
Block_Cell[1][1] = '1';
Block_Cell[1][2] = '4';
Block_Cell[1][3] = '2';
Block_Cell[2][0] = '2';
Block_Cell[2][1] = '2';
Block_Cell[2][2] = '1';
Block_Cell[2][3] = '4';
Block_Cell[3][0] = '3';
Block_Cell[3][1] = '3';
Block_Cell[3][2] = '1';
Block_Cell[3][3] = '1';
for (j = fs.height - 1;j >= 0;j--)
for (i = fs.width - 1;i >= 0;i--)
psn_of_Cell_harif[j][i] = -1;
}
else if (c == 50) {
k = Load_map();
if (k == -1)
return -1;
if (k == -2) {
clrscr();
printf("Your cell number is less than your selection map's cells, Try again with more cell number by Enter!");
getch();
return -1;
}
}
else {
goto a;
}
if (xn < fs.height*fs.width - cnt_wall) {
for (k = x1;k < xn;k++) {
b: a = fs.height - randn(0, fs.height) - 1;
b = randn(0, fs.width);
if (Block_Cell[a][b] == '3' || psn_of_Cell[fs.height - 1 - a][b] == 0)
goto b;
else {
psn_of_Cell[fs.height - 1 - a][b] = 0;
if (b % 2 == 0) {
SetConsoleTextAttribute(hConsole, 14);
gotoxy(b * 7 + 3, a * 4 + 2);
printf("X");
}
else {
SetConsoleTextAttribute(hConsole, 14);
gotoxy(b * 7 + 3, a * 4 + 4);
printf("X");
}
}
}
Update_Screen();
SetConsoleTextAttribute(hConsole, 15);
gotoxy(0, fs.height * 4 + 4);
k = show_Menu();
if (k == -1)
return -1;
}
else {
SetConsoleTextAttribute(hConsole, 15);
clrscr();
printf("Please select a correct number!");
return -1;
}
return 0;
}
//What to do :
| [
"[email protected]"
] | |
c57a23757a0041e67185c40ca383d3a1fb62215e | 0f281a124dc184d3facac4320e568188d027089a | /sp5/Queue.cpp | dcd4f3824f8143f7449fe3ddab87ded494f8dde5 | [] | no_license | tonussi/so | b0feb8b050b3c65f0b3e6a1c532cd122721504e0 | 8b66193c4988d04636a1c2a11f528288004d2496 | refs/heads/master | 2021-01-17T02:31:20.450476 | 2016-10-11T11:25:41 | 2016-10-11T11:25:41 | 54,274,846 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 332 | cpp | /*
* File: Queue.cpp
* Author: <preencher>
*
* Created on September 27, 2015, 11:28 AM
*/
#include "Queue.h"
template <class T> Queue<T>::Queue() : std::list<T>() {
}
template <class T> Queue<T>::Queue(const Queue& orig) : std::list<T>(orig) {
}
template <class T> Queue<T>::~Queue() {
}
// INSERT YOUR CODE HERE
// ...
| [
"[email protected]"
] | |
9e70fb57a20d1083b0e7822308d8f9661f4a41dd | 7b6dfaa5015385a3ed0c98471c382eb3e8586b72 | /mp7/dsets.h | 4a2b7b48ea32b8576dd95a5d9996100eae8940d8 | [] | no_license | wsun26/cs225 | d33106d3cab4a77f693bdd4ff9e084058421fcfe | a097a8751a6522ff864794af2da059d3127f4a69 | refs/heads/master | 2020-05-14T12:08:23.679514 | 2019-04-17T00:42:18 | 2019-04-17T00:42:18 | 181,788,451 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 280 | h | /* Your code here! */
#ifndef DSETS
#define DSETS
#include <vector>
using namespace std;
class DisjointSets
{
public:
void addelements(int num);
int find(int elem);
void setunion(int a, int b);
int operator[](int elem);
private:
vector<int> nodes;
};
#endif
| [
"[email protected]"
] | |
baba375399a6aeaf496fdc28e53fc55b6400e143 | fd42310229173b2e1c64fb5c27d7729664f3be2e | /Homeworks/Hw3/src/patron.cpp | ffe8632af5425510bd8d3467fc2ddd9786a21e8c | [] | no_license | quantumlycharmed/UNT | 29d7842b9331a10cced25d1ba574fb057a43f504 | efafa40e0f73b680042e4c481a1ec5573ac86264 | refs/heads/main | 2023-04-05T13:44:56.395719 | 2021-03-31T18:03:37 | 2021-03-31T18:03:37 | 353,447,484 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19 | cpp | #include "patron.h" | [
"[email protected]"
] | |
ee4bd505cadbda86e99115efd4662cd31acda0c7 | 60bb67415a192d0c421719de7822c1819d5ba7ac | /blazetest/src/mathtest/dmatsmatschur/DDbMIb.cpp | 84bbdd5742aa28e7a0b26a792ff2fcff0cf67cd1 | [
"BSD-3-Clause"
] | permissive | rtohid/blaze | 48decd51395d912730add9bc0d19e617ecae8624 | 7852d9e22aeb89b907cb878c28d6ca75e5528431 | refs/heads/master | 2020-04-16T16:48:03.915504 | 2018-12-19T20:29:42 | 2018-12-19T20:29:42 | 165,750,036 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,994 | cpp | //=================================================================================================
/*!
// \file src/mathtest/dmatsmatschur/DDbMIb.cpp
// \brief Source file for the DDbMIb dense matrix/sparse matrix Schur product math test
//
// Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DiagonalMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/IdentityMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatsmatschur/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'DDbMIb'..." << std::endl;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
using DDb = blaze::DiagonalMatrix< blaze::DynamicMatrix<TypeB> >;
using MIb = blaze::IdentityMatrix<TypeB>;
// Creator type definitions
using CDDb = blazetest::Creator<DDb>;
using CMIb = blazetest::Creator<MIb>;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
RUN_DMATSMATSCHUR_OPERATION_TEST( CDDb( i ), CMIb( i ) );
}
// Running tests with large matrices
RUN_DMATSMATSCHUR_OPERATION_TEST( CDDb( 67UL ), CMIb( 67UL ) );
RUN_DMATSMATSCHUR_OPERATION_TEST( CDDb( 128UL ), CMIb( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse matrix Schur product:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"[email protected]"
] | |
479c5960c89f168af08f652fc60ed74c98e1411e | 5a02bb2008b94df952d980d411a6295c9cbedbed | /index_join/src/query0_main.cpp | 14b4bff93d9f76586eac9db4e4e01d871f71b09d | [] | no_license | qingzma/IndexSampling | ef10cbb38fee1bd351b349c2256180451562a33d | 31442e2c883e6655dfe563815bcf67a4ca81f782 | refs/heads/master | 2020-07-07T14:16:06.692581 | 2019-09-17T07:28:38 | 2019-09-17T07:28:38 | 203,372,343 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,559 | cpp | // This implemented the different algorithms for query0
// Programmer: Robert Christensen
// email: [email protected]
// SELECT r_name, n_regionkey, s_nationkey, ps_suppkey
// FROM region, nation, supplier, partsupp
// WHERE r_name = 'ASIA'
// AND r_regionkey = n_regionkey
// AND n_nationkey = s_nationkey
// AND s_suppkey = ps_suppkey;
#include <iostream>
#include <fstream>
#include <memory>
#include <random>
#include <map>
#include <vector>
#include <thread>
#include <future>
#include "util/Timer.h"
#include "util/FileSizeTable.h"
#include "util/FileKeyValue.h"
#include "util/accumulator.h"
#include "util/joinSettings.h"
#include "database/TableRegion.h"
#include "database/TableNation.h"
#include "database/TableSupplier.h"
#include "database/TablePartsupp.h"
#include "database/Table.h"
#include "database/jefastIndex.h"
#include "database/jefastBuilder.h"
#include "database/pseudoIndex.h"
#include "database/JoinOutputColumnContainer.h"
#include "database/PathIndexBuilder.h"
#include "database/JoinPath.h"
#include "database/pseudoIndexAdvanced.h"
static std::shared_ptr<Table> region_table;
static std::shared_ptr<Table> nation_table;
static std::shared_ptr<Table> supplier_table;
static std::shared_ptr<Table> partssupp_table;
static std::shared_ptr<jefastIndexLinear> jefastIndex;
static std::shared_ptr<FileKeyValue> data_map;
static global_settings query0Settings;
// Note, we will require a filter for each column. It can just be an empty filter (an everything filter)
// we will be doing a linear scan of the data to implement this algorithm for now.
int64_t exactJoinNoIndex(std::string outfile, std::vector<std::shared_ptr<jefastFilter> > filters) {
// implements a straightforward implementation of a join which
// does not require an index.
std::ofstream output_file(outfile, std::ios::out);
int64_t count = 0;
auto Table_1 = region_table;
auto Table_2 = nation_table;
auto Table_3 = supplier_table;
auto Table_4 = partssupp_table;
int table1Index2 = Table_Region::R_REGIONKEY;
int table2Index1 = Table_Nation::N_REGIONKEY;
int table2Index2 = Table_Nation::N_NATIONKEY;
int table3Index1 = Table_Supplier::S_NATIONKEY;
int table3Index2 = Table_Supplier::S_SUPPKEY;
int table4Index1 = Table_Partsupp::PS_SUPPKEY;
// build the hash for table 1
std::map<jfkey_t, std::vector<int64_t> > Table1_hash;
//int64_t Table_1_count = Table_1->row_count();
//for (int64_t i = 0; i < Table_1_count; ++i) {
for (auto f1_enu = filters.at(0)->getEnumerator(); f1_enu->Step();) {
Table1_hash[Table_1->get_int64(f1_enu->getValue(), table1Index2)].push_back(f1_enu->getValue());
}
// for (auto elem : Table1_hash){
// for (auto item_in_vector: elem.second){
// std::cout<<elem.first<<", "<<item_in_vector<<std::endl;
// }
//
// }
// build the hash for table 2. All matched elements from table 1 hash will be emitted
// the tuple has the form <index from table 1, index for table 2> for all matching tuple
std::map<jfkey_t, std::vector<std::tuple<int64_t, int64_t> > > Table2_hash;
//int64_t Table_2_count = Table_2->row_count();
//for (int64_t i = 0; i < Table_2_count; ++i) {
for (auto f2_enu = filters.at(1)->getEnumerator(); f2_enu->Step();) {
jfkey_t value = Table_2->get_int64(f2_enu->getValue(), table2Index1);
for (auto matching_indexes : Table1_hash[value]) {
Table2_hash[Table_2->get_int64(f2_enu->getValue(), table2Index2)].emplace_back(matching_indexes, f2_enu->getValue());
}
}
// for (auto elem : Table2_hash){
// std::cout<<elem.first<<", <";
// for (auto item_in_vector: elem.second){
// std::cout<<"("<<std::get<0>(item_in_vector)<<","<<std::get<1>(item_in_vector)<<"), ";
// }
// std::cout<<">"<<std::endl;
//
// }
// build the hash for table 3. All matched elements from table 2 hash will be emitted.
std::map<jfkey_t, std::vector<std::tuple<int64_t, int64_t, int64_t> > > Table3_hash;
//int64_t Table_3_count = Table_3->row_count();
//for (int64_t i = 0; i < Table_3_count; ++i) {
for (auto f3_enu = filters.at(2)->getEnumerator(); f3_enu->Step();) {
jfkey_t value = Table_3->get_int64(f3_enu->getValue(), table3Index1);
for (auto matching_indexes : Table2_hash[value]) {
Table3_hash[Table_3->get_int64(f3_enu->getValue(), table3Index2)].emplace_back(std::get<0>(matching_indexes), std::get<1>(matching_indexes), f3_enu->getValue());
}
}
// for (auto elem : Table3_hash){
// std::cout<<elem.first<<", <";
// for (auto item_in_vector: elem.second){
// std::cout<<"("<<std::get<0>(item_in_vector)<<","<<std::get<1>(item_in_vector)<<","<<std::get<2>(item_in_vector)<<"), ";
// }
// std::cout<<">"<<std::endl;
//
// }
// build the hash for table 4? No, we can just emit when we find a match in this case.
//int64_t Table_4_count = Table_4->row_count();
//for (int64_t i = 0; i < Table_5_count; ++i) {
for (auto f4_enu = filters.at(3)->getEnumerator(); f4_enu->Step();) {
int64_t value = Table_4->get_int64(f4_enu->getValue(), table4Index1);
for (auto matching_indexes : Table3_hash[value]) {
// emit the join results here.
output_file << count << ' '
<< std::to_string(Table_1->get_int64(std::get<0>(matching_indexes), table1Index2)) << ' '
<< std::to_string(Table_2->get_int64(std::get<1>(matching_indexes), table2Index2)) << ' '
<< std::to_string(Table_3->get_int64(std::get<2>(matching_indexes), table3Index2)) << ' '
<< std::to_string(Table_4->get_int64(f4_enu->getValue(), 1)) << '\n';
++count;
}
}
output_file.close();
return count;
}
int64_t randomjefastJoin(std::ofstream & output_file, int64_t output_count, std::shared_ptr<jefastIndexLinear> jefast) {
std::vector<int64_t> results;
auto Table_1 = region_table;
auto Table_2 = nation_table;
auto Table_3 = supplier_table;
auto Table_4 = partssupp_table;
int table1Index2 = Table_Region::R_REGIONKEY;
int table2Index2 = Table_Nation::N_NATIONKEY;
int table3Index2 = Table_Supplier::S_SUPPKEY;
int64_t max = jefast->GetTotal();
std::vector<weight_t> random_values;
std::uniform_int_distribution<weight_t> distribution(0, max-1);
random_values.resize(output_count);
static std::default_random_engine generator;
std::generate(random_values.begin(), random_values.end(), [&]() {return distribution(generator);});
std::sort(random_values.begin(), random_values.end());
int counter = 0;
for (int i : random_values) {
jefast->GetJoinNumber(i, results);
output_file << counter << ' '
<< std::to_string(Table_1->get_int64(results[0], table1Index2)) << ' '
<< std::to_string(Table_2->get_int64(results[1], table2Index2)) << ' '
<< std::to_string(Table_3->get_int64(results[2], table3Index2)) << ' '
<< std::to_string(Table_4->get_int64(results[3], 1)) << '\n';
}
return output_count;
}
int64_t randomjefastJoin(std::string outfile, int64_t output_count, std::shared_ptr<jefastIndexLinear> jefast) {
// this will do a full table join using the jefast datastructure
// NOTE, jefast is not optimized for scanning right now. It is
// optimized for point queries
std::ofstream output_file(outfile, std::ios::out);
int64_t count = randomjefastJoin(output_file, output_count, jefast);
output_file.close();
return count;
}
int64_t randomjefastJoinT(std::string outfile, int64_t output_count, std::shared_ptr<jefastIndexLinear> jefast) {
return randomjefastJoin(outfile, output_count, jefast);
}
int64_t baselineJoin(std::ofstream & output_file, int output_count, const std::vector<weight_t> &max_cardinality) {
//std::ofstream output_file(outfile, std::ios::out);
auto Table_1 = region_table;
auto Table_2 = nation_table;
auto Table_3 = supplier_table;
auto Table_4 = partssupp_table;
int table1Index2 = Table_Region::R_REGIONKEY;
int table2Index1 = Table_Nation::N_REGIONKEY;
int table2Index2 = Table_Nation::N_NATIONKEY;
int table3Index1 = Table_Supplier::S_NATIONKEY;
int table3Index2 = Table_Supplier::S_SUPPKEY;
int table4Index1 = Table_Partsupp::PS_SUPPKEY;
int64_t count = 0;
int64_t rejected = 0;
int64_t max_possible_path = 0;
std::default_random_engine generator;
int64_t Table1_size = Table_1->row_count();
std::uniform_int_distribution<int64_t> region_dist(0, Table1_size - 1);
int64_t M_value = 1;
for (weight_t x : max_cardinality)
M_value *= x;
std::uniform_int_distribution<int64_t> rejection_filter(1, M_value);
while (count < output_count)
{
// do random selection of Table 1
int64_t Table1_idx = region_dist(generator);
int64_t Table1_v = Table_1->get_int64(Table1_idx, table1Index2);
// do random selection of Table 2
auto Table2_range = Table_2->get_key_index(table2Index1)->equal_range(Table1_v);
int64_t Table2_count = Table_2->get_key_index(table2Index1)->count(Table1_v);
if (Table2_count == 0)
continue;
std::uniform_int_distribution<int64_t> Table2_dist(0, Table2_count - 1);
int64_t selection_count_2 = Table2_dist(generator);
auto Table2_i = Table2_range.first;
while (selection_count_2 > 0) {
Table2_i++;
--selection_count_2;
}
int64_t Table2_v = Table_2->get_int64(Table2_i->second, table2Index2);
// do random selection of Table3
auto Table3_range = Table_3->get_key_index(table3Index1)->equal_range(Table2_v);
int64_t Table3_count = Table_3->get_key_index(table3Index1)->count(Table2_v);
if (Table3_count == 0)
continue;
std::uniform_int_distribution<int64_t> Table3_dist(0, Table3_count - 1);
int64_t selection_count_3 = Table3_dist(generator);
auto Table3_i = Table3_range.first;
while (selection_count_3 > 0) {
Table3_i++;
--selection_count_3;
}
int64_t Table3_v = Table_3->get_int64(Table3_i->second, table3Index2);
// do random selection of Table4
auto Table4_range = Table_4->get_key_index(table4Index1)->equal_range(Table3_v);
int64_t Table4_count = Table_4->get_key_index(table4Index1)->count(Table3_v);
if (Table4_count == 0)
continue;
std::uniform_int_distribution<int64_t> Table4_dist(0, Table4_count - 1);
int64_t selection_count_4 = Table4_dist(generator);
auto Table4_i = Table4_range.first;
while (selection_count_4 > 0) {
Table4_i++;
--selection_count_4;
}
int64_t Table4_v = Table_4->get_int64(Table4_i->second, 1);
//// do random selection of Table5
//auto Table5_range = Table_5->get_key_index(table5Index1)->equal_range(Table4_v);
//int64_t Table5_count = Table_5->get_key_index(table5Index1)->count(Table4_v);
//if (Table5_count == 0)
// continue;
//std::uniform_int_distribution<int64_t> Table5_dist(0, Table5_count - 1);
//int64_t selection_count_5 = Table5_dist(generator);
//auto Table5_i = Table5_range.first;
//while (selection_count_5 > 0) {
// Table5_i++;
// --selection_count_5;
//}
//int64_t Table5_v = Table_5->get_int64(Table5_i->second, 1);
// decide if we should reject
int64_t possible_paths = Table2_count * Table3_count * Table4_count;
max_possible_path = std::max(possible_paths, max_possible_path);
// if true, accept
if (rejection_filter(generator) < possible_paths) {
output_file << count << ' '
<< std::to_string(Table1_v) << ' '
//<< regionName << ' '
<< std::to_string(Table2_v) << ' '
//<< nationName << ' '
<< std::to_string(Table3_v) << ' '
<< std::to_string(Table4_v) << '\n';
count++;
}
else {
rejected++;
}
}
output_file.close();
return rejected;
}
int64_t baselineJoin(std::string outfile, int output_count, const std::vector<weight_t> &max_cardinality) {
// the exact join will combine between the four tables
std::ofstream output_file(outfile, std::ios::out);
int count = baselineJoin(output_file, output_count, max_cardinality);
output_file.close();
return count;
}
// Note, we will require a filter for each column. It can just be an empty filter (an everything filter)
// we will be doing a linear scan of the data to implement this algorithm for now.
int64_t pseudoIndexJoin(std::string outfile, std::vector<std::shared_ptr<jefastFilter> > filters) {
// implements a straightforward implementation of a join which
// does not require an index.
std::ofstream output_file(outfile, std::ios::out);
int64_t count = 0;
auto Table_1 = region_table;
auto Table_2 = nation_table;
auto Table_3 = supplier_table;
auto Table_4 = partssupp_table;
int table1Index2 = Table_Region::R_REGIONKEY;
int table2Index1 = Table_Nation::N_REGIONKEY;
int table2Index2 = Table_Nation::N_NATIONKEY;
int table3Index1 = Table_Supplier::S_NATIONKEY;
int table3Index2 = Table_Supplier::S_SUPPKEY;
int table4Index1 = Table_Partsupp::PS_SUPPKEY;
// build the hash for table 1
std::map<jfkey_t, std::vector<int64_t> > Table1_hash;
//int64_t Table_1_count = Table_1->row_count();
//for (int64_t i = 0; i < Table_1_count; ++i) {
for (auto f1_enu = filters.at(0)->getEnumerator(); f1_enu->Step();) {
Table1_hash[Table_1->get_int64(f1_enu->getValue(), table1Index2)].push_back(f1_enu->getValue());
}
// for (auto elem : Table1_hash){
// for (auto item_in_vector: elem.second){
// std::cout<<elem.first<<", "<<item_in_vector<<std::endl;
// }
//
// }
// build the hash for table 2. All matched elements from table 1 hash will be emitted
// the tuple has the form <index from table 1, index for table 2> for all matching tuple
std::map<jfkey_t, std::vector<std::tuple<int64_t, int64_t> > > Table2_hash;
//int64_t Table_2_count = Table_2->row_count();
//for (int64_t i = 0; i < Table_2_count; ++i) {
for (auto f2_enu = filters.at(1)->getEnumerator(); f2_enu->Step();) {
jfkey_t value = Table_2->get_int64(f2_enu->getValue(), table2Index1);
for (auto matching_indexes : Table1_hash[value]) {
Table2_hash[Table_2->get_int64(f2_enu->getValue(), table2Index2)].emplace_back(matching_indexes, f2_enu->getValue());
}
}
// for (auto elem : Table2_hash){
// std::cout<<elem.first<<", <";
// for (auto item_in_vector: elem.second){
// std::cout<<"("<<std::get<0>(item_in_vector)<<","<<std::get<1>(item_in_vector)<<"), ";
// }
// std::cout<<">"<<std::endl;
// }
// build the hash for table 3. All matched elements from table 2 hash will be emitted.
std::map<jfkey_t, std::vector<std::tuple<int64_t, int64_t, int64_t> > > Table3_hash;
//int64_t Table_3_count = Table_3->row_count();
//for (int64_t i = 0; i < Table_3_count; ++i) {
for (auto f3_enu = filters.at(2)->getEnumerator(); f3_enu->Step();) {
jfkey_t value = Table_3->get_int64(f3_enu->getValue(), table3Index1);
for (auto matching_indexes : Table2_hash[value]) {
Table3_hash[Table_3->get_int64(f3_enu->getValue(), table3Index2)].emplace_back(std::get<0>(matching_indexes), std::get<1>(matching_indexes), f3_enu->getValue());
}
}
// for (auto elem : Table3_hash){
// std::cout<<elem.first<<", <";
// for (auto item_in_vector: elem.second){
// std::cout<<"("<<std::get<0>(item_in_vector)<<","<<std::get<1>(item_in_vector)<<","<<std::get<2>(item_in_vector)<<"), ";
// }
// std::cout<<">"<<std::endl;
//
// }
// build the hash for table 4? No, we can just emit when we find a match in this case.
//int64_t Table_4_count = Table_4->row_count();
//for (int64_t i = 0; i < Table_5_count; ++i) {
for (auto f4_enu = filters.at(3)->getEnumerator(); f4_enu->Step();) {
int64_t value = Table_4->get_int64(f4_enu->getValue(), table4Index1);
for (auto matching_indexes : Table3_hash[value]) {
// emit the join results here.
output_file << count << ' '
<< std::to_string(Table_1->get_int64(std::get<0>(matching_indexes), table1Index2)) << ' '
<< std::to_string(Table_2->get_int64(std::get<1>(matching_indexes), table2Index2)) << ' '
<< std::to_string(Table_3->get_int64(std::get<2>(matching_indexes), table3Index2)) << ' '
<< std::to_string(Table_4->get_int64(f4_enu->getValue(), 1)) << '\n';
++count;
}
}
output_file.close();
return count;
}
void setup_data() {
// load the tables into memory
FileSizeTable table_sizes("fileInfo.txt");
data_map.reset(new FileKeyValue("query0_timings.txt"));
Timer timer;
std::cout << "opening tables" << std::endl;
timer.reset();
timer.start();
region_table.reset(new Table_Region("region.tbl", table_sizes.get_lines("region.tbl")));
nation_table.reset(new Table_Nation("nation.tbl", table_sizes.get_lines("nation.tbl")));
supplier_table.reset(new Table_Supplier("supplier.tbl", table_sizes.get_lines("supplier.tbl")));
partssupp_table.reset(new Table_Partsupp("partsupp.tbl", table_sizes.get_lines("partsupp.tbl")));
timer.stop();
std::cout << "opening tables took " << timer.getSeconds() << " seconds" << std::endl;
data_map->appendArray("opening_tables", long(timer.getMilliseconds()));
// build the indexes which might be used in the experiment
std::cout << "building indexes" << std::endl;
timer.reset();
timer.start();
// join indexes
if (query0Settings.buildIndex) {
region_table->get_key_index(Table_Region::R_REGIONKEY);
nation_table->get_key_index(Table_Nation::N_REGIONKEY);
nation_table->get_key_index(Table_Nation::N_NATIONKEY);
supplier_table->get_key_index(Table_Supplier::S_NATIONKEY);
supplier_table->get_key_index(Table_Supplier::S_SUPPKEY);
partssupp_table->get_key_index(Table_Partsupp::PS_SUPPKEY);
nation_table->get_composite_key_index(Table_Nation::N_REGIONKEY,Table_Nation::N_NATIONKEY);
supplier_table->get_composite_key_index(Table_Supplier::S_NATIONKEY, Table_Supplier::S_SUPPKEY);
}
// filtering conditions
// we do not currently have plans to do selection conditions on query 0
timer.stop();
std::cout << "done building indexes took " << timer.getMilliseconds() << " milliseconds" << std::endl;
data_map->appendArray("building_indexes", long(timer.getMilliseconds()));
// find max outdegree of each join?
}
int main(int argc, char** argv) {
query0Settings = parse_args(argc, argv);
setup_data();
Timer timer;
// do hash join
if(query0Settings.hashJoin)
{
std::vector<std::shared_ptr<jefastFilter> > filters(4);
filters.at(0) = std::shared_ptr<jefastFilter>(new all_jefastFilter(region_table, Table_Region::R_REGIONKEY));
filters.at(1) = std::shared_ptr<jefastFilter>(new all_jefastFilter(nation_table, Table_Nation::N_NATIONKEY));
filters.at(2) = std::shared_ptr<jefastFilter>(new all_jefastFilter(supplier_table, Table_Supplier::S_SUPPKEY));
filters.at(3) = std::shared_ptr<jefastFilter>(new all_jefastFilter(partssupp_table, Table_Partsupp::PS_PARTKEY));
timer.reset();
timer.start();
auto count = exactJoinNoIndex("query0_full.txt", filters);
timer.stop();
std::cout << "full join took " << timer.getMilliseconds() << " milliseconds with cardinality " << count << std::endl;
data_map->appendArray("full_join", long(timer.getMilliseconds()));
data_map->appendArray("full_join_cadinality", count);
}
// building jefast
if(query0Settings.buildJefast)
{
timer.reset();
timer.start();
JefastBuilder jefast_index_builder;
jefast_index_builder.AppendTable(region_table, -1, Table_Region::R_REGIONKEY, 0);
jefast_index_builder.AppendTable(nation_table, Table_Nation::N_REGIONKEY, Table_Nation::N_NATIONKEY, 1);
jefast_index_builder.AppendTable(supplier_table, Table_Supplier::S_NATIONKEY, Table_Supplier::S_SUPPKEY, 2);
jefast_index_builder.AppendTable(partssupp_table, Table_Partsupp::PS_SUPPKEY, -1, 3);
jefastIndex = jefast_index_builder.Build();
timer.stop();
std::cout << "building jefast took " << timer.getMilliseconds() << " milliseconds with cardinality " << jefastIndex->GetTotal() << std::endl;
data_map->appendArray("jefast_build", long(timer.getMilliseconds()));
}
// do a 10% sample using jefast
if(query0Settings.jefastSample)
{
timer.reset();
timer.start();
auto toRequest = jefastIndex->GetTotal() / 32;
auto count = randomjefastJoin("query0_sample.txt", toRequest, jefastIndex);
timer.stop();
std::cout << "sampling 10% took " << timer.getMilliseconds() << " milliseconds with cardinality " << count << std::endl;
data_map->appendArray("jefast_10p", long(timer.getMilliseconds()));
}
if (query0Settings.jefastModify)
{
// do random modifications for supplier, table 2
int table_id = 2;
data_map->appendArray("modifyCount", query0Settings.modifyCount);
// generate random ids to remove/insert
std::vector<jfkey_t> modify_records = generate_unique_random_numbers(query0Settings.modifyCount, 0, supplier_table->row_count());
// do delete
timer.reset();
timer.start();
for (auto record_id : modify_records) {
//std::cout << "removing " << record_id << std::endl;
jefastIndex->Delete(table_id, record_id);
}
timer.stop();
data_map->appendArray("DeleteTime", long(timer.getMilliseconds()));
std::cout << "delete of " << query0Settings.modifyCount << " took " << timer.getMilliseconds() << "ms. The cardinality is now " << jefastIndex->GetTotal() << std::endl;
// do insert
timer.reset();
timer.start();
for (auto record_id : modify_records) {
jefastIndex->Insert(table_id, record_id);
}
timer.stop();
std::cout << "insert of " << query0Settings.modifyCount << " took " << timer.getMilliseconds() << "ms. The cardinality is now " << jefastIndex->GetTotal() << std::endl;
}
// do a 10% baseline olkin join
if(query0Settings.olkenSample)
{
auto max_outdegree = jefastIndex->MaxOutdegree();
timer.reset();
timer.start();
auto toRequest = 100000;//jefastIndex->GetTotal() / 10;
auto rejected = baselineJoin("query0_samples.txt", toRequest, max_outdegree);
timer.stop();
std::cout << "baseline sample for 10% took " << timer.getMilliseconds() << " milliseconds accepted=" << toRequest << " rejected=" << rejected << std::endl;
data_map->appendArray("baseline_100000p", long(timer.getMilliseconds()));
data_map->appendArray("baseline_100000pRejected", rejected);
}
// do threading experiment for jefast
if (query0Settings.threading)
{
int64_t max_threads = 8;
int64_t requests = jefastIndex->GetTotal();
std::vector<std::string> output_file_names;
std::vector<std::future<int64_t> > results;
// open all the files
for (int i = 0; i < max_threads; ++i)
{
std::string filename = "query_";
filename += "0123456789"[i];
output_file_names.push_back(filename);
}
// do the trials.
for (int64_t i = 1; i <= max_threads; i *= 2) {
timer.reset();
timer.start();
// start the threads
for (int t = 0; t < i; ++t) {
results.emplace_back(std::async(randomjefastJoinT, query0Settings.null_file_name, requests / i, jefastIndex));
}
// wait for all the joins to finish
for (int t = 0; t < i; ++t) {
results[t].wait();
}
// all results are in!
timer.stop();
std::string results_string = "jefast_thread_";
results_string += "0123456789"[i];
std::cout << "finished test with " << i << " threads, taking " << timer.getMilliseconds() << " milliseconds" << std::endl;
data_map->appendArray(results_string, long(timer.getMilliseconds()));
}
}
if(query0Settings.jefastRate)
{
// do the sample rate test for jefast
Timer total_time;
double last_ms = 0;
int per_sample_request = 8000;
int total_samples = 0;
std::ofstream output_file("query0_sample.txt", std::ios::out);
std::ofstream results_file("query0_jefast_sample_rate.txt", std::ios::out);
total_time.reset();
do {
total_samples += randomjefastJoin(output_file, per_sample_request, jefastIndex);
total_time.update_accumulator();
total_time.update_accumulator();
results_file << total_time.getMilliseconds() << '\t' << total_samples << '\t' << per_sample_request << '\t' << (total_time.getMicroseconds() / 1000 - last_ms) << '\n';
last_ms = total_time.getMicroseconds() / 1000;
} while (total_time.getSeconds() < 4);
results_file.close();
}
if(query0Settings.OlkenRate)
{
// do the sample rate test for olkin join
Timer total_time;
double last_ms = 0;
int per_sample_request = 2000;
int total_samples = 0;
std::ofstream output_file("query0_sample.txt", std::ios::out);
std::ofstream results_file("query0_olkin_sample_rate.txt", std::ios::out);
auto max_outdegree = jefastIndex->MaxOutdegree();
total_time.reset();
do {
total_samples += baselineJoin(output_file, per_sample_request, max_outdegree);
total_time.update_accumulator();
total_time.update_accumulator();
results_file << total_time.getMilliseconds() << '\t' << total_samples << '\t' << per_sample_request << '\t' << (total_time.getMicroseconds() / 1000 - last_ms) << '\n';
last_ms = total_time.getMicroseconds() / 1000;
} while (total_time.getSeconds() < 4);
results_file.close();
}
// do index join
PseudoIndexBuilder pseudoIndexBuilder;
if (query0Settings.buildPseudoIndex){
std::cout<<"Start building pseudo index ..."<<std::endl;
timer.reset();
timer.start();
nation_table->get_join_attribute_relation_index(Table_Nation::N_REGIONKEY, Table_Nation::N_NATIONKEY);
supplier_table->get_join_attribute_relation_index( Table_Supplier::S_NATIONKEY, Table_Supplier::S_SUPPKEY);
pseudoIndexBuilder.AppendTable(region_table, -1, Table_Region::R_REGIONKEY, 0);
pseudoIndexBuilder.AppendTable(nation_table, Table_Nation::N_REGIONKEY, Table_Nation::N_NATIONKEY, 1);
pseudoIndexBuilder.AppendTable(supplier_table, Table_Supplier::S_NATIONKEY, -1,2);//Table_Supplier::S_SUPPKEY, 2);
// pseudoIndexBuilder.AppendTable(partssupp_table, Table_Partsupp::PS_SUPPKEY, -1, 3);
pseudoIndexBuilder.Build();
timer.stop();
std::cout << "building pseudo index took " << timer.getMilliseconds() << " milliseconds with cardinality " << pseudoIndexBuilder.getCardinality() << std::endl;
data_map->appendArray("pseudo index built ", long(timer.getMilliseconds()));
}
// do a 10% sample using pseudoIndex
if(query0Settings.indexJoin)
{
timer.reset();
timer.start();
JoinOutputColumnContainer joinOutputColumnContainer;
joinOutputColumnContainer.addColumn(0,Table_Region::R_NAME);
joinOutputColumnContainer.addColumn(1,Table_Nation::N_REGIONKEY);
joinOutputColumnContainer.addColumn(2,Table_Supplier::S_NATIONKEY);
joinOutputColumnContainer.addColumn(3,Table_Partsupp::PS_SUPPKEY);
// pseudoIndexBuilder.Sample(1000000);
pseudoIndexBuilder.Sample(1000000,joinOutputColumnContainer);
timer.stop();
std::cout << "sampling 100 took " << timer.getMilliseconds() << " milliseconds with cardinality " << "NEED FIXED" << std::endl;
data_map->appendArray("pseudo index took ", long(timer.getMilliseconds()));
}
PseudoIndexAdvancedBuilder pseudoIndexAdvancedBuilder;
if (query0Settings.buildPseudoIndexA){
std::cout<<"Start building advanced pseudo index ..."<<std::endl;
timer.reset();
timer.start();
nation_table->get_join_attribute_relation_index(Table_Nation::N_REGIONKEY, Table_Nation::N_NATIONKEY);
supplier_table->get_join_attribute_relation_index( Table_Supplier::S_NATIONKEY, Table_Supplier::S_SUPPKEY);
/*JoinPath joinPath;
joinPath.addNode("key",DATABASE_DATA_TYPES::STRING);
joinPath.addNode("12",DATABASE_DATA_TYPES::INT64);
std::cout<<joinPath.toString()<<std::endl;*/
// PathIndex pathIndex("joinPath",0);
pseudoIndexAdvancedBuilder.AppendTable(region_table, -1, Table_Region::R_REGIONKEY, 0);
pseudoIndexAdvancedBuilder.AppendTable(nation_table, Table_Nation::N_REGIONKEY, Table_Nation::N_NATIONKEY, 1);
pseudoIndexAdvancedBuilder.AppendTable(supplier_table, Table_Supplier::S_NATIONKEY, Table_Supplier::S_SUPPKEY, 2);
pseudoIndexAdvancedBuilder.AppendTable(partssupp_table, Table_Partsupp::PS_SUPPKEY, -1, 3);
pseudoIndexAdvancedBuilder.Build();
timer.stop();
std::cout << "building pseudo index took " << timer.getMilliseconds() << " milliseconds with cardinality " << pseudoIndexAdvancedBuilder.getCardinality() << std::endl;
data_map->appendArray("pseudo index built ", long(timer.getMilliseconds()));
}
data_map->flush();
std::cout << "done" << std::endl;
} | [
"[email protected]"
] | |
57118a63620da7ba4d1f9884855da442c4fe41ad | ac372e2fdc9352414169b4791e58f43ec56b8922 | /Export/linux/obj/include/lime/math/_BGRA/BGRA_Impl_.h | 92a5579c050704ad4694c8da76f459d8591c66fc | [] | no_license | JavaDeva/HAXE_TPE | 4c7023811b153061038fe0effe913f055f531e22 | a201e718b73658bff943c268b097a86f858d3817 | refs/heads/master | 2022-08-15T21:33:14.010205 | 2020-05-28T15:34:32 | 2020-05-28T15:34:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 3,384 | h | // Generated by Haxe 4.1.1
#ifndef INCLUDED_lime_math__BGRA_BGRA_Impl_
#define INCLUDED_lime_math__BGRA_BGRA_Impl_
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS3(lime,math,_BGRA,BGRA_Impl_)
HX_DECLARE_CLASS2(lime,utils,ArrayBufferView)
namespace lime{
namespace math{
namespace _BGRA{
class HXCPP_CLASS_ATTRIBUTES BGRA_Impl__obj : public ::hx::Object
{
public:
typedef ::hx::Object super;
typedef BGRA_Impl__obj OBJ_;
BGRA_Impl__obj();
public:
enum { _hx_ClassId = 0x7ecac4f2 };
void __construct();
inline void *operator new(size_t inSize, bool inContainer=false,const char *inName="lime.math._BGRA.BGRA_Impl_")
{ return ::hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return ::hx::Object::operator new(inSize+extra,false,"lime.math._BGRA.BGRA_Impl_"); }
inline static ::hx::ObjectPtr< BGRA_Impl__obj > __new() {
::hx::ObjectPtr< BGRA_Impl__obj > __this = new BGRA_Impl__obj();
__this->__construct();
return __this;
}
inline static ::hx::ObjectPtr< BGRA_Impl__obj > __alloc(::hx::Ctx *_hx_ctx) {
BGRA_Impl__obj *__this = (BGRA_Impl__obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(BGRA_Impl__obj), false, "lime.math._BGRA.BGRA_Impl_"));
*(void **)__this = BGRA_Impl__obj::_hx_vtable;
return __this;
}
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(::hx::DynamicArray inArgs);
//~BGRA_Impl__obj();
HX_DO_RTTI_ALL;
static bool __GetStatic(const ::String &inString, Dynamic &outValue, ::hx::PropertyAccess inCallProp);
static void __register();
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_("BGRA_Impl_",54,f8,cb,41); }
static int a16;
static Float unmult;
static int _new(::hx::Null< int > bgra);
static ::Dynamic _new_dyn();
static int create(int b,int g,int r,int a);
static ::Dynamic create_dyn();
static void multiplyAlpha(int this1);
static ::Dynamic multiplyAlpha_dyn();
static void readUInt8(int this1, ::lime::utils::ArrayBufferView data,int offset,::hx::Null< int > format,::hx::Null< bool > premultiplied);
static ::Dynamic readUInt8_dyn();
static void set(int this1,int b,int g,int r,int a);
static ::Dynamic set_dyn();
static void unmultiplyAlpha(int this1);
static ::Dynamic unmultiplyAlpha_dyn();
static void writeUInt8(int this1, ::lime::utils::ArrayBufferView data,int offset,::hx::Null< int > format,::hx::Null< bool > premultiplied);
static ::Dynamic writeUInt8_dyn();
static int _hx___fromARGB(int argb);
static ::Dynamic _hx___fromARGB_dyn();
static int _hx___fromRGBA(int rgba);
static ::Dynamic _hx___fromRGBA_dyn();
static int get_a(int this1);
static ::Dynamic get_a_dyn();
static int set_a(int this1,int value);
static ::Dynamic set_a_dyn();
static int get_b(int this1);
static ::Dynamic get_b_dyn();
static int set_b(int this1,int value);
static ::Dynamic set_b_dyn();
static int get_g(int this1);
static ::Dynamic get_g_dyn();
static int set_g(int this1,int value);
static ::Dynamic set_g_dyn();
static int get_r(int this1);
static ::Dynamic get_r_dyn();
static int set_r(int this1,int value);
static ::Dynamic set_r_dyn();
};
} // end namespace lime
} // end namespace math
} // end namespace _BGRA
#endif /* INCLUDED_lime_math__BGRA_BGRA_Impl_ */
| [
"[email protected]"
] | |
875300cf96fb5ef57da0ec35ace5ef9314d17944 | e22b3d1db6dc9e33374a80b82441795fe43d5daf | /backend/status/SystemStatus.cc | ef189f5822c80aba2b194733ecbe6d13a096bdf8 | [
"Apache-2.0",
"CC0-1.0"
] | permissive | paulamma/primarysources | 8bfd6f3d4a10b3ddf461cdfd381f3b1ac86bc29a | d5d38d890bc4e10b2b2dedd158d6ae21f3303159 | refs/heads/master | 2021-01-18T04:36:26.469737 | 2016-03-28T20:25:36 | 2016-03-28T20:25:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,202 | cc | // Copyright 2015 Google Inc. All Rights Reserved.
// Author: Sebastian Schaffert <[email protected]>
#include <util/MemStat.h>
#include <status/Version.h>
#include <ctime>
#include "SystemStatus.h"
using wikidata::primarysources::model::ApprovalState;
namespace wikidata {
namespace primarysources {
namespace status {
namespace {
// format a time_t using ISO8601 GMT time
inline std::string formatGMT(time_t* time) {
char result[128];
std::strftime(result, 128, "%Y-%m-%dT%H:%M:%SZ", gmtime(time));
return std::string(result);
}
} // namespace
StatusService::StatusService(const std::string& connstr)
: connstr_(connstr), dirty_(true) {
// set system startup time
time_t startupTime = std::time(nullptr);
status_.mutable_system()->set_startup(formatGMT(&startupTime));
status_.mutable_system()->set_version(std::string(GIT_SHA1));
}
void StatusService::AddCacheHit() {
std::lock_guard<std::mutex> lock(status_mutex_);
status_.mutable_system()->set_cache_hits(
status_.system().cache_hits() + 1);
}
void StatusService::AddCacheMiss() {
std::lock_guard<std::mutex> lock(status_mutex_);
status_.mutable_system()->set_cache_misses(
status_.system().cache_misses() + 1);
}
void StatusService::AddGetEntityRequest() {
std::lock_guard<std::mutex> lock(status_mutex_);
status_.mutable_requests()->set_get_entity(
status_.requests().get_entity() + 1);
}
void StatusService::AddGetRandomRequest() {
std::lock_guard<std::mutex> lock(status_mutex_);
status_.mutable_requests()->set_get_random(
status_.requests().get_random() + 1);
}
void StatusService::AddGetStatementRequest() {
std::lock_guard<std::mutex> lock(status_mutex_);
status_.mutable_requests()->set_get_statement(
status_.requests().get_statement() + 1);
}
void StatusService::AddUpdateStatementRequest() {
std::lock_guard<std::mutex> lock(status_mutex_);
status_.mutable_requests()->set_update_statement(
status_.requests().update_statement() + 1);
}
void StatusService::AddGetStatusRequest() {
std::lock_guard<std::mutex> lock(status_mutex_);
status_.mutable_requests()->set_get_status(
status_.requests().get_status() + 1);
}
// Update the system status and return a constant reference.
model::Status StatusService::Status(const std::string& dataset) {
std::lock_guard<std::mutex> lock(status_mutex_);
MemStat memstat;
status_.mutable_system()->set_shared_memory(memstat.getSharedMem());
status_.mutable_system()->set_private_memory(memstat.getPrivateMem());
status_.mutable_system()->set_resident_set_size(memstat.getRSS());
model::Status copy;
model::Status* work;
// work directly on the status in case we do not request a specific
// dataset, otherwise make a copy.
if (dataset == "") {
work = &status_;
} else {
copy = status_;
work = ©
}
if (dirty_) {
cppdb::session sql(connstr_); // released when sql is destroyed
Persistence p(sql, true);
sql.begin();
work->mutable_statements()->set_statements(p.countStatements(dataset));
work->mutable_statements()->set_approved(p.countStatements(ApprovalState::APPROVED, dataset));
work->mutable_statements()->set_unapproved(p.countStatements(ApprovalState::UNAPPROVED, dataset));
work->mutable_statements()->set_duplicate(p.countStatements(ApprovalState::DUPLICATE, dataset));
work->mutable_statements()->set_blacklisted(p.countStatements(ApprovalState::BLACKLISTED, dataset));
work->mutable_statements()->set_wrong(p.countStatements(ApprovalState::WRONG, dataset));
work->set_total_users(p.countUsers());
work->clear_top_users();
for (model::UserStatus &st : p.getTopUsers(10)) {
work->add_top_users()->Swap(&st);
}
if (dataset == "") {
dirty_ = false;
}
sql.commit();
}
return *work;
}
std::string StatusService::Version() {
return std::string(GIT_SHA1);
}
} // namespace status
} // namespace primarysources
} // namespace wikidata
| [
"[email protected]"
] | |
42f53044302167c6c9309e3c7085d45724ae04a7 | c4165e745412ade20a59bbaad5755ed8f1f54c6a | /Code/IO/test/mapIOHeaderTest.cpp | 6eeead0716c1457283be902e0eff739f75e82426 | [] | no_license | MIC-DKFZ/MatchPoint | e0e3fb45a274a6de4b6c49397ea1e9b5bbed4620 | a45efdf977418305039df6a4f98efe6e7ed1f578 | refs/heads/master | 2023-06-22T07:52:46.870768 | 2023-06-17T07:43:48 | 2023-06-17T07:43:48 | 186,114,444 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,617 | cpp | // -----------------------------------------------------------------------
// MatchPoint - DKFZ translational registration framework
//
// Copyright (c) German Cancer Research Center (DKFZ),
// Software development for Integrated Diagnostics and Therapy (SIDT).
// ALL RIGHTS RESERVED.
// See mapCopyright.txt or
// http://www.dkfz.de/en/sidt/projects/MatchPoint/copyright.html
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notices for more information.
//
//------------------------------------------------------------------------
/*!
// @file
// @version $Revision$ (last changed revision)
// @date $Date$ (last change date)
// @author $Author$ (last changed by)
// Subversion HeadURL: $HeadURL$
*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include "mapExpandingFieldKernelLoader.h"
#include "mapExpandingFieldKernelWriter.h"
#include "mapKernelLoaderLoadPolicy.h"
#include "mapKernelWriterLoadPolicy.h"
#include "mapMatrixModelBasedKernelLoader.h"
#include "mapMatrixModelBasedKernelWriter.h"
#include "mapNullRegistrationKernelLoader.h"
#include "mapNullRegistrationKernelWriter.h"
#include "mapRegistrationFileReader.h"
#include "mapRegistrationFileTags.h"
#include "mapRegistrationFileWriter.h"
#include "mapRegistrationKernelLoaderBase.h"
#include "mapRegistrationKernelLoadRequest.h"
#include "mapRegistrationKernelWriterBase.h"
#include "mapRegistrationKernelWriteRequest.h"
int main(int , char**)
{
return EXIT_SUCCESS;
}
| [
"[email protected]"
] | |
15a11b592960f01ca1c1a73f797789f8af79d0cd | 44f35ba1e2332d24c8a5c4837c29ddf6a40397f8 | /test/test_lsd.cpp | 41e54b76b9997425e8d64111aee61f076d066fe0 | [] | no_license | chongyc/libtorrent | 8a65406254844d525d02cb0c5bbfe0f8210dc07c | 73b4af0eeb0937e571e22ba30742210fb8187371 | refs/heads/master | 2016-09-06T20:10:46.200474 | 2008-08-25T22:32:50 | 2008-08-25T22:32:50 | 27,843 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,631 | cpp | /*
Copyright (c) 2008, Arvid Norberg
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 author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/session.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/hasher.hpp"
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/filesystem/operations.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
using boost::filesystem::remove_all;
void test_lsd()
{
using namespace libtorrent;
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48100, 49000));
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49100, 50000));
session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50100, 51000));
// this is to avoid everything finish from a single peer
// immediately. To make the swarm actually connect all
// three peers before finishing.
float rate_limit = 180000;
ses1.set_upload_rate_limit(int(rate_limit));
ses2.set_download_rate_limit(int(rate_limit));
ses3.set_download_rate_limit(int(rate_limit));
ses2.set_upload_rate_limit(int(rate_limit / 2));
ses3.set_upload_rate_limit(int(rate_limit / 2));
session_settings settings;
settings.allow_multiple_connections_per_ip = true;
settings.ignore_limits_on_local_network = false;
ses1.set_settings(settings);
ses2.set_settings(settings);
ses3.set_settings(settings);
ses1.start_lsd();
ses2.start_lsd();
ses3.start_lsd();
#ifndef TORRENT_DISABLE_ENCRYPTION
pe_settings pes;
pes.out_enc_policy = pe_settings::forced;
pes.in_enc_policy = pe_settings::forced;
ses1.set_pe_settings(pes);
ses2.set_pe_settings(pes);
ses3.set_pe_settings(pes);
#endif
torrent_handle tor1;
torrent_handle tor2;
torrent_handle tor3;
boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, false, "_lsd");
for (int i = 0; i < 30; ++i)
{
print_alerts(ses1, "ses1", true);
print_alerts(ses2, "ses2", true);
print_alerts(ses3, "ses3", true);
torrent_status st1 = tor1.status();
torrent_status st2 = tor2.status();
torrent_status st3 = tor3.status();
std::cerr
<< "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s "
<< st1.num_peers << ": "
<< "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st2.progress * 100) << "% "
<< st2.num_peers << " - "
<< "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st3.progress * 100) << "% "
<< st3.num_peers
<< std::endl;
if (tor2.is_seed() && tor3.is_seed()) break;
test_sleep(1000);
}
TEST_CHECK(tor2.is_seed());
TEST_CHECK(tor3.is_seed());
if (tor2.is_seed() && tor3.is_seed()) std::cerr << "done\n";
}
int test_main()
{
using namespace libtorrent;
using namespace boost::filesystem;
// in case the previous run was terminated
try { remove_all("./tmp1_lsd"); } catch (std::exception&) {}
try { remove_all("./tmp2_lsd"); } catch (std::exception&) {}
try { remove_all("./tmp3_lsd"); } catch (std::exception&) {}
test_lsd();
remove_all("./tmp1_lsd");
remove_all("./tmp2_lsd");
remove_all("./tmp3_lsd");
return 0;
}
| [
"arvidn@a83610d8-ad2a-0410-a6ab-fc0612d85776"
] | arvidn@a83610d8-ad2a-0410-a6ab-fc0612d85776 |
05cd2cf9a7b84136e265a663367451ac5f7f61ba | c88a1c6623b40dca33d80d8be89a35b451bfe28b | /MQ2Main/ArrayClass.h | 9f3a933b96b6d12c8bcf2d55dd0806d5480984d5 | [] | no_license | thepluralevan/macroquest2 | de941d6fdea91094689af1f9f277ccb4f93ed603 | d5d72d9ac297067ea4f93e30d66efda3ac765398 | refs/heads/master | 2020-08-03T08:41:51.443441 | 2019-09-18T22:21:08 | 2019-09-18T22:21:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,957 | h | /*****************************************************************************
MQ2Main.dll: MacroQuest2's extension DLL for EverQuest
Copyright (C) 2002-2003 Plazmic, 2003-2005 Lax
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.
******************************************************************************/
#pragma once
#include <cstdint>
#pragma pack(push)
#pragma pack(4)
struct CStrPtr
{
int RefCount;
long MaxLength;
long Length;
int Encoding;
void *Buff;
union
{
char Ansi[1000];
wchar_t Unicode[500];
CStrPtr* pNext;
};
};
class CCXStr
{
public:
EQLIB_OBJECT CCXStr& operator= (char const *str);
CStrPtr* Ptr;
};
//----------------------------------------------------------------------------
class CDynamicArrayBase;
struct CEQException {};
struct CExceptionApplication : CEQException {};
struct CExceptionMemoryAllocation : public CEQException {
int size;
CExceptionMemoryAllocation(int size_) : size(size_) {}
};
// inherits from CExceptionApplication and CEQException
struct CDynamicArrayException : public CExceptionApplication {
const CDynamicArrayBase* obj;
CDynamicArrayException(const CDynamicArrayBase* obj_) : obj(obj_) {}
};
// base class for the dynamic array types
class CDynamicArrayBase
{
protected:
/*0x00*/ int m_length;
/*0x04*/
public:
// two names for the same thing
int GetLength() const { return m_length; }
// a microsoft extension - lets us get away with changing the implementation
__declspec(property(get = GetLength)) int Count;
protected:
void ThrowArrayClassException() const
{
throw CDynamicArrayException(this);
}
};
// split into two types - one that is read-only and does not allocate or modify
// memory, and one that can. Be careful using the ones that can modify memory,
// as you can't memcpy, memset, etc on them.
template <typename T>
class ArrayClass2_RO : public CDynamicArrayBase
{
#define GET_BIN_INDEX(x) (x >> static_cast<uint8_t>(m_binShift))
#define GET_SLOT_INDEX(x) (m_slotMask & index)
public:
inline T& operator[](int index) { return Get(index); }
inline const T& operator[](int index) const { return Get(index); }
T& Get(int index) { return m_array[GET_BIN_INDEX(index)][GET_SLOT_INDEX(index)]; }
inline const T& Get(int index) const { return m_array[GET_BIN_INDEX(index)][GET_SLOT_INDEX(index)]; }
// try to get an element by index, returns pointer to the element.
// if the index is out of bounds, returns null.
T* SafeGet(int index)
{
if (index < m_length)
{
int bin = GET_BIN_INDEX(index);
if (bin < m_binCount)
{
int slot = GET_SLOT_INDEX(index);
if (slot < m_maxPerBin)
{
return &m_array[bin][slot];
}
}
}
return nullptr;
}
bool IsMember(const T& element) const
{
if (m_length <= 0)
return false;
for (int i = 0; i < m_length; ++i) {
if (Get(i) == element)
return true;
}
return false;
}
protected:
/*0x04*/ int m_maxPerBin;
/*0x08*/ int m_slotMask;
/*0x0c*/ int m_binShift;
/*0x10*/ T** m_array;
/*0x14*/ int m_binCount;
#if !defined(TEST) && !defined(LIVE)
/*0x18*/ bool m_valid;
#endif
/*0x1c*/
};
#undef GET_BIN_INDEX
#undef GET_SLOT_INDEX
//----------------------------------------------------------------------------
// ArrayClass2 is a dynamic array implementation that makes use of bins
// to reduce the overhead of reallocation. This allows for faster resize
// operations as existing bins do not need to be relocated, just the
// list of bins. See Assure() for more information.
template <typename T>
class ArrayClass2 : public ArrayClass2_RO<T>
{
public:
// constructs the array
ArrayClass2()
{
m_maxPerBin = 1;
m_binShift = 0;
do {
m_maxPerBin <<= 1;
m_binShift++;
} while (m_maxPerBin < 32);
m_slotMask = m_maxPerBin - 1;
m_array = nullptr;
m_length = 0;
m_binCount = 0;
#if !defined(TEST) && !defined(LIVE)
m_valid = true;
#endif
}
ArrayClass2(const ArrayClass2& rhs) : ArrayClass2()
{
this->operator=(rhs);
}
~ArrayClass2()
{
Reset();
}
ArrayClass2& operator=(const ArrayClass2& rhs)
{
if (this != &rhs)
{
if (m_array)
m_length = 0;
if (rhs.m_length) {
Assure(rhs.m_length);
#if !defined(TEST) && !defined(LIVE)
if (m_valid)
#endif
{
for (int i = 0; i < rhs.m_length; ++i)
Get(i) = rhs.Get(i);
}
m_length = rhs.m_length;
}
}
return *this;
}
// clear the contents of the array and make it empty
void Reset()
{
for (int i = 0; i < m_binCount; ++i)
delete[] m_array[i];
delete[] m_array;
m_array = nullptr;
m_binCount = 0;
m_length = 0;
}
void Add(const T& value)
{
SetElementIdx(m_length, value);
}
void InsertElement(int index, const T& value)
{
if (index >= 0) {
if (index < m_length) {
Assure(m_length + 1);
for (int idx = m_length; idx > index; --idx)
Get(idx) = Get(idx - 1);
Get(index) = value;
++m_length;
}
else {
SetElementIdx(index, value);
}
}
}
void SetElementIdx(int index, const T& value)
{
if (index >= 0) {
if (index >= m_length) {
Assure(index + 1);
#if !defined(TEST) && !defined(LIVE)
if (m_valid) {
#else
{
#endif
m_length = index + 1;
}
}
#if !defined(TEST) && !defined(LIVE)
if (m_valid) {
#else
{
#endif
Get(index) = value;
}
}
}
void DeleteElement(int index)
{
if (index >= 0 && index < m_length && m_array) {
for (; index < m_length - 1; ++index)
Get(index) = Get(index + 1);
--m_length;
}
}
private:
// Assure() makes sure that there is enough allocated space for
// the requested size. This is the primary function used for allocating
// memory in ArrayClass2. Because the full array is broken down into
// a set of bins, it is more efficient at growing than ArrayClass.
// When the array needs to be resized, it only needs to reallocate the
// list of bins and create more bins. Existing bins do not need to be
// reallocated, they can just be copied to the new list of bins.
void Assure(int requestedSize)
{
#if !defined(TEST) && !defined(LIVE)
if (m_valid && requestedSize > 0) {
#else
//if (m_binCount && requestedSize > 0) {
if (requestedSize > 0) {
#endif
int newBinCount = ((requestedSize - 1) >> static_cast<int8_t>(m_binShift)) + 1;
if (newBinCount > m_binCount) {
T** newArray = new T*[newBinCount];
if (newArray) {
for (int i = 0; i < m_binCount; ++i)
newArray[i] = m_array[i];
for (int curBin = m_binCount; curBin < newBinCount; ++curBin) {
T* newBin = new T[m_maxPerBin];
newArray[curBin] = newBin;
if (!newBin) {
#if !defined(TEST) && !defined(LIVE)
m_valid = false;
#else
//m_binCount = 0;
#endif
break;
}
}
#if !defined(TEST) && !defined(LIVE)
if (m_valid)
#endif
{
delete[] m_array;
m_array = newArray;
m_binCount = newBinCount;
}
} else {
#if !defined(TEST) && !defined(LIVE)
m_valid = false;
#else
//m_binCount = 0;
#endif
}
}
// special note about this exception: the eq function was written this way,
// but its worth noting that new will throw if it can't allocate, which means
// this will never be hit anyways. The behavior would not change if we removed
// all of the checks for null returns values from new in this function.
#if !defined(TEST) && !defined(LIVE)
if (!m_valid) {
Reset();
ThrowArrayClassException();
}
#endif
}
}
};
//----------------------------------------------------------------------------
// simpler than ArrayClass2, ArrayClass is a simple wrapper around a dynamically
// allocated array. To grow this array requires reallocating the entire array and
// copying objects into the new array.
template <typename T>
class ArrayClass_RO : public CDynamicArrayBase
{
public:
T& Get(int index)
{
if (index >= m_length || index < 0 || m_array == nullptr)
ThrowArrayClassException();
return m_array[index];
}
const T& Get(int index) const
{
if (index >= m_length || index < 0 || m_array == nullptr)
ThrowArrayClassException();
return m_array[index];
}
//0090C580
EQLIB_OBJECT void DeleteElement(int index);
T& operator[](int index) { return Get(index); }
const T& operator[](int index) const { return Get(index); }
// const function that returns the element at the index *by value*
T GetElementIdx(int index) const { return Get(index); }
protected:
/*0x04*/ T* m_array;
/*0x08*/ int m_alloc;
/*0x0c*/ bool m_isValid;
/*0x10*/
};
template <typename T>
class ArrayClass : public ArrayClass_RO<T>
{
public:
ArrayClass()
{
m_length = 0;
m_array = nullptr;
m_alloc = 0;
m_isValid = true;
}
ArrayClass(int reserve) : ArrayClass()
{
m_array = new T[reserve];
m_alloc = reserve;
}
ArrayClass(const ArrayClass& rhs) : ArrayClass()
{
if (rhs.m_length) {
AssureExact(rhs.m_length);
if (m_array) {
for (int i = 0; i < rhs.m_length; ++i)
m_array[i] = rhs.m_array[i];
}
m_length = rhs.m_length;
}
}
~ArrayClass()
{
Reset();
}
ArrayClass& operator=(const ArrayClass& rhs)
{
if (this == &rhs)
return *this;
Reset();
if (rhs.m_length) {
AssureExact(rhs.m_length);
if (m_array) {
for (int i = 0; i < rhs.m_length; ++i)
m_array[i] = rhs.m_array[i];
}
m_length = rhs.m_length;
}
return *this;
}
void Reset()
{
if (m_array) {
delete[] m_array;
}
m_array = nullptr;
m_alloc = 0;
m_length = 0;
}
void Add(const T& element)
{
SetElementIdx(m_length, element);
}
T *GetBuffPtr()
{
return m_array;
}
void SetElementIdx(int index, const T& element)
{
if (index >= 0) {
if (index >= m_length) {
Assure(index + 1);
if (m_array) {
m_length = index + 1;
}
}
if (m_array) {
m_array[index] = element;
}
}
}
void InsertElement(int index, const T& element)
{
if (index >= 0) {
if (index < m_length) {
Assure(m_length + 1);
if (m_array) {
for (int idx = m_length; idx > index; --idx)
m_array[idx] = m_array[idx - 1];
m_array[index] = element;
m_length++;
}
} else {
SetElementIdx(index, element);
}
}
}
void DeleteElement(int index)
{
if (index >= 0 && index < m_length && m_array) {
for (; index < m_length - 1; ++index)
m_array[index] = m_array[index + 1];
m_length--;
}
}
void SetLength(int size)
{
AssureExact(size);
if (this->m_array)
this->m_length = size;
}
private:
// this function will ensure that there is enough space allocated for the
// requested size. the underlying array is one contiguous block of memory.
// In order to grow it, we will need to allocate a new array and move
// everything over.
// this function will allocate 2x the amount of memory requested as an
// optimization aimed at reducing the number of allocations that occur.
void Assure(int requestedSize)
{
if (requestedSize && (requestedSize > m_alloc || !m_array)) {
int allocatedSize = (requestedSize + 4) << 1;
T* newArray = new T[allocatedSize];
if (!newArray) {
delete[] m_array;
m_array = nullptr;
m_alloc = 0;
m_isValid = false;
throw CExceptionMemoryAllocation{ allocatedSize };
}
if (m_array) {
for (int i = 0; i < m_length; ++i)
newArray[i] = m_array[i];
delete[] m_array;
}
m_array = newArray;
m_alloc = allocatedSize;
}
}
// this behaves the same as Assure, except for its allocation of memory
// is exactly how much is requested.
void AssureExact(int requestedSize)
{
if (requestedSize && (requestedSize > m_alloc || !m_array)) {
T* newArray = new T[requestedSize];
if (!newArray) {
delete[] m_array;
m_array = nullptr;
m_alloc = 0;
m_isValid = false;
throw CExceptionMemoryAllocation(requestedSize);
}
if (m_array) {
for (int i = 0; i < m_length; ++i)
newArray[i] = m_array[i];
delete[] m_array;
}
m_array = newArray;
m_alloc = requestedSize;
}
}
};
struct HashTableStatistics
{
int TableSize;
int UsedSlots;
int TotalEntries;
};
struct ResizePolicyNoShrink
{
template <typename Hash>
static void ResizeOnAdd(Hash& hash)
{
HashTableStatistics hashStats;
hash.GetStatistics(&hashStats);
if (hashStats.TotalEntries * 100 / hashStats.TableSize > 70)
{
hash.Resize(hashStats.TableSize * 2);
}
}
};
struct ResizePolicyNoResize {};
template <typename T, typename Key = int, typename ResizePolicy = ResizePolicyNoResize>
class HashTable
{
public:
struct HashEntry
{
T Obj;
Key Key;
HashEntry *NextEntry;
};
template <typename K>
static unsigned HashValue(const K& key)
{
return key;
}
T* FindFirst(const Key& key) const;
int GetTotalEntries() const;
T* WalkFirst() const;
T* WalkNext(const T* prevRes) const;
void GetStatistics(HashTableStatistics* stats) const;
void Resize(int hashSize);
void Insert(const T& obj, const Key& key);
/*0x00*/ HashEntry **Table;
/*0x04*/ int TableSize;
/*0x08*/ int EntryCount;
/*0x0c*/ int StatUsedSlots;
/*0x10*/
};
template <typename T, typename Key, typename ResizePolicy>
void HashTable<T, Key, ResizePolicy>::GetStatistics(HashTableStatistics *stats) const
{
stats->TotalEntries = EntryCount;
stats->UsedSlots = StatUsedSlots;
stats->TableSize = TableSize;
}
inline bool IsPrime(int value)
{
for (int i = 2; i <= value / 2; ++i) {
if (value % i == 0)
return false;
}
return true;
}
inline int NextPrime(int value)
{
if (value % 2 == 0)
value++;
while (!IsPrime(value))
value += 2;
return(value);
}
template <typename T, typename Key, typename ResizePolicy>
void HashTable<T, Key, ResizePolicy>::Resize(int hashSize)
{
HashEntry** oldTable = Table;
int oldSize = TableSize;
TableSize = NextPrime(hashSize);
if (TableSize != oldSize)
{
Table = new HashEntry*[TableSize];
memset(Table, 0, sizeof(HashEntry*) * TableSize);
StatUsedSlots = 0;
if (EntryCount > 0)
{
for (int i = 0; i < oldSize; i++)
{
HashEntry* next = oldTable[i];
while (next != NULL)
{
HashEntry* hold = next;
next = next->NextEntry;
int spot = HashValue<Key>(hold->Key) % TableSize;
if (Table[spot] == NULL)
{
hold->NextEntry = NULL;
Table[spot] = hold;
StatUsedSlots++;
}
else
{
hold->NextEntry = Table[spot];
Table[spot] = hold;
}
}
}
}
delete[] oldTable;
}
}
template <typename T, typename Key, typename ResizePolicy>
T* HashTable<T, Key, ResizePolicy>::WalkFirst() const
{
for (int i = 0; i < TableSize; i++)
{
HashEntry *entry = Table[i];
if (entry != NULL)
return(&entry->Obj);
}
return NULL;
}
template <typename T, typename Key, typename ResizePolicy>
T* HashTable<T, Key, ResizePolicy>::WalkNext(const T* prevRes) const
{
HashEntry *entry = (HashEntry *)(((char *)prevRes) - offsetof(HashEntry, Obj));
int i = (HashValue<Key>(entry->Key)) % TableSize;
entry = entry->NextEntry;
if (entry != NULL)
return(&entry->Obj);
i++;
for (; i < TableSize; i++)
{
HashEntry *entry = Table[i];
if (entry != NULL)
return(&entry->Obj);
}
return NULL;
}
template <typename T, typename Key, typename ResizePolicy>
int HashTable<T, Key, ResizePolicy>::GetTotalEntries() const
{
return EntryCount;
}
template <typename T, typename Key, typename ResizePolicy>
T* HashTable<T, Key, ResizePolicy>::FindFirst(const Key& key) const
{
if (Table == NULL)
return NULL;
HashEntry* entry = Table[(HashValue<Key>(key)) % TableSize];
while (entry != NULL)
{
if (entry->Key == key)
return(&entry->Obj);
entry = entry->NextEntry;
}
return NULL;
}
template <typename T, typename Key, typename ResizePolicy>
void HashTable<T, Key, ResizePolicy>::Insert(const T& obj, const Key& key)
{
HashEntry *entry = new HashEntry;
entry->Obj = obj;
entry->Key = key;
int spot = HashValue<Key>(key) % TableSize;
if (Table[spot] == NULL)
{
entry->NextEntry = NULL;
Table[spot] = entry;
StatUsedSlots++;
}
else
{
entry->NextEntry = Table[spot];
Table[spot] = entry;
}
EntryCount++;
ResizePolicy::ResizeOnAdd(*this);
}
// lists
template <typename T, int _cnt>
class EQList;
template <typename T>
class EQList<T, -1>
{
public:
struct Node
{
T Value;
Node* pNext;
Node* pPrev;
};
/*0x00*/ void* vfTable;
/*0x04*/ Node* pFirst;
/*0x08*/ Node* pLast;
/*0x0c*/ int Count;
/*0x10*/
};
template <typename T, int _cnt = -1>
class EQList : public EQList<T, -1>
{};
// strings
template <typename TheType, unsigned int _Size>
class TSafeArrayStatic
{
public:
inline TheType& operator[](uint32_t index)
{
return Data[index];
}
TheType Data[_Size];
};
template <uint32_t _Len>
class TString : public TSafeArrayStatic<char, _Len>
{};
template <uint32_t _Len>
class TSafeString : public TString<_Len>
{};
class VePointerBase
{
public:
intptr_t Address;
};
template <class T>
class VePointer// : public VePointerBase
{
public:
VePointer();
~VePointer();
T* pObject;
};
template <class T>
VePointer<T>::VePointer()
{
//absolutely not do this here
//pObject = new T;
pObject = 0;
}
template <class T>
VePointer<T>::~VePointer()
{
//absolutely not do this here
//delete pObject;
}
template <typename T>
class VeArray
{
public:
T& operator[](uint32_t);
const T& operator[](uint32_t) const;
/*0x00*/ T* Begin;
/*0x04*/ uint32_t Size;
/*0x08*/ uint32_t Capacity;
/*0x0c*/
};
template <typename T>
const T& VeArray<T>::operator[](uint32_t i) const
{
return Begin[i];
}
template <typename T>
T& VeArray<T>::operator[](uint32_t i)
{
return Begin[i];
}
// LinkedLists
template <class T>
class LinkedListNode
{
public:
/*0x00*/ T Object;
/*0x04*/ LinkedListNode* pNext;
/*0x08*/ LinkedListNode* pPrev;
/*0x0c*/
};
template <class T>
class DoublyLinkedList
{
public:
/*0x00*/ void* vfTable;
/*0x04*/ LinkedListNode<T>* pHead;
/*0x08*/ LinkedListNode<T>* pTail;
/*0x0c*/ LinkedListNode<T>* pCurObject;
/*0x10*/ LinkedListNode<T>* pCurObjectNext;
/*0x14*/ LinkedListNode<T>* pCurObjectPrev;
/*0x18*/ int NumObjects;
/*0x1c*/ int RefCount;
/*0x20*/
};
template <typename KeyType, typename T, int _Size, int _Cnt>
class HashListMap;
template <typename KeyType, typename T, int _Size>
class HashListMap<KeyType, T, _Size, -1>
{
public:
struct Node
{
T Value;
Node* pNext;
Node* pPrev;
KeyType Key;
Node *pHashNext;
};
Node* NodeGet(const T* cur) const
{
return (Node *)((byte *)cur - (size_t)((byte *)(&((Node*)1)->Value) - (byte *)1));
}
enum { TheSize = ((_Size == 0) ? 1 : _Size) };
void* vfTable;
int DynSize;
int MaxDynSize;
Node* pHead;
Node* pTail;
int Count;
union
{
Node *Table[TheSize];
Node **DynTable;
};
};
template <typename T_KEY, typename T, int _Size, int _Cnt = -1>
class HashListMap : public HashListMap<T_KEY, T, _Size, -1>
{
};
template <typename T, int _Size, int _Cnt = -1>
class HashList : public HashListMap<int, T, _Size, _Cnt>
{
};
template <typename T, int _Size, int _Cnt>
class HashListSet;
template <typename T, int _Size>
class HashListSet<T, _Size, -1>
{
public:
using ValueType = T;
struct Node
{
T Value;
Node* pNext;
Node* pPrev;
Node* pNextHash;
};
enum { TheSize = ((_Size == 0) ? 1 : _Size) };
/*0x00*/ PVOID vfTable;
/*0x04*/ int DynSize;
/*0x08*/ int MaxDynSize;
/*0x0c*/ int Count;
/*0x10*/
union
{
Node *Table[TheSize];
Node **DynTable;
};
};
template <typename T, int _Size, int _Cnt = -1>
class HashListSet : public HashListSet<T, _Size, -1>
{};
template <typename T, int _Size>
class HashListSet<T, _Size, -2> : public HashListSet<T, _Size, -1>
{
// todo: change to whatever stl replacement this it, for now we just void* it...
void* MemPool;
};
template <typename T, int _Size, bool _bGrow>
class EQArray;
template <typename T, int _Size, bool _bGrow>
class EQArray2;
template <typename T>
class EQArray<T, 0, true>
{
public:
/*0x00*/ void* pvfTable;
/*0x04*/ T* m_array;
/*0x08*/ int m_length;
/*0x0c*/ int m_space;
/*0x10*/
};
template <typename T>
class EQArray2<T, 0, true>
{
public:
/*0x00*/ void* pvfTable;
/*0x04*/ void* pvfTable2;
/*0x08*/ T* m_array;
/*0x0c*/ int m_length;
/*0x10*/ int m_space;
/*0x14*/
};
template <typename T>
class IString
{
public:
/*0x00*/ void* vfTable;
/*0x04*/ T* String;
/*0x08*/ int Len;
/*0x0c*/ int Space;
/*0x10*/ //0x14? not sure.
};
class IString2
{
public:
EQLIB_OBJECT void Append(char* c);
/*0x00*/ void* vfTable;
/*0x04*/ char* String;
/*0x08*/ int Len;
/*0x0c*/ int Space;
/*0x10*/
};
class AtomicInt
{
public:
volatile int Value;
};
template <typename T, int T_SIZE>
class IStringFixed : public IString<T>
{
public:
BYTE FixedData[(T_SIZE * sizeof(T)) + sizeof(AtomicInt)];
};
template <int T_SIZE>
class StringFixed : public IStringFixed<char, T_SIZE>
{
public:
};
template <typename T, int _Size = 0, bool _bGrow = true>
class EQArray : public EQArray<T, 0, true>
{
public:
enum { cTCount = _Size };
static const bool cTGrow = _bGrow;
};
template <typename T, int _Size = 0, bool _bGrow = true>
class EQArray2 : public EQArray2<T, 0, true>
{
public:
enum { cTCount = _Size };
static const bool cTGrow = _bGrow;
};
template <typename ET>
class CircularArrayClass2 : public CDynamicArrayBase
{
public:
int HeadIndex;
int WrapIndex;
int ArraySize;
int ChunkSize;
int ChunkMask;
int ChunkShift;
ET** Chunks;
int ChunkAlloc;
#if !defined(TEST) && !defined(LIVE)
bool bValid;
#endif
};
template <typename TNumBitsType, typename TElementType>
class DynamicBitField
{
using NumBitsType = TNumBitsType;
using ElementType = TElementType;
NumBitsType NumBits;
ElementType Element;
ElementType* Elements;
};
#pragma pack(pop)
| [
"[email protected]"
] | |
5f7477d21db4620b2933830c9415d51fac77a649 | e8ae83f378a3f373ab3a7ebb058da5c8a91e13ff | /Roguelike/Code/Game/Inventory.cpp | 4a440a9da667eb6d5ea132820cdc2c9a425efa6d | [
"MIT"
] | permissive | cugone/Roguelike | 417cea31ddbb650ab72d55d0a90e5336ee4362bd | a62e83df50fda7311f8c89828cd68789de88d9e6 | refs/heads/master | 2023-01-27T20:36:48.213029 | 2023-01-24T16:01:06 | 2023-01-24T16:01:06 | 181,536,221 | 0 | 2 | MIT | 2023-01-20T02:00:30 | 2019-04-15T17:38:06 | C++ | UTF-8 | C++ | false | false | 6,543 | cpp | #include "Game/Inventory.hpp"
#include "Engine/Core/ErrorWarningAssert.hpp"
#include "Game/GameCommon.hpp"
#include "Game/Item.hpp"
#include "Game/Layer.hpp"
#include <utility>
Inventory::Inventory(const XMLElement& elem) noexcept
{
LoadFromXml(elem);
}
Item* Inventory::HasItem(const Item* item) const noexcept {
if(!item) {
return nullptr;
}
auto found_iter = std::find(std::begin(_items), std::end(_items), item);
if(found_iter != std::end(_items)) {
return *found_iter;
}
return nullptr;
}
Item* Inventory::HasItem(const std::string& name) const noexcept {
auto found_iter = std::find_if(std::begin(_items), std::end(_items), [&name](const Item* item) { return StringUtils::ToLowerCase(item->GetName()) == StringUtils::ToLowerCase(name); });
if(found_iter != std::end(_items)) {
return *found_iter;
}
return nullptr;
}
void Inventory::AddStack(Item* item, std::size_t count) noexcept {
if(auto* i = HasItem(item)) {
i->AdjustCount(count);
} else {
i = AddItem(item);
i->SetCount(count);
}
}
void Inventory::AddStack(const std::string& name, std::size_t count) noexcept {
if(auto* item = HasItem(name)) {
item->AdjustCount(count);
} else {
if((item = AddItem(name)) != nullptr) {
item->SetCount(count);
}
}
}
Item* Inventory::AddItem(Item* item) noexcept {
if(item) {
if(auto i = HasItem(item)) {
i->IncrementCount();
return i;
} else {
_items.push_back(item);
_items.back()->IncrementCount();
return _items.back();
}
}
return nullptr;
}
Item* Inventory::AddItem(const std::string& name) noexcept {
if(auto* item_in_inventory = HasItem(name)) {
item_in_inventory->IncrementCount();
return item_in_inventory;
} else {
if(auto* item_in_registry = Item::GetItem(name)) {
_items.push_back(item_in_registry);
_items.back()->IncrementCount();
return _items.back();
}
}
return nullptr;
}
void Inventory::RemoveItem(Item* item) noexcept {
if(item) {
if(auto i = HasItem(item)) {
if(!i->DecrementCount()) {
auto found_iter = std::find(std::begin(_items), std::end(_items), i);
if(found_iter != std::end(_items)) {
_items.erase(found_iter);
}
}
}
}
}
void Inventory::RemoveItem(Item* item, std::size_t count) noexcept {
if(item) {
if(auto i = HasItem(item)) {
if(count < i->GetCount()) {
i->AdjustCount(-static_cast<long long>(count));
} else {
RemoveItem(i);
}
}
}
}
void Inventory::RemoveItem(const std::string& name) noexcept {
if(auto i = HasItem(name)) {
if(!i->DecrementCount()) {
auto found_iter = std::find(std::begin(_items), std::end(_items), i);
if(found_iter != std::end(_items)) {
_items.erase(found_iter);
}
}
}
}
const Item* Inventory::GetItem(const std::string& name) const noexcept {
auto found_iter = std::find_if(std::begin(_items), std::end(_items), [&name](const Item* item)->bool { return item->GetName() == name; });
if(found_iter == std::end(_items)) {
return nullptr;
}
return *found_iter;
}
const Item* Inventory::GetItem(std::size_t idx) const noexcept {
if(_items.size() < idx) {
return nullptr;
}
return _items[idx];
}
Item* Inventory::GetItem(const std::string& name) noexcept {
return const_cast<Item*>(static_cast<const Inventory&>(*this).GetItem(name));
}
Item* Inventory::GetItem(std::size_t idx) noexcept {
return const_cast<Item*>(static_cast<const Inventory&>(*this).GetItem(idx));
}
bool Inventory::TransferItem(Inventory& source, Inventory& dest, Item* item) noexcept {
source.RemoveItem(item);
return dest.AddItem(item) != nullptr;
}
bool Inventory::TransferItem(Inventory& dest, Item* item) noexcept {
return Inventory::TransferItem(*this, dest, item);
}
bool Inventory::TransferItem(Inventory& source, Inventory& dest, const std::string& name) noexcept {
auto item = source.GetItem(name);
source.RemoveItem(item);
return dest.AddItem(item) != nullptr;
}
bool Inventory::TransferItem(Inventory& dest, const std::string& name) noexcept {
return Inventory::TransferItem(*this, dest, name);
}
void Inventory::TransferAll(Inventory& source, Inventory& dest) noexcept {
for(const auto& item : source) {
dest.AddItem(item);
}
source.clear();
}
void Inventory::TransferAll(Inventory& dest) noexcept {
return Inventory::TransferAll(*this, dest);
}
std::size_t Inventory::size() const noexcept {
return _items.size();
}
bool Inventory::empty() const noexcept {
return _items.empty();
}
void Inventory::clear() noexcept {
_items.clear();
}
Inventory::iterator Inventory::begin() noexcept {
return _items.begin();
}
Inventory::iterator Inventory::end() noexcept {
return _items.end();
}
Inventory::const_iterator Inventory::begin() const noexcept {
return _items.begin();
}
Inventory::const_iterator Inventory::end() const noexcept {
return _items.end();
}
Inventory::const_iterator Inventory::cbegin() const noexcept {
return _items.cbegin();
}
Inventory::const_iterator Inventory::cend() const noexcept {
return _items.cend();
}
Inventory::reverse_iterator Inventory::rbegin() noexcept {
return _items.rbegin();
}
Inventory::reverse_iterator Inventory::rend() noexcept {
return _items.rend();
}
Inventory::const_reverse_iterator Inventory::rbegin() const noexcept {
return _items.rbegin();
}
Inventory::const_reverse_iterator Inventory::rend() const noexcept {
return _items.rend();
}
Inventory::const_reverse_iterator Inventory::crbegin() const noexcept {
return _items.crbegin();
}
Inventory::const_reverse_iterator Inventory::crend() const noexcept {
return _items.crend();
}
void Inventory::LoadFromXml(const XMLElement& elem) {
DataUtils::ValidateXmlElement(elem, "inventory", "item", "");
DataUtils::ForEachChildElement(elem, "item",
[this](const XMLElement& elem) {
auto item_name = DataUtils::ParseXmlAttribute(elem, "name", std::string{});
if(auto item = Item::GetItem(item_name)) {
_items.emplace_back(item);
}
});
}
| [
"[email protected]"
] | |
561c1c31f5ecf0a5ec3c17f83b46afbc5a458671 | 1cf02ad632e9c15e9ec6be4886cb4aa75eef4049 | /Bohge_Engine/Framework/TextureMetadata.h | 2e0b66f52578280726d23e43185e71a903f7e07b | [
"MIT"
] | permissive | xywwf/Bohge_Engine | 5b92152468fdfb19062d8f5b607c728bb503987e | 7695a8633260652035e56842ea75c9013258c5a1 | refs/heads/master | 2020-05-24T08:44:16.355433 | 2017-08-04T07:54:43 | 2017-08-04T07:55:57 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,731 | h | //////////////////////////////////////////////////////////////////////////////////////
//
// The Bohge Engine License (BEL)
//
// Copyright (c) 2011-2014 Peng Zhao
//
// 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. And the logo of
// Bohge Engine shall be displayed full screen for more than 3 seconds
// when the software is started. Copyright holders are allowed to develop
// game edit based on Bohge Engine, The edit must be released under the MIT
// open source license if it is going to be published. In no event shall
// copyright holders be prohibited from using any code of Bohge Engine
// to develop any other analogous game engines.
//
// 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
//
//////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "TextureProperty.h"
#include "IMetadata.h"
namespace BohgeEngine
{
class BOHGE_FRAMEWORK TextureFileMetadata : public IMetadata
{
RTTI_DRIVER_TYPE_DECLEAR( TextureFileMetadata, IMetadata );
private:
eastl::string m_Path;
TextureProperty::TextureUseage m_eUsage;
TextureProperty::PixelFormat m_ePixelFormat;
TextureProperty::TextureWarp m_eSWarp;
TextureProperty::TextureWarp m_eTWarp;
TextureProperty::TextureFilter m_eMagFilter;
TextureProperty::TextureFilter m_eMinFilter;
uint m_uAnisotropic;
bool m_isMipMap;
TextureProperty::TextrueSourceData* m_pTextureData;
public:
TextureFileMetadata(
TextureProperty::TextureUseage mu, TextureProperty::PixelFormat pf,
uint x, bool mip,
TextureProperty::TextureWarp s, TextureProperty::TextureWarp t,
TextureProperty::TextureFilter mag, TextureProperty::TextureFilter min,
const eastl::string& path );
virtual ~TextureFileMetadata();
private:
virtual void* _ReturnMetadata( );
public:
virtual void GetIdentifier( eastl::vector<byte>& bytes ) const;//在str中推入表示符号
virtual void ProcessMetadata();//处理原始资源
virtual void ReleaseMetadate();
};
//本地数据生成纹理
class BOHGE_FRAMEWORK TextureBufferMetadata : public IMetadata
{
RTTI_DRIVER_TYPE_DECLEAR( TextureBufferMetadata, IMetadata );
private:
byte* m_pData;
TextureProperty::TextrueSourceData* m_pTextureData;
TextureProperty::TextureType m_eType;
TextureProperty::TextureUseage m_Usage;
TextureProperty::PixelFormat m_ePixelFormat;
TextureProperty::TextureWarp m_eSWarp;
TextureProperty::TextureWarp m_eTWarp;
TextureProperty::TextureFilter m_eMagFilter;
TextureProperty::TextureFilter m_eMinFilter;
uint m_uAnisotropic;
bool m_isMipMap;
byte m_Channel;
vector2d m_Size;
public:
//TextureBufferMetadata(
// const vector2d& size, TextureProperty::TextureType type,
// TextureProperty::PixelFormat pf, uint anisotropic,
// TextureProperty::TextureWarp s, TextureProperty::TextureWarp t,
// TextureProperty::TextureFilter mag, TextureProperty::TextureFilter min,
// byte pixelsize, byte* buf );//数据可以为空,这样会生成一张白色纹理
TextureBufferMetadata(
const vector2d& size, TextureProperty::TextureType type,
TextureProperty::TextureUseage mu, TextureProperty::PixelFormat pf,
uint anisotropic, bool mip,
TextureProperty::TextureWarp s, TextureProperty::TextureWarp t,
TextureProperty::TextureFilter mag, TextureProperty::TextureFilter min,
byte* buf );//数据可以为空,这样会生成一张白色纹理
virtual ~TextureBufferMetadata();
private:
virtual void* _ReturnMetadata( );
public:
virtual void GetIdentifier( eastl::vector<byte>& bytes ) const;//在str中推入表示符号
virtual void ProcessMetadata();//处理原始资源
virtual void ReleaseMetadate();
};
} | [
"[email protected]"
] | |
0e83d6cd153da2e65fda496d18562963a2eab688 | 5aaa3824fe15e80c7ee5a5150a7a14d15d8d3089 | /engine/include/PerformanceTest.h | 8ca59a0f0d0e3d3485d9363baf5de4babda45869 | [
"MIT"
] | permissive | Vbif/geometric-diversity | a7314d5eb2c4182925e8cb901ba054a6d39e1933 | 6e9d5a923db68acb14a0a603bd2859f4772db201 | refs/heads/master | 2021-09-04T02:15:33.285195 | 2018-01-14T13:56:50 | 2018-01-14T13:56:50 | 115,753,012 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 748 | h | #ifndef __PerformanceTest_h__
#define __PerformanceTest_h__
#if defined(_MSC_VER) && (_MSC_VER > 1300)
#pragma once
#endif
namespace Render {
class Target;
class Texture;
}
///
/// Измеряет производительность видеосистемы
///
class PerformanceTest {
public:
static const int kTargetSize, kTextureSize, kLoopSize, kEstimateCount;
PerformanceTest();
~PerformanceTest();
float Estimate(int loopSize = kLoopSize, int estimateCount = kEstimateCount) const;
private:
float Run(int loopSize) const;
PerformanceTest(const PerformanceTest&);
const PerformanceTest& operator=(const PerformanceTest&);
private:
Render::Target* _target;
Render::Texture* _texture;
};
#endif // __PerformanceTest_h__
| [
"[email protected]"
] | |
86a85560961b6d6a17f74dba0936b063b5eb0427 | 73ee941896043f9b3e2ab40028d24ddd202f695f | /external/chromium_org/content/renderer/media/video_capture_message_filter_unittest.cc | 222600ad830fc7020c6334dcc9113928740f1826 | [
"BSD-3-Clause"
] | permissive | CyFI-Lab-Public/RetroScope | d441ea28b33aceeb9888c330a54b033cd7d48b05 | 276b5b03d63f49235db74f2c501057abb9e79d89 | refs/heads/master | 2022-04-08T23:11:44.482107 | 2016-09-22T20:15:43 | 2016-09-22T20:15:43 | 58,890,600 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 7,135 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/shared_memory.h"
#include "base/message_loop/message_loop.h"
#include "content/common/media/video_capture_messages.h"
#include "content/renderer/media/video_capture_message_filter.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
namespace {
class MockVideoCaptureDelegate : public VideoCaptureMessageFilter::Delegate {
public:
MockVideoCaptureDelegate() {
Reset();
device_id_received_ = false;
device_id_ = 0;
}
virtual void OnBufferCreated(base::SharedMemoryHandle handle,
int length, int buffer_id) OVERRIDE {
buffer_created_ = true;
handle_ = handle;
}
// Called when a video frame buffer is received from the browser process.
virtual void OnBufferReceived(int buffer_id, base::Time timestamp) OVERRIDE {
buffer_received_ = true;
buffer_id_ = buffer_id;
timestamp_ = timestamp;
}
virtual void OnStateChanged(VideoCaptureState state) OVERRIDE {
state_changed_received_ = true;
state_ = state;
}
virtual void OnDeviceInfoReceived(
const media::VideoCaptureParams& params) OVERRIDE {
device_info_received_ = true;
params_.width = params.width;
params_.height = params.height;
params_.frame_per_second = params.frame_per_second;
}
virtual void OnDelegateAdded(int32 device_id) OVERRIDE {
device_id_received_ = true;
device_id_ = device_id;
}
void Reset() {
buffer_created_ = false;
handle_ = base::SharedMemory::NULLHandle();
buffer_received_ = false;
buffer_id_ = -1;
timestamp_ = base::Time();
state_changed_received_ = false;
state_ = VIDEO_CAPTURE_STATE_ERROR;
device_info_received_ = false;
params_.width = 0;
params_.height = 0;
params_.frame_per_second = 0;
}
bool buffer_created() { return buffer_created_; }
base::SharedMemoryHandle received_buffer_handle() { return handle_; }
bool buffer_received() { return buffer_received_; }
int received_buffer_id() { return buffer_id_; }
base::Time received_buffer_ts() { return timestamp_; }
bool state_changed_received() { return state_changed_received_; }
VideoCaptureState state() { return state_; }
bool device_info_receive() { return device_info_received_; }
const media::VideoCaptureParams& received_device_info() { return params_; }
int32 device_id() { return device_id_; }
private:
bool buffer_created_;
base::SharedMemoryHandle handle_;
bool buffer_received_;
int buffer_id_;
base::Time timestamp_;
bool state_changed_received_;
VideoCaptureState state_;
bool device_info_received_;
media::VideoCaptureParams params_;
bool device_id_received_;
int32 device_id_;
DISALLOW_COPY_AND_ASSIGN(MockVideoCaptureDelegate);
};
} // namespace
TEST(VideoCaptureMessageFilterTest, Basic) {
base::MessageLoop message_loop(base::MessageLoop::TYPE_IO);
scoped_refptr<VideoCaptureMessageFilter> filter(
new VideoCaptureMessageFilter());
filter->channel_ = reinterpret_cast<IPC::Channel*>(1);
MockVideoCaptureDelegate delegate;
filter->AddDelegate(&delegate);
// VideoCaptureMsg_StateChanged
EXPECT_FALSE(delegate.state_changed_received());
filter->OnMessageReceived(
VideoCaptureMsg_StateChanged(delegate.device_id(),
VIDEO_CAPTURE_STATE_STARTED));
EXPECT_TRUE(delegate.state_changed_received());
EXPECT_TRUE(VIDEO_CAPTURE_STATE_STARTED == delegate.state());
delegate.Reset();
// VideoCaptureMsg_NewBuffer
const base::SharedMemoryHandle handle =
#if defined(OS_WIN)
reinterpret_cast<base::SharedMemoryHandle>(10);
#else
base::SharedMemoryHandle(10, true);
#endif
EXPECT_FALSE(delegate.buffer_created());
filter->OnMessageReceived(VideoCaptureMsg_NewBuffer(
delegate.device_id(), handle, 1, 1));
EXPECT_TRUE(delegate.buffer_created());
EXPECT_EQ(handle, delegate.received_buffer_handle());
delegate.Reset();
// VideoCaptureMsg_BufferReady
int buffer_id = 1;
base::Time timestamp = base::Time::FromInternalValue(1);
EXPECT_FALSE(delegate.buffer_received());
filter->OnMessageReceived(VideoCaptureMsg_BufferReady(
delegate.device_id(), buffer_id, timestamp));
EXPECT_TRUE(delegate.buffer_received());
EXPECT_EQ(buffer_id, delegate.received_buffer_id());
EXPECT_TRUE(timestamp == delegate.received_buffer_ts());
delegate.Reset();
// VideoCaptureMsg_DeviceInfo
media::VideoCaptureParams params;
params.width = 320;
params.height = 240;
params.frame_per_second = 30;
EXPECT_FALSE(delegate.device_info_receive());
filter->OnMessageReceived(VideoCaptureMsg_DeviceInfo(
delegate.device_id(), params));
EXPECT_TRUE(delegate.device_info_receive());
EXPECT_EQ(params.width, delegate.received_device_info().width);
EXPECT_EQ(params.height, delegate.received_device_info().height);
EXPECT_EQ(params.frame_per_second,
delegate.received_device_info().frame_per_second);
delegate.Reset();
message_loop.RunUntilIdle();
}
TEST(VideoCaptureMessageFilterTest, Delegates) {
base::MessageLoop message_loop(base::MessageLoop::TYPE_IO);
scoped_refptr<VideoCaptureMessageFilter> filter(
new VideoCaptureMessageFilter());
filter->channel_ = reinterpret_cast<IPC::Channel*>(1);
MockVideoCaptureDelegate delegate1;
MockVideoCaptureDelegate delegate2;
filter->AddDelegate(&delegate1);
filter->AddDelegate(&delegate2);
// Send an IPC message. Make sure the correct delegate gets called.
EXPECT_FALSE(delegate1.state_changed_received());
EXPECT_FALSE(delegate2.state_changed_received());
filter->OnMessageReceived(
VideoCaptureMsg_StateChanged(delegate1.device_id(),
VIDEO_CAPTURE_STATE_STARTED));
EXPECT_TRUE(delegate1.state_changed_received());
EXPECT_FALSE(delegate2.state_changed_received());
delegate1.Reset();
EXPECT_FALSE(delegate1.state_changed_received());
EXPECT_FALSE(delegate2.state_changed_received());
filter->OnMessageReceived(
VideoCaptureMsg_StateChanged(delegate2.device_id(),
VIDEO_CAPTURE_STATE_STARTED));
EXPECT_FALSE(delegate1.state_changed_received());
EXPECT_TRUE(delegate2.state_changed_received());
delegate2.Reset();
// Remove the delegates. Make sure they won't get called.
filter->RemoveDelegate(&delegate1);
EXPECT_FALSE(delegate1.state_changed_received());
filter->OnMessageReceived(
VideoCaptureMsg_StateChanged(delegate1.device_id(),
VIDEO_CAPTURE_STATE_STARTED));
EXPECT_FALSE(delegate1.state_changed_received());
filter->RemoveDelegate(&delegate2);
EXPECT_FALSE(delegate2.state_changed_received());
filter->OnMessageReceived(
VideoCaptureMsg_StateChanged(delegate2.device_id(),
VIDEO_CAPTURE_STATE_STARTED));
EXPECT_FALSE(delegate2.state_changed_received());
message_loop.RunUntilIdle();
}
} // namespace content
| [
"[email protected]"
] | |
21e612cfdee3b2f3d10efa2233eb5886bdb65bf7 | 4509f3721d6ebea8fd7f4cb23450d2fe56060c77 | /src/engine/graphics/source/TextureFactory.cpp | 091d58a8432fcfabccba56224e0c0beb62fbe731 | [] | no_license | Kadowns/RIFE-Engine | 54fa0199a4ba6856f3d925cbcf035f60eb53a75f | 975373ef1e4104edbfcf5fddc5a065dd9e5b05a7 | refs/heads/master | 2020-03-28T02:50:08.366865 | 2019-05-24T15:55:00 | 2019-05-24T15:55:00 | 147,600,758 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,782 | cpp | #include <TextureFactory.h>
#include <VulkanTools.h>
#include <VulkanData.h>
#include <RifePath.h>
//#define STB_IMAGE_IMPLEMENTATION
//#include <stb_image.h>
#include <gli/gli.hpp>
#include <Buffer.h>
namespace Rife::Graphics {
Texture* TextureFactory::loadTexture(const std::string& path) {
TextureInfo textureInfo = {};
createTexture2DImage(path, textureInfo);
return new Texture(textureInfo);
}
Texture* TextureFactory::defaultTexture() {
TextureInfo textureInfo = {};
createTexture2DImage("",textureInfo);
return new Texture(textureInfo);
}
Texture* TextureFactory::loadCubemap(const std::string& path) {
TextureInfo textureInfo = {};
createCubemapImage(path, textureInfo);
return new Texture(textureInfo);
}
void TextureFactory::createTexture2DImage(const std::string& path, TextureInfo& texture) {
gli::texture tex(gli::load(TEXTURE_FOLDER + path));
if (tex.empty()) {
gli::texture tex = gli::load(TEXTURE_FOLDER + std::string("default_texture.ktx"));
}
texture.extent.width = tex.extent().x;
texture.extent.height = tex.extent().y;
texture.mipLevels = tex.levels();
texture.layerCount = tex.layers();
Buffer stagingBuffer;
BufferInfo info = {};
info.memoryPropertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
info.usageFlags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
VulkanTools::createBuffer(
tex.size(),
info,
stagingBuffer,
tex.data()
);
VkFormat format;
VkPhysicalDeviceFeatures deviceFeatures = Vulkan::physicalDeviceFeatures;
if (deviceFeatures.textureCompressionBC) {
format = VK_FORMAT_BC3_UNORM_BLOCK;
}
else if (deviceFeatures.textureCompressionASTC_LDR) {
format = VK_FORMAT_ASTC_8x8_UNORM_BLOCK;
}
else if (deviceFeatures.textureCompressionETC2) {
format = VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK;
}
else {
throw std::runtime_error("Failed to find a supported texture format!");
}
VulkanTools::createImage(
texture.extent.width, texture.extent.height, texture.mipLevels, 1,
format, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
texture.image,
texture.memory,
0
);
VkImageSubresourceRange subresourceRange = {};
subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
subresourceRange.baseMipLevel = 0;
subresourceRange.levelCount = 1;
subresourceRange.baseArrayLayer = 0;
subresourceRange.layerCount = 1;
VulkanTools::transitionImageLayout(texture.image, format, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresourceRange);
copyBufferToImage(stagingBuffer.buffer, texture.image, texture.extent.width, texture.extent.height);
VulkanTools::transitionImageLayout(texture.image, format, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresourceRange);
stagingBuffer.destroy();
texture.imageView = VulkanTools::createImageView(texture.image, format, VK_IMAGE_VIEW_TYPE_2D, subresourceRange);
createTextureSampler(texture);
}
void TextureFactory::createCubemapImage(const std::string& path, TextureInfo& texture) {
gli::texture_cube texCube(gli::load(TEXTURE_FOLDER + path));
assert(!texCube.empty());
texture.extent.width = texCube.extent().x;
texture.extent.height = texCube.extent().y;
texture.mipLevels = texCube.levels();
texture.layerCount = texCube.layers();
Buffer stagingBuffer;
BufferInfo info = {};
info.memoryPropertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
info.usageFlags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
VulkanTools::createBuffer(
texCube.size(),
info,
stagingBuffer,
texCube.data()
);
VkFormat format;
VkPhysicalDeviceFeatures deviceFeatures = Vulkan::physicalDeviceFeatures;
if (deviceFeatures.textureCompressionBC) {
format = VK_FORMAT_BC3_UNORM_BLOCK;
}
else if (deviceFeatures.textureCompressionASTC_LDR) {
format = VK_FORMAT_ASTC_8x8_UNORM_BLOCK;
}
else if (deviceFeatures.textureCompressionETC2) {
format = VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK;
}
else {
throw std::runtime_error("Failed to find a supported texture format!");
}
VulkanTools::createImage(
texture.extent.width, texture.extent.height, texture.mipLevels, 6,
format, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
texture.image,
texture.memory,
VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT
);
VkImageSubresourceRange subresourceRange = {};
subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
subresourceRange.baseMipLevel = 0;
subresourceRange.levelCount = texture.mipLevels;
subresourceRange.layerCount = 6;
VulkanTools::transitionImageLayout(
texture.image, format, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresourceRange
);
copyBufferToCubemap(stagingBuffer.buffer, texture.image, texCube);
VulkanTools::transitionImageLayout(
texture.image, format, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresourceRange
);
stagingBuffer.destroy();
texture.imageView = VulkanTools::createImageView(texture.image, format, VK_IMAGE_VIEW_TYPE_CUBE, subresourceRange);
createTextureSampler(texture);
}
void TextureFactory::createTextureSampler(TextureInfo& texture) {
VkSamplerCreateInfo samplerInfo = {};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_TRUE;
samplerInfo.maxAnisotropy = 16;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = texture.mipLevels;
if (vkCreateSampler(Vulkan::device, &samplerInfo, nullptr, &texture.sampler) != VK_SUCCESS) {
throw std::runtime_error("failed to create texture sampler!");
}
}
void TextureFactory::copyBufferToImage(VkBuffer buffer, VkImage image, uint32_t width, uint32_t height) {
VkCommandBuffer commandBuffer = VulkanTools::beginSingleTimeCommands();
VkBufferImageCopy region = {};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = { 0, 0, 0 };
region.imageExtent = {
width,
height,
1
};
vkCmdCopyBufferToImage(
commandBuffer,
buffer,
image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
®ion
);
VulkanTools::endSingleTimeCommands(commandBuffer);
}
void TextureFactory::copyBufferToCubemap(VkBuffer buffer, VkImage image, gli::texture_cube& cube) {
VkCommandBuffer commandBuffer = VulkanTools::beginSingleTimeCommands();
std::vector<VkBufferImageCopy> bufferCopyRegions;
uint32_t offset = 0;
for (uint32_t face = 0; face < 6; face++) {
for (uint32_t level = 0; level < cube.levels(); level++) {
VkBufferImageCopy bufferCopyRegion = {};
bufferCopyRegion.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
bufferCopyRegion.imageSubresource.mipLevel = level;
bufferCopyRegion.imageSubresource.baseArrayLayer = face;
bufferCopyRegion.imageSubresource.layerCount = 1;
bufferCopyRegion.imageExtent.width = cube[face][level].extent().x;
bufferCopyRegion.imageExtent.height = cube[face][level].extent().y;
bufferCopyRegion.imageExtent.depth = 1;
bufferCopyRegion.bufferOffset = offset;
bufferCopyRegions.push_back(bufferCopyRegion);
// Increase offset into staging buffer for next level / face
offset += cube[face][level].size();
}
}
vkCmdCopyBufferToImage(
commandBuffer,
buffer,
image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
static_cast<uint32_t>(bufferCopyRegions.size()),
bufferCopyRegions.data()
);
VulkanTools::endSingleTimeCommands(commandBuffer);
}
}
| [
"[email protected]"
] | |
3c5a5b67066e8217dbf08b37ec94c1c62f8e68a1 | cb2ec9ec2366d8bf5e279eae2cb33ec28f93760a | /ProgramEncryptoAndDecrypto.cpp | 983bedc2c1de5c5a2ccfdb66513c8d01a8d0b794 | [] | no_license | trungliennd/Elliptic25519 | 8949d34836e4f93a24ad2c251a2dd9ff57cd5c53 | c70e51d1688dd8c90d49db5f574889a9f05e988e | refs/heads/master | 2020-05-25T20:19:29.396976 | 2017-03-14T15:38:10 | 2017-03-14T15:38:10 | 84,964,394 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,901 | cpp | #include <stdio.h>
#include <sodium.h>
#include <string>
#include <string.h>
#include <iostream>
#include <fstream>
#define MESSAGE_LEN 10240 // 1024 bytes
#define CIPHERTEXT_LEN_MESSAGE (MESSAGE_LEN + crypto_aead_aes256gcm_ABYTES) // 10240 + 16 bytes
#define NONCE_LEN crypto_secretbox_NONCEBYTES
#define BASE64_LEN 44
using namespace std;
unsigned char publicKey25519[crypto_scalarmult_curve25519_BYTES]; // use 32 bytes
unsigned char secretKey25519[crypto_scalarmult_curve25519_BYTES]; // use 32 bytes
unsigned char sharesKey25519[crypto_scalarmult_curve25519_BYTES]; // user 32 bytes
unsigned char nonce[crypto_secretbox_NONCEBYTES];
unsigned char MESSAGES[MESSAGE_LEN];
unsigned char CIPHERTEXT[MESSAGE_LEN + crypto_aead_aes256gcm_ABYTES];
void createPublicKeyAndSecretKey(char secretKey[],char publicKey[]);
void encrypto_messages(char file_message[],char file_ciphertext[]);
void decrypto_messages(char file_ciphertext[],char file_message[]);
string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len);
string base64_decode(std::string const& encoded_string);
inline bool is_base64(unsigned char c);
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
void createPublicKeyAndSecretKey(char secretKey[],char publicKey[]) {
unsigned char publicKeyEd25519[crypto_sign_ed25519_PUBLICKEYBYTES];
unsigned char secretKeyEd25519[crypto_sign_ed25519_SECRETKEYBYTES];
/*
* convert ed25519 to curver295519
*/
crypto_sign_ed25519_keypair(publicKeyEd25519,secretKeyEd25519);
if(crypto_sign_ed25519_pk_to_curve25519(publicKey25519, publicKeyEd25519) == 0
&& crypto_sign_ed25519_sk_to_curve25519(secretKey25519,secretKeyEd25519) == 0){
printf("\nCreate Key Successfully!!!\n");
}
/*
* write public key and secret key
*/
FILE *out = fopen(secretKey,"w");
if(out == NULL) {
printf("\nWrite secretKey Fail");
exit(EXIT_FAILURE);
}else {
string secret = base64_encode(secretKey25519,crypto_scalarmult_curve25519_BYTES);
int len = secret.length();
fprintf(out,"---------------- SECERT KEY ----------------\n");
fwrite(secret.c_str(),1,len,out);
fprintf(out,"\n--------------------------------------------");
}
fclose(out);
FILE *inp = fopen(publicKey,"w");
if(inp == NULL) {
printf("\nWrite publicKey Fail");
exit(EXIT_FAILURE);
}else {
string pub = base64_encode(publicKey25519,crypto_scalarmult_curve25519_BYTES);
int len = pub.length();
fprintf(inp,"---------------- PUBLIC KEY ----------------\n");
fwrite(pub.c_str(),1,len,inp);
fprintf(inp,"\n--------------------------------------------");
/*
* printf public key
*/
printf("\n---------------- PUBLIC KEY ----------------\n");
printf("%s",pub.c_str());
printf("\n--------------------------------------------\n");
}
fclose(inp);
}
void copyKey(unsigned char *a,const char* b,int len) {
for(int i =0 ;i < len;i++) {
a[i] = b[i];
}
}
void loadPublicKeyOfPartnerAndMySecretKey(char publickey[],char secretkey[]) {
/*
* read publicKeyOfPartner
*/
FILE *inp = fopen(publickey,"r");
if(inp == NULL) {
printf("\nCan't read publicKey");
exit(EXIT_FAILURE);
}else {
unsigned char pub[BASE64_LEN];
fread(pub,1,BASE64_LEN,inp);
fscanf(inp,"%c",&pub[BASE64_LEN - 1]);
fread(pub,1,BASE64_LEN,inp);
pub[BASE64_LEN] = '\0';
string s((char*)pub);
copyKey(publicKey25519,base64_decode(s).c_str(),crypto_scalarmult_curve25519_BYTES);
}
publicKey25519[crypto_scalarmult_curve25519_BYTES] = '\0';
fclose(inp);
/*
* write MysecretKey
*/
FILE *out = fopen(secretkey,"r");
if(out == NULL) {
printf("\nCan't read secretKey");
exit(EXIT_FAILURE);
}else {
unsigned char secret[BASE64_LEN];
fread(secret,1,BASE64_LEN,out);
fscanf(out,"%c",&secret[BASE64_LEN - 1]);
fread(secret,1,BASE64_LEN,out);
secret[BASE64_LEN] = '\0';
string s((char*)secret);
copyKey(secretKey25519,base64_decode(s).c_str(),crypto_scalarmult_curve25519_BYTES);
}
secretKey25519[crypto_scalarmult_curve25519_BYTES] = '\0';
fclose(out);
// read successfully
}
inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
string base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
/*
void loadAndWriteNonce(char non[],char checked) {
if(checked == 'r') {
FILE *inp = fopen(non,"r");
if(inp == NULL) {
printf("\nCan't read Nonce");
exit(EXIT_FAILURE);
}else {
for(int i = 0;i < crypto_secretbox_NONCEBYTES;i++) {
fscanf(inp,"%c",&nonce[i]);
}
}
}else {
randombytes_buf(nonce, sizeof nonce);
FILE *inp = fopen(non,"w");
if(inp == NULL) {
printf("\nCan't write Nonce");
exit(EXIT_FAILURE);
}else {
for(int i = 0;i < crypto_secretbox_NONCEBYTES;i++) {
fprintf(inp,"%c",nonce[i]);
}
}
}
}
*/
void WriteFile(char non[],unsigned char key[],int len) {
FILE *inp = fopen(non,"wb");
if(inp == NULL) {
printf("\nCan't write Nonce");
exit(EXIT_FAILURE);
}else {
fwrite(CIPHERTEXT,1,len,inp);
}
}
void clearMESSAGES() {
for(int i = 0;i < MESSAGE_LEN;i++) {
MESSAGES[i] = '\0';
}
}
void encrypto_messages(char file_message[],char file_ciphertext[]) {
randombytes_buf(nonce, sizeof nonce);
//loadAndWriteNonce((char*)"nonce.txt",'w');
FILE *inp = fopen(file_message,"rb");
FILE *out = fopen(file_ciphertext,"wb");
if(inp == NULL || out == NULL) {
printf("\nCan't not encrypto");
exit(EXIT_FAILURE);
}
fwrite(nonce,1,NONCE_LEN,out);
//printf("\nnonce is: %d",(int)NONCE_LEN);
if (crypto_aead_aes256gcm_is_available() == 0) {
abort(); /* Not available on this CPU */
}
if(crypto_scalarmult(sharesKey25519,secretKey25519,publicKey25519) != 0) {
printf("\nCan't caculation share key");
exit(EXIT_FAILURE);
}
unsigned long long CIPHERTEXT_LEN;
int index = 0;
while(index = fread(MESSAGES,1,MESSAGE_LEN,inp) != 0){
if(crypto_aead_aes256gcm_encrypt(CIPHERTEXT,&CIPHERTEXT_LEN,MESSAGES,
MESSAGE_LEN, NULL,0,NULL,nonce,sharesKey25519) != 0){
printf("\nEncrypto Fail");
exit(EXIT_FAILURE);
}
fwrite(CIPHERTEXT,1,CIPHERTEXT_LEN,out);
clearMESSAGES();
}
fclose(inp);
fclose(out);
}
void decrypto_messages(char file_ciphertext[],char file_message[]) {
FILE *inp = fopen(file_ciphertext,"rb");
FILE *out = fopen(file_message,"w");
if(inp == NULL || out == NULL) {
printf("\nCan't decrypto ciphertext");
exit(EXIT_FAILURE);
}
if (crypto_aead_aes256gcm_is_available() == 0) {
abort(); /* Not available on this CPU */
}
if(crypto_scalarmult(sharesKey25519,secretKey25519,publicKey25519) != 0) {
printf("\nCan't caculation share key");
exit(EXIT_FAILURE);
}
char c;
int index = 0;
unsigned long long len;
/*
* read nonce into file cipher_text
*/
int size = fread(nonce,1,NONCE_LEN,inp);
if(size != (int)NONCE_LEN) {
printf("\nNonce not correct, size is: %d",size);
exit(EXIT_FAILURE);
}
while(fread(CIPHERTEXT,1,CIPHERTEXT_LEN_MESSAGE,inp) == (int)CIPHERTEXT_LEN_MESSAGE) {
if(crypto_aead_aes256gcm_decrypt(MESSAGES,&len,
NULL,CIPHERTEXT,CIPHERTEXT_LEN_MESSAGE,NULL,0,nonce,sharesKey25519)!=0
|| CIPHERTEXT_LEN_MESSAGE < crypto_aead_aes256gcm_KEYBYTES) {
printf("\nMessages is forged???");
}else {
for(int i = 0;i < MESSAGE_LEN;i++) {
if(MESSAGES[i] != '\0')
fprintf(out,"%c",MESSAGES[i]);
}
}
}
fclose(inp);
fclose(out);
}
int main(int argc,char **argv) {
if(sodium_init() == -1) {
return 1;
}
/*char file_one[] = "Alice";
char file_two[] = "Alice.pub";
char file_three[] = "Bob";
char file_four[] = "Bob.pub";
char out[] = "out.txt";*/
//createPublicKeyAndSecretKey(file_three ,file_four);
//loadPublicKeyOfPartnerAndMySecretKey(file_two,file_three);
//loadPublicKeyOfPartnerAndMySecretKey(file_four,file_one);
//decrypto_messages(out,(char*)"mess.txt");
//encrypto_messages((char*)"messages.txt",(char*)"out.txt");
//char file_mess[] = "mess.txt";
// char filename[] ="messages.txt";
//char fileout[] = "out.txt";
//loadPublicKeyOfPartnerAndMySecretKey((char*)"Bob.pub",(char*)"Alice");
//encrypto_messages(filename,fileout);
//decrypto_messages(fileout,file_mess);*/
if(strcmp(argv[1],"-genkey") == 0) {
printf("\n-genkey");
if(argv[2] == 0 || argv[3] == 0){
//printf("\ncase genkey\n");
createPublicKeyAndSecretKey((char*)"secretKey",(char*)"publicKey.pub");
}else {
createPublicKeyAndSecretKey(argv[2],argv[3]);
}
}else if(strcmp(argv[1],"-en") == 0) {
printf("\n-encrypto");
if(argv[2] == 0){
printf("\nPlease enter message need encryption");
}else {
if(argv[3] != 0) {
if(argv[4] == 0) {
loadPublicKeyOfPartnerAndMySecretKey(argv[3],(char*)"secretKey");
encrypto_messages(argv[2],(char*)"ciphertext.txt");
}else {
loadPublicKeyOfPartnerAndMySecretKey(argv[3],argv[4]);
if(argv[5] != 0) {
encrypto_messages(argv[2],argv[5]);
}else {
encrypto_messages(argv[2],(char*)"ciphertext.txt");
}
}
}else {
printf("\nPlease enter file contain secretkey and publickey of partner");
}
}
}else if(strcmp(argv[1],"-de") == 0) {
printf("\n-decrypto");
if(argv[2] == 0){
printf("\nPlease enter ciphertex need decryption");
}else {
if(argv[3] != 0) {
if(argv[4] == 0) {
loadPublicKeyOfPartnerAndMySecretKey(argv[3],(char*)"secretKey");
decrypto_messages(argv[2],(char*)"messages_text.txt");
}else {
loadPublicKeyOfPartnerAndMySecretKey(argv[3],argv[4]);
if(argv[5] != 0) {
decrypto_messages(argv[2],argv[5]);
}else {
decrypto_messages(argv[2],(char*)"messages_text.txt");
}
}
}else {
printf("\nPlease enter file contain secretkey and publickey of partner");
}
}
}else {
printf("\nNo Have Option %s",argv[1]);
printf("\nPlease choose a into -options: -genkey, -en, -de");
}
}
| [
"[email protected]"
] | |
814d9d012dd866e0a33e6c927731ca93088cb2f8 | c9ef7415e544524d6e0733c82b839f6e4a3fa6f1 | /src/entrydialog.cpp | 6bb79db78d1a1921071807cc39b328adc9d978b9 | [
"MIT"
] | permissive | vladyslavmakartet/recipe_planner_qt | e0adda722b67cc8087d37ae0952029bc1b46d7b4 | 84a5af03d11674cb426b37ec52016a3a2781c800 | refs/heads/master | 2023-04-12T22:44:52.972786 | 2021-04-23T21:49:47 | 2021-04-23T21:49:47 | 355,707,111 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,230 | cpp | #include "entrydialog.h"
EntryDialog::EntryDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::EntryDialog)
{
ui->setupUi(this);
model = new ingredientTableModel();
ui->IngredientsTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->IngredientsTableView->setCornerButtonEnabled(false);
ui->IngredientsTableView->setStyleSheet("QHeaderView::section{"
"border-top:0px solid #D8D8D8;"
"border-left:0px solid #D8D8D8;"
"border-right:1px solid #D8D8D8;"
"border-bottom: 1px solid #D8D8D8;"
"background-color:white;"
"padding:4px;"
"}");
ui->IngredientsTableView->setStyleSheet("QTableCornerButton::section{"
"border-top:0px solid #D8D8D8;"
"border-left:0px solid #D8D8D8;"
"border-right:1px solid #D8D8D8;"
"border-bottom: 1px solid #D8D8D8;"
"background-color:white;"
"}");
ui->IngredientsTableView->setModel(model);
ui->IngredientsTableView->setEditTriggers(QAbstractItemView::NoEditTriggers); //To disable editing
ui->addButton->setEnabled(false);
ui->modifyButton->setEnabled(false);
ui->deleteButton->setEnabled(false);
ui->applyButton->setEnabled(false);
ui->IngredientsTableView->setSelectionMode(QAbstractItemView::SingleSelection);
ui->IngredientsTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
connect(ui->ingredientNameLine, &QLineEdit::textChanged, this, &EntryDialog::allLinesFilled);
connect(ui->QuantityLine, &QLineEdit::textChanged, this, &EntryDialog::allLinesFilled);
connect(ui->UnitLine, &QLineEdit::textChanged, this, &EntryDialog::allLinesFilled);
connect(ui->RecipeNameLine, &QLineEdit::textChanged, this, &EntryDialog::allFieldsFilled);
connect(ui->RecipeTextEdit, &QTextEdit::textChanged, this, &EntryDialog::allFieldsFilled);
connect(this, &EntryDialog::FieldsFilled, this, &EntryDialog::allFieldsFilled);
connect(ui->IngredientsTableView, &QAbstractItemView::clicked,this, &EntryDialog::enableButtons);
connect(this, &EntryDialog::clearLineEdits,ui->ingredientNameLine, &QLineEdit::clear);
connect(this, &EntryDialog::clearLineEdits,ui->QuantityLine, &QLineEdit::clear);
connect(this, &EntryDialog::clearLineEdits,ui->UnitLine, &QLineEdit::clear);
}
EntryDialog::~EntryDialog()
{
delete ui;
}
void EntryDialog::allLinesFilled()
{
ui->QuantityLine->setValidator(new QDoubleValidator(0,1000,2,this));
bool ok = !ui->ingredientNameLine->text().isEmpty()
&& !ui->UnitLine->text().isEmpty()
&& !ui->QuantityLine->text().isEmpty();
ui->addButton->setEnabled(ok);
}
void EntryDialog::allFieldsFilled()
{
bool ok = model->rowCount() != 0
&& !ui->RecipeNameLine->text().isEmpty()
&& !ui->RecipeTextEdit->document()->isEmpty();
ui->applyButton->setEnabled(ok);
}
void EntryDialog::on_modifyButton_clicked()
{
QModelIndex selected = model->index(ui->IngredientsTableView->selectionModel()->currentIndex().row(),0, QModelIndex());
int selectedRow = ui->IngredientsTableView->selectionModel()->currentIndex().row();
if (selected.isValid()){
if(ui->ingredientNameLine->text() != ingredientVector[selectedRow].getIngredientName()\
|| ui->QuantityLine->text().toFloat() != ingredientVector[selectedRow].getIngredientQuantity()
|| ui->UnitLine->text() != ingredientVector[selectedRow].getIngredientUnit()){
if(!ui->ingredientNameLine->text().isEmpty() && ui->ingredientNameLine->text() != ingredientVector[selectedRow].getIngredientName()){
model->setData(selected,ui->ingredientNameLine->text(),Qt::EditRole);
ingredientVector[selectedRow].setIngredientName(ui->ingredientNameLine->text());
}
if(!ui->QuantityLine->text().isEmpty() && ui->QuantityLine->text().toFloat() != ingredientVector[selectedRow].getIngredientQuantity()){
if(ui->QuantityLine->text().toFloat()!=0)
{
selected = model->index(ui->IngredientsTableView->selectionModel()->currentIndex().row(),1, QModelIndex());
model->setData(selected,ui->QuantityLine->text().toFloat(),Qt::EditRole);
ingredientVector[selectedRow].setIngredientQuantity(ui->QuantityLine->text().toFloat());
}
}
if(!ui->UnitLine->text().isEmpty() && ui->UnitLine->text() != ingredientVector[selectedRow].getIngredientUnit()){
selected = model->index(ui->IngredientsTableView->selectionModel()->currentIndex().row(),2, QModelIndex());
model->setData(selected,ui->UnitLine->text(),Qt::EditRole);
ingredientVector[selectedRow].setIngredientUnit(ui->UnitLine->text());
}
ui->IngredientsTableView->setModel(model);
ui->modifyButton->setEnabled(false);
ui->deleteButton->setEnabled(false);
emit clearLineEdits();
}
}
}
void EntryDialog::on_addButton_clicked()
{
if(!(ui->ingredientNameLine->text().isEmpty() || ui->QuantityLine->text().isEmpty() || ui->UnitLine->text().isEmpty())){
if(ui->QuantityLine->text().toFloat()!=0){
ingredient.setIngredientName(ui->ingredientNameLine->text());
ingredient.setIngredientQuantity(ui->QuantityLine->text().toFloat());
ingredient.setIngredientUnit(ui->UnitLine->text());
bool sameItem = false;
if(!ingredientVector.isEmpty()){
for(int i=0; i<ingredientVector.size(); i++){
if(ingredientVector[i].getIngredientName() == ingredient.getIngredientName()
&& ingredientVector[i].getIngredientUnit() == ingredient.getIngredientUnit())
sameItem = true;
}
}
if(!sameItem){
model->insertRow(model->rowCount());
QModelIndex index = model->index(model->rowCount()-1,0, QModelIndex());
model->setData(index,ui->ingredientNameLine->text(),Qt::EditRole);
index = model->index(model->rowCount()-1,1, QModelIndex());
model->setData(index,ui->QuantityLine->text().toFloat(),Qt::EditRole);
index = model->index(model->rowCount()-1,2, QModelIndex());
model->setData(index,ui->UnitLine->text(),Qt::EditRole);
ui->IngredientsTableView->setModel(model);
ui->modifyButton->setEnabled(false);
ui->deleteButton->setEnabled(false);
ingredientVector.append(ingredient);
ui->IngredientsTableView->resizeRowsToContents();
emit clearLineEdits();
emit FieldsFilled();
}
}
}
}
void EntryDialog::enableButtons()
{
if(!ui->ingredientNameLine->text().isEmpty() || !ui->QuantityLine->text().isEmpty() || !ui->UnitLine->text().isEmpty())
ui->modifyButton->setEnabled(true);
ui->deleteButton->setEnabled(true);
}
void EntryDialog::on_deleteButton_clicked()
{
QModelIndexList selected = ui->IngredientsTableView->selectionModel()->selectedIndexes();
if (!selected.isEmpty())
{
ingredientVector.removeAt(selected.first().row());
ui->IngredientsTableView->model()->removeRow(selected.first().row());
if (ingredientVector.isEmpty())
{
ui->modifyButton->setEnabled(false);
ui->deleteButton->setEnabled(false);
emit FieldsFilled();
}
}
}
void EntryDialog::on_okButton_clicked()
{
done(Accepted);
}
void EntryDialog::on_applyButton_clicked()
{
Recipe *recipe = new Recipe(ui->RecipeNameLine->text(),ui->RecipeTextEdit->toPlainText(),ingredientVector);
emit applyPressed(*recipe);
delete recipe;
setResult(Accepted);
}
void EntryDialog::on_cancelButton_clicked()
{
done(Rejected);
}
| [
"[email protected]"
] | |
c3d62b9d663aa3d0d5ea3adcd9bdc2a0707691a5 | 501f8e21ce973c6e2e6417dee665b712af7f8101 | /src/maplab_dependencies/3rdparty/opengv/python/pyopengv.cpp | d6fc7a87f800b6657cad7613c1a7698f7a3ba158 | [
"Apache-2.0"
] | permissive | Abdob/maplab_ws | b5bd5393faf382290acc48a3a0d049f32b79ee0f | fbd198179329dc1522cdfb70d057c137f608d069 | refs/heads/master | 2022-07-27T06:28:08.286116 | 2020-05-17T19:09:22 | 2020-05-17T19:09:22 | 262,687,071 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 17,114 | cpp | #include <boost/python.hpp>
#include <iostream>
#include <vector>
#include <opengv/absolute_pose/AbsoluteAdapterBase.hpp>
#include <opengv/absolute_pose/methods.hpp>
#include <opengv/relative_pose/RelativeAdapterBase.hpp>
#include <opengv/relative_pose/methods.hpp>
#include <opengv/sac/Ransac.hpp>
#include <opengv/sac_problems/absolute_pose/AbsolutePoseSacProblem.hpp>
#include <opengv/sac_problems/relative_pose/CentralRelativePoseSacProblem.hpp>
#include <opengv/sac_problems/relative_pose/RotationOnlySacProblem.hpp>
#include <opengv/triangulation/methods.hpp>
#include "types.hpp"
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/ndarrayobject.h>
#if (PY_VERSION_HEX < 0x03000000)
static void numpy_import_array_wrapper()
#else
static int* numpy_import_array_wrapper()
#endif
{
/* Initialise numpy API and use 2/3 compatible return */
import_array();
}
namespace pyopengv {
namespace bp = boost::python;
namespace bpn = boost::python::numeric;
typedef PyArrayContiguousView<double> pyarray_t;
opengv::bearingVector_t bearingVectorFromArray(
const pyarray_t &array,
size_t index )
{
opengv::bearingVector_t v;
v[0] = array.get(index, 0);
v[1] = array.get(index, 1);
v[2] = array.get(index, 2);
return v;
}
opengv::point_t pointFromArray(
const pyarray_t &array,
size_t index )
{
opengv::point_t p;
p[0] = array.get(index, 0);
p[1] = array.get(index, 1);
p[2] = array.get(index, 2);
return p;
}
bp::object arrayFromPoints( const opengv::points_t &points )
{
std::vector<double> data(points.size() * 3);
for (size_t i = 0; i < points.size(); ++i) {
data[3 * i + 0] = points[i][0];
data[3 * i + 1] = points[i][1];
data[3 * i + 2] = points[i][2];
}
npy_intp shape[2] = {(npy_intp)points.size(), 3};
return bpn_array_from_data(2, shape, &data[0]);
}
bp::object arrayFromTranslation( const opengv::translation_t &t )
{
npy_intp shape[1] = {3};
return bpn_array_from_data(1, shape, t.data());
}
bp::object arrayFromRotation( const opengv::rotation_t &R )
{
Eigen::Matrix<double, 3, 3, Eigen::RowMajor> R_row_major = R;
npy_intp shape[2] = {3, 3};
return bpn_array_from_data(2, shape, R_row_major.data());
}
bp::list listFromRotations( const opengv::rotations_t &Rs )
{
bp::list retn;
for (size_t i = 0; i < Rs.size(); ++i) {
retn.append(arrayFromRotation(Rs[i]));
}
return retn;
}
bp::object arrayFromEssential( const opengv::essential_t &E )
{
Eigen::Matrix<double, 3, 3, Eigen::RowMajor> E_row_major = E;
npy_intp shape[2] = {3, 3};
return bpn_array_from_data(2, shape, E_row_major.data());
}
bp::list listFromEssentials( const opengv::essentials_t &Es )
{
bp::list retn;
for (size_t i = 0; i < Es.size(); ++i) {
retn.append(arrayFromEssential(Es[i]));
}
return retn;
}
bp::object arrayFromTransformation( const opengv::transformation_t &t )
{
Eigen::Matrix<double, 3, 4, Eigen::RowMajor> t_row_major = t;
npy_intp shape[2] = {3, 4};
return bpn_array_from_data(2, shape, t_row_major.data());
}
bp::list listFromTransformations( const opengv::transformations_t &t )
{
bp::list retn;
for (size_t i = 0; i < t.size(); ++i) {
retn.append(arrayFromTransformation(t[i]));
}
return retn;
}
std::vector<int> getNindices( int n )
{
std::vector<int> indices;
for(int i = 0; i < n; i++)
indices.push_back(i);
return indices;
}
namespace absolute_pose {
class CentralAbsoluteAdapter : public opengv::absolute_pose::AbsoluteAdapterBase
{
protected:
using AbsoluteAdapterBase::_t;
using AbsoluteAdapterBase::_R;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
CentralAbsoluteAdapter(
bpn::array & bearingVectors,
bpn::array & points )
: _bearingVectors(bearingVectors)
, _points(points)
{}
CentralAbsoluteAdapter(
bpn::array & bearingVectors,
bpn::array & points,
bpn::array & R )
: _bearingVectors(bearingVectors)
, _points(points)
{
pyarray_t R_view(R);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
_R(i, j) = R_view.get(i, j);
}
}
}
CentralAbsoluteAdapter(
bpn::array & bearingVectors,
bpn::array & points,
bpn::array & t,
bpn::array & R )
: _bearingVectors(bearingVectors)
, _points(points)
{
pyarray_t t_view(t);
for (int i = 0; i < 3; ++i) {
_t(i) = t_view.get(i);
}
pyarray_t R_view(R);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
_R(i, j) = R_view.get(i, j);
}
}
}
virtual ~CentralAbsoluteAdapter() {}
//Access of correspondences
virtual opengv::bearingVector_t getBearingVector( size_t index ) const {
return bearingVectorFromArray(_bearingVectors, index);
}
virtual double getWeight( size_t index ) const {
return 1.0;
}
virtual opengv::translation_t getCamOffset( size_t index ) const {
return Eigen::Vector3d::Zero();
}
virtual opengv::rotation_t getCamRotation( size_t index ) const {
return opengv::rotation_t::Identity();
}
virtual opengv::point_t getPoint( size_t index ) const {
return pointFromArray(_points, index);
}
virtual size_t getNumberCorrespondences() const {
return _bearingVectors.shape(0);
}
protected:
pyarray_t _bearingVectors;
pyarray_t _points;
};
bp::object p2p( bpn::array &v, bpn::array &p, bpn::array &R )
{
CentralAbsoluteAdapter adapter(v, p, R);
return arrayFromTranslation(
opengv::absolute_pose::p2p(adapter, 0, 1));
}
bp::object p3p_kneip( bpn::array &v, bpn::array &p )
{
CentralAbsoluteAdapter adapter(v, p);
return listFromTransformations(
opengv::absolute_pose::p3p_kneip(adapter, 0, 1, 2));
}
bp::object p3p_gao( bpn::array &v, bpn::array &p )
{
CentralAbsoluteAdapter adapter(v, p);
return listFromTransformations(
opengv::absolute_pose::p3p_gao(adapter, 0, 1, 2));
}
bp::object gp3p( bpn::array &v, bpn::array &p )
{
CentralAbsoluteAdapter adapter(v, p);
return listFromTransformations(
opengv::absolute_pose::gp3p(adapter, 0, 1, 2));
}
bp::object epnp( bpn::array &v, bpn::array &p )
{
CentralAbsoluteAdapter adapter(v, p);
return arrayFromTransformation(
opengv::absolute_pose::epnp(adapter));
}
bp::object gpnp( bpn::array &v, bpn::array &p )
{
CentralAbsoluteAdapter adapter(v, p);
return arrayFromTransformation(
opengv::absolute_pose::gpnp(adapter));
}
bp::object upnp( bpn::array &v, bpn::array &p )
{
CentralAbsoluteAdapter adapter(v, p);
return listFromTransformations(
opengv::absolute_pose::upnp(adapter));
}
bp::object optimize_nonlinear( bpn::array &v,
bpn::array &p,
bpn::array &t,
bpn::array &R )
{
CentralAbsoluteAdapter adapter(v, p, t, R);
return arrayFromTransformation(
opengv::absolute_pose::optimize_nonlinear(adapter));
}
bp::object ransac(
bpn::array &v,
bpn::array &p,
std::string algo_name,
double threshold,
int max_iterations )
{
using namespace opengv::sac_problems::absolute_pose;
CentralAbsoluteAdapter adapter(v, p);
// Create a ransac problem
AbsolutePoseSacProblem::algorithm_t algorithm = AbsolutePoseSacProblem::KNEIP;
if (algo_name == "TWOPT") algorithm = AbsolutePoseSacProblem::TWOPT;
else if (algo_name == "KNEIP") algorithm = AbsolutePoseSacProblem::KNEIP;
else if (algo_name == "GAO") algorithm = AbsolutePoseSacProblem::GAO;
else if (algo_name == "EPNP") algorithm = AbsolutePoseSacProblem::EPNP;
else if (algo_name == "GP3P") algorithm = AbsolutePoseSacProblem::GP3P;
std::shared_ptr<AbsolutePoseSacProblem>
absposeproblem_ptr(
new AbsolutePoseSacProblem(adapter, algorithm));
// Create a ransac solver for the problem
opengv::sac::Ransac<AbsolutePoseSacProblem> ransac;
ransac.sac_model_ = absposeproblem_ptr;
ransac.threshold_ = threshold;
ransac.max_iterations_ = max_iterations;
// Solve
ransac.computeModel();
return arrayFromTransformation(ransac.model_coefficients_);
}
} // namespace absolute_pose
namespace relative_pose
{
class CentralRelativeAdapter : public opengv::relative_pose::RelativeAdapterBase
{
protected:
using RelativeAdapterBase::_t12;
using RelativeAdapterBase::_R12;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
CentralRelativeAdapter(
bpn::array & bearingVectors1,
bpn::array & bearingVectors2 )
: _bearingVectors1(bearingVectors1)
, _bearingVectors2(bearingVectors2)
{}
CentralRelativeAdapter(
bpn::array & bearingVectors1,
bpn::array & bearingVectors2,
bpn::array & R12 )
: _bearingVectors1(bearingVectors1)
, _bearingVectors2(bearingVectors2)
{
pyarray_t R12_view(R12);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
_R12(i, j) = R12_view.get(i, j);
}
}
}
CentralRelativeAdapter(
bpn::array & bearingVectors1,
bpn::array & bearingVectors2,
bpn::array & t12,
bpn::array & R12 )
: _bearingVectors1(bearingVectors1)
, _bearingVectors2(bearingVectors2)
{
pyarray_t t12_view(t12);
for (int i = 0; i < 3; ++i) {
_t12(i) = t12_view.get(i);
}
pyarray_t R12_view(R12);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
_R12(i, j) = R12_view.get(i, j);
}
}
}
virtual ~CentralRelativeAdapter() {}
virtual opengv::bearingVector_t getBearingVector1( size_t index ) const {
return bearingVectorFromArray(_bearingVectors1, index);
}
virtual opengv::bearingVector_t getBearingVector2( size_t index ) const {
return bearingVectorFromArray(_bearingVectors2, index);
}
virtual double getWeight( size_t index ) const {
return 1.0;
}
virtual opengv::translation_t getCamOffset1( size_t index ) const {
return Eigen::Vector3d::Zero();
}
virtual opengv::rotation_t getCamRotation1( size_t index ) const {
return opengv::rotation_t::Identity();
}
virtual opengv::translation_t getCamOffset2( size_t index ) const {
return Eigen::Vector3d::Zero();
}
virtual opengv::rotation_t getCamRotation2( size_t index ) const {
return opengv::rotation_t::Identity();
}
virtual size_t getNumberCorrespondences() const {
return _bearingVectors1.shape(0);
}
protected:
pyarray_t _bearingVectors1;
pyarray_t _bearingVectors2;
};
bp::object twopt( bpn::array &b1, bpn::array &b2, bpn::array &R )
{
CentralRelativeAdapter adapter(b1, b2, R);
return arrayFromTranslation(
opengv::relative_pose::twopt(adapter, true, 0, 1));
}
bp::object twopt_rotationOnly( bpn::array &b1, bpn::array &b2 )
{
CentralRelativeAdapter adapter(b1, b2);
return arrayFromRotation(
opengv::relative_pose::twopt_rotationOnly(adapter, 0, 1));
}
bp::object rotationOnly( bpn::array &b1, bpn::array &b2 )
{
CentralRelativeAdapter adapter(b1, b2);
return arrayFromRotation(
opengv::relative_pose::rotationOnly(adapter));
}
bp::object fivept_nister( bpn::array &b1, bpn::array &b2 )
{
CentralRelativeAdapter adapter(b1, b2);
return listFromEssentials(
opengv::relative_pose::fivept_nister(adapter));
}
bp::object fivept_kneip( bpn::array &b1, bpn::array &b2 )
{
CentralRelativeAdapter adapter(b1, b2);
return listFromRotations(
opengv::relative_pose::fivept_kneip(adapter, getNindices(5)));
}
bp::object sevenpt( bpn::array &b1, bpn::array &b2 )
{
CentralRelativeAdapter adapter(b1, b2);
return listFromEssentials(
opengv::relative_pose::sevenpt(adapter));
}
bp::object eightpt( bpn::array &b1, bpn::array &b2 )
{
CentralRelativeAdapter adapter(b1, b2);
return arrayFromEssential(
opengv::relative_pose::eightpt(adapter));
}
bp::object eigensolver( bpn::array &b1, bpn::array &b2, bpn::array &R )
{
CentralRelativeAdapter adapter(b1, b2, R);
return arrayFromRotation(
opengv::relative_pose::eigensolver(adapter));
}
bp::object sixpt( bpn::array &b1, bpn::array &b2 )
{
CentralRelativeAdapter adapter(b1, b2);
return listFromRotations(
opengv::relative_pose::sixpt(adapter));
}
bp::object optimize_nonlinear( bpn::array &b1,
bpn::array &b2,
bpn::array &t12,
bpn::array &R12 )
{
CentralRelativeAdapter adapter(b1, b2, t12, R12);
return arrayFromTransformation(
opengv::relative_pose::optimize_nonlinear(adapter));
}
bp::object ransac(
bpn::array &b1,
bpn::array &b2,
std::string algo_name,
double threshold,
int max_iterations )
{
using namespace opengv::sac_problems::relative_pose;
CentralRelativeAdapter adapter(b1, b2);
// Create a ransac problem
CentralRelativePoseSacProblem::algorithm_t algorithm = CentralRelativePoseSacProblem::NISTER;
if (algo_name == "STEWENIUS") algorithm = CentralRelativePoseSacProblem::STEWENIUS;
else if (algo_name == "NISTER") algorithm = CentralRelativePoseSacProblem::NISTER;
else if (algo_name == "SEVENPT") algorithm = CentralRelativePoseSacProblem::SEVENPT;
else if (algo_name == "EIGHTPT") algorithm = CentralRelativePoseSacProblem::EIGHTPT;
std::shared_ptr<CentralRelativePoseSacProblem>
relposeproblem_ptr(
new CentralRelativePoseSacProblem(adapter, algorithm));
// Create a ransac solver for the problem
opengv::sac::Ransac<CentralRelativePoseSacProblem> ransac;
ransac.sac_model_ = relposeproblem_ptr;
ransac.threshold_ = threshold;
ransac.max_iterations_ = max_iterations;
// Solve
ransac.computeModel();
return arrayFromTransformation(ransac.model_coefficients_);
}
bp::object ransac_rotationOnly(
bpn::array &b1,
bpn::array &b2,
double threshold,
int max_iterations )
{
using namespace opengv::sac_problems::relative_pose;
CentralRelativeAdapter adapter(b1, b2);
std::shared_ptr<RotationOnlySacProblem>
relposeproblem_ptr(
new RotationOnlySacProblem(adapter));
// Create a ransac solver for the problem
opengv::sac::Ransac<RotationOnlySacProblem> ransac;
ransac.sac_model_ = relposeproblem_ptr;
ransac.threshold_ = threshold;
ransac.max_iterations_ = max_iterations;
// Solve
ransac.computeModel();
return arrayFromRotation(ransac.model_coefficients_);
}
} // namespace relative_pose
namespace triangulation
{
bp::object triangulate( bpn::array &b1,
bpn::array &b2,
bpn::array &t12,
bpn::array &R12 )
{
pyopengv::relative_pose::CentralRelativeAdapter adapter(b1, b2, t12, R12);
opengv::points_t points;
for (size_t i = 0; i < adapter.getNumberCorrespondences(); ++i)
{
opengv::point_t p = opengv::triangulation::triangulate(adapter, i);
points.push_back(p);
}
return arrayFromPoints(points);
}
bp::object triangulate2( bpn::array &b1,
bpn::array &b2,
bpn::array &t12,
bpn::array &R12 )
{
pyopengv::relative_pose::CentralRelativeAdapter adapter(b1, b2, t12, R12);
opengv::points_t points;
for (size_t i = 0; i < adapter.getNumberCorrespondences(); ++i)
{
opengv::point_t p = opengv::triangulation::triangulate2(adapter, i);
points.push_back(p);
}
return arrayFromPoints(points);
}
} // namespace triangulation
} // namespace pyopengv
BOOST_PYTHON_MODULE(pyopengv) {
using namespace boost::python;
boost::python::numeric::array::set_module_and_type("numpy", "ndarray");
numpy_import_array_wrapper();
def("absolute_pose_p2p", pyopengv::absolute_pose::p2p);
def("absolute_pose_p3p_kneip", pyopengv::absolute_pose::p3p_kneip);
def("absolute_pose_p3p_gao", pyopengv::absolute_pose::p3p_gao);
def("absolute_pose_gp3p", pyopengv::absolute_pose::gp3p);
def("absolute_pose_epnp", pyopengv::absolute_pose::epnp);
def("absolute_pose_gpnp", pyopengv::absolute_pose::gpnp);
def("absolute_pose_upnp", pyopengv::absolute_pose::upnp);
def("absolute_pose_optimize_nonlinear", pyopengv::absolute_pose::optimize_nonlinear);
def("absolute_pose_ransac", pyopengv::absolute_pose::ransac);
def("relative_pose_twopt", pyopengv::relative_pose::twopt);
def("relative_pose_twopt_rotation_only", pyopengv::relative_pose::twopt_rotationOnly);
def("relative_pose_rotation_only", pyopengv::relative_pose::rotationOnly);
def("relative_pose_fivept_nister", pyopengv::relative_pose::fivept_nister);
def("relative_pose_fivept_kneip", pyopengv::relative_pose::fivept_kneip);
def("relative_pose_sevenpt", pyopengv::relative_pose::sevenpt);
def("relative_pose_eightpt", pyopengv::relative_pose::eightpt);
def("relative_pose_eigensolver", pyopengv::relative_pose::eigensolver);
def("relative_pose_sixpt", pyopengv::relative_pose::sixpt);
def("relative_pose_optimize_nonlinear", pyopengv::relative_pose::optimize_nonlinear);
def("relative_pose_ransac", pyopengv::relative_pose::ransac);
def("relative_pose_ransac_rotation_only", pyopengv::relative_pose::ransac_rotationOnly);
def("triangulation_triangulate", pyopengv::triangulation::triangulate);
def("triangulation_triangulate2", pyopengv::triangulation::triangulate2);
}
| [
"[email protected]"
] | |
8d8937853b8340849a32a9e081799ce1ffdd3f64 | c68f791005359cfec81af712aae0276c70b512b0 | /0-unclassified/segment.cpp | 5a72fb734ac618199935a7b6b94c402d03a25d1b | [] | no_license | luqmanarifin/cp | 83b3435ba2fdd7e4a9db33ab47c409adb088eb90 | 08c2d6b6dd8c4eb80278ec34dc64fd4db5878f9f | refs/heads/master | 2022-10-16T14:30:09.683632 | 2022-10-08T20:35:42 | 2022-10-08T20:35:42 | 51,346,488 | 106 | 46 | null | 2017-04-16T11:06:18 | 2016-02-09T04:26:58 | C++ | UTF-8 | C++ | false | false | 1,292 | cpp | #include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstdio>
#include <climits>
#include <vector>
#include <map>
#include <list>
#include <deque>
#include <stack>
#include <set>
#include <string>
#include <cstring>
#include <algorithm>
#include <bitset>
#include <cmath>
#include <utility>
#include <functional>
using namespace std;
#define LL long long
#define PI acos(-1.0)
#define sf scanf
#define pf printf
#define nl printf("\n")
#define FOR(i,a,b) for( i=a; i<=b; i++)
#define FORD(i,a,b) for( i=b; i>=a; i--)
#define FORS(i,n) FOR(i, 0, n-1)
#define FORM(i,n) FORD(i, 0, n-1)
#define mp make_pair
#define open freopen("input.txt","r",stdin); freopen("output.txt","w",stdout)
#define close fclose(stdin); fclose(stdout)
#define db double
const int N = 1e5 + 7;
int gcd(int a, int b) { return b? gcd(b,a%b): a; }
int lcm(int a, int b) { return a*b / gcd(a,b); }
int a[N];
int main(void)
{
int n, i, j, ans = 0, temp;
sf("%d", &n);
FOR(i,1,n) sf("%d", &a[i]);
if(n <= 2) { pf("%d\n", n); nl; return 0; }
i = 1;
while(i <= n-2) {
temp = 2;
FOR(j,i+2,n) {
if(a[j-2] + a[j-1] == a[j])
temp++;
else break;
}
if(temp >= ans) {
ans = temp;
if(n-i <= ans) break;
}
if(temp > 2) i = j - 1;
else i++;
}
cout << ans << endl;
return 0;
} | [
"[email protected]"
] | |
9f92f4c7171814b541bfc3ce14bbdfb7b9f58df4 | a460b51188e5126092379b927ff26141bf21f25f | /src/ob/readline.cc | a01f439e86475c6ef44207a2239282b8e3327361 | [
"MIT"
] | permissive | octobanana/nyble | 14722021dbcef4978312bbe5c5131de9f276819a | 122fcfd38b2f2cc414452087d99c3f60e29d3f7f | refs/heads/master | 2020-09-12T22:31:28.269349 | 2020-01-04T05:19:43 | 2020-01-04T05:19:43 | 222,580,485 | 21 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 27,305 | cc | /*
88888888
888888888888
88888888888888
8888888888888888
888888888888888888
888888 8888 888888
88888 88 88888
888888 8888 888888
88888888888888888888
88888888888888888888
8888888888888888888888
8888888888888888888888888888
88888888888888888888888888888888
88888888888888888888
888888888888888888888888
888888 8888888888 888888
888 8888 8888 888
888 888
OCTOBANANA
Licensed under the MIT License
Copyright (c) 2019 Brett Robinson <https://octobanana.com/>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "ob/readline.hh"
#include "ob/string.hh"
#include "ob/text.hh"
#include "ob/term.hh"
#include <cstdio>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <deque>
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <chrono>
#include <thread>
#include <algorithm>
#include <filesystem>
namespace OB
{
namespace aec = OB::Term::ANSI_Escape_Codes;
namespace fs = std::filesystem;
void Readline::autocomplete(std::function<std::vector<std::string>()> const& val_)
{
_autocomplete._update = val_;
}
void Readline::boundaries(std::string const& val_)
{
_boundaries = val_;
}
std::string Readline::word_under_cursor(std::string const& delimiters_)
{
auto const word = std::string(_input.str.prev_word(_input.off + _input.idx - 1, OB::Text::View(delimiters_)));
return word.size() == 1 && word.find_first_of(_boundaries) != std::string::npos ? "" : word;
}
Readline& Readline::style(std::string const& style_)
{
_style.input = style_;
_autocomplete._style.normal = style_;
return *this;
}
Readline& Readline::prompt(std::string const& str_, std::string const& style_)
{
_prompt.str = str_;
_style.prompt = style_;
_autocomplete._style.prompt = style_;
_prompt.fmt = aec::wrap(str_, style_);
return *this;
}
std::string Readline::render() const
{
std::ostringstream ss;
// -------------------------------------------------------------
switch (_mode)
{
case Mode::autocomplete_init:
case Mode::autocomplete:
{
ss
// << aec::cursor_hide
<< aec::cr
<< _autocomplete
<< aec::clear;
break;
}
default:
{
ss
// << aec::cursor_hide
<< aec::cr
<< _style.input
<< OB::String::repeat(_width, " ")
<< aec::cr
<< _prompt.lhs
<< _style.input
<< _input.fmt
<< aec::clear
<< _prompt.rhs
<< aec::cr
<< aec::cursor_right(_input.cur + 1);
if (_input.cur + 2 == _width) {
if (_prompt.rhs.size()) {
ss
<< aec::reverse
<< _prompt.rhs;
}
else {
ss
<< _style.input
<< aec::reverse
<< " ";
}
}
else {
ss
<< _style.input
<< aec::reverse;
auto const c = _input.fmt.colstr(_input.fmt.byte_to_char(_input.cur), 1);
if (c.size())
{
ss << c;
}
else
{
ss << " ";
}
}
ss << aec::clear;
// << aec::cursor_right(_input.cur + 1)
// << aec::cursor_show;
break;
}
}
// -------------------------------------------------------------
// ss
// << aec::cursor_hide
// << aec::cr
// << _style.input
// << OB::String::repeat(_width, " ")
// << aec::cr
// << _prompt.lhs
// << _style.input
// << _input.fmt
// << aec::clear
// << _prompt.rhs;
// switch (_mode)
// {
// case Mode::autocomplete_init:
// case Mode::autocomplete:
// {
// ss
// << aec::nl
// << _autocomplete
// << aec::cursor_up(1);
// break;
// }
// default:
// {
// if (_mode_prev == Mode::autocomplete_init || _mode_prev == Mode::autocomplete)
// {
// ss
// << aec::nl
// << aec::erase_line
// << aec::cursor_up(1);
// }
// break;
// }
// }
// ss
// << aec::cr
// << aec::cursor_right(_input.cur + 1)
// << aec::cursor_show;
return ss.str();
}
Readline& Readline::refresh()
{
_prompt.lhs = ">";
_prompt.rhs = " ";
if (_input.str.cols() + 2 > _width)
{
std::size_t pos {_input.off + _input.idx - 1};
std::size_t cols {0};
for (; pos != OB::Text::String::npos && cols < _width - 2; --pos)
{
cols += _input.str.at(pos).cols;
}
if (pos == OB::Text::String::npos)
{
pos = 0;
}
std::size_t end {_input.off + _input.idx - pos};
_input.fmt.str(_input.str.substr(pos, end));
if (_input.fmt.cols() > _width - 2)
{
while (_input.fmt.cols() > _width - 2)
{
_input.fmt.erase(0, 1);
}
_input.cur = _input.fmt.cols();
if (_input.cur == OB::Text::String::npos)
{
_input.cur = 0;
}
_prompt.lhs = "<";
}
else
{
_input.cur = _input.fmt.cols();
if (_input.cur == OB::Text::String::npos)
{
_input.cur = 0;
}
while (_input.fmt.cols() <= _width - 2)
{
_input.fmt.append(std::string(_input.str.at(end++).str));
}
_input.fmt.erase(_input.fmt.size() - 1, 1);
}
if (_input.off + _input.idx < _input.str.size())
{
_prompt.rhs = ">";
}
}
else
{
_input.fmt = _input.str;
_input.cur = _input.fmt.cols(0, _input.idx);
if (_input.cur == OB::Text::String::npos)
{
_input.cur = 0;
}
}
return *this;
}
// Readline& Readline::refresh()
// {
// _prompt.lhs = _prompt.fmt;
// _prompt.rhs.clear();
// if (_input.str.cols() + 2 > _width)
// {
// std::size_t pos {_input.off + _input.idx - 1};
// std::size_t cols {0};
// for (; pos != OB::Text::String::npos && cols < _width - 2; --pos)
// {
// cols += _input.str.at(pos).cols;
// }
// if (pos == OB::Text::String::npos)
// {
// pos = 0;
// }
// std::size_t end {_input.off + _input.idx - pos};
// _input.fmt.str(_input.str.substr(pos, end));
// if (_input.fmt.cols() > _width - 2)
// {
// while (_input.fmt.cols() > _width - 2)
// {
// _input.fmt.erase(0, 1);
// }
// _input.cur = _input.fmt.cols();
// if (_input.cur == OB::Text::String::npos)
// {
// _input.cur = 0;
// }
// _prompt.lhs = aec::wrap("<", _style.prompt);
// }
// else
// {
// _input.cur = _input.fmt.cols();
// if (_input.cur == OB::Text::String::npos)
// {
// _input.cur = 0;
// }
// while (_input.fmt.cols() <= _width - 2)
// {
// _input.fmt.append(std::string(_input.str.at(end++).str));
// }
// _input.fmt.erase(_input.fmt.size() - 1, 1);
// }
// if (_input.off + _input.idx < _input.str.size())
// {
// _prompt.rhs = aec::wrap(
// OB::String::repeat(_width - _input.fmt.cols() - 2, " ") + ">",
// _style.prompt);
// }
// }
// else
// {
// _input.fmt = _input.str;
// _input.cur = _input.fmt.cols(0, _input.idx);
// if (_input.cur == OB::Text::String::npos)
// {
// _input.cur = 0;
// }
// }
// return *this;
// }
Readline& Readline::size(std::size_t const width_, std::size_t const height_)
{
_width = width_;
_height = height_;
_autocomplete.width(width_);
return *this;
}
Readline& Readline::clear()
{
mode(Mode::normal);
_input = {};
return *this;
}
std::string Readline::get()
{
return _res;
}
Readline& Readline::normal()
{
mode(Mode::normal);
_input.off = _input.offp;
_input.idx = _input.idxp;
_input.str = _input.buf;
hist_reset();
refresh();
return *this;
}
bool Readline::operator()(OB::Text::Char32 input)
{
bool loop {true};
switch (input.ch())
{
case OB::Term::Key::escape:
{
if (_mode != Mode::normal)
{
normal();
break;
}
loop = false;
_input.save_file = false;
_input.clear_input = true;
break;
}
case OB::Term::ctrl_key('r'):
case OB::Term::Key::tab:
{
if (_mode != Mode::autocomplete_init && _mode != Mode::autocomplete)
{
ac_init();
}
else
{
mode(Mode::autocomplete);
ac_next();
}
break;
}
case OB::Term::ctrl_key('c'):
{
// exit the command prompt
mode(Mode::normal);
loop = false;
_input.save_file = false;
_input.save_local = false;
_input.clear_input = true;
break;
}
// TODO impl copy/paste like shell
case OB::Term::ctrl_key('u'):
{
mode(Mode::normal);
_input.clipboard = _input.str;
edit_clear();
refresh();
hist_reset();
break;
}
case OB::Term::ctrl_key('y'):
{
mode(Mode::normal);
edit_insert(_input.clipboard);
refresh();
hist_reset();
break;
}
case OB::Term::Key::newline:
{
switch (_mode)
{
case Mode::autocomplete_init:
case Mode::autocomplete:
{
mode(Mode::normal);
break;
}
default:
{
// submit the input string
loop = false;
break;
}
}
break;
}
case OB::Term::Key::up:
case OB::Term::ctrl_key('p'):
{
switch (_mode)
{
case Mode::normal:
{
mode(Mode::history_init);
hist_next();
break;
}
case Mode::history_init:
{
mode(Mode::history);
hist_next();
break;
}
case Mode::history:
{
hist_next();
break;
}
case Mode::autocomplete_init:
{
mode(Mode::autocomplete);
ac_prev_section();
break;
}
case Mode::autocomplete:
{
ac_prev_section();
break;
}
}
break;
}
case OB::Term::Key::down:
case OB::Term::ctrl_key('n'):
{
switch (_mode)
{
case Mode::normal:
{
mode(Mode::history_init);
hist_prev();
break;
}
case Mode::history_init:
{
mode(Mode::history);
hist_prev();
break;
}
case Mode::history:
{
hist_prev();
break;
}
case Mode::autocomplete_init:
{
mode(Mode::autocomplete);
ac_next_section();
break;
}
case Mode::autocomplete:
{
ac_next_section();
break;
}
}
break;
}
case OB::Term::Key::right:
case OB::Term::ctrl_key('f'):
{
switch (_mode)
{
case Mode::autocomplete_init:
{
mode(Mode::autocomplete);
ac_next();
break;
}
case Mode::autocomplete:
{
ac_next();
break;
}
default:
{
curs_right();
break;
}
}
break;
}
case OB::Term::Key::left:
case OB::Term::ctrl_key('b'):
{
switch (_mode)
{
case Mode::autocomplete_init:
{
mode(Mode::autocomplete);
ac_prev();
break;
}
case Mode::autocomplete:
{
ac_prev();
break;
}
default:
{
curs_left();
break;
}
}
break;
}
case OB::Term::Key::end:
case OB::Term::ctrl_key('e'):
{
switch (_mode)
{
case Mode::autocomplete_init:
{
mode(Mode::autocomplete);
ac_end();
break;
}
case Mode::autocomplete:
{
ac_end();
break;
}
default:
{
curs_end();
break;
}
}
break;
}
case OB::Term::Key::home:
case OB::Term::ctrl_key('a'):
{
switch (_mode)
{
case Mode::autocomplete_init:
{
mode(Mode::autocomplete);
ac_begin();
break;
}
case Mode::autocomplete:
{
ac_begin();
break;
}
default:
{
curs_begin();
break;
}
}
break;
}
case OB::Term::Key::delete_:
case OB::Term::ctrl_key('d'):
{
mode(Mode::normal);
edit_delete();
refresh();
hist_reset();
break;
}
case OB::Term::Key::backspace:
case OB::Term::ctrl_key('h'):
{
mode(Mode::normal);
edit_backspace_autopair();
refresh();
hist_reset();
break;
}
default:
{
mode(Mode::normal);
if (input.ch() < 0xF0000 &&
(input.ch() == OB::Term::Key::space ||
OB::Text::is_graph(static_cast<std::int32_t>(input.ch()))))
{
edit_insert_autopair(input);
refresh();
hist_reset();
}
break;
}
}
if (loop)
{
return false;
}
_res = normalize(_input.str);
if (! _res.empty())
{
if (_input.save_local)
{
hist_push(_res);
}
if (_input.save_file && _input.str.str().front() != ' ')
{
hist_save(_res);
}
}
hist_reset();
if (_input.clear_input)
{
_res.clear();
}
return true;
}
void Readline::curs_begin()
{
// move cursor to start of line
if (_input.idx || _input.off)
{
_input.idx = 0;
_input.off = 0;
refresh();
}
}
void Readline::curs_end()
{
// move cursor to end of line
if (_input.str.empty())
{
return;
}
if (_input.off + _input.idx < _input.str.size())
{
if (_input.str.cols() + 2 > _width)
{
_input.off = _input.str.size() - _width + 2;
_input.idx = _width - 2;
}
else
{
_input.idx = _input.str.size();
}
refresh();
}
}
void Readline::curs_left()
{
// move cursor left
if (_input.off || _input.idx)
{
if (_input.off)
{
--_input.off;
}
else
{
--_input.idx;
}
refresh();
}
}
void Readline::curs_right()
{
// move cursor right
if (_input.off + _input.idx < _input.str.size())
{
if (_input.idx + 2 < _width)
{
++_input.idx;
}
else
{
++_input.off;
}
refresh();
}
}
void Readline::edit_insert(std::string const& str)
{
// insert or append char to input buffer
auto size {_input.str.size()};
_input.str.insert(_input.off + _input.idx, str);
if (size != _input.str.size())
{
size = _input.str.size() - size;
if (_input.idx + size + 1 < _width)
{
_input.idx += size;
}
else
{
_input.off += _input.idx + size - _width + 1;
_input.idx = _width - 1;
}
}
}
void Readline::edit_clear()
{
// clear line
_input.idx = 0;
_input.off = 0;
_input.str.clear();
}
bool Readline::edit_delete()
{
// erase char under cursor
if (_input.str.empty())
{
_input.str.clear();
return false;
}
if (_input.off + _input.idx < _input.str.size())
{
if (_input.idx + 2 < _width)
{
_input.str.erase(_input.off + _input.idx, 1);
}
else
{
_input.str.erase(_input.idx, 1);
}
return true;
}
else if (_input.off || _input.idx)
{
if (_input.off)
{
_input.str.erase(_input.off + _input.idx - 1, 1);
--_input.off;
}
else
{
--_input.idx;
_input.str.erase(_input.idx, 1);
}
return true;
}
return false;
}
bool Readline::edit_backspace()
{
// erase char behind cursor
if (_input.str.empty())
{
_input.str.clear();
return false;
}
_input.str.erase(_input.off + _input.idx - 1, 1);
if (_input.off || _input.idx)
{
if (_input.off)
{
--_input.off;
}
else if (_input.idx)
{
--_input.idx;
}
return true;
}
return false;
}
void Readline::hist_next()
{
// cycle backwards in history
if (_history().empty() && _history.search().empty())
{
return;
}
bool bounds {_history.search().empty() ?
(_history.idx < _history().size() - 1) :
(_history.idx < _history.search().size() - 1)};
if (bounds || _history.idx == History::npos)
{
if (_history.idx == History::npos)
{
_input.buf = _input.str;
if (! _input.buf.empty())
{
hist_search(_input.buf);
}
}
++_history.idx;
if (_history.search().empty())
{
// normal search
_input.str = _history().at(_history.idx);
}
else
{
// fuzzy search
_input.str = _history().at(_history.search().at(_history.idx).idx);
}
if (_input.str.size() + 1 >= _width)
{
_input.off = _input.str.size() - _width + 2;
_input.idx = _width - 2;
}
else
{
_input.off = 0;
_input.idx = _input.str.size();
}
refresh();
}
}
void Readline::hist_prev()
{
// cycle forwards in history
if (_history.idx != History::npos)
{
--_history.idx;
if (_history.idx == History::npos)
{
_input.str = _input.buf;
}
else if (_history.search().empty())
{
// normal search
_input.str = _history().at(_history.idx);
}
else
{
// fuzzy search
_input.str = _history().at(_history.search().at(_history.idx).idx);
}
if (_input.str.size() + 1 >= _width)
{
_input.off = _input.str.size() - _width + 2;
_input.idx = _width - 2;
}
else
{
_input.off = 0;
_input.idx = _input.str.size();
}
refresh();
}
}
void Readline::hist_reset()
{
_history.search.clear();
_history.idx = History::npos;
}
void Readline::hist_search(std::string const& str)
{
_history.search.clear();
OB::Text::String input {OB::Text::normalize_foldcase(
std::regex_replace(OB::Text::trim(str), std::regex("\\s+"),
" ", std::regex_constants::match_not_null))};
if (input.empty())
{
return;
}
std::size_t idx {0};
std::size_t count {0};
std::size_t weight {0};
std::string prev_hist {" "};
std::string prev_input {" "};
OB::Text::String hist;
for (std::size_t i = 0; i < _history().size(); ++i)
{
hist.str(OB::Text::normalize_foldcase(_history().at(i)));
if (hist.size() <= input.size())
{
continue;
}
idx = 0;
count = 0;
weight = 0;
prev_hist = " ";
prev_input = " ";
for (std::size_t j = 0, seq = 0; j < hist.size(); ++j)
{
if (idx < input.size() &&
hist.at(j).str == input.at(idx).str)
{
++seq;
count += 1;
if (seq > 1)
{
count += 1;
}
if (prev_hist == " " && prev_input == " ")
{
count += 1;
}
prev_input = input.at(idx).str;
++idx;
// short circuit to keep history order
// comment out to search according to closest match
if (idx == input.size())
{
break;
}
}
else
{
seq = 0;
weight += 2;
if (prev_input == " ")
{
weight += 1;
}
}
prev_hist = hist.at(j).str;
}
if (idx != input.size())
{
continue;
}
while (count && weight)
{
--count;
--weight;
}
_history.search().emplace_back(weight, i);
}
std::sort(_history.search().begin(), _history.search().end(),
[](auto const& lhs, auto const& rhs)
{
// default to history order if score is equal
return lhs.score == rhs.score ? lhs.idx < rhs.idx : lhs.score < rhs.score;
});
}
void Readline::hist_push(std::string const& str)
{
if (_history().empty())
{
_history().emplace_front(str);
}
else if (_history().back() != str)
{
if (auto pos = std::find(_history().begin(), _history().end(), str);
pos != _history().end())
{
_history().erase(pos);
}
_history().emplace_front(str);
}
}
void Readline::hist_load(fs::path const& path)
{
if (! path.empty())
{
std::ifstream ifile {path};
if (ifile && ifile.is_open())
{
std::string line;
while (std::getline(ifile, line))
{
hist_push(line);
}
}
hist_open(path);
}
}
void Readline::hist_save(std::string const& str)
{
if (_history.file.is_open())
{
_history.file
<< str << "\n"
<< std::flush;
}
}
void Readline::hist_open(fs::path const& path)
{
_history.file.open(path, std::ios::app);
if (! _history.file.is_open())
{
throw std::runtime_error("could not open file '" + path.string() + "'");
}
}
void Readline::ac_init()
{
mode(Mode::autocomplete_init);
_input.offp = _input.off;
_input.idxp = _input.idx;
_input.buf = _input.str;
_autocomplete.word(word_under_cursor(_boundaries));
_autocomplete.generate().refresh();
ac_sync();
}
void Readline::ac_sync()
{
_input.str = _input.buf;
auto const word = _autocomplete._match.at(_autocomplete._off + _autocomplete._idx);
_input.str.replace(_input.offp + _input.idxp - _autocomplete.word().size(), _autocomplete.word().size(), word);
// place cursor at end of new word
std::size_t const pos {_input.offp + _input.idxp - _autocomplete.word().size() + word.size()};
if (pos + 1 >= _width)
{
_input.off = pos - _width + 2;
_input.idx = _width - 2;
}
else
{
_input.idx = pos;
}
refresh();
}
void Readline::ac_begin()
{
_autocomplete.begin().refresh();
ac_sync();
}
void Readline::ac_end()
{
_autocomplete.end().refresh();
ac_sync();
}
void Readline::ac_prev()
{
_autocomplete.prev().refresh();
ac_sync();
}
void Readline::ac_next()
{
_autocomplete.next().refresh();
ac_sync();
}
void Readline::ac_prev_section()
{
_autocomplete.prev_section().refresh();
ac_sync();
}
void Readline::ac_next_section()
{
_autocomplete.next_section().refresh();
ac_sync();
}
void Readline::edit_insert_autopair(OB::Text::Char32 const& val)
{
auto const i = _input.off + _input.idx;
auto const lhs = val.ch();
auto const rhs = i < _input.str.size() ? OB::Text::Char32(std::string(_input.str.at(i))).ch() : '\0';
auto const prv = i > 0 ? OB::Text::Char32(std::string(_input.str.at(i - 1))).ch() : '\0';
switch (lhs)
{
case '"':
{
if (rhs == '"')
{
if (prv == '\\')
{
edit_insert(val.str());
}
else
{
curs_right();
}
}
else if (prv != '\\')
{
edit_insert(val.str());
edit_insert("\"");
curs_left();
}
else
{
edit_insert(val.str());
}
break;
}
case '(':
{
if (prv == '\\')
{
edit_insert(val.str());
}
else
{
edit_insert(val.str());
edit_insert(")");
curs_left();
}
break;
}
case ')':
{
if (rhs == ')')
{
if (prv == '\\')
{
edit_insert(val.str());
}
else
{
curs_right();
}
}
else
{
edit_insert(val.str());
}
break;
}
case '[':
{
if (prv == '\\')
{
edit_insert(val.str());
}
else
{
edit_insert(val.str());
edit_insert("]");
curs_left();
}
break;
}
case ']':
{
if (rhs == ']')
{
if (prv == '\\')
{
edit_insert(val.str());
}
else
{
curs_right();
}
}
else
{
edit_insert(val.str());
}
break;
}
case '{':
{
if (prv == '\\')
{
edit_insert(val.str());
}
else
{
edit_insert(val.str());
edit_insert("}");
curs_left();
}
break;
}
case '}':
{
if (rhs == '}')
{
if (prv == '\\')
{
edit_insert(val.str());
}
else
{
curs_right();
}
}
else
{
edit_insert(val.str());
}
break;
}
default:
{
edit_insert(val.str());
break;
}
}
}
void Readline::edit_backspace_autopair()
{
auto const i = _input.off + _input.idx;
if (i < 1 || i >= _input.str.size())
{
edit_backspace();
return;
}
auto const lhs = OB::Text::Char32(std::string(_input.str.at(i - 1))).ch();
auto const rhs = OB::Text::Char32(std::string(_input.str.at(i))).ch();
auto const prv = i > 1 ? OB::Text::Char32(std::string(_input.str.at(i - 2))).ch() : '\0';
switch (lhs)
{
case '"':
{
if (rhs == '"' && prv != '\\')
{
edit_delete();
}
break;
}
case '(':
{
if (rhs == ')' && prv != '\\')
{
edit_delete();
}
break;
}
case '[':
{
if (rhs == ']' && prv != '\\')
{
edit_delete();
}
break;
}
case '{':
{
if (rhs == '}' && prv != '\\')
{
edit_delete();
}
break;
}
default:
{
break;
}
}
edit_backspace();
}
std::string Readline::normalize(std::string const& str) const
{
// trim leading and trailing whitespace
// collapse sequential whitespace
// return std::regex_replace(OB::Text::trim(str), std::regex("\\s+"),
// " ", std::regex_constants::match_not_null);
return str;
}
void Readline::mode(Readline::Mode const mode_)
{
_mode_prev = _mode;
_mode = mode_;
}
std::ostream& operator<<(std::ostream& os, Readline const& obj)
{
os << obj.render();
return os;
}
} // namespace OB
| [
"[email protected]"
] | |
4bf03faa4649d419b57a8badc14ab4c4c9d9fe1d | e036d5f3991cb93fbe0baea82f250c6f79dc1493 | /moreAlgorithms/MinNumberInRotatedArray.cpp | c9f3c34d3e49ee16b3a315539674b043582bba09 | [] | no_license | aibbgiser/leetcode | ad2dc77756b5e6623337fc5172457a31f2e95f2b | 6eef6693eb0659b448310e8cde444775a330d7c6 | refs/heads/master | 2020-07-04T21:18:45.162433 | 2016-12-30T10:04:55 | 2016-12-30T10:04:55 | 74,137,061 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,310 | cpp | #include<exception>
#include <iostream>
using std::cout;
using std::endl;
using std::exception;
int MinInOrder( int* numbers, int index1, int index2 ){
int result = numbers[index1];
for ( int i=index1+1; i<=index2 ;++i ){
if ( result>numbers[i] ){
result = numbers[i];
}
}
return result;
}
int min( int* numbers, int length ){
if ( numbers==NULL || length<=0 ){
throw new exception("Invalid parameters");
}
int index1 = 0;
int index2 = length - 1;
int indexMid = index1; //最后返回这个
while( numbers[index1]>=numbers[index2] ){
if ( index2-index1 == 1 ){
indexMid = index2;
break;
}
indexMid = (index1 + index2) / 2;
if ( numbers[index1]==numbers[index2] && numbers[index1]==numbers[indexMid] ){
return MinInOrder(numbers, index1, index2);
}
if(numbers[indexMid] >= numbers[index1]){
index1 = indexMid;
}else{
if(numbers[indexMid] <= numbers[index2])
index2 = indexMid;
}
}
return numbers[indexMid];
}
void Test(int* numbers, int length, int expected){
int result;
try{
result = min(numbers,length);
for ( int i=0; i<length; ++i ){
cout<<numbers[i]<<" ";
}
if(result==expected)
cout<<"test passed."<<endl;
else
cout<<"test failed."<<endl;
}
catch(...){
if(numbers==NULL)
cout<<"test passed."<<endl;
else
cout<<"test failed."<<endl;
}
}
int main(){
// 典型输入,单调升序的数组的一个旋转
int array1[] = {3, 4, 5, 1, 2};
Test(array1, sizeof(array1) / sizeof(int), 1);
// 有重复数字,并且重复的数字刚好的最小的数字
int array2[] = {3, 4, 5, 1, 1, 2};
Test(array2, sizeof(array2) / sizeof(int), 1);
// 有重复数字,但重复的数字不是第一个数字和最后一个数字
int array3[] = {3, 4, 5, 1, 2, 2};
Test(array3, sizeof(array3) / sizeof(int), 1);
// 有重复的数字,并且重复的数字刚好是第一个数字和最后一个数字
int array4[] = {1, 0, 1, 1, 1};
Test(array4, sizeof(array4) / sizeof(int), 0);
// 单调升序数组,旋转0个元素,也就是单调升序数组本身
int array5[] = {1, 2, 3, 4, 5};
Test(array5, sizeof(array5) / sizeof(int), 1);
// 数组中只有一个数字
int array6[] = {2};
Test(array6, sizeof(array6) / sizeof(int), 2);
// 输入NULL
Test(NULL, 0, 0);
system("pause");
return 0;
} | [
"[email protected]"
] | |
0c68c67acd5dd4c5d7f7b51077ad5b573efa954e | 0019f0af5518efe2144b6c0e63a89e3bd2bdb597 | /antares/src/apps/screenshot/Screenshot.cpp | 35bdbba1e93cbc05535b726674c984e31755adb4 | [] | no_license | mmanley/Antares | 5ededcbdf09ef725e6800c45bafd982b269137b1 | d35f39c12a0a62336040efad7540c8c5bce9678a | refs/heads/master | 2020-06-02T22:28:26.722064 | 2010-03-08T21:51:31 | 2010-03-08T21:51:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,727 | cpp | /*
* Copyright Karsten Heimrich, [email protected]. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Karsten Heimrich
* Fredrik Modéen
*/
#include "Screenshot.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Catalog.h>
#include <Locale.h>
#include <TranslatorFormats.h>
#include "ScreenshotWindow.h"
Screenshot::Screenshot()
:
BApplication("application/x-vnd.Antares-Screenshot"),
fArgvReceived(false),
fRefsReceived(false),
fImageFileType(B_PNG_FORMAT),
fTranslator(8)
{
be_locale->GetAppCatalog(&fCatalog);
}
Screenshot::~Screenshot()
{
}
void
Screenshot::ReadyToRun()
{
if (!fArgvReceived && !fRefsReceived)
new ScreenshotWindow();
fArgvReceived = false;
fRefsReceived = false;
}
void
Screenshot::RefsReceived(BMessage* message)
{
int32 delay = 0;
message->FindInt32("delay", &delay);
bool includeBorder = false;
message->FindBool("border", &includeBorder);
bool includeMouse = false;
message->FindBool("border", &includeMouse);
bool grabActiveWindow = false;
message->FindBool("window", &grabActiveWindow);
bool saveScreenshotSilent = false;
message->FindBool("silent", &saveScreenshotSilent);
bool showConfigureWindow = false;
message->FindBool("configure", &showConfigureWindow);
new ScreenshotWindow(delay * 1000000, includeBorder, includeMouse,
grabActiveWindow, showConfigureWindow, saveScreenshotSilent);
fRefsReceived = true;
}
void
Screenshot::ArgvReceived(int32 argc, char** argv)
{
bigtime_t delay = 0;
bool includeBorder = false;
bool includeMouse = false;
bool grabActiveWindow = false;
bool showConfigureWindow = false;
bool saveScreenshotSilent = false;
for (int32 i = 0; i < argc; i++) {
if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0)
_ShowHelp();
else if (strcmp(argv[i], "-b") == 0
|| strcmp(argv[i], "--border") == 0)
includeBorder = true;
else if (strcmp(argv[i], "-m") == 0
|| strcmp(argv[i], "--mouse-pointer") == 0)
includeMouse = true;
else if (strcmp(argv[i], "-w") == 0
|| strcmp(argv[i], "--window") == 0)
grabActiveWindow = true;
else if (strcmp(argv[i], "-s") == 0
|| strcmp(argv[i], "--silent") == 0)
saveScreenshotSilent = true;
else if (strcmp(argv[i], "-o") == 0
|| strcmp(argv[i], "--options") == 0)
showConfigureWindow = true;
else if (strcmp(argv[i], "-f") == 0
|| strncmp(argv[i], "--format", 6) == 0
|| strncmp(argv[i], "--format=", 7) == 0) {
_SetImageTypeSilence(argv[i + 1]);
} else if (strcmp(argv[i], "-d") == 0
|| strncmp(argv[i], "--delay", 7) == 0
|| strncmp(argv[i], "--delay=", 8) == 0) {
int32 seconds = -1;
if (argc > i + 1)
seconds = atoi(argv[i + 1]);
if (seconds >= 0) {
delay = seconds * 1000000;
i++;
} else {
printf("Screenshot: option requires an argument -- %s\n"
, argv[i]);
exit(0);
}
}
}
fArgvReceived = true;
new ScreenshotWindow(delay, includeBorder, includeMouse, grabActiveWindow,
showConfigureWindow, saveScreenshotSilent, fImageFileType,
fTranslator);
}
void
Screenshot::_ShowHelp() const
{
printf("Screenshot [OPTION]... Creates a bitmap of the current screen\n\n");
printf("OPTION\n");
printf(" -o, --options Show options window first\n");
printf(" -m, --mouse-pointer Include the mouse pointer\n");
printf(" -b, --border Include the window border\n");
printf(" -w, --window Capture the active window instead of the entire screen\n");
printf(" -d, --delay=seconds Take screenshot after specified delay [in seconds]\n");
printf(" -s, --silent Saves the screenshot without showing the app window\n");
printf(" overrides --options\n");
printf(" -f, --format=image Write the image format you like to save as\n");
printf(" [bmp], [gif], [jpg], [png], [ppm], [targa], [tiff]\n");
printf("\n");
printf("Note: OPTION -b, --border takes only effect when used with -w, --window\n");
exit(0);
}
void
Screenshot::_SetImageTypeSilence(const char* name)
{
if (strcmp(name, "bmp") == 0) {
fImageFileType = B_BMP_FORMAT;
fTranslator = 1;
} else if (strcmp(name, "gif") == 0) {
fImageFileType = B_GIF_FORMAT;
fTranslator = 3;
} else if (strcmp(name, "jpg") == 0) {
fImageFileType = B_JPEG_FORMAT;
fTranslator = 6;
} else if (strcmp(name, "ppm") == 0) {
fImageFileType = B_PPM_FORMAT;
fTranslator = 9;
} else if (strcmp(name, "targa") == 0) {
fImageFileType = B_TGA_FORMAT;
fTranslator = 14;
} else if (strcmp(name, "tif") == 0) {
fImageFileType = B_TIFF_FORMAT;
fTranslator = 15;
} else { //png
fImageFileType = B_PNG_FORMAT;
fTranslator = 8;
}
}
| [
"michael@Inferno.(none)"
] | michael@Inferno.(none) |
92aad1168c268b4f1a9452a9b7adfc9cea09f934 | 071d41f458b7b1f2a9879744ba5b09fc2972ff65 | /src/util/unix.h | d6a2839f7d62e400269373cb85067a7842af28ad | [
"BSL-1.0"
] | permissive | 9Skrip/pd-visualization | e57a55b56400bc83f89cd83b6a8a28c0a0a26985 | b303c457298be2642c4a131315109996b3da8d8d | refs/heads/master | 2022-01-24T20:27:47.129206 | 2019-07-26T19:29:02 | 2019-07-26T19:29:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 470 | h | #pragma once
#include "util/unix_fd.h"
#include "util/unix_sock.h"
#if !defined(_WIN32) || _WIN32_WINNT >= 0x600
int poll1(SOCKET fd, int timeout, int events);
#endif
int select1(SOCKET readfd, SOCKET writefd, SOCKET exceptfd, struct timeval *timeout);
int socksetblocking(SOCKET fd, bool block);
template <class F, class... A> auto posix_retry(const F &f, A &&... args);
template <class F, class... A> auto socket_retry(const F &f, A &&... args);
#include "unix.tcc"
| [
"[email protected]"
] | |
d531430023f98dd2a20cc2d9d66455b6b28c059c | 9c41914aaa17a090cadb7cf843510ebe15805ca5 | /src/gl/debug.cpp | 61b8ed9bf363f513dcb0686ce4d28ebf4f809945 | [] | no_license | Netdex/renden | 16ed7c9d1e1b89ebed2e6ef017ad1ffa6d91e65c | ccd53062ee9da797132cc60192a67bf702510aa0 | refs/heads/master | 2021-08-16T14:23:39.630577 | 2020-04-30T18:51:44 | 2020-04-30T18:51:44 | 171,771,075 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,788 | cpp | #include "gl/debug.hpp"
#include <sstream>
#include <spdlog/spdlog.h>
void APIENTRY debug_callback(GLenum source, GLenum type, GLuint /*id*/,
GLenum severity, GLsizei /*length*/, const GLchar* message, const void* /*userParam*/)
{
std::stringstream output;
output << "OGL:";
switch (type)
{
case GL_DEBUG_TYPE_ERROR:
output << "Error";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
output << "Deprecated Behaviour";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
output << "Undefined Behaviour";
break;
case GL_DEBUG_TYPE_PORTABILITY:
output << "Portability";
break;
case GL_DEBUG_TYPE_PERFORMANCE:
output << "Performance";
break;
case GL_DEBUG_TYPE_MARKER:
output << "Marker";
break;
case GL_DEBUG_TYPE_PUSH_GROUP:
output << "Push Group";
break;
case GL_DEBUG_TYPE_POP_GROUP:
output << "Pop Group";
break;
case GL_DEBUG_TYPE_OTHER:
output << "Other";
break;
default: break;
}
output << ":";
switch (source)
{
case GL_DEBUG_SOURCE_API:
output << "API";
break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM:
output << "Window System";
break;
case GL_DEBUG_SOURCE_SHADER_COMPILER:
output << "Shader Compiler";
break;
case GL_DEBUG_SOURCE_THIRD_PARTY:
output << "Third Party";
break;
case GL_DEBUG_SOURCE_APPLICATION:
output << "Application";
break;
case GL_DEBUG_SOURCE_OTHER:
output << "Other";
break;
default: break;
}
output << " - " << message;
switch (severity)
{
case GL_DEBUG_SEVERITY_HIGH:
spdlog::error(output.str());
break;
case GL_DEBUG_SEVERITY_MEDIUM:
spdlog::warn(output.str());
break;
case GL_DEBUG_SEVERITY_LOW:
spdlog::info(output.str());
break;
case GL_DEBUG_SEVERITY_NOTIFICATION:
spdlog::trace(output.str());
break;
default: break;
}
}
| [
"[email protected]"
] | |
8f88a23e0687a8688a32730f189ee7b88fa88cc1 | 682dd1e591a9be6dbc7c0970752a882a8a553a7c | /src/lib/qrc_lib.cpp | 9ffb737828cc9cc8c3121f89e8d8425b86c34b8b | [] | no_license | heiheshang/ananas-labs-qt4 | e3f9977857aea80fa23f6cb3939fd3572005c682 | cc5edc868cefbed8c6a3c4fdf9a2d502e934399f | refs/heads/master | 2021-01-16T19:53:27.799927 | 2009-08-19T12:36:36 | 2009-08-19T12:36:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,476 | cpp | /****************************************************************************
** Resource object code
**
** Created: Thu Jul 30 22:49:29 2009
** by: The Resource Compiler for Qt version 4.5.3
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <QtCore/qglobal.h>
static const unsigned char qt_resource_data[] = {
// /home/oper/Documents/ananas/ananas-qt4/src/lib/images/print.png
0x0,0x0,0x3,0x21,
0x89,
0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,
0x0,0x0,0x16,0x0,0x0,0x0,0x16,0x8,0x6,0x0,0x0,0x0,0xc4,0xb4,0x6c,0x3b,
0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5,
0x0,0x0,0x0,0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,
0xa7,0x93,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x12,0x0,0x0,
0xb,0x12,0x1,0xd2,0xdd,0x7e,0xfc,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,
0xd4,0x4,0x13,0x12,0x17,0x30,0xce,0xaf,0x69,0xc,0x0,0x0,0x2,0x9e,0x49,0x44,
0x41,0x54,0x78,0xda,0x8d,0x94,0xaf,0x6f,0x14,0x41,0x14,0xc7,0x3f,0xd7,0x9c,0x78,
0x93,0x20,0x76,0xdd,0x5e,0x82,0xe8,0x39,0xce,0x75,0xab,0xe0,0x5c,0x71,0x5c,0x52,
0xd3,0x2a,0xda,0x60,0x68,0xc0,0xf0,0x2f,0x5c,0x25,0x12,0x45,0x90,0x75,0x5,0x4,
0x1,0x43,0x52,0x1c,0x8,0xd2,0xab,0x21,0x3d,0x4,0xb9,0xad,0x20,0x99,0x13,0x4d,
0x76,0xdd,0x8e,0xdb,0xe7,0xe,0xb1,0xbb,0xd3,0xdb,0xfb,0x41,0xfb,0xcc,0xec,0xce,
0xbc,0xf9,0xce,0x77,0xbe,0xef,0xfb,0xa6,0x75,0x3e,0x3a,0x67,0x55,0xe4,0x2e,0x9f,
0x19,0x31,0x4,0x41,0xd0,0x98,0x57,0xd5,0xc6,0x98,0xbb,0x9c,0x30,0x8,0x11,0x91,
0xd6,0x7c,0x5e,0x9b,0x35,0x61,0xc4,0x10,0x6f,0xc5,0x1e,0x60,0x3e,0x44,0xc4,0x7f,
0x3b,0xe7,0xb0,0x53,0xbb,0x94,0xb3,0x16,0x18,0x20,0xb9,0x4a,0x96,0xc0,0x16,0xf,
0x52,0xd5,0xc6,0x41,0xb7,0x2,0x17,0x5a,0x2c,0x1,0x14,0x5a,0x60,0xc4,0x34,0xd6,
0x55,0xb5,0x96,0xa2,0x91,0xbf,0xb1,0x6,0x77,0x36,0xcf,0x44,0x44,0x10,0x11,0xc2,
0x20,0x6c,0x48,0x55,0x3,0x2e,0xea,0xbb,0x96,0x71,0xcd,0x22,0x77,0x39,0x46,0xcc,
0xad,0x3a,0xaf,0x8a,0x8d,0xff,0x49,0x31,0xcf,0x70,0x11,0x74,0xd1,0x1d,0x77,0x62,
0xbc,0xae,0x50,0xab,0x2c,0xb7,0x8e,0xf9,0x4a,0xe0,0x34,0x4b,0xe9,0x6e,0x76,0xe9,
0x44,0x9d,0xb5,0xe0,0x75,0x21,0x47,0x17,0x23,0x5c,0xee,0x66,0x62,0x2,0x3a,0x51,
0xd8,0x5a,0x9,0xac,0xaa,0x33,0x6b,0x2d,0xc9,0xaf,0x4,0xd9,0x15,0x7f,0xe5,0x55,
0x63,0xed,0xe,0x97,0x39,0x46,0x3f,0x47,0xa4,0x2e,0xa5,0xd7,0xeb,0xcd,0x6,0xbb,
0x3,0xc2,0x20,0x6c,0xb5,0xea,0xce,0x53,0xd5,0x59,0x92,0x58,0xf2,0xeb,0x94,0x92,
0xa4,0xae,0x2d,0x8c,0x48,0x80,0x60,0xe0,0x1e,0xd8,0x6b,0xcb,0x78,0x7c,0x49,0x9a,
0x65,0xa8,0x16,0xf4,0x1e,0x74,0x39,0x7a,0x71,0x54,0x32,0xae,0x99,0xe,0x76,0x1e,
0x23,0x41,0x50,0x5e,0x5f,0x95,0x62,0x49,0xdc,0x2,0x30,0x5c,0x30,0xe2,0x3b,0x67,
0xf4,0xb5,0x4f,0x3f,0x89,0x49,0x92,0x4b,0xd0,0x2,0x1,0x92,0xdf,0x9,0xef,0xde,
0x9e,0xd0,0x2e,0x41,0x53,0xf6,0x9e,0xec,0x11,0x76,0x42,0x6e,0x8b,0x9,0x13,0xde,
0xf0,0x1a,0x8b,0x65,0xcc,0x98,0x53,0x39,0x65,0xf0,0x77,0x9f,0xf,0xee,0x84,0x34,
0xcb,0x51,0x94,0x74,0x6a,0x69,0xe7,0x69,0xce,0xc1,0xd3,0x3d,0x8c,0x31,0xdc,0x25,
0x42,0x42,0x76,0x78,0x84,0x20,0xc,0x18,0xb0,0x1d,0x6f,0x13,0x4a,0x7,0xa7,0x29,
0x27,0x1f,0xdf,0xe3,0x9c,0x23,0x88,0x2,0xda,0xa,0xd8,0x69,0xa9,0xf,0xaa,0x20,
0x42,0xe9,0x20,0x53,0x75,0x18,0x8,0x52,0x2a,0x5e,0xad,0xbf,0xd2,0x21,0xfb,0x58,
0x22,0x8d,0xb8,0x64,0x2,0xaa,0x4,0xf7,0x3b,0x50,0xdb,0x10,0x68,0xbb,0x2c,0xc3,
0x5e,0x4d,0xca,0x8d,0x85,0xe2,0xeb,0x26,0x15,0x10,0x95,0x4f,0x45,0x41,0xc5,0x2f,
0xa,0x60,0x35,0x45,0x51,0xa,0x55,0xec,0x9f,0x89,0x2f,0xb7,0xd4,0x76,0x53,0x6f,
0xb7,0x1a,0x47,0xfd,0xa4,0xa2,0x37,0x67,0xdc,0x64,0xfa,0x7f,0x29,0xf9,0x34,0x6b,
0x8c,0xd2,0x46,0x40,0xf3,0xe6,0x6,0x59,0x30,0x5b,0x79,0xe0,0x3c,0x63,0x6f,0x3c,
0x54,0x1d,0xb5,0x7f,0xea,0x1e,0xdc,0xde,0xea,0xb3,0xc1,0x3c,0x4b,0x4f,0xb6,0x62,
0xac,0xd5,0xb8,0x20,0x43,0x9d,0xad,0xea,0x28,0xea,0x19,0x31,0x28,0x10,0x45,0x11,
0xcf,0x5f,0x1e,0x94,0x8c,0xed,0xd4,0x56,0xe9,0x6,0xa4,0x0,0x67,0x80,0x1c,0xc4,
0x54,0x74,0x8b,0xf2,0x1b,0x30,0x15,0x3f,0xe3,0x39,0x6a,0xf9,0xa7,0x5,0x22,0x30,
0x3c,0x1e,0xd2,0x89,0x3a,0xad,0xf6,0x66,0x77,0x13,0xfb,0xf5,0x7,0x9f,0xbf,0x9d,
0xa1,0xd5,0x22,0x18,0x4c,0xb3,0xd5,0xfc,0x35,0xa9,0xdf,0x68,0x2f,0xde,0x8d,0x5b,
0x86,0xc7,0x43,0xe2,0x38,0x6e,0x1,0xf8,0x96,0x4e,0xb3,0x74,0xf6,0xe5,0xd3,0x19,
0xa9,0xb5,0xbe,0x0,0x8b,0xad,0x5d,0x3f,0x48,0x85,0x82,0x6a,0x5e,0xce,0x39,0x25,
0x7e,0x18,0x73,0xf8,0xec,0x90,0x5e,0xaf,0xe7,0x1f,0xa1,0x7f,0xe5,0xe2,0x7c,0x96,
0xcb,0x42,0x73,0x6b,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82,
// /home/oper/Documents/ananas/ananas-qt4/src/lib/images/lib_database.png
0x0,0x0,0x4,0xf,
0x89,
0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,
0x0,0x0,0x16,0x0,0x0,0x0,0x16,0x8,0x6,0x0,0x0,0x0,0xc4,0xb4,0x6c,0x3b,
0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xd6,0xd8,0xd4,0x4f,0x58,0x32,
0x0,0x0,0x0,0x19,0x74,0x45,0x58,0x74,0x53,0x6f,0x66,0x74,0x77,0x61,0x72,0x65,
0x0,0x41,0x64,0x6f,0x62,0x65,0x20,0x49,0x6d,0x61,0x67,0x65,0x52,0x65,0x61,0x64,
0x79,0x71,0xc9,0x65,0x3c,0x0,0x0,0x3,0xa1,0x49,0x44,0x41,0x54,0x48,0xc7,0x95,
0x95,0x5f,0x4c,0x5b,0x65,0x18,0xc6,0x8f,0x5b,0x2f,0xd0,0x9c,0x45,0xec,0x66,0x33,
0xb8,0xd0,0x42,0x52,0x58,0x24,0x24,0xb8,0x79,0x21,0xd0,0xd0,0x92,0x5a,0x9b,0xb6,
0x38,0xd7,0xd3,0x8d,0x55,0xd7,0xc0,0xa0,0xed,0x2a,0x83,0x4e,0x62,0x58,0x99,0x56,
0x8a,0x2b,0x41,0x5b,0x50,0xc7,0x40,0xea,0x26,0x8b,0x5b,0x93,0x5d,0x34,0x6a,0x64,
0x23,0xc6,0x66,0x31,0x1b,0x93,0x2d,0x33,0x23,0xdc,0x2c,0xc3,0xfd,0x89,0x22,0x48,
0x56,0x8d,0xc6,0xab,0x5d,0x19,0x6f,0x1e,0xdf,0xf7,0x5b,0x3b,0xbb,0x84,0xd2,0x7a,
0x92,0x27,0xdf,0x77,0xde,0xef,0x7d,0x7e,0x27,0x7d,0xce,0xdb,0x1c,0x9,0x80,0xc4,
0xa2,0xcb,0x44,0xfa,0x80,0x34,0x4d,0x5a,0x20,0xa5,0x49,0x7f,0x67,0x94,0xce,0xd4,
0xa6,0x33,0x3d,0xa6,0xac,0x2f,0x9f,0xf8,0x7a,0x96,0x14,0xad,0x7c,0xce,0xa,0xbd,
0x3d,0x82,0x9d,0xed,0x9,0xb8,0xdf,0x4c,0xe1,0x8d,0xd0,0x3c,0x7a,0x87,0xef,0x8,
0xf1,0x9e,0x6b,0x7c,0xd6,0x68,0x3b,0xa,0xed,0x36,0x2b,0x3b,0xa3,0xec,0x5d,0xf,
0x1c,0x35,0xbe,0x32,0x4,0x6f,0xf0,0x7b,0xbc,0x15,0x5d,0x2a,0x4a,0xdc,0x6b,0x20,
0xf,0x7b,0xd7,0x3,0x2f,0x1f,0x38,0x72,0xad,0x68,0x68,0x56,0xec,0x61,0xef,0x7a,
0xe0,0x39,0xc5,0x3b,0x8d,0x40,0xf8,0x1a,0xc2,0xc7,0x97,0x31,0x38,0xbe,0x8c,0x77,
0x8f,0x2d,0xa3,0x7f,0xf4,0x17,0xf4,0xc5,0x96,0x84,0x78,0xcf,0x35,0x3e,0xe3,0x1e,
0xee,0x75,0x90,0x87,0xbc,0x57,0xd6,0x3,0xc3,0x79,0xe8,0x16,0xec,0x9e,0x59,0xec,
0xf6,0xcf,0xe0,0xc0,0xe1,0x14,0xc2,0x1f,0xfe,0x80,0xb1,0xcf,0x6f,0xe3,0xd4,0x17,
0xf7,0x84,0x78,0xcf,0x35,0x3e,0x73,0x78,0xcf,0xe1,0xe5,0xfd,0x97,0xb0,0xf3,0xe0,
0x8f,0xec,0x46,0x41,0x30,0x37,0x9a,0x3d,0x37,0x61,0xda,0xbf,0x80,0xe6,0x7d,0x73,
0x30,0xb8,0x2e,0x42,0xbf,0x27,0x85,0xc6,0xdd,0xdf,0x88,0xf5,0x79,0x73,0x1c,0xcf,
0xd4,0xec,0x83,0x5c,0xaa,0x83,0xac,0xae,0x82,0x6e,0xbb,0xaf,0x20,0xf8,0x7e,0xd5,
0x76,0xf,0x4c,0xaf,0xa7,0xf2,0x82,0xb7,0xd5,0xbf,0x83,0x3a,0xab,0x82,0xce,0x4f,
0x92,0x78,0x7f,0x3e,0x8d,0xc8,0xf5,0x34,0x5c,0x63,0x49,0x54,0xbf,0xa4,0x30,0xc1,
0x93,0x37,0xe3,0xd6,0xd6,0x56,0x94,0x6a,0x6a,0xa1,0xad,0xed,0x40,0x4d,0xd3,0x10,
0x76,0x58,0x3f,0x43,0xfd,0xae,0x2f,0xd1,0xe8,0x9c,0x41,0x6d,0xf3,0x8,0x6a,0x2d,
0xa,0xfa,0x2e,0x2c,0x22,0xf6,0x33,0x30,0x74,0x17,0x18,0xb8,0x5,0x9c,0x5e,0x1,
0x7c,0xe7,0x17,0xb3,0x70,0xe3,0x9a,0x51,0xc4,0xe3,0x71,0xf4,0xf7,0xf7,0xa3,0xad,
0xad,0xd,0x2d,0x2d,0x2d,0x68,0x68,0x68,0x40,0x65,0x65,0x25,0x64,0x59,0x86,0x4a,
0xa5,0xc2,0xde,0x8f,0x93,0x18,0xfb,0x9,0x38,0x49,0x33,0x90,0x20,0xe0,0xd7,0xf7,
0x80,0xd9,0x3f,0x81,0x23,0x8b,0xc0,0xab,0xa3,0x49,0xa6,0x9c,0xcc,0xb,0x1e,0x1f,
0x1f,0xc7,0xc8,0xc8,0x8,0x22,0x91,0x88,0x78,0x48,0x6f,0x6f,0x2f,0xba,0xba,0xba,
0xa0,0x56,0xab,0xf1,0xe9,0x42,0x1a,0x5f,0x11,0xec,0x7c,0x1a,0xf8,0xf6,0x77,0xe0,
0xbb,0x3f,0xfe,0x3,0x7,0x66,0xd3,0x4c,0x59,0x59,0x33,0x63,0xb3,0xd9,0x8c,0x81,
0x81,0x81,0xa2,0xc1,0xe7,0x68,0x9d,0x5c,0x2a,0xc,0x9e,0x73,0xbb,0xdd,0xd0,0x6a,
0xb5,0x30,0x1a,0x8d,0x70,0x3a,0x9d,0x68,0x6f,0x6f,0x87,0xcf,0xe7,0x83,0xdf,0xef,
0x47,0x5d,0x5d,0x1d,0x7a,0xe8,0xa5,0x9d,0x59,0x79,0x10,0xc5,0x71,0xce,0xf9,0xe,
0x45,0xf2,0x6b,0x11,0x51,0x24,0x12,0x9,0xc,0xe,0xe,0xc2,0xeb,0xf5,0xc2,0xe1,
0x70,0xa0,0xa9,0xa9,0x9,0x3a,0x9d,0x4e,0x64,0x5c,0x52,0x52,0x82,0x1a,0xb3,0x82,
0xb7,0x53,0x8b,0x38,0x45,0xe0,0xb3,0xab,0xc0,0xcc,0x6f,0xc0,0xd5,0xbf,0x1e,0x79,
0x79,0x1f,0x91,0xca,0x49,0x1b,0x48,0x8f,0x3d,0x2,0x9e,0x9a,0x9a,0xc2,0xc4,0xc4,
0x4,0x62,0xb1,0x98,0x78,0x48,0x30,0x18,0x14,0x71,0x4,0x2,0x1,0xd8,0xed,0x76,
0xd4,0xdb,0x14,0x4,0x4f,0x24,0x91,0xbc,0x41,0xb1,0xdc,0x4c,0xe3,0xe8,0xd4,0xc3,
0x71,0xbb,0xfc,0x9a,0x45,0x87,0xad,0xea,0xd,0xbc,0x3f,0x4c,0x7a,0x3c,0xf3,0x0,
0xe9,0xbe,0xcd,0x66,0xc3,0xf0,0xf0,0x70,0x5e,0x30,0xaf,0x3c,0x31,0x7a,0xbd,0x1e,
0x65,0x65,0x65,0xd0,0x68,0x34,0x62,0x6a,0xc8,0xfb,0x8f,0xdb,0x56,0x85,0xb,0x63,
0xcd,0x98,0xf0,0xcb,0xd0,0x3c,0x29,0x71,0x2d,0x4c,0x92,0x1f,0x66,0x5c,0x51,0x51,
0x1,0x93,0xc9,0x4,0x97,0xcb,0x25,0xf2,0xed,0xe9,0xe9,0x11,0xd0,0xee,0xee,0x6e,
0x71,0xcf,0x60,0x45,0x51,0x60,0x30,0x18,0xc4,0xfb,0x60,0xf,0x79,0xe7,0xcb,0x37,
0xab,0x30,0xda,0x29,0xe3,0xcc,0x21,0x15,0xa2,0x6e,0x9,0x65,0x6a,0x1,0x7f,0xaf,
0x60,0xc6,0x2c,0xde,0x73,0x8d,0xcf,0x3a,0x3a,0x3a,0x10,0xa,0x85,0x44,0x74,0xec,
0x25,0x5,0xb7,0x96,0x4a,0x8,0xed,0x91,0x70,0xcc,0x23,0xa1,0x6f,0x97,0x84,0xcd,
0x9b,0x44,0xbd,0x70,0xc6,0xbc,0xf2,0x3d,0xd7,0xf9,0x9c,0xfb,0x72,0xc0,0x4f,0xf0,
0xcf,0x7f,0x9a,0x62,0xe8,0xb2,0x4a,0x70,0xe9,0x25,0xe8,0xca,0x1f,0x80,0xe3,0xc5,
0x64,0x9c,0xb,0xe,0x87,0xc3,0xb0,0x58,0x2c,0x6c,0x8e,0x93,0x36,0x92,0x36,0xf1,
0xcf,0x2f,0x95,0x25,0x54,0x68,0x4,0x34,0x95,0x9d,0xb9,0x83,0xff,0x37,0x63,0xf6,
0xe4,0xcc,0x6c,0x16,0xfe,0x62,0xe6,0x9b,0xf8,0x42,0xee,0x40,0x57,0x93,0x3a,0x49,
0x93,0x3c,0x42,0xa4,0xd5,0x9c,0x8f,0xe9,0x6a,0xa6,0x36,0x99,0xe9,0xa9,0x5e,0xe3,
0xf,0xb1,0x31,0x13,0xcb,0x53,0xa4,0x2d,0xff,0x2,0x66,0x27,0xf,0x70,0x4,0xd8,
0x4f,0x2b,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82,
// /home/oper/Documents/ananas/ananas-qt4/src/lib/images/lib_dbgroup.png
0x0,0x0,0x2,0xa9,
0x89,
0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,
0x0,0x0,0x16,0x0,0x0,0x0,0x16,0x8,0x6,0x0,0x0,0x0,0xc4,0xb4,0x6c,0x3b,
0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xd6,0xd8,0xd4,0x4f,0x58,0x32,
0x0,0x0,0x0,0x19,0x74,0x45,0x58,0x74,0x53,0x6f,0x66,0x74,0x77,0x61,0x72,0x65,
0x0,0x41,0x64,0x6f,0x62,0x65,0x20,0x49,0x6d,0x61,0x67,0x65,0x52,0x65,0x61,0x64,
0x79,0x71,0xc9,0x65,0x3c,0x0,0x0,0x2,0x3b,0x49,0x44,0x41,0x54,0x48,0xc7,0xb5,
0x95,0xcb,0x6f,0x12,0x51,0x1c,0x85,0xfb,0xc7,0xb5,0x58,0xeb,0x8b,0x18,0xe2,0xc2,
0xb6,0x20,0x26,0x46,0x91,0xd2,0x62,0xb1,0xb4,0x5,0x86,0x3e,0x98,0x96,0xe,0xb4,
0x86,0x88,0xd0,0x8,0x4a,0xa,0x55,0x1a,0xc4,0x27,0x3e,0x62,0xc2,0x96,0x2d,0x61,
0x63,0x60,0xc1,0x2,0x12,0x16,0x10,0x36,0xc0,0x2,0x36,0x34,0x39,0x32,0xb7,0xcc,
0x95,0xc9,0x5c,0xa0,0x86,0x74,0x71,0x12,0x2e,0x73,0xf9,0xbe,0xdf,0x3d,0x30,0xc3,
0x14,0x80,0xa9,0xab,0x88,0x7c,0xd1,0x5b,0xf6,0xa3,0xe9,0x87,0xae,0x27,0x6,0x27,
0x93,0x49,0x9,0x86,0xd3,0x3f,0x27,0x30,0xbd,0x30,0x82,0x25,0x18,0x27,0x53,0x80,
0xcf,0xcf,0xcf,0xd1,0xed,0x76,0x91,0x48,0x24,0x46,0xa,0xc6,0x9d,0x46,0x1,0xee,
0x74,0x3a,0x68,0xb7,0xdb,0x24,0xe2,0xeb,0x78,0x3c,0xce,0x14,0x8c,0x3a,0x4d,0x9f,
0x25,0xb3,0x23,0x16,0x8b,0xa1,0xd1,0x68,0xd0,0x34,0x9b,0x4d,0xb4,0x5a,0x2d,0xf2,
0xfe,0xa0,0x60,0x30,0x2c,0x1,0x99,0x52,0xe7,0xd0,0x42,0xef,0xd4,0xd1,0x8b,0xe1,
0x70,0x18,0xd5,0x6a,0x55,0x96,0x5a,0xad,0x86,0x7a,0xbd,0x8e,0x48,0x24,0x42,0xf7,
0x89,0x40,0x96,0x80,0x82,0x17,0xd6,0xe7,0xe1,0xfd,0x29,0xe0,0xe8,0xb7,0x17,0x7a,
0xee,0x9f,0x20,0x18,0xc,0xa2,0x54,0x2a,0xc9,0x52,0x2e,0x97,0x51,0xa9,0x54,0x10,
0xa,0x85,0x98,0x82,0x41,0x30,0xa9,0x62,0xff,0x33,0x8f,0x83,0x6f,0xfb,0xf0,0xfc,
0x38,0xe8,0x9,0x3c,0x78,0x30,0x20,0xf0,0xf9,0x7c,0xc8,0xe7,0xf3,0xb2,0x14,0xa,
0x5,0x14,0x8b,0x45,0x4,0x2,0x1,0x59,0x45,0x14,0x2c,0x7d,0x69,0xf7,0xcc,0x1a,
0xb8,0x3e,0x6c,0x63,0xef,0x93,0xb,0xee,0xaf,0x7b,0xf0,0x7c,0x77,0xe3,0xf0,0x97,
0x87,0xd4,0x24,0x7d,0x50,0x10,0x4,0x64,0xb3,0x59,0x59,0x72,0xb9,0x1c,0xd2,0xe9,
0xf4,0x50,0x30,0x99,0x9a,0x8b,0xd9,0xb0,0xf5,0x9e,0xc3,0x6e,0x62,0xb,0xfc,0xc7,
0x5d,0xb8,0xbf,0xf0,0x10,0x52,0x6e,0x52,0x93,0xce,0xbe,0x48,0x5,0x2e,0x97,0xb,
0x99,0x4c,0x86,0x26,0x1a,0x8d,0xb2,0xc1,0xd2,0xd4,0x77,0x1e,0xdf,0xc6,0xe6,0x5b,
0x2b,0x1c,0x51,0x1b,0x9c,0xef,0x1c,0xd8,0x39,0x73,0xf6,0x4e,0xb1,0x23,0xab,0x69,
0x50,0xc0,0x71,0x1c,0x99,0x56,0xea,0x7b,0x18,0x98,0x4c,0x6d,0x9,0x98,0x61,0x7d,
0x6d,0xc1,0xc6,0x1b,0x2b,0xec,0x27,0x9b,0xe0,0x4e,0xed,0xd8,0x3e,0xe3,0x14,0x35,
0x69,0x6d,0x17,0x82,0x54,0x2a,0x5,0xbf,0xdf,0x3f,0x1c,0x2c,0x4d,0x3d,0xab,0xbb,
0x86,0x15,0x9f,0x9,0xab,0xaf,0xcc,0x58,0x3b,0xb6,0x60,0x3d,0xbc,0x6,0x5b,0x64,
0x83,0x59,0x93,0xb8,0x5f,0xbc,0x43,0xbd,0x5e,0xef,0x58,0x30,0xbd,0x59,0x66,0xb5,
0x2a,0x2c,0xf7,0x4,0xcf,0xfc,0x2b,0xb0,0x1c,0xaf,0xc2,0x1a,0x7a,0xae,0xa8,0x49,
0xdc,0x67,0x34,0x1a,0xc1,0xf3,0xfc,0x68,0x30,0x53,0xb0,0xa8,0x22,0xbf,0x53,0xf3,
0xcb,0x65,0x45,0x4d,0x1a,0xd3,0x5d,0xda,0xf5,0xa5,0xc0,0x2c,0x81,0x6a,0x41,0x85,
0xa5,0xa3,0xa7,0x8a,0x9a,0xc4,0x6b,0x6a,0xb5,0xfa,0xff,0xc0,0x4c,0xc1,0xfc,0xc,
0x96,0xe,0xd,0xb4,0xa6,0x5b,0x8f,0x6e,0xe,0xbf,0x41,0x2e,0xfd,0xf0,0x96,0x9,
0xa6,0x61,0xf4,0x18,0x48,0x4d,0x37,0x1e,0xce,0x4d,0x6,0x66,0x9,0x66,0xee,0x4f,
0xc3,0x20,0x3c,0x21,0x35,0xcd,0xe9,0xaf,0x4f,0x6,0x66,0x9,0x14,0x8f,0xcd,0xab,
0xfa,0x33,0xfd,0xb,0x6b,0x4c,0x83,0xb2,0x3e,0x78,0xa,0x5d,0x0,0x0,0x0,0x0,
0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82,
};
static const unsigned char qt_resource_name[] = {
// images
0x0,0x6,
0x7,0x3,0x7d,0xc3,
0x0,0x69,
0x0,0x6d,0x0,0x61,0x0,0x67,0x0,0x65,0x0,0x73,
// print.png
0x0,0x9,
0x0,0x57,0xb8,0x67,
0x0,0x70,
0x0,0x72,0x0,0x69,0x0,0x6e,0x0,0x74,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67,
// lib_database.png
0x0,0x10,
0x3,0xdd,0xa6,0x47,
0x0,0x6c,
0x0,0x69,0x0,0x62,0x0,0x5f,0x0,0x64,0x0,0x61,0x0,0x74,0x0,0x61,0x0,0x62,0x0,0x61,0x0,0x73,0x0,0x65,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67,
// lib_dbgroup.png
0x0,0xf,
0x6,0x77,0x81,0x87,
0x0,0x6c,
0x0,0x69,0x0,0x62,0x0,0x5f,0x0,0x64,0x0,0x62,0x0,0x67,0x0,0x72,0x0,0x6f,0x0,0x75,0x0,0x70,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67,
};
static const unsigned char qt_resource_struct[] = {
// :
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1,
// :/images
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x3,0x0,0x0,0x0,0x2,
// :/images/print.png
0x0,0x0,0x0,0x12,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0,
// :/images/lib_database.png
0x0,0x0,0x0,0x2a,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x3,0x25,
// :/images/lib_dbgroup.png
0x0,0x0,0x0,0x50,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x7,0x38,
};
QT_BEGIN_NAMESPACE
extern bool qRegisterResourceData
(int, const unsigned char *, const unsigned char *, const unsigned char *);
extern bool qUnregisterResourceData
(int, const unsigned char *, const unsigned char *, const unsigned char *);
QT_END_NAMESPACE
int QT_MANGLE_NAMESPACE(qInitResources_lib)()
{
QT_PREPEND_NAMESPACE(qRegisterResourceData)
(0x01, qt_resource_struct, qt_resource_name, qt_resource_data);
return 1;
}
Q_CONSTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qInitResources_lib))
int QT_MANGLE_NAMESPACE(qCleanupResources_lib)()
{
QT_PREPEND_NAMESPACE(qUnregisterResourceData)
(0x01, qt_resource_struct, qt_resource_name, qt_resource_data);
return 1;
}
Q_DESTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qCleanupResources_lib))
| [
"[email protected]"
] | |
df44645df08452e52dd8e6c60e49e68413285594 | 00e42b9c61d911f12bb66294b98ee2bf8c3109d9 | /TextView/TextViewKeyNav.cpp | a6b44b477935cc6f7b8442637234e58b90404a5f | [
"MIT"
] | permissive | kxkx5150/TextEditor | 0eccb913235c345f7e8efabf1dd5adab82b9300c | e5a8876372d141d08341a35773cc8636bfc54e4b | refs/heads/main | 2023-08-10T22:21:33.385634 | 2021-09-08T03:45:39 | 2021-09-08T03:45:39 | 403,313,471 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,171 | cpp | //
// MODULE: TextViewKeyNav.cpp
//
// PURPOSE: Keyboard navigation for TextView
//
// NOTES: www.catch22.net
//
#define STRICT
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <tchar.h>
#include "TextView_def.h"
#include "TextView.h"
/*struct SCRIPT_LOGATTR
{
BYTE fSoftBreak :1;
BYTE fWhiteSpace :1;
BYTE fCharStop :1;
BYTE fWordStop :1;
BYTE fInvalid :1;
BYTE fReserved :3;
};*/
bool IsKeyPressed(UINT nVirtKey)
{
return GetKeyState(nVirtKey) < 0 ? true : false;
}
//
// Get the UspCache and logical attributes for specified line
//
bool TextView::GetLogAttr(ULONG nLineNo, USPCACHE **puspCache, CSCRIPT_LOGATTR **plogAttr, ULONG *pnOffset)
{
if((*puspCache = GetUspCache(0, nLineNo, pnOffset)) == 0)
return false;
if(plogAttr && (*plogAttr = UspGetLogAttr((*puspCache)->uspData)) == 0)
return false;
return true;
}
//
// Move caret up specified number of lines
//
VOID TextView::MoveLineUp(int numLines)
{
USPDATA * uspData;
ULONG lineOffset;
int charPos;
BOOL trailing;
m_nCurrentLine -= min(m_nCurrentLine, (unsigned)numLines);
// get Uniscribe data for prev line
uspData = GetUspData(0, m_nCurrentLine, &lineOffset);
// move up to character nearest the caret-anchor positions
UspXToOffset(uspData, m_nAnchorPosX, &charPos, &trailing, 0);
m_nCursorOffset = lineOffset + charPos + trailing;
}
//
// Move caret down specified number of lines
//
VOID TextView::MoveLineDown(int numLines)
{
USPDATA * uspData;
ULONG lineOffset;
int charPos;
BOOL trailing;
m_nCurrentLine += min(m_nLineCount-m_nCurrentLine-1, (unsigned)numLines);
// get Uniscribe data for prev line
uspData = GetUspData(0, m_nCurrentLine, &lineOffset);
// move down to character nearest the caret-anchor position
UspXToOffset(uspData, m_nAnchorPosX, &charPos, &trailing, 0);
m_nCursorOffset = lineOffset + charPos + trailing;
}
//
// Move to start of previous word (to the left)
//
VOID TextView::MoveWordPrev()
{
USPCACHE * uspCache;
CSCRIPT_LOGATTR * logAttr;
ULONG lineOffset;
int charPos;
// get Uniscribe data for current line
if(!GetLogAttr(m_nCurrentLine, &uspCache, &logAttr, &lineOffset))
return;
// move 1 character to left
charPos = m_nCursorOffset - lineOffset - 1;
// skip to end of *previous* line if necessary
if(charPos < 0)
{
charPos = 0;
if(m_nCurrentLine > 0)
{
MoveLineEnd(m_nCurrentLine-1);
return;
}
}
// skip preceding whitespace
while(charPos > 0 && logAttr[charPos].fWhiteSpace)
charPos--;
// skip whole characters until we hit a word-break/more whitespace
for( ; charPos > 0 ; charPos--)
{
if(logAttr[charPos].fWordStop || logAttr[charPos-1].fWhiteSpace)
break;
}
m_nCursorOffset = lineOffset + charPos;
}
//
// Move to start of next word
//
VOID TextView::MoveWordNext()
{
USPCACHE * uspCache;
CSCRIPT_LOGATTR * logAttr;
ULONG lineOffset;
int charPos;
// get Uniscribe data for current line
if(!GetLogAttr(m_nCurrentLine, &uspCache, &logAttr, &lineOffset))
return;
charPos = m_nCursorOffset - lineOffset;
// if already at end-of-line, skip to next line
if(charPos == uspCache->length_CRLF)
{
if(m_nCurrentLine + 1 < m_nLineCount)
MoveLineStart(m_nCurrentLine+1);
return;
}
// if already on a word-break, go to next char
if(logAttr[charPos].fWordStop)
charPos++;
// skip whole characters until we hit a word-break/more whitespace
for( ; charPos < uspCache->length_CRLF; charPos++)
{
if(logAttr[charPos].fWordStop || logAttr[charPos].fWhiteSpace)
break;
}
// skip trailing whitespace
while(charPos < uspCache->length_CRLF && logAttr[charPos].fWhiteSpace)
charPos++;
m_nCursorOffset = lineOffset + charPos;
}
//
// Move to start of current word
//
VOID TextView::MoveWordStart()
{
USPCACHE * uspCache;
CSCRIPT_LOGATTR * logAttr;
ULONG lineOffset;
int charPos;
// get Uniscribe data for current line
if(!GetLogAttr(m_nCurrentLine, &uspCache, &logAttr, &lineOffset))
return;
charPos = m_nCursorOffset - lineOffset;
while(charPos > 0 && !logAttr[charPos-1].fWhiteSpace)
charPos--;
m_nCursorOffset = lineOffset + charPos;
}
//
// Move to end of current word
//
VOID TextView::MoveWordEnd()
{
USPCACHE * uspCache;
CSCRIPT_LOGATTR * logAttr;
ULONG lineOffset;
int charPos;
// get Uniscribe data for current line
if(!GetLogAttr(m_nCurrentLine, &uspCache, &logAttr, &lineOffset))
return;
charPos = m_nCursorOffset - lineOffset;
while(charPos < uspCache->length_CRLF && !logAttr[charPos].fWhiteSpace)
charPos++;
m_nCursorOffset = lineOffset + charPos;
}
//
// Move to previous character
//
VOID TextView::MoveCharPrev()
{
USPCACHE * uspCache;
CSCRIPT_LOGATTR * logAttr;
ULONG lineOffset;
int charPos;
// get Uniscribe data for current line
if(!GetLogAttr(m_nCurrentLine, &uspCache, &logAttr, &lineOffset))
return;
charPos = m_nCursorOffset - lineOffset;
// find the previous valid character-position
for( --charPos; charPos >= 0; charPos--)
{
if(logAttr[charPos].fCharStop)
break;
}
// move up to end-of-last line if necessary
if(charPos < 0)
{
charPos = 0;
if(m_nCurrentLine > 0)
{
MoveLineEnd(m_nCurrentLine-1);
return;
}
}
// update cursor position
m_nCursorOffset = lineOffset + charPos;
}
//
// Move to next character
//
VOID TextView::MoveCharNext()
{
USPCACHE * uspCache;
CSCRIPT_LOGATTR * logAttr;
ULONG lineOffset;
int charPos;
// get Uniscribe data for specified line
if(!GetLogAttr(m_nCurrentLine, &uspCache, &logAttr, &lineOffset))
return;
charPos = m_nCursorOffset - lineOffset;
// find the next valid character-position
for( ++charPos; charPos <= uspCache->length_CRLF; charPos++)
{
if(logAttr[charPos].fCharStop)
break;
}
// skip to beginning of next line if we hit the CR/LF
if(charPos > uspCache->length_CRLF)
{
if(m_nCurrentLine + 1 < m_nLineCount)
MoveLineStart(m_nCurrentLine+1);
}
// otherwise advance the character-position
else
{
m_nCursorOffset = lineOffset + charPos;
}
}
//
// Move to start of specified line
//
VOID TextView::MoveLineStart(ULONG lineNo)
{
ULONG lineOffset;
USPCACHE * uspCache;
CSCRIPT_LOGATTR * logAttr;
int charPos;
// get Uniscribe data for current line
if(!GetLogAttr(lineNo, &uspCache, &logAttr, &lineOffset))
return;
charPos = m_nCursorOffset - lineOffset;
// if already at start of line, skip *forwards* past any whitespace
if(m_nCursorOffset == lineOffset)
{
// skip whitespace
while(logAttr[m_nCursorOffset - lineOffset].fWhiteSpace)
m_nCursorOffset++;
}
// if not at start, goto start
else
{
m_nCursorOffset = lineOffset;
}
}
//
// Move to end of specified line
//
VOID TextView::MoveLineEnd(ULONG lineNo)
{
USPCACHE *uspCache;
if((uspCache = GetUspCache(0, lineNo)) == 0)
return;
m_nCursorOffset = uspCache->offset + uspCache->length_CRLF;
}
//
// Move to start of file
//
VOID TextView::MoveFileStart()
{
m_nCursorOffset = 0;
}
//
// Move to end of file
//
VOID TextView::MoveFileEnd()
{
m_nCursorOffset = m_pTextDoc->size();
}
//
// Process keyboard-navigation keys
//
LONG TextView::OnKeyDown(UINT nKeyCode, UINT nFlags)
{
bool fCtrlDown = IsKeyPressed(VK_CONTROL);
bool fShiftDown = IsKeyPressed(VK_SHIFT);
BOOL fAdvancing = FALSE;
//
// Process the key-press. Cursor movement is different depending
// on if <ctrl> is held down or not, so act accordingly
//
switch(nKeyCode)
{
case VK_SHIFT: case VK_CONTROL:
return 0;
// CTRL+Z undo
case 'z': case 'Z':
if(fCtrlDown && Undo())
NotifyParent(TVN_CHANGED);
return 0;
// CTRL+Y redo
case 'y': case 'Y':
if(fCtrlDown && Redo())
NotifyParent(TVN_CHANGED);
return 0;
// Change insert mode / clipboard copy&paste
case VK_INSERT:
if(fCtrlDown)
{
OnCopy();
NotifyParent(TVN_CHANGED);
}
else if(fShiftDown)
{
OnPaste();
NotifyParent(TVN_CHANGED);
}
else
{
if(m_nEditMode == MODE_INSERT)
m_nEditMode = MODE_OVERWRITE;
else if(m_nEditMode == MODE_OVERWRITE)
m_nEditMode = MODE_INSERT;
NotifyParent(TVN_EDITMODE_CHANGE);
}
return 0;
case VK_DELETE:
if(m_nEditMode != MODE_READONLY)
{
if(fShiftDown)
OnCut();
else
ForwardDelete();
NotifyParent(TVN_CHANGED);
}
return 0;
case VK_BACK:
if(m_nEditMode != MODE_READONLY)
{
BackDelete();
fAdvancing = FALSE;
NotifyParent(TVN_CHANGED);
}
return 0;
case VK_LEFT:
if(fCtrlDown) MoveWordPrev();
else MoveCharPrev();
fAdvancing = FALSE;
break;
case VK_RIGHT:
if(fCtrlDown) MoveWordNext();
else MoveCharNext();
fAdvancing = TRUE;
break;
case VK_UP:
if(fCtrlDown) Scroll(0, -1);
else MoveLineUp(1);
break;
case VK_DOWN:
if(fCtrlDown) Scroll(0, 1);
else MoveLineDown(1);
break;
case VK_PRIOR:
if(!fCtrlDown) MoveLineUp(m_nWindowLines);
break;
case VK_NEXT:
if(!fCtrlDown) MoveLineDown(m_nWindowLines);
break;
case VK_HOME:
if(fCtrlDown) MoveFileStart();
else MoveLineStart(m_nCurrentLine);
break;
case VK_END:
if(fCtrlDown) MoveFileEnd();
else MoveLineEnd(m_nCurrentLine);
break;
default:
return 0;
}
// Extend selection if <shift> is down
if(fShiftDown)
{
InvalidateRange(m_nSelectionEnd, m_nCursorOffset);
m_nSelectionEnd = m_nCursorOffset;
}
// Otherwise clear the selection
else
{
if(m_nSelectionStart != m_nSelectionEnd)
InvalidateRange(m_nSelectionStart, m_nSelectionEnd);
m_nSelectionEnd = m_nCursorOffset;
m_nSelectionStart = m_nCursorOffset;
}
// update caret-location (xpos, line#) from the offset
UpdateCaretOffset(m_nCursorOffset, fAdvancing, &m_nCaretPosX, &m_nCurrentLine);
// maintain the caret 'anchor' position *except* for up/down actions
if(nKeyCode != VK_UP && nKeyCode != VK_DOWN)
{
m_nAnchorPosX = m_nCaretPosX;
// scroll as necessary to keep caret within viewport
ScrollToPosition(m_nCaretPosX, m_nCurrentLine);
}
else
{
// scroll as necessary to keep caret within viewport
if(!fCtrlDown)
ScrollToPosition(m_nCaretPosX, m_nCurrentLine);
}
NotifyParent(TVN_CURSOR_CHANGE);
return 0;
}
| [
"[email protected]"
] | |
7b910e3a235974c7261279c439e4565c4737c49d | 5ec0229926c9fb692ee7dbd8495e5434080b4944 | /src/core/mesh_box.cpp | e8e529332ec783218d67c944d2556054ac560813 | [] | no_license | LenyKholodov/CoolWork | 3ed314ad8efeb6a82158035a13342ad5a3ecfc42 | 45c0d7cf6e034b44511e5482caee522572a4f5dc | refs/heads/master | 2020-04-14T02:14:36.840572 | 2018-12-30T10:27:32 | 2018-12-30T10:27:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,274 | cpp | #include <mesh.h>
struct Build
{
DrawVertex* vert;
Triangle* face;
int vpos;
inline void push_face (const vec3f& n) {
vec3f s1 = vec3f (1.0f) - abs (n),
s2 = rotatef ((float)M_PI/2.0f,n) * s1;
vert [0].pos = n + s1;
vert [1].pos = n + s2;
vert [2].pos = n - s1;
vert [3].pos = n - s2;
for (int i=0;i<4;i++)
{
vert [i].n = n;
vert [i].color = 0.0f;
}
face [0].v [0] = vpos+3;
face [0].v [1] = vpos+2;
face [0].v [2] = vpos;
face [1].v [0] = vpos+2;
face [1].v [1] = vpos+1;
face [1].v [2] = vpos;
vert += 4;
vpos += 4;
face += 2;
}
};
Surface* Primitives::CreateBox (float width,float height,float depth)
{
Surface* surface = Surface::create (24,12);
Build build = {surface->GetVertexes (),surface->GetTriangles (),0};
build.push_face (vec3f (1,0,0));
build.push_face (vec3f (-1,0,0));
build.push_face (vec3f (0,1,0));
build.push_face (vec3f (0,-1,0));
build.push_face (vec3f (0,0,1));
build.push_face (vec3f (0,0,-1));
DrawVertex* verts = surface->GetVertexes ();
vec3f size (width*0.5f,height*0.5f,depth*0.5f);
for (int i=0;i<24;i++)
verts [i].pos *= size;
return surface;
}
| [
"[email protected]"
] | |
0db02ba94854e8a65b743cf696fe52c258d8711b | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14452/function14452_schedule_25/function14452_schedule_25.cpp | 00cf7549a91d645f223ed864b6b00395c4a67d3e | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,247 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function14452_schedule_25");
constant c0("c0", 128), c1("c1", 64), c2("c2", 64), c3("c3", 64);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i3("i3", 0, c3), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06");
input input00("input00", {i0, i3}, p_int32);
input input01("input01", {i1, i3}, p_int32);
input input02("input02", {i0, i3, i2}, p_int32);
computation comp0("comp0", {i0, i1, i2, i3}, input00(i0, i3) * input01(i1, i3) * input02(i0, i3, i2));
comp0.tile(i1, i2, i3, 64, 32, 64, i01, i02, i03, i04, i05, i06);
comp0.parallelize(i0);
buffer buf00("buf00", {128, 64}, p_int32, a_input);
buffer buf01("buf01", {64, 64}, p_int32, a_input);
buffer buf02("buf02", {128, 64, 64}, p_int32, a_input);
buffer buf0("buf0", {128, 64, 64, 64}, p_int32, a_output);
input00.store_in(&buf00);
input01.store_in(&buf01);
input02.store_in(&buf02);
comp0.store_in(&buf0);
tiramisu::codegen({&buf00, &buf01, &buf02, &buf0}, "../data/programs/function14452/function14452_schedule_25/function14452_schedule_25.o");
return 0;
} | [
"[email protected]"
] | |
4e7d8676f0dc817afdd5ee2434b88203dbb3d201 | c512a9b075f6c5ca0b34bc1e1073c301cf9692d5 | /src/main.cpp | a329fe102b3f60943e77d30409b0ada70ac6c199 | [] | no_license | DerZwergGimli/HeatMeterInterface | dd0f80d6b145fc23aea9ff4aa946702161c0b7c3 | 17b61d3f77772a2cc17f0a479688f0e081951637 | refs/heads/master | 2022-04-17T16:35:31.589906 | 2020-03-04T15:20:57 | 2020-03-04T15:20:57 | 255,759,453 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,615 | cpp | #include <Wire.h>
#include <Arduino.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "ShiftRegisterIO.h"
#include "ConfigInterface.h"
#include "TemperatureInterface.h"
#include "DisplayInterface.h"
#include <Adafruit_MAX31865.h>
#include <Esp.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
//Scheduled Task setup
//#define _TASK_ESP32_DLY_THRESHOLD 40L
#define _TASK_SLEEP_ON_IDLE_RUN
#include <TaskScheduler.h>
//Delegates for platform.io
void displayTask_Callback();
void measureTask_Callback();
void sendDataTask_Callback();
void readyLED(bool state);
WiFiEventHandler connectedWIFIEventHandler, disconnectedWIFIEventHandler;
Scheduler runner;
Task displayTask(1100, TASK_FOREVER, &displayTask_Callback, &runner, true);
Task measureTask(700, TASK_FOREVER, &measureTask_Callback, &runner, true);
//Task sendDataTask(10000, TASK_FOREVER, &sendDataTask_Callback, &runner, false);
// Display Configuration
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
DisplayInterface displayInterface;
//PT100 Configurartion
Adafruit_MAX31865 thermo = Adafruit_MAX31865(D8, D7, D6, D5);
TemperatureInterface temperatureInterface;
//#define RREF 430.0 old Version
#define RREF 240.0
#define RNOMINAL 100.0
// ShiftRegister Configuration
ShiftRegisterIO shiftRegisterIO;
SR_IO sr_io;
#define RMUX_IN A0
//Configuration
ConfigInterface configInterface;
Configuratrion config;
MeterData meterData[4];
int displayState = 0;
void setup()
{
Serial.begin(115200);
Serial.print("Starting...");
delay(100);
shiftRegisterIO.init();
shiftRegisterIO.write(&sr_io);
shiftRegisterIO.write(&sr_io);
//pinMode(RMUX_IN, INPUT);
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C))
{
Serial.println(F("SSD1306 allocation failed"));
for (;;)
Serial.print("Error while connecting to Display"); // Don't proceed, loop forever
}
displayInterface.boot(&display);
configInterface.init();
configInterface.loadConfig(&config, meterData);
temperatureInterface.init(thermo);
//runner.init();
//runner.addTask(displayTask);
//runner.addTask(measureTask);
// connectedWIFIEventHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP &event) {
// Serial.print("Station connected, IP: ");
// Serial.println(WiFi.localIP());
// sendDataTask.enable();
// });
// disconnectedWIFIEventHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected &event) {
// Serial.println("Station disconnected");
// sendDataTask.disable();
// });
// WiFi.begin(config.wifi_SSID, config.wifi_Password);
delay(1000);
//displayTask.enable();
//measureTask.enable();
//shiftRegisterIO.led_READY(&shiftRegisterIO, &sr_io, true);
runner.startNow();
//shiftRegisterIO.ledBlink(1000);
}
void loop()
{
//shiftRegisterIO.led_READY(&shiftRegisterIO, &sr_io, true);
runner.execute();
//1. Display
//displayInterface.displayMeter(&display, &meterData[0]);
//2.1 Take Measurements
//2.2 Calculate
//3. Send Measuremnts
//4. check user input
// do all over again
//display.clearDisplay();
//display.setCursor(10, 10);
// int analogValue = analogRead(RMUX_IN);
// Serial.print("Analaog: ");
// Serial.println(String(analogValue));
// //display.println(analogValue);
// channel_RJ1.temperature_up_Celcius = temperatureInterface.readTemperature(thermo, RNOMINAL, config.RREF_RJ1_T1, true);
// sr_io = shiftRegisterIO.t_MuxSelect(sr_io, 7);
// shiftRegisterIO.write(sr_io);
// channel_RJ1.temperature_down_Celcius = temperatureInterface.readTemperature(&thermo, RNOMINAL, config.RREF_RJ1_T2, true);
// meterData[0].mux_up = 5;
// meterData[0].mux_down = 7;
// Serial.print(meterData[0].RREF_up);
// //meterData[0].RREF_up = 240;
//meterData[0].RREF_down = 240;
//temperatureInterface.readTemperature(thermo, &sr_io, &meterData[0]);
// Serial.print("UP ");
// Serial.println(String(meterData[0].temperature_up_Celcius));
// Serial.print("DOWN ");
// Serial.println(String(meterData[0].temperature_down_Celcius));
//readTemperature(0, 0, true);
//sr_io = shiftRegisterIO.t_MuxSelect(sr_io, -1);
//shiftRegisterIO.write(sr_io);
//display.display();
//delay(1000);
}
void displayTask_Callback()
{
shiftRegisterIO.led_READY(&shiftRegisterIO, &sr_io, false);
switch (displayState)
{
case 0:
displayInterface.boot(&display);
displayState++;
break;
case 1: //Show Meter 1
displayInterface.displayMeter(&display, &meterData[0]);
//displayState++;
break;
case 2: //Show Meter 2
displayInterface.displayMeter(&display, &meterData[1]);
displayState++;
break;
case 3: //Show Meter 3
displayInterface.displayMeter(&display, &meterData[2]);
displayState++;
break;
case 4: //Show Meter 4
displayInterface.displayMeter(&display, &meterData[3]);
displayState = 1;
break;
default:
break;
}
}
void measureTask_Callback()
{
shiftRegisterIO.led_READY(&shiftRegisterIO, &sr_io, false);
unsigned long start = millis();
shiftRegisterIO.led_RJ1(&shiftRegisterIO, &sr_io, true);
temperatureInterface.readTemperature(thermo, &sr_io, &meterData[0]);
shiftRegisterIO.checkMeterResistance(&shiftRegisterIO, &sr_io, &meterData[0]);
if (meterData[0].waterMeterState)
{
shiftRegisterIO.led_statusRJ1(&shiftRegisterIO, &sr_io, true);
}
else
{
shiftRegisterIO.led_statusRJ1(&shiftRegisterIO, &sr_io, false);
}
if (meterData[0].mux_resistance_edgeDetect)
{
meterData->water_CounterValue_m3 += 5;
meterData->delta_HeatEnergy_J += 4200 * 5 * (meterData->temperature_up_Celcius_mean - meterData->temperature_down_Celcius_mean);
meterData->absolute_HeatEnergy_MWh = meterData->delta_HeatEnergy_J * 0.000000000277778;
Serial.println(meterData->absolute_HeatEnergy_MWh);
}
shiftRegisterIO.led_RJ1(&shiftRegisterIO, &sr_io, false);
//shiftRegisterIO.led_RJ2(&shiftRegisterIO, &sr_io, true);
//temperatureInterface.readTemperature(thermo, &sr_io, &meterData[1]);
//shiftRegisterIO.led_RJ2(&shiftRegisterIO, &sr_io, false);
//shiftRegisterIO.led_RJ3(&shiftRegisterIO, &sr_io, true);
//temperatureInterface.readTemperature(thermo, &sr_io, &meterData[2]);
//shiftRegisterIO.led_RJ3(&shiftRegisterIO, &sr_io, false);
//shiftRegisterIO.led_RJ4(&shiftRegisterIO, &sr_io, true);
//temperatureInterface.readTemperature(thermo, &sr_io, &meterData[3]);
//shiftRegisterIO.led_RJ4(&shiftRegisterIO, &sr_io, false);
unsigned long end = millis();
unsigned long duration = end - start;
Serial.print("Duration:");
Serial.println(duration);
}
void sendDataTask_Callback()
{
measureTask.disable();
WiFiClient espClient;
PubSubClient client(espClient);
// WiFi.forceSleepWake();
// WiFi.mode(WIFI_STA);
// WiFi.begin(config.wifi_SSID, config.wifi_Password);
// Serial.print("Connecting to WIFI");
// while (WiFi.status() != WL_CONNECTED)
// {
// shiftRegisterIO.led_WIFI(&shiftRegisterIO, &sr_io, true);
// unsigned long timestamp = millis();
// //while (millis() <= timestamp + 500)
// //{
// // ;
// //}
// //delay(100);
// delay(500);
// Serial.print(".");
// shiftRegisterIO.led_WIFI(&shiftRegisterIO, &sr_io, false);
// //system_soft_wdt_feed();
// //ESP.wdtFeed();
// //system_soft_wdt_feed();
// //wdt_reset();
// //ESP.wdtFeed();
// }
//Serial.println("Connected to the WiFi network");
shiftRegisterIO.led_WIFI(&shiftRegisterIO, &sr_io, true);
client.setServer(config.mqtt_ServerAddress, config.mqtt_Port);
//client.setCallback(callback
while (!client.connected())
{
Serial.println("Connecting to MQTT...");
if (client.connect(config.name))
{
Serial.println("connected");
}
else
{
Serial.print("failed with state ");
Serial.print(client.state());
shiftRegisterIO.led_ERROR(&shiftRegisterIO, &sr_io, true);
//delay(2000);
}
client.publish("esp/test", "Hello from ESP8266");
//char *s = ""; // initialized properly
//char *s;
//sprintf(char *s, "%s/temperature_down_Celcius", config.name);
//Serial.print(s);
char topic[100];
char message[100];
sprintf(topic, "%s/%d/water_CounterValue_m3", config.name, meterData[0].meterID);
sprintf(message, "%f", meterData[0].water_CounterValue_m3);
client.publish(topic, message);
sprintf(topic, "%s/%d/absolute_HeatEnergy_MWh", config.name, meterData[0].meterID);
sprintf(message, "%f", meterData[0].absolute_HeatEnergy_MWh);
client.publish(topic, message);
sprintf(topic, "%s/%d/temperature_up_Celcius", config.name, meterData[0].meterID);
sprintf(message, "%0.2f", meterData[0].temperature_up_Celcius);
client.publish(topic, message);
sprintf(topic, "%s/%d/temperature_down_Celcius", config.name, meterData[0].meterID);
sprintf(message, "%0.2f", meterData[0].temperature_down_Celcius);
client.publish(topic, message);
}
client.disconnect();
//wifi_set_sleep_type(LIGHT_SLEEP_T);
//WiFi.disconnect();
//WiFi.mode(WIFI_OFF);
//WiFi.disconnect();
//WiFi.forceSleepBegin();
measureTask.enable();
shiftRegisterIO.led_WIFI(&shiftRegisterIO, &sr_io, false);
shiftRegisterIO.led_ERROR(&shiftRegisterIO, &sr_io, false);
}
void readyLED(bool state)
{
sr_io.LED_Ready = state;
shiftRegisterIO.write(&sr_io);
} | [
"[email protected]"
] | |
77fe90a6777c19b3017f00e95fa9f1f1e8e4c522 | 674396d0c086b9ae0618248ad0b298c16e38a85d | /Algorithms/ConvexPartitionCharacteristics.cpp | 59cab844e37733f3e3e5cf56046cba170331605a | [] | no_license | HannaZhuravskaya/PolygonPartition-Diploma | fd7ef9e6a56feed8a3802e0b0f191586163b078b | 2528a0137da48ead9059c89996a17284ccd1ff46 | refs/heads/master | 2022-08-28T05:10:25.499268 | 2020-05-28T10:35:23 | 2020-05-28T10:35:23 | 249,015,157 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,231 | cpp | #include "pch.h"
#include "ConvexPartitionCharacteristics.h"
namespace algo {
ConvexPartitionCharacteristics::ConvexPartitionCharacteristics() {}
ConvexPartitionCharacteristics::ConvexPartitionCharacteristics(double areaOfNotSplittedParts, double percentageOfNotSplittedParts, double optimizationFuncValue) {
this->areaOfNotSplittedParts = areaOfNotSplittedParts;
this->percentageOfNotSplittedParts = percentageOfNotSplittedParts;
this->optimizationFuncValue = optimizationFuncValue;
}
double ConvexPartitionCharacteristics::getAreaOfNotSplittedParts(int prec) {
return getDoubleWithPrecision(areaOfNotSplittedParts, prec);
}
double ConvexPartitionCharacteristics::getPercentageOfNotSplittedParts(int prec) {
return getDoubleWithPrecision(percentageOfNotSplittedParts, prec);
}
double ConvexPartitionCharacteristics::getOptimizationFuncValue(int prec) {
return getDoubleWithPrecision(optimizationFuncValue, prec);
}
double ConvexPartitionCharacteristics::getDoubleWithPrecision(double number, int prec) {
int count = prec;
while (count > 0) {
number *= 10;
count--;
}
number = (int)number;
count = prec;
while (count > 0) {
number /= 10;
count--;
}
return number;
}
} | [
"[email protected]"
] | |
8e8aa914eab7e27ac76714855b30da01f7cbb782 | f0a26ec6b779e86a62deaf3f405b7a83868bc743 | /Engine/Source/Editor/UnrealEd/Classes/Commandlets/FixupRedirectsCommandlet.h | 444dcf6958352733935ac523d26cc308acd35fcb | [] | no_license | Tigrouzen/UnrealEngine-4 | 0f15a56176439aef787b29d7c80e13bfe5c89237 | f81fe535e53ac69602bb62c5857bcdd6e9a245ed | refs/heads/master | 2021-01-15T13:29:57.883294 | 2014-03-20T15:12:46 | 2014-03-20T15:12:46 | 18,375,899 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 399 | h | // Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "FixupRedirectsCommandlet.generated.h"
UCLASS()
class UFixupRedirectsCommandlet : public UCommandlet
{
GENERATED_UCLASS_BODY()
// Begin UCommandlet Interface
virtual void CreateCustomEngine(const FString& Params) OVERRIDE;
virtual int32 Main(const FString& Params) OVERRIDE;
// End UCommandlet Interface
};
| [
"[email protected]"
] | |
efe2023385d50437ac5b55bb091fe6388188d1af | a9985e489ca004af650fcdf6a5667ae93ecee29f | /11/src/include/oop11v2.h | afb94f6cbaff69ed8e0c54aaf843288a5d9f610f | [] | no_license | dazzlemon/diit_121-ipz_y2_oop | 8d47cca7ee1924826b43a97e3f509644b6f61f6b | f8ece4aaacd9fbe0e77124349a8ba72d4851be66 | refs/heads/main | 2023-03-23T04:37:27.052661 | 2021-03-03T11:12:42 | 2021-03-03T11:12:42 | 332,752,873 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,202 | h | /// @file oop11v2.h
#ifndef OOP11V2_H
#define OOP11V2_H
#include <concepts>
#include <functional>
#include <list>
namespace v2 {
/**
* @brief Returns intersections of f and g on range_.
* @param[in] f y(x) function on 2d plane which exists for all xs in range_
* @param[in] g y(x) function on 2d plane which exists for all xs in range_
* @param[in] range_ Range on which intersections between f and g will be searched
* @tparam N Floating point Numeric Type orderable with int
* @return list<N> of xs in which f and g intersect
*/
template<class N>
requires std::floating_point<N> && std::totally_ordered_with<N, int>
auto intersections(std::function<N(N)> f, std::function<N(N)> g, std::pair<N, N> range_) -> std::list<N>;
/**
* @brief Returns num evenly spaced samples, calculate over the interval [start, stop].
* @param[in] start The starting value of the sequence
* @param[in] stop The end value of the sequence
* @param[in] num Number of samples to generate
* @tparam N Floating point Numeric Type orderable with int
* @return num equally spaced samples in the closed interval [start, stop]
*/
template<class N>
requires std::floating_point<N> && std::totally_ordered_with<N, int>
auto linspace(N start, N stop, size_t num) -> std::list<N>;
template<class N>
requires std::floating_point<N> && std::totally_ordered_with<N, int>
auto intersections(std::function<N(N)> f, std::function<N(N)> g, std::pair<N, N> range_) -> std::list<N> {
const size_t NUMS = 1000;
auto xs = linspace(range_.first, range_.second, NUMS);
std::list<int> signs(NUMS);
for (auto x = xs.begin(), s = signs.begin(); x != xs.end(); x++, s++) {
*s = sign(f(*x) - g(*x));
}
auto res = std::list<N>();
for (auto x = xs.begin(), s1 = signs.begin(), s2 = ++signs.begin(); s2 != signs.end(); x++, s1++, s2++) {
if (*s1 - *s2 != 0) {
res.push_back(*x);
}
}
return res;
}
template<class N>
requires std::floating_point<N> && std::totally_ordered_with<N, int>
auto linspace(N start, N stop, size_t num) -> std::list<N> {
std::list<N> l(num);
N step = (stop -start) / (num - 1);
N val = start;
for (auto& i : l) {
i = val;
val += step;
}
return l;
}
}//namespace v2
#endif
| [
"[email protected]"
] | |
8f3c4da9bcd39b1b9b3f9a2e2661182af2879157 | 447f792edcfd464bc6e99c80754986f84f1c5bb5 | /practice/1015C.cpp | a8b626931db864cfb394ce4b9ed7a9010ca69a87 | [] | no_license | srajang123/Competitive-Programming | 5e0a42b0c500bf43cad0106cf9bc30d3849babc3 | f3f3973dd700236f2ce722f425f118a5a13ed41d | refs/heads/master | 2021-01-16T09:29:52.269639 | 2020-11-22T08:48:17 | 2020-11-22T08:48:17 | 243,060,688 | 2 | 1 | null | 2020-11-22T08:48:18 | 2020-02-25T17:37:54 | C++ | UTF-8 | C++ | false | false | 2,849 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define N 1000005
#define M 1000000007
/*
*********************************************************************
* Code By *
* *
* Srajan Gupta *
* srajang_123 *
* *
*********************************************************************
*/
//Prime Numbers
vector<bool>prime(N+1,true);
void sieve()
{
ll i,j,k;
prime[0]=prime[1]=false;
for(i=2;i*i<=N;i++)
{
if(prime[i])
{
for(j=i*i;j<=N;j+=i)
{
prime[j]=false;
}
}
}
}
//Exponentiation
ll power(ll a,ll b)
{
ll r=1;
while(b)
{
if(b%2==1)
r=r*a;
b/=2;
a*=a;
}
return r;
}
ll power(ll a,ll b,ll m)
{
a=a%m;
ll r=1;
while(b)
{
if(b%2==1)
r=(r*a)%m;
b/=2;
a=(a*a)%m;
}
return r;
}
//Prime Factors
vector<ll> factors(ll n)
{
vector<ll>r;
ll i,j;
for(i=1;i*i<=n;i++)
{
if(n%i==0)
{
r.push_back(i);
if(n/i!=i)
r.push_back(n/i);
}
}
return r;
}
//GCD
ll gcd(ll a,ll b)
{
if(b>a)
{
ll t=a;
a=b;
b=t;
}
if(b==0)return a;
return gcd(b,a%b);
}
ll lcm(ll a,ll b)
{
return (a*b)/gcd(a,b);
}
//Graphs
vector<bool>bvisited(N,false);
vector<vector<ll>>G(N);
vector<ll> bfs(ll s)
{
vector<ll>order;
queue<ll>q;
bvisited[s]=true;
q.push(s);
while(!q.empty())
{
s=q.front();
q.pop();
order.push_back(s);
for(auto x:G[s])
{
if(!bvisited[x])
{
bvisited[x]=true;
q.push(x);
}
}
}
return order;
}
vector<bool>dvisited(N,false);
vector<ll> dfs(ll s)
{
vector<ll>order;
stack<ll>q;
q.push(s);
while(!q.empty())
{
ll v=q.top();
q.pop();
if(!dvisited[v])
{
order.push_back(v);
dvisited[v]=true;
}
for(ll i=0;i<G[v].size();i++)
{
if(!dvisited[G[v][i]])
{
q.push(G[v][i]);
}
}
}
return order;
}
//My Functions
void print(pair<ll,ll>a)
{
cout<<a.first<<" "<<a.second;
}
void print(vector<ll>a)
{
for(auto x:a)
cout<<x<<" ";
}
bool sortbysec(const pair<ll,ll>&a,const pair<ll,ll>&b)
{
return a.second<b.second;
}
//Main Solution
bool compress(const pair<ll,ll>&a,const pair<ll,ll>&b)
{
return (a.first-a.second)>(b.first-b.second);
}
void solve()
{
ll n,m,i,j,k,l=0,u=0;
cin>>n>>m;
vector<pair<ll,ll>>a(n);
for(i=0;i<n;i++)
{
cin>>j>>k;
l+=j;
a[i]={j,k};
}
sort(a.begin(),a.end(),compress);
i=0;
while(l>m && i<n)
{
l-=a[i].first-a[i].second;
i++;
u++;
}
if(l>m)
cout<<"-1";
else
cout<<u;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll t=1;
//cin>>t;
while(t--)
{
solve();
}
}
| [
"[email protected]"
] | |
709f2a88c3fd33bef9db1fd138a394cbda1df3cd | 73c236437958c9fde595609a0ce8d24823e46071 | /auto_read/work_thread.cpp | ed51652e8ab101924ea7abc23a23ab76d8fbd57e | [] | no_license | blacksjt/autobots | f7f4bd4e870066a44ad83f86020aeb3e580a523c | 0b92d832afa6b3afcbc49b677c1489029227fae0 | refs/heads/master | 2020-04-16T02:11:56.871238 | 2017-06-27T12:01:18 | 2017-06-27T12:01:18 | 63,883,688 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,055 | cpp |
#include "work_thread.h"
void network::OnAuthenticationRequired(QNetworkReply* reply, QAuthenticator* authenticator)
{
}
void network::OnSsllErrors(QNetworkReply* reply, const QList<QSslError>& errors)
{
}
void network::ProcessReplyData(QNetworkReply* reply)
{
}
network::network(QObject* parent /*= 0*/)
: HttpBase(parent)
{
}
network::~network()
{
}
WorkThread::WorkThread(QObject *parent /*= 0*/)
: QThread(parent)
{
}
WorkThread::~WorkThread()
{
}
//void WorkThread::run()
// {
//
// QString msg = QStringLiteral("运行中");
// int count = 0;
//
// while( /*control_status*/ true)
// {
// QString temp = msg;
//
// work_run();
//
// count ++;
//
// QString temp2;
// temp2.setNum(count);
//
// // 发送消息
// QString msg = temp +temp2;
// emitMsg(msg);
// //ui.lineEdit_msg->setText(temp + temp2);
//
// sleep(2);
//
// }
// }
// void WorkThread::work_run()
// {
// QNetworkCookieJar* cookie = new QNetworkCookieJar(this);
// m_manager.setCookieJar(cookie);
//
// foreach(QString str, m_comment_list)
// {
// QString str_url1 = m_url;
// QNetworkRequest req;
//
// req.setUrl(QUrl(str_url1));
//
// //HttpParamList header_list;
// req.setRawHeader("Referer", m_referer.toUtf8());
// req.setRawHeader("Cache-Control","no-cache");
// req.setRawHeader("Connection","Keep-Alive");
// req.setRawHeader("Accept-Encoding","gzip, deflate");
// req.setRawHeader("Accept-Language","zh-CN");
// req.setRawHeader("Host", "comment8.mydrivers.com");
// req.setRawHeader("Origin", "http://comment8.mydrivers.com");
// req.setRawHeader("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
//
// //HttpParamList post_data;
// QString post_data = QString("act=support&rid=%1&tid=%2").arg(str,m_news_id);
// QByteArray request_params = post_data.toUtf8();
//
// // post_data.push_back(HttpParamItem("act","support"));
// // post_data.push_back(HttpParamItem("rid",str));
// // post_data.push_back(HttpParamItem("tid", m_news_id));
//
// QNetworkReply* reply = m_manager.post(req, request_params);
//
// //#ifdef _DEBUG
// QTime _t;
// _t.start();
//
// bool _timeout = false;
//
// while (reply && !reply->isFinished())
// {
// QCoreApplication::processEvents();
// if (_t.elapsed() >= 10*1000) {
// _timeout = true;
// break;
// }
// }
//
// QString msg;
// if (reply->error() != QNetworkReply::NoError)
// {
// msg = reply->errorString();
// }
//
// QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
//
// int n = statusCodeV.toInt();
//
// msg = reply->readAll();
// //#endif
//
// reply->deleteLater();
//
// msleep(100);
//
// }
//
// cookie->deleteLater();
// } | [
"[email protected]"
] | |
793d9855d433ae3fb347aa58b62d6da0febb5010 | 6ee567fc3836fce02cc2b4c9c87f107e85164b1e | /owreader/onewire.cpp | f2cba38914f6d01ccf7870d57bfce8bc04d9fb09 | [] | no_license | kamilmmach/projects | 761f65ea73427786ce5a67f7fcfdb3b78b61dcaa | a73708af576c93e282cd31b10a9446b7bda63891 | refs/heads/master | 2023-01-07T17:07:06.442548 | 2020-11-10T15:00:02 | 2020-11-10T15:00:02 | 311,422,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,348 | cpp | #include <iostream>
#include <cstring>
#include "onewire.hpp"
#include "utils.hpp"
bool OneWire::IsUnique()
{
if (device_length_ == 0)
return true;
// Compare rom buffer with every rom in found devices list
for (int i = 0; i < device_length_; i++)
{
if (memcmp(rom_buffer_, devices_[i].rom_num, 8) == 0)
{
return false;
}
}
return true;
}
uint8_t OneWire::Discover()
{
device_length_ = 0;
ResetSearch();
while (DeviceSearch())
{
// Sometimes, because of bad wiring, a device may report itself multiple times
// This is a temporary fix, so that every device found is unique
if (!IsUnique())
{
device_length_ = 0;
ResetSearch();
continue;
}
// Copy ROM number from buffer
memcpy(devices_[device_length_].rom_num, rom_buffer_, 8);
device_length_++;
}
return device_length_;
}
void OneWire::SendCommand(Command command)
{
WriteByte(static_cast<uint8_t>(command));
}
bool OneWire::SelectDevice(uint8_t device_id)
{
if (device_id >= device_length_)
return false;
SendCommand(Command::match_rom);
for (int i = 0; i < 8; i++)
WriteByte(devices_[device_id].rom_num[i]);
return true;
}
bool OneWire::DeviceSearch()
{
if (last_device_flag_)
{
ResetSearch();
return false;
}
if (!ResetAndPresence())
{
ResetSearch();
return false;
}
// Send Search ROM command
//WriteByte(0xF0);
SendCommand(Command::search_rom);
bool rom_bit = false, rom_bit_cmp = false;
bool search_direction = false;
uint8_t rom_bit_number = 1, rom_byte_mask = 1, last_bit_zero = 0, rom_byte_number = 0;
do
{
rom_bit = ReadBit();
rom_bit_cmp = ReadBit();
if (rom_bit == true && rom_bit_cmp == true)
{
return false;
}
// 0 && 1
if (rom_bit != rom_bit_cmp)
search_direction = rom_bit;
else
{
if (rom_bit_number < last_discrepancy_)
search_direction = ((rom_buffer_[rom_byte_number] & rom_byte_mask) > 0);
else
search_direction = (rom_bit_number == last_discrepancy_);
if (search_direction == false)
{
last_bit_zero = rom_bit_number;
if (last_bit_zero < 9)
last_family_discrepancy_ = last_bit_zero;
}
}
if (search_direction == true)
rom_buffer_[rom_byte_number] |= rom_byte_mask;
else
rom_buffer_[rom_byte_number] &= ~rom_byte_mask;
// Tell devices which direction we take so that
// other devices shut down
WriteBit(search_direction);
rom_bit_number++;
rom_byte_mask <<= 1;
// Whole byte has been read
if (rom_byte_mask == 0)
{
rom_byte_number++;
rom_byte_mask = 1;
}
} while (rom_byte_number < 8);
if (!((rom_bit_number < 65) || Utils::crc8(rom_buffer_, 8) != 0))
{
last_discrepancy_ = last_bit_zero;
if (last_discrepancy_ == 0)
last_device_flag_ = true;
return true;
}
if (!rom_buffer_[0])
ResetSearch();
return false;
}
void OneWire::ResetSearch()
{
last_device_flag_ = false;
last_discrepancy_ = 0;
last_family_discrepancy_ = 0;
}
bool OneWire::ResetAndPresence()
{
// Reset
bcm2835_gpio_fsel(pin_, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_write(pin_, LOW);
bcm2835_delayMicroseconds(480);
// Read presence
bcm2835_gpio_fsel(pin_, BCM2835_GPIO_FSEL_INPT);
bcm2835_delayMicroseconds(70);
uint8_t b = bcm2835_gpio_lev(pin_);
bcm2835_delayMicroseconds(410);
return !b;
}
void OneWire::WriteBit(bool value)
{
int delay1 = 6, delay2 = 64;
if (value == false)
{
delay1 = 80;
delay2 = 10;
}
bcm2835_gpio_fsel(pin_, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_write(pin_, LOW);
bcm2835_delayMicroseconds(delay1);
bcm2835_gpio_fsel(pin_, BCM2835_GPIO_FSEL_INPT);
bcm2835_delayMicroseconds(delay2);
}
void OneWire::WriteByte(uint8_t value)
{
for (int i = 0; i < 8; ++i)
{
WriteBit(value & 1);
value = value >> 1;
}
}
bool OneWire::ReadBit()
{
bcm2835_gpio_fsel(pin_, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_write(pin_, LOW);
bcm2835_delayMicroseconds(6);
bcm2835_gpio_fsel(pin_, BCM2835_GPIO_FSEL_INPT);
bcm2835_delayMicroseconds(8);
uint8_t b = bcm2835_gpio_lev(pin_);
bcm2835_delayMicroseconds(55);
return b;
}
uint8_t OneWire::ReadByte()
{
uint8_t rbyte = 0;
for (int i = 0; i < 8; ++i)
{
rbyte = rbyte | (ReadBit() << i);
}
return rbyte;
}
void OneWire::SkipROM()
{
SendCommand(Command::skip_rom);
}
uint8_t *OneWire::GetROM64(uint8_t device_id)
{
return devices_[device_id].rom_num;
}
uint8_t OneWireDevice::GetFamilyCode()
{
return rom_num[0];
}
| [
"[email protected]"
] | |
d172eb7a5f9323c5ea4f74d39fa3d2eb26304f81 | b9c61c27a363ac866ac2d9d6a085e7e2db29f5db | /src/Utils/Utils/GeometryOptimization/IRCOptimizer.h | d62baa81b564bb2c162074451f855d196a2ba801 | [
"BSD-3-Clause"
] | permissive | ehermes/utilities | e2d6eb8221e0a992701cc42bd719cb9f4d12e372 | 052452fcc3a4f7cc81740086d837c5d03652c030 | refs/heads/master | 2020-06-04T10:20:30.232921 | 2019-06-12T12:36:36 | 2019-06-12T12:36:36 | 191,976,830 | 0 | 0 | BSD-3-Clause | 2019-06-14T16:44:19 | 2019-06-14T16:44:19 | null | UTF-8 | C++ | false | false | 11,076 | h | /**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#ifndef UTILS_IRCOPTIMIZER_H_
#define UTILS_IRCOPTIMIZER_H_
#include "Utils/CalculatorBasics/PropertyList.h"
#include "Utils/CalculatorBasics/Results.h"
#include "Utils/Geometry/AtomCollection.h"
#include "Utils/Geometry/ElementInfo.h"
#include "Utils/GeometryOptimization/GeometryOptimizer.h"
#include "Utils/Optimizer/GradientBased/GradientBasedCheck.h"
#include <Core/Interfaces/Calculator.h>
#include <Eigen/Core>
namespace Scine {
namespace Utils {
/**
* @brief The base class for all IRC optimizers.
*
* The main purpose of this base class is to hide the template parameter(s)
* of the derived class(es).
*/
class IRCOptimizerBase {
public:
static constexpr const char* ircInitialStepSizeKey = "irc_initial_step_size";
static constexpr const char* ircTransfromCoordinatesKey = "irc_transfrom_coordinates";
/// @brief Default constructor.
IRCOptimizerBase() = default;
/// @brief Virtual default destructor.
virtual ~IRCOptimizerBase() = default;
/**
* @brief The main functionality of the IRC optimizer.
*
* This function wraps the optimize functions of the underlying optimizer.
*
* @param atoms The AtomCollection (Geometry) to be optimized.
* @return int The final number of optimization cycles carried out.
*/
virtual int optimize(AtomCollection& atoms, const Eigen::VectorXd& mode, bool forward = true) = 0;
/**
* @brief Function to apply the given settings to underlying classes.
* @param settings The new settings.
*/
virtual void setSettings(const Settings& settings) = 0;
/**
* @brief Get the public settings as a Utils::Settings object.
* @return Settings A settings object with the current settings.
*/
virtual Settings getSettings() const = 0;
/**
* @brief Add an observer function that will be triggered in each iteration.
*
* @param function A function to be executed in every loop of the optimization.
* The function will have access to the current cycle count,
* the current value and to a const reference of the current
* parameters.
*/
virtual void addObserver(std::function<void(const int&, const double&, const Eigen::VectorXd&)> function) = 0;
/**
* @brief Clear all existing observer functions.
*
* For optimization problems with very fast evaluations of the underlying function
* the removal of all observers can increase performance as the observers are given
* as std::functions and can not be added via templates.
*/
virtual void clearObservers() = 0;
/// @brief The size of the initial step along the chosen mode.
double initialStepSize = 0.01;
/**
* @brief Switch to transform the coordinates from Cartesian into an internal space.
*
* The optimization will be carried out in the internal coordinate space possibly
* accellerating convergence.
*/
bool transformCoordinates = true;
};
/**
* @brief Settings for an IRCOptimizer.
*
* Uses template arguments in order to automatically include the
* settings of underlying objects into the given settings.
*
* @tparam OptimizerType The underlying Optimizer class.
* @tparam ConvergenceCheckType The underlying ConvergenceCheck class.
*/
template<class OptimizerType, class ConvergenceCheckType>
class IRCOptimizerSettings : public Settings {
public:
/**
* @brief Construct a new IRCOptimizerSettings object.
*
* Sets the default values of the settings to the current values set in the objects
* given to the constructor.
*
* @param ircBase The IRC optimizer.
* @param optimizer The optimizer.
* @param check The convergence check criteria.
*/
IRCOptimizerSettings(const IRCOptimizerBase& ircBase, const OptimizerType& optimizer, const ConvergenceCheckType& check)
: Settings("IRCOptimizerSettings") {
optimizer.addSettingsDescriptors(this->_fields);
check.addSettingsDescriptors(this->_fields);
UniversalSettings::BoolDescriptor irc_initial_step_size("The size of the initial step along the chosen mode.");
irc_initial_step_size.setDefaultValue(ircBase.initialStepSize);
this->_fields.push_back(IRCOptimizerBase::ircInitialStepSizeKey, irc_initial_step_size);
UniversalSettings::BoolDescriptor irc_transfrom_coordinates(
"Switch to transform the coordinates from Cartesian into an internal space.");
irc_transfrom_coordinates.setDefaultValue(ircBase.transformCoordinates);
this->_fields.push_back(IRCOptimizerBase::ircTransfromCoordinatesKey, irc_transfrom_coordinates);
this->resetToDefaults();
}
};
/**
* @brief A version of the GeometryOptimizer that optimizes along an internal reaction coordinate (IRC).
*
* This optimizer mass-weights the actual gradient in order to optimize in the mass-weighted
* coordinate system.
*
* @tparam OptimizerType Expects any of the Optimizer classes. Note that some special optimizers
* may not yet be supported or may need additional specialization.
*/
template<class OptimizerType>
class IRCOptimizer : public IRCOptimizerBase {
public:
/**
* @brief Construct a new IRCOptimizer object.
* @param calculator The calculator to be used for the single point/gradient calculations.
*/
IRCOptimizer(Core::Calculator& calculator) : _calculator(calculator){};
/**
* @brief See IRCOptimizerBase::optimize().
*
* @param atoms The AtomCollection (Geometry) to be optimized.
* @param mode The mode to follow in the IRC.
* @param forward A boolean signaling to follow the mode forwards (true, current positions + mode)
* or backwards (false, current positions - mode)
* @return int The final number of optimization cycles carried out.
*/
virtual int optimize(AtomCollection& atoms, const Eigen::VectorXd& mode, bool forward = true) final {
// Configure Calculator
_calculator.setStructure(atoms);
_calculator.setRequiredProperties(Utils::Property::Energy | Utils::Property::Gradients);
// Collect masses
Eigen::VectorXd masses = Eigen::VectorXd::Zero(atoms.size());
const auto& elements = atoms.getElements();
for (unsigned int i = 0; i < atoms.size(); i++) {
masses[i] = ElementInfo::mass(elements[i]);
}
masses.array() /= masses.sum();
// Transformation into internal basis
Eigen::MatrixXd transformation;
if (this->transformCoordinates) {
transformation = Geometry::calculateRotTransFreeTransformMatrix(atoms.getPositions(), atoms.getElements());
}
// Define update function
const unsigned int nAtoms = atoms.size();
auto const update = [&](const Eigen::VectorXd& parameters, double& value, Eigen::VectorXd& gradients) {
Utils::PositionCollection coordinates;
if (this->transformCoordinates) {
auto tmp = (transformation * parameters).eval();
coordinates = Eigen::Map<const Utils::PositionCollection>(tmp.data(), nAtoms, 3);
}
else {
coordinates = Eigen::Map<const Utils::PositionCollection>(parameters.data(), nAtoms, 3);
}
_calculator.modifyPositions(coordinates);
Utils::Results results = _calculator.calculate("Geometry Optimization Cycle");
value = results.getEnergy();
auto gradientMatrix = results.getGradients();
gradientMatrix.col(0).array() *= masses.array();
gradientMatrix.col(1).array() *= masses.array();
gradientMatrix.col(2).array() *= masses.array();
if (this->transformCoordinates) {
auto tmp = Eigen::Map<const Eigen::VectorXd>(gradientMatrix.data(), nAtoms * 3);
gradients = (transformation.transpose() * tmp).eval();
}
else {
gradients = Eigen::Map<const Eigen::VectorXd>(gradientMatrix.data(), nAtoms * 3);
}
};
// Move initial positions along mode
Eigen::VectorXd positions;
if (this->transformCoordinates) {
Eigen::VectorXd tmp = Eigen::Map<const Eigen::VectorXd>(atoms.getPositions().data(), nAtoms * 3);
tmp += (forward ? this->initialStepSize : -1.0 * this->initialStepSize) * (mode / mode.norm());
positions = (transformation.transpose() * tmp).eval();
}
else {
positions = Eigen::Map<const Eigen::VectorXd>(atoms.getPositions().data(), nAtoms * 3);
positions += (forward ? this->initialStepSize : -1.0 * this->initialStepSize) * (mode / mode.norm());
}
// Optimize
auto cycles = optimizer.optimize(positions, update, check);
// Update Atom collection and return
Utils::PositionCollection coordinates;
if (this->transformCoordinates) {
auto tmp = (transformation * positions).eval();
coordinates = Eigen::Map<const Utils::PositionCollection>(tmp.data(), nAtoms, 3);
}
else {
coordinates = Eigen::Map<const Utils::PositionCollection>(positions.data(), nAtoms, 3);
}
atoms.setPositions(coordinates);
return cycles;
}
/**
* @brief Function to apply the given settings to underlying classes.
* @param settings The new settings.
*/
virtual void setSettings(const Settings& settings) override {
check.applySettings(settings);
optimizer.applySettings(settings);
this->initialStepSize = settings.getBool(IRCOptimizerBase::ircInitialStepSizeKey);
this->transformCoordinates = settings.getBool(IRCOptimizerBase::ircTransfromCoordinatesKey);
};
/**
* @brief Get the public settings as a Utils::Settings object.
* @return Settings A settings object with the current settings.
*/
virtual Settings getSettings() const override {
return IRCOptimizerSettings<OptimizerType, GradientBasedCheck>(*this, optimizer, check);
};
/**
* @brief Add an observer function that will be triggered in each iteration.
*
* @param function A function to be executed in every loop of the optimization.
* The function will have access to the current cycle count
* the current value and to a const reference of the current
* parameters.
*/
virtual void addObserver(std::function<void(const int&, const double&, const Eigen::VectorXd&)> function) final {
optimizer.addObserver(function);
}
/**
* @brief Clear all existing observer functions.
*
* For optimization problems with very fast evaluations of the underlying function
* the removal of all observers can increase performance as the observers are given
* as std::functions and can not be added via templates.
*/
virtual void clearObservers() final {
optimizer.clearObservers();
}
/// @brief The underlying optimizer, public in order to change it's settings.
OptimizerType optimizer;
/// @brief The underlying convergence check, public in order to change it's settings.
GradientBasedCheck check;
private:
Core::Calculator& _calculator;
};
} // namespace Utils
} // namespace Scine
#endif // UTILS_GEOMETRYOPTIMIZER_H_
| [
"[email protected]"
] | |
7e8a8c9a98926d971dc735503a59ddaa1517a85e | 4bd4cd8725113cf6172005e36c1d22d2c04df769 | /code2/include/general.h | 44648c22febc682da1714238ac8a241884f6b081 | [] | no_license | gjwei1999/PandaX-4T_sdu | 0389999da02334e1201efb8a7e534421401e7cdc | 7134cd5cd37e5be788d962ea7ee49ade0e9e660f | refs/heads/master | 2023-06-26T00:59:44.196253 | 2021-07-22T14:04:40 | 2021-07-22T14:04:40 | 318,829,423 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 155 | h | #pragma once
namespace pandax {
enum class EnergyType { NR = 1, GAMMA, ELECTRON, ALPHA, NRX, ERX };
constexpr double kW = 13.7 / 1000; // work function
}
| [
"[email protected]"
] | |
91d0dcfe49e4fae6e7cadef42c878c41decb38c4 | 4ad2ec9e00f59c0e47d0de95110775a8a987cec2 | /_zFTP-backup/_Surse/BR_lic/BR_9_lic/BR_9_016/BR_9_0161.cpp | e6d2241fa5fc067af325bb66e2415b9af94c0b86 | [] | no_license | atatomir/work | 2f13cfd328e00275672e077bba1e84328fccf42f | e8444d2e48325476cfbf0d4cfe5a5aa1efbedce9 | refs/heads/master | 2021-01-23T10:03:44.821372 | 2021-01-17T18:07:15 | 2021-01-17T18:07:15 | 33,084,680 | 2 | 1 | null | 2015-08-02T20:16:02 | 2015-03-29T18:54:24 | C++ | UTF-8 | C++ | false | false | 1,025 | cpp | #include <fstream>
using namespace std;
void ord(int test[5001], int k) {
int i,aux;
for(int j=1;j<=k;j++)
for(i=1;i<k;i++)
if(test[i]>test[i+1]) {
aux=test[i];
test[i]=test[i+1];
test[i+1]=aux;
}
}
int cool(int test[5001], int k) {
int i;
bool ok=false;
for(i=1;i<k&&ok==false;i++)
if(test[i]+1!=test[i+1])
ok=true;
return ok;
}
int main()
{
ifstream in("cool.in");
ofstream out("cool.out");
int p,n,k,i;
in>>p>>n>>k;
if(p==1) {
int test[k+1];
//Punctul 1
//Citire
for(i=1;i<=k;i++) {
in>>test[i];
}
//Ordonare test
ord(test, k);
//Verificare cool
bool ok;
ok=cool(test, k);
if(!ok)
out<<test[k]<<endl;
else {
int j,nrv=0;
for(j=1;j<=k;j++) {
for(i=1;i<=k;i++)
if(test[i]==test[j]&&i!=j)
nrv++;
}
out<<k-nrv<<endl;
}
}
in.close();
out.close();
return 0;
}
| [
"[email protected]"
] | |
1d63cfff83fa2f9ba0e925b28cb953e3059f63d7 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/squid/old_hunk_6534.cpp | 3e5a075e5441a82113bf36049fe7a7dc1a913696 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 623 | cpp | xfree(fi);
}
static void
fileIteratorAdvance(FileIterator *fi)
{
int res;
assert(fi);
do {
time_t last_time = fi->inner_time;
res = fi->reader(fi);
fi->line_count++;
if (res == frError)
fi->bad_line_count++;
else
if (res == frEof)
fi->inner_time = -1;
else
if (fi->inner_time < last_time) {
assert(last_time >= 0);
fi->time_warp_count++;
fi->inner_time = last_time;
}
/* report progress */
if (!(fi->line_count % 50000))
fprintf(stderr, "%s scanned %d K entries (%d bad)\n",
fi->fname, fi->line_count / 1000, fi->bad_line_count);
} while (res < 0);
}
| [
"[email protected]"
] | |
4101ded7e9b24cd5f25e8111f0d4ecff4496d3a4 | 4e032b7e98626e42c385f9b5b5d9acff1aa18ff0 | /aten/src/ATen/native/quantized/QTensor.cpp | ef4c7eb686d7a0d85f958a311b31fc1b450fc27b | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | hermeshephaestus/pytorch | aafd0c69efa8561dfd277985e7e84497623aec18 | 71260b98e2b215b166d5515b496ceee4a36dd86d | refs/heads/master | 2020-05-25T06:18:42.956613 | 2019-05-20T15:01:47 | 2019-05-20T15:08:28 | 187,665,394 | 1 | 0 | NOASSERTION | 2019-05-20T15:16:52 | 2019-05-20T15:16:52 | null | UTF-8 | C++ | false | false | 1,455 | cpp | #include <ATen/ATen.h>
#include <ATen/NativeFunctions.h>
#include <ATen/quantized/Quantizer.h>
#include <ATen/quantized/QTensorImpl.h>
namespace at {
namespace native {
Tensor quantize_linear_cpu(const Tensor& self, double scale, int64_t zero_point, ScalarType dtype) {
auto quantizer = make_per_tensor_affine_quantizer(scale, zero_point, dtype);
return quantizer->quantize(self);
}
Tensor dequantize_quant(const Tensor& self) {
return get_qtensorimpl(self)->quantizer()->dequantize(self);
}
Scalar q_scale_quant(const Tensor& self) {
auto quantizer = get_qtensorimpl(self)->quantizer();
AT_ASSERT(quantizer->qscheme() == kPerTensorAffine);
return Scalar(static_cast<PerTensorAffineQuantizer*>(quantizer.get())->scale());
}
Scalar q_zero_point_quant(const Tensor& self) {
auto quantizer = get_qtensorimpl(self)->quantizer();
AT_ASSERT(quantizer->qscheme() == kPerTensorAffine);
return Scalar(static_cast<PerTensorAffineQuantizer*>(quantizer.get())->zero_point());
}
Quantizer* quantizer(const Tensor& self) {
return get_qtensorimpl(self)->quantizer().get();
}
Tensor int_repr_quant(const Tensor& self) {
Tensor dst = at::empty(self.sizes(), self.options().dtype(at::kByte));
uint8_t* self_data = reinterpret_cast<uint8_t *>(self.data<quint8>());
uint8_t* dst_data = dst.data<uint8_t>();
if (self.numel() > 0) {
memcpy(dst_data, self_data, self.numel());
}
return dst;
}
} // namespace native
} // namespace at
| [
"[email protected]"
] | |
6acfcf4264da1e212f73d77ffce2660207862436 | 00c5a83bf2d267ff96b8041d75fadfa95af1891e | /RtosWrapper/MyTasks/Led3Task.hpp | 558a32cb14599a8a91d6f602340399b570c0259e | [
"MIT"
] | permissive | katyachalykh/Kursovaya | 7afca3b304deccbde64fdf69fcffcea7c3fdf9b7 | 1d0220dac6676c7210d082a217b6919fa72aa85d | refs/heads/main | 2023-04-28T21:21:32.928751 | 2021-05-28T07:21:10 | 2021-05-28T07:21:10 | 371,413,489 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 158 | hpp | /* #pragma once
#include "thread.hpp"
using namespace OsWrapper;
class Led3Task : public Thread<128U>
{
public:
void Execute() override;
};*/ | [
"[email protected]"
] | |
3ddc2aedf3dd8c9c211da48d4154b686dee9ca18 | e414c59e690b8fa17507a2d41748bdd5b37e9d1a | /91.cpp | 58c1278d119e2113e89d25a0d9122f170dfae5fe | [] | no_license | asimali246/Spoj-solutions | ab3890ad77a2410bf76c76c48b60eafa1596737e | 056e8e31f39355d56c9090742c9080e9c6445324 | refs/heads/master | 2020-06-03T01:09:56.532294 | 2015-05-11T12:26:17 | 2015-05-11T12:26:17 | 17,375,799 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,454 | cpp | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <set>
#include <cstring>
#include <iomanip>
#include <map>
#include <algorithm>
#include <stack>
#include <queue>
#include <list>
#include <string>
#include <vector>
#include <new>
#include <bitset>
#include <ctime>
#include <stdint.h>
#include <unistd.h>
using namespace std;
#define ll long long int
#define INF 1000000000
#define PI acos(-1.0)
#define EPS 1e-9
template <typename X> X gcd(X a, X b){if(!b)return a; else return gcd(b, a%b);}
typedef vector<int> vi;
typedef pair<int, int> ii;
int t, flag, c, prime[100100], l, j;
ll n, i, x;
bitset<1000010> bs;
int main(){
bs.reset();
l=1;
for(i=3;i<=1000000;++i){
if(!bs[i]){
prime[l++]=i;
for(j=i+i;j<=1000000;j+=i)
bs[j]=1;
}
}
--l;
scanf("%d", &t);
while(t--){
flag=0;
scanf("%lld", &n);
while(n%2==0 && n)
n/=2;
for(i=1;i<=l;++i){
if(prime[i]>n)
break;
c=0;
while(n%prime[i]==0)
n/=prime[i], c++;
if(prime[i]%4==3 && c%2!=0){
printf("No\n");
flag=1;
break;
}
}
if(n>1 && n%4==3 && !flag){
printf("No\n");
continue;
}
if(!flag)
printf("Yes\n");
}
return 0;
}
| [
"[email protected]"
] | |
f2d8d83850bb0e038335a3320b19d27fc41d4cf1 | 4ff6383d4318a33b6217ffc84a849eeef68b898a | /src/qt/openuridialog.cpp | 96fe72aa4922b093254841aa80725afd04761de5 | [
"MIT"
] | permissive | PayQ/QpayCoin | 31863c2bd8e1073f67bfa4bc852e664b1464cd55 | 6c346fc83ca9b9c91171ee3866cf597e22ad075e | refs/heads/master | 2020-05-07T09:04:43.835417 | 2019-04-09T12:32:23 | 2019-04-09T12:32:23 | 180,361,388 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,411 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The QpayCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "openuridialog.h"
#include "ui_openuridialog.h"
#include "guiutil.h"
#include "walletmodel.h"
#include <QUrl>
OpenURIDialog::OpenURIDialog(QWidget* parent) : QDialog(parent),
ui(new Ui::OpenURIDialog)
{
ui->setupUi(this);
#if QT_VERSION >= 0x040700
ui->uriEdit->setPlaceholderText("qpaycoin:");
#endif
}
OpenURIDialog::~OpenURIDialog()
{
delete ui;
}
QString OpenURIDialog::getURI()
{
return ui->uriEdit->text();
}
void OpenURIDialog::accept()
{
SendCoinsRecipient rcp;
if (GUIUtil::parseBitcoinURI(getURI(), &rcp)) {
/* Only accept value URIs */
QDialog::accept();
} else {
ui->uriEdit->setValid(false);
}
}
void OpenURIDialog::on_selectFileButton_clicked()
{
QString filename = GUIUtil::getOpenFileName(this, tr("Select payment request file to open"), "", "", NULL);
if (filename.isEmpty())
return;
QUrl fileUri = QUrl::fromLocalFile(filename);
ui->uriEdit->setText("qpaycoin:?r=" + QUrl::toPercentEncoding(fileUri.toString()));
}
| [
"[email protected]"
] | |
76fd64b10cc5a455ba7f7aa8102e55e679c8dbb6 | 732e78bc08828027257a8495e6759e6a03e5eb55 | /王道/chapter4/特殊乘法.cpp | a21a5d52b74874ecee106fae86e16bc856139825 | [] | no_license | soleil0510/Algorithm | dd80bd8bc41301874eb2b2dba3cad55613b15199 | ab688af0f7f62462d3bf6759e7133cd2ab6276f3 | refs/heads/master | 2020-07-14T17:39:59.595116 | 2019-09-15T14:54:54 | 2019-09-15T14:54:54 | 205,365,040 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 829 | cpp | //ÌØÊâ³Ë·¨£º123*45=1*4+1*5+2*4+2*5+3*4+3*5
//#include<iostream>
//#include<cstring>
//#define N 20
//using namespace std;
//
//int a[N],b[N];
//
//int main(){
// int A,B;
//
// while(cin>>A>>B){
// int i=0,j=0;
// while(A/10!=0){
// a[i]=A%10;
// A=A/10;
// i++;
// }
// a[i]=A;
// while(B/10!=0){
// b[j]=B%10;
// B=B/10;
// j++;
// }
// b[j]=B;
//
// int sum=0;
// for(int m=0;m<=i;m++){
// for(int n=0;n<=j;n++){
// sum+=a[m]*b[n];
// }
//
// }
// cout<<sum<<endl;
//
// }
//
//
// return 0;
//}
#include<iostream>
#include<cstring>
using namespace std;
int main(){
char s1[20],s2[20];
while(scanf("%s%s",s1,s2)!=EOF){
int ans=0;
for(int i=0;i<strlen(s1);i++){
for(int j=0;j<strlen(s2);j++){
ans+=(s1[i]-'0')*(s2[j]-'0');
}
}
cout<<ans<<endl;
}
}
| [
"[email protected]"
] | |
7ed24c9cc09a19d3a6420d54e41f18e8c187f09a | 1a17167c38dc9a12c1f72dd0f3ae7288f5cd7da0 | /Source/ThirdParty/angle/third_party/SwiftShader/src/Common/Debug.cpp | acf469e5ab58ac5f8701160d4a6e55d72225522a | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"Zlib",
"LicenseRef-scancode-khronos",
"BSL-1.0",
"BSD-2-Clause"
] | permissive | elix22/Urho3D | c57c7ecb58975f51fabb95bcc4330bc5b0812de7 | 99902ae2a867be0d6dbe4c575f9c8c318805ec64 | refs/heads/master | 2023-06-01T01:19:57.155566 | 2021-12-07T16:47:20 | 2021-12-07T17:46:58 | 165,504,739 | 21 | 4 | MIT | 2021-11-05T01:02:08 | 2019-01-13T12:51:17 | C++ | UTF-8 | C++ | false | false | 938 | cpp | // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "Debug.hpp"
#include <stdio.h>
#include <stdarg.h>
namespace sw
{
void trace(const char *format, ...)
{
if(false)
{
FILE *file = fopen("debug.txt", "a");
if(file)
{
va_list vararg;
va_start(vararg, format);
vfprintf(file, format, vararg);
va_end(vararg);
fclose(file);
}
}
}
}
| [
"[email protected]"
] | |
4af229f96c87280ca0656b3c50ff34849f9090bb | f3c8d78b4f8af9a5a0d047fbae32a5c2fca0edab | /Qt/lib2/Box2D/win/Box2D/Dynamics/Contacts/b2EdgeCircleContact.cpp | fb919f92c3088992b96b3b6cdcca6605b3727c1d | [] | no_license | RinatB2017/mega_GIT | 7ddaa3ff258afee1a89503e42b6719fb57a3cc32 | f322e460a1a5029385843646ead7d6874479861e | refs/heads/master | 2023-09-02T03:44:33.869767 | 2023-08-21T08:20:14 | 2023-08-21T08:20:14 | 97,226,298 | 5 | 2 | null | 2022-12-09T10:31:43 | 2017-07-14T11:17:39 | C++ | UTF-8 | C++ | false | false | 2,185 | cpp | // MIT License
// Copyright (c) 2019 Erin Catto
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <b2EdgeCircleContact.h>
#include <b2BlockAllocator.h>
#include <b2Fixture.h>
#include <new>
b2Contact* b2EdgeAndCircleContact::Create(b2Fixture* fixtureA, int, b2Fixture* fixtureB, int, b2BlockAllocator* allocator)
{
void* mem = allocator->Allocate(sizeof(b2EdgeAndCircleContact));
return new (mem) b2EdgeAndCircleContact(fixtureA, fixtureB);
}
void b2EdgeAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator)
{
((b2EdgeAndCircleContact*)contact)->~b2EdgeAndCircleContact();
allocator->Free(contact, sizeof(b2EdgeAndCircleContact));
}
b2EdgeAndCircleContact::b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB)
: b2Contact(fixtureA, 0, fixtureB, 0)
{
b2Assert(m_fixtureA->GetType() == b2Shape::e_edge);
b2Assert(m_fixtureB->GetType() == b2Shape::e_circle);
}
void b2EdgeAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB)
{
b2CollideEdgeAndCircle( manifold,
(b2EdgeShape*)m_fixtureA->GetShape(), xfA,
(b2CircleShape*)m_fixtureB->GetShape(), xfB);
}
| [
"[email protected]"
] | |
7a3ba6476a0a783290686eb439996215953a97b0 | 070277d0b4cffd2fdf1e4f7821e9fd9027930bbf | /source/all/testcore/zprog.all.cpp | 11b969c1f128ef49c2e229125cec364bae91093a | [
"LicenseRef-scancode-other-permissive"
] | permissive | waterlink/Cursov2011 | af6c8e95b037be4b42df089b751c1adf83a7015d | e458646b394fb0d3b1fcce0c41fabb83c2d95af0 | refs/heads/master | 2016-08-04T18:24:53.793823 | 2012-03-17T12:10:05 | 2012-03-17T12:10:05 | 1,543,450 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,088 | cpp | //
// Author: Fedorov Alexey
// Type: Open-Source Project
// Platform: Linux and Windows
// Codename: Project Santiago
//
// Designer of the robot behavior
//
// sharp-end must not to be deleted
//
//
// source file
// emulator class for z0rch's module
//
#include "zprog.all.hpp"
#include <cmath>
#include <ctime>
#include "../utilcore/mather.all.hpp"
zprog::zprog(btexecutor * btexec, robot * robo){
this->btexec = btexec;
this->robo = robo;
}
zprog::~zprog(){}
void zprog::passstartcoords(int sx, int sy, int lx, int ly){
pos = make_pair(1.0 * sx, 1.0 * sy);
look = make_pair(1.0 * lx, 1.0 * ly);
}
void zprog::moverel(int dx, int dy){
moverelcommands.push_back(make_pair(dx, dy));
}
void zprog::beep(){
withbeep.push_back(moverelcommands.size() - 1);
}
void zprog::setlight(bool fLight){
if (fLight)
withlighton.push_back(moverelcommands.size() - 1);
else withlightoff.push_back(moverelcommands.size() - 1);
}
void zprog::run(){
// TODO: code this up
int withbeepPos = 0;
int withlightonPos = 0;
int withlightoffPos = 0;
int commandsPos = -1;
do {
if (commandsPos > 0){
realrelmove(moverelcommands[commandsPos].first, moverelcommands[commandsPos].first);
if (btexec->getTouchSensorState())
break;
}
if (withbeep.size() > 0)
if (withbeep[withbeepPos] == commandsPos)
robo->beep();
if (withlighton.size() > 0)
if (withlighton[withlightonPos] == commandsPos)
robo->slight(true);
if (withlightoff.size() > 0)
if (withlightoff[withlightoffPos] == commandsPos)
robo->slight(false);
} while (++commandsPos < moverelcommands.size());
}
/*
P0:
_______________________________________________
look
/ targ
/ R-dist *
/ b-angle
* a-angle -> x
sp
_______________________________________________
P1:
_______________________________________________
look,targ
R --------*
a=b ----------
*-----
sp
_______________________________________________
P2:
_______________________________________________
targ -------- look
*-----
sp
_______________________________________________
*/
void zprog::realrelmove(int dx, int dy){
double mullifier = 100.0;
double rotspeed = 0.3;
double gospeed = 0.5;
double maxspeed = robo->getmaxspeed();
double rspeed = maxspeed * rotspeed;
double gspeed = 2.0 * maxspeed * gospeed;
double sizex = robo->getsize().first;
pair < double, double > xylxy = make_pair(look.first - pos.first, look.second - pos.second);
xylxy = mather::normalize(xylxy, 1.0);
double a = acos(xylxy.first);
if (xylxy.second < 0.0)
a = 2.0 * mather::pi() - a;
pair < double, double > xyt = make_pair(1.0 * dx, 1.0 * dy);
xyt = mather::normalize(xyt, 1.0);
double b = acos(xyt.first);
if (xyt.second < 0.0)
b = 2.0 * mather::pi() - b;
a -= b;
//a = -a;
printf("a-angle: %.3lf\n", a);
double R = sizex;
double l = R * fabs(a);
double ndt = l / rspeed;
int counter = 0;
double t = 1.0 * clock() / CLOCKS_PER_SEC;
double dt = 0.0;
if (a < -mather::epsilon()){
btexec->setRD0power(rotspeed * mullifier);
btexec->setRD1power(0.0);
}
else if (a > mather::epsilon()){
btexec->setRD1power(rotspeed * mullifier);
btexec->setRD0power(0.0);
}
if (a < 0.0) a = -a;
if (a > mather::epsilon()){
while (1){
if (counter == 100){
dt = 1.0 * clock() / CLOCKS_PER_SEC - t;
if (dt >= ndt){
btexec->setRD0power(0.0);
btexec->setRD1power(0.0);
break;
}
counter = 0;
}
++counter;
}
}
l = mather::dist(make_pair(1.0 * dx, 1.0 * dy));
ndt = l / gspeed;
counter = 0;
t = 1.0 * clock() / CLOCKS_PER_SEC;
btexec->setRD0power(gospeed * mullifier);
btexec->setRD1power(gospeed * mullifier);
while (1){
if (counter == 100){
dt = 1.0 * clock() / CLOCKS_PER_SEC - t;
if (dt >= ndt){
btexec->setRD0power(0.0);
btexec->setRD1power(0.0);
break;
}
counter = 0;
}
++counter;
}
pos.first += 1.0 * dx;
pos.second += 1.0 * dy;
look.first = pos.first + 1.0 * dx;
look.second = pos.second + 1.0 * dy;
}
//#end
| [
"[email protected]"
] | |
406bfec0c8ae220c4aef03c400ded6fd20b89a7b | 3dae85df94e05bb1f3527bca0d7ad413352e49d0 | /ml/nn/runtime/test/generated/examples/conv_quant8_overflow.example.cpp | 3fd52820f5e7f1008caf1ce1c03ee252df2c22b4 | [
"Apache-2.0"
] | permissive | Wenzhao-Xiang/webml-wasm | e48f4cde4cb986eaf389edabe78aa32c2e267cb9 | 0019b062bce220096c248b1fced09b90129b19f9 | refs/heads/master | 2020-04-08T11:57:07.170110 | 2018-11-29T07:21:37 | 2018-11-29T07:21:37 | 159,327,152 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 772 | cpp | // clang-format off
// Generated file (from: conv_quant8_overflow.mod.py). Do not edit
std::vector<MixedTypedExample> examples = {
// Begin of an example
{
.operands = {
//Input(s)
{ // See tools/test_generator/include/TestHarness.h:MixedTyped
// int -> FLOAT32 map
{},
// int -> INT32 map
{},
// int -> QUANT8_ASYMM map
{{0, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}}},
// int -> QUANT16_ASYMM map
{}
},
//Output(s)
{ // See tools/test_generator/include/TestHarness.h:MixedTyped
// int -> FLOAT32 map
{},
// int -> INT32 map
{},
// int -> QUANT8_ASYMM map
{{0, {75, 90, 105, 165, 203, 240, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}}},
// int -> QUANT16_ASYMM map
{}
}
},
}, // End of an example
};
| [
"[email protected]"
] | |
25c91dd33c7e833516a488dccef881b845505cd7 | 89b7e4a17ae14a43433b512146364b3656827261 | /testcases/CWE78_OS_Command_Injection/s07/CWE78_OS_Command_Injection__wchar_t_environment_system_81.h | a6a8be4db9f376126afcbf87b5f64a8149c279c7 | [] | no_license | tuyen1998/Juliet_test_Suite | 7f50a3a39ecf0afbb2edfd9f444ee017d94f99ee | 4f968ac0376304f4b1b369a615f25977be5430ac | refs/heads/master | 2020-08-31T23:40:45.070918 | 2019-11-01T07:43:59 | 2019-11-01T07:43:59 | 218,817,337 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,408 | h | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_environment_system_81.h
Label Definition File: CWE78_OS_Command_Injection.one_string.label.xml
Template File: sources-sink-81.tmpl.h
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: environment Read input from an environment variable
* GoodSource: Fixed string
* Sinks: system
* BadSink : Execute command in data using system()
* Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define FULL_COMMAND L"dir "
#else
#include <unistd.h>
#define FULL_COMMAND L"ls "
#endif
namespace CWE78_OS_Command_Injection__wchar_t_environment_system_81
{
class CWE78_OS_Command_Injection__wchar_t_environment_system_81_base
{
public:
/* pure virtual function */
virtual void action(wchar_t * data) const = 0;
};
#ifndef OMITBAD
class CWE78_OS_Command_Injection__wchar_t_environment_system_81_bad : public CWE78_OS_Command_Injection__wchar_t_environment_system_81_base
{
public:
void action(wchar_t * data) const;
};
#endif /* OMITBAD */
#ifndef OMITGOOD
class CWE78_OS_Command_Injection__wchar_t_environment_system_81_goodG2B : public CWE78_OS_Command_Injection__wchar_t_environment_system_81_base
{
public:
void action(wchar_t * data) const;
};
#endif /* OMITGOOD */
}
| [
"[email protected]"
] | |
1e34bda912a843045c5e16ff3036eaefcddbe589 | c3d7ad47f0a31ba23dc88b53500e4148713656a0 | /团体程序设计天梯赛-练习集/L1-013.cpp | 716e6ffb8dd4956b93b71c29a9325b219aa6e5d9 | [] | no_license | xs172595372/C_Practise | a6a29d2655bd8110e788a8e08c3a8c584120e81d | 028007ce639feced24427efd4587f44593f278f9 | refs/heads/master | 2020-04-12T23:19:28.699559 | 2018-12-22T14:02:09 | 2018-12-22T14:02:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 152 | cpp | #include<stdio.h>
int main(){
int num,sum=1,i,x=1;
scanf("%d",&num);
for(i=1;i<num;i++){
x=x*(i+1);
sum=sum+x;
}
printf("%d",sum);
return 0;
} | [
"[email protected]"
] | |
204aa20350216df5df95f471f78cd5225fd0cb49 | 70f5e9fffef678a25596dfbbacbc20fb7130be76 | /src/game_object/cube.h | 7217edbc982dde0cd2b8547d75c8fe395d40e192 | [] | no_license | yxyxnrh/CG_Group14 | 69c9064d49c0d0859f614939fe8949b53abd9d5c | 9e1dda46e09d346ea594ad3e873c064364324a49 | refs/heads/master | 2022-01-25T14:28:10.474900 | 2019-07-19T16:23:26 | 2019-07-19T16:23:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,401 | h | #ifndef CUBE_H
#define CUBE_H
#include "./entity.h"
#include "../stb_image/stb_image.h"
#include "../renderers/RendererManager.h"
class Cube : public Entity {
public:
float cubeVertices[36 * 8] = {
// positions // normals // texcoords
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,0.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,0.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f,0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f,0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,0.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f,0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f,0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,0.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,0.0f, 0.0f
};
unsigned int cubeVAO, texture;
void initCubeVAO();
Cube();
void draw(Shader* shader = nullptr) const;
glm::mat4 getModelMat() const;
void initTexture();
};
#endif
| [
"[email protected]"
] | |
7369047d90954733107e9671263b61c19334d870 | ffcb4a1ac26b61cce1298ba1b2d01d0599755311 | /Cubitos.h | 0b28bd26cb739e5dc8f4a5ed13f85e2f41ca2440 | [] | no_license | eulalie/AErubik | 3928c4adf35a0726f082851f33c72769c1083508 | f988a2448c9d5e538f1c72dc45fad1f417bcb9dc | refs/heads/master | 2020-12-24T15:40:18.855811 | 2014-05-21T01:26:46 | 2014-05-21T01:26:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,820 | h | //***********************************************************************
//
//
//
//***********************************************************************
#ifndef __CUBITOS_H__
#define __CUBITOS_H__
// ======================================================================
// Libraries
// ======================================================================
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <time.h>
// ======================================================================
// Project Files
// ======================================================================
// ======================================================================
// Class declarations
// ======================================================================
using namespace std;
class Cubitos
{
// ======================================================================
// Friend Class
// ======================================================================
public :
// ==================================================================
// Enums
// ==================================================================
// ==================================================================
// Constructors
// ==================================================================
Cubitos(int* pos,string colors);
// ==================================================================
// Destructor
// ==================================================================
virtual ~Cubitos(void);
// ==================================================================
// Accessors: getters
// ==================================================================
inline int get_x(void)const;
inline int get_y(void)const;
inline int get_z(void)const;
inline string get_colors(void)const;
// ==================================================================
// Accessors: setters
// ==================================================================
// ==================================================================
// Operators
// ==================================================================
// ==================================================================
// Public Methods
// ==================================================================
void print_cubito(void);
// ==================================================================
// Public Attributes
// ==================================================================
protected :
// ==================================================================
// Forbidden Constructors
// ==================================================================
Cubitos( void )
{
printf( "%s:%d: error: call to forbidden constructor.\n", __FILE__, __LINE__ );
exit( EXIT_FAILURE );
};
Cubitos( const Cubitos &model )
{
printf( "%s:%d: error: call to forbidden constructor.\n", __FILE__, __LINE__ );
exit( EXIT_FAILURE );
};
// ==================================================================
// Protected Methods
// ==================================================================
// ==================================================================
// Protected Attributes
// ==================================================================
int x;
int y;
int z;
string colors;
};
// ======================================================================
// Getters' definitions
// ======================================================================
int Cubitos::get_x(void)const
{
return x;
}
int Cubitos::get_y(void)const
{
return y;
}
int Cubitos::get_z(void)const
{
return z;
}
string Cubitos::get_colors(void)const
{
return colors;
}
// ======================================================================
// Operators' definitions
// ======================================================================
// ======================================================================
// Inline functions' definition
// ======================================================================
#endif // __CUBITOS_H__
| [
"[email protected]"
] | |
d83effed37e560149c6d74876999da7e0255e873 | 64539fcb220fcdd37435956a60f38040beb2b8ca | /MegaDataProject/Model/Timer.cpp | 209551844735d041ab09d26ef367f955b83878a6 | [] | no_license | isaach0011/MegaDataProject | 6dc7f2aedf4b8ef2c5eca26db138faadf660be91 | 8663271954c2366486b451c02b5d7c03ecfa86ca | refs/heads/master | 2021-01-22T03:23:47.815751 | 2017-05-19T19:40:35 | 2017-05-19T19:40:35 | 81,123,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 742 | cpp | //
// Timer.cpp
// FirstCPlusPlusProject
//
// Created by Hill, Isaac on 1/31/17.
// Copyright © 2017 Hill, Isaac. All rights reserved.
//
#include "Timer.hpp"
#include <iostream>
using namespace std;
Timer :: Timer()
{
executionTime = 0;
}
void Timer :: resetTimer()
{
executionTime = 0;
}
void Timer :: startTimer()
{
executionTime = clock();
}
void Timer :: stopTimer()
{
executionTime = clock() - executionTime;
}
long Timer :: getExecutionTimeInMicroseconds()
{
return executionTime;
}
void Timer :: displayTimerInformation()
{
cout << "It took this long to execute: " << executionTime << " microseconds." << endl;
cout << "That is this many seconds: " << executionTime/CLOCKS_PER_SEC << endl;
}
| [
"[email protected]"
] | |
daebb8b8cdd6edb2e5f4b892d37ccf35a22c83f0 | 3b4822ffbda76e8b8f5503746d356da8c3d02ddb | /engine/digest/md5.h | 080fafaf1b532c5ba0d32810fc136a40562f666f | [
"MIT"
] | permissive | fcarreiro/genesis | e8982e3c5a9567de3551f83c2e31adbfb7b967a7 | 48b5c3bac888d999fb1ae17f1a864b59e2c85bc8 | refs/heads/master | 2021-01-10T12:12:09.401644 | 2016-03-29T17:44:52 | 2016-03-29T17:44:52 | 54,992,295 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,211 | h | #ifndef __MD5_H__
#define __MD5_H__
//////////////////////////////////////////////////////////////////////////
// MD5 class
//////////////////////////////////////////////////////////////////////////
class CDigestMd5 : public CDigest
{
public:
// default constructor
CDigestMd5();
virtual ~CDigestMd5();
public:
// initializes the hashing machine
virtual bool Initialize();
// appends a string
virtual bool Append(const std::string & str);
// appends an unknown ptr
virtual bool Append(unsigned char *ptr, unsigned long length);
// finishes the hash
virtual bool Finish();
// get the digest in binary format
virtual bool GetDigest(char **ptr);
// get the digest in binary format
virtual bool GetDigest(std::string & str);
// get the digest in hex format
virtual bool GetDigestHex(char **ptr);
// get the digest in hex format
virtual bool GetDigestHex(std::string & str);
private:
// md5 state
md5_state_t m_State;
// md5 digest
unsigned char m_Digest[16];
};
//////////////////////////////////////////////////////////////////////////
// End
//////////////////////////////////////////////////////////////////////////
#endif
| [
"[email protected]"
] | |
89c8b3d2c5754ef8d65a02bc7f03d55bafef89b5 | 56649046304376279d71bf6fd82562f7efa293ca | /sims/arproctest_sim.cpp | af1a2e89f8e90e835f586afb28e1a88a664d20ea | [] | no_license | zwm152/WirelessCommSystemSimuC-Model | b9b3de73956caa8e872c3d36580ec863962d8ef2 | 7be3562b5a516c73f06c4090b5806ffe7319fe8a | refs/heads/master | 2021-09-23T15:41:08.088030 | 2018-09-25T12:04:04 | 2018-09-25T12:04:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,710 | cpp | //
// File = arproctest_sim.cpp
//
#define SIM_NAME "ArProcTest\0"
#define SIM_TITLE "Autoregressive Noise Testbed\0"
#include "global_stuff.h"
#include "rayleigh_theory.h"
#include "level_gen.h"
#include "disc_auto_cov.h"
#include "histogram.h"
#include "ogive.h"
#include "siganchr.h"
#include "ar_proc_gen.h"
#include "spec_analyzer.h"
#include "ar_spec.h"
main()
{
#include "sim_preamble.cpp"
//=========================================================================
// Misc special processing
double a_coeffs[3];
a_coeffs[0] = 1.0;
a_coeffs[1] = -0.6;
a_coeffs[2] = 0.8;
ArSpectrum *ar_spectrum = new ArSpectrum( 2,//true_ar_order,
a_coeffs,
0.0009765625,
0.32,
512,
0.5);//true_ar_drv_var );
ar_spectrum->DumpSpectrum( "ar_true_spec.txt\0",
true);
//=========================================================================
// Allocate signals
FLOAT_SIGNAL(noisy_sig);
//============================================================
// Construct, initialize and connect models
ArProcessGenerator<float>* noise_source = new ArProcessGenerator<float>(
"noise_source\0",
CommSystem,
noisy_sig);
SignalAnchor* sig_anchr = new SignalAnchor( "sig_anchr\0",
CommSystem,
noisy_sig );
// DiscreteAutoCovar* disc_autocovar = new DiscreteAutoCovar( "disc_autocovar\0",
// CommSystem,
// bit_seq);
HistogramBuilder<float>* histogram = new HistogramBuilder<float>( "histogram\0",
CommSystem,
noisy_sig);
// OgiveBuilder<float>* ogive = new OgiveBuilder<float>( "ogive\0",
// CommSystem,
// noisy_sig);
SpectrumAnalyzer<float>* spec_analyzer =
new SpectrumAnalyzer<float>( "spec_analyzer\0",
CommSystem,
noisy_sig );
//=============================================================
#include "sim_postamble.cpp"
return 0;
}
| [
"[email protected]"
] | |
925b9b8c6eaf887be9a85bc87eab4adc8aa8d204 | b4126e320f6f9e9e05c8ca855426ece11b478d49 | /Arduino/Main_Arduino_Loop/Main_Arduino_Loop.ino | 4893aee2eb7f33a4a4723fa0a7e39a589dd956d3 | [] | no_license | brad6459/rasp | c7692c95a012d89a6f1de3f74d33bab8442cca9b | e1f32ee12af90b9cac2359b4b43fa3b22087ded5 | refs/heads/master | 2020-03-20T08:48:17.149963 | 2019-02-09T09:27:07 | 2019-02-09T09:27:07 | 137,319,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,896 | ino | /*------------------------------------------------------------------
Author: Brindan Adhikari
Pupose: This will be the main arduino loop
Included:
1) 2x Ultrasonic
2) 1x single beam
Future Work:
1) Motor controller
2) Linear-mass controller
3) Encoders
-------------------------------------------------------------------*/
//Define all constants from every mode
const int semi_aut_mod_pin = 12; //Semi-autonomous-mode
//Define the Single Beam Pins
const int trigPin_lidar1 = 2;
const int monitorPin_lidar1 = 3;
unsigned long pulseWidth;
const int discont_mod_pin = 13; //Discontinuity-mode
//Define the ultrasonic Sensors pins
const int trigPin_ultra1 = 9; //ultrasonic#1
const int echoPin_ultra1 = 10;
const int trigPin_ultra2 = 4; //ultrasonic#2
const int echoPin_ultra2 = 5;
long duration;
float distance;
//Start all modes at false
int semi_aut_mod = 0;
int discont_mod =0;
//Define mode
int MODE;
int lastMODE;
/*-------------------------------------------------------------------
Setup:setup all the pins as either inputs or outputs &set all
modes to LOW*/
void setup()
{ //MODES set to low
pinMode(semi_aut_mod_pin, INPUT);
digitalWrite(semi_aut_mod_pin,LOW);
pinMode(discont_mod_pin, INPUT);
digitalWrite(discont_mod_pin,LOW);
//Single Beam Setup
pinMode(trigPin_lidar1,OUTPUT);
digitalWrite(trigPin_lidar1,LOW);
pinMode(monitorPin_lidar1,INPUT);
//Ultrasonic Setup
pinMode(trigPin_ultra1, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin_ultra1, INPUT); // Sets the echoPin as an Input
pinMode(trigPin_ultra2, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin_ultra2, INPUT); // Sets the echoPin as an Input
}
/*___________________________________________________________________
---------------------------MAIN LOOP---------------------------------
_____________________________________________________________________*/
void loop()
{
//Set all modes to reading the respective pins to verify current mode
semi_aut_mod = digitalRead(semi_aut_mod_pin);
discont_mod = digitalRead(discont_mod_pin);
//Select the mode
if (semi_aut_mod == HIGH)
{
MODE = 3;
Serial.print("Semi-Autonomous-Mode Activated");
}
else if (discont_mod == HIGH)
{
MODE = 4;
Serial.print("Discontinuity-Mode Activated");
}
else
{
Serial.print("No Modes Detected");
}
//See if MODES have switched
if(MODE !=lastMODE)
{
// Enter Swtich cases for the modes
switch(MODE)
{
//------------------------Discontinuity MODE------------------------
case 4:
Serial.begin(9600); //Starts the serial communication
// Ultrasonics #1
// Clears the trigPin
digitalWrite(trigPin_ultra1, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin_ultra1, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin_ultra1, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin_ultra1, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance#1: ");
Serial.println(distance);
// Ultrasonic #2
// Clears the trigPin
digitalWrite(trigPin_ultra2, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin_ultra2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin_ultra2, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin_ultra2, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance#2: ");
Serial.println(distance);
break;
//-----------------------Semi-autonomous-Mode--------------------
case 3:
Serial.begin(115200); //Start Serial communications
//Single-Beam#1
pulseWidth = pulseIn(monitorPin_lidar1, HIGH); // Count how long the pulse is high in microseconds
if(pulseWidth != 0) //If reading isn't 0
{
pulseWidth = pulseWidth / 10; // 10usec = 1 cm of distance
Serial.println(pulseWidth); // Print the distance
}
break;
}
lastMODE = MODE;
}
}
| [
"[email protected]"
] | |
7e3106183688079988a4c8206679ffed0aad98ae | 9b7964822100a804450fadfe3cd7ea72180eadcb | /src/qt/askpassphrasedialog.cpp | 06d3efa953d4d636477843be05b9c1d7eba55980 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | thnass/adeptio | 7415d6300e0aec964e2223c4c7b19ea51b173816 | 65aad9209588e62a3e58d6187a88253d3d5f04b1 | refs/heads/master | 2020-08-04T03:40:56.444722 | 2019-10-01T01:28:09 | 2019-10-01T01:28:09 | 211,990,234 | 0 | 0 | MIT | 2019-10-01T01:25:17 | 2019-10-01T01:25:16 | null | UTF-8 | C++ | false | false | 11,460 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017-2019 The Adeptio developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "allocators.h"
#include <QKeyEvent>
#include <QMessageBox>
#include <QPushButton>
#include <QWidget>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel* model, Context context) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(model),
context(context),
fCapsLock(false)
{
ui->setupUi(this);
this->setStyleSheet(GUIUtil::loadStyleSheet());
ui->passEdit1->setMinimumSize(ui->passEdit1->sizeHint());
ui->passEdit2->setMinimumSize(ui->passEdit2->sizeHint());
ui->passEdit3->setMinimumSize(ui->passEdit3->sizeHint());
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
this->model = model;
switch (mode) {
case Mode::Encrypt: // Ask passphrase x2
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>."));
ui->passLabel1->hide();
ui->passEdit1->hide();
setWindowTitle(tr("Encrypt wallet"));
break;
case Mode::UnlockAnonymize:
ui->anonymizationCheckBox->show();
case Mode::Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Mode::Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case Mode::ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
// Set checkbox "For anonymization, automint, and staking only" depending on from where we were called
if (context == Context::Unlock_Menu || context == Context::Mint_zADE || context == Context::BIP_38) {
ui->anonymizationCheckBox->setChecked(true);
}
else {
ui->anonymizationCheckBox->setChecked(false);
}
// It doesn't make sense to show the checkbox for sending ADE because you wouldn't check it anyway.
if (context == Context::Send_ADE || context == Context::Send_zADE) {
ui->anonymizationCheckBox->hide();
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if (!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch (mode) {
case Mode::Encrypt: {
if (newpass1.empty() || newpass2.empty()) {
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR ADE</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel);
if (retval == QMessageBox::Yes) {
if (newpass1 == newpass2) {
if (model->setWalletEncrypted(true, newpass1)) {
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("ADE will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your ADEs from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
} else {
QDialog::reject(); // Cancelled
}
} break;
case Mode::UnlockAnonymize:
case Mode::Unlock:
if (!model->setWalletLocked(false, oldpass, ui->anonymizationCheckBox->isChecked())) {
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
} else {
QDialog::accept(); // Success
}
break;
case Mode::Decrypt:
if (!model->setWalletEncrypted(false, oldpass)) {
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
} else {
QDialog::accept(); // Success
}
break;
case Mode::ChangePass:
if (newpass1 == newpass2) {
if (model->changePassphrase(oldpass, newpass1)) {
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch (mode) {
case Mode::Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case Mode::UnlockAnonymize: // Old passphrase x1
case Mode::Unlock: // Old passphrase x1
case Mode::Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case Mode::ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent* event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent* ke = static_cast<QKeyEvent*>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject* object, QEvent* event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent* ke = static_cast<QKeyEvent*>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar* psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
| [
"[email protected]"
] | |
af963f36231eaaaa91bb0a75c67a3af172d0f23a | 3ec5c47c6d2907bbe94daab2eacb0a04320d43f8 | /entities/point.h | b790d28695fae4b44e94c7c97572300686ef5ec2 | [] | no_license | NEDJIMAbelgacem/vectorization-tool | 7a61c5e6a38e55aae9705fbaf764858b8b599442 | 0463e28bae17bc892e0a955d393f437e173102e3 | refs/heads/master | 2021-01-06T16:41:22.870145 | 2020-03-19T10:59:13 | 2020-03-19T10:59:13 | 241,402,181 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,657 | h | #pragma once
#include "entity.h"
#include "mainwindow.h"
#include "entitiesmanager.h"
#include "drawingconfig.h"
class PointEntity;
#include <QRect>
#include <QGraphicsEllipseItem>
class PointEntity : public Entity {
DrawingConfig config;
private:
void applyConfig();
QPen getPen();
QGraphicsEllipseItem* selection_item = nullptr;
public:
PointEntity();
PointEntity(QDomElement& element);
void setPosition(QPointF pos);
void setWidth(qreal w) override { this->config.setConfig("width", w); applyConfig(); }
qreal getWidth() override { return config.getConfig<qreal>("width"); }
void setColor(QColor color) override { this->config.setConfig("color", color); applyConfig(); }
QColor getColor() override { return config.getConfig<QColor>("color"); }
QPointF getPoint();
void setConfig(DrawingConfig config);
bool isNeighboursWith(PointEntity* point, qreal threshold);
bool isNeighboursWith(LineEntity* line, qreal threshold);
bool isNeighboursWith(PolygonEntity* polygon, qreal threshold);
bool isNeighboursWith(PolylineEntity* polyline, qreal threshold);
QGraphicsEllipseItem* getItem();
void selectedEvent() override;
void deselectedEvent() override;
TopologyCheckResult checkTopologyCondition(LineEntity* entity) override;
TopologyCheckResult checkTopologyCondition(PolygonEntity* entity) override;
TopologyCheckResult checkTopologyCondition(PointEntity* entity) override;
TopologyCheckResult checkTopologyCondition(PolylineEntity* entity) override;
void moveBy(QPointF dp) override;
QDomElement toDomElement(QDomDocument &doc) override;
};
| [
"[email protected]"
] | |
001e62dd7a098d73d5dda5a16ae05e8dfb056ae2 | 1959f7f7014ebfcad68bffb4b81bbcae332c73bb | /Tests/QtAutogen/same_name/bbb/item.hpp | eda84a2e8fb0e2a9d8f8610c1306fd7ef47595ef | [
"BSD-3-Clause"
] | permissive | mutual-ai/CMake | 6d6f3ff1bde0259c46687d18b8f90f1b3e145fd4 | d08281094948eaefb495040f4a7bb45cba17a5a7 | refs/heads/master | 2020-04-06T06:29:37.461188 | 2016-05-16T14:11:43 | 2016-05-16T14:11:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 159 | hpp | #ifndef SDB_ITEM_HPP
#define SDB_ITEM_HPP
#include <QObject>
namespace bbb {
class Item : public QObject
{
Q_OBJECT
Q_SLOT
void go ( );
};
}
#endif
| [
"[email protected]"
] | |
c4cc0b1282c2884f653bdb20750e35d36ac2f20c | c080549fb807238a22d14f2ea0b0e805a0db3b21 | /MainMenuState.cpp | 050cec4438394ecd432d59c7d400f11a9337d76b | [] | no_license | bodaiboka/sdldemo | d41c17efb63f9efdf98d7fecbb38e8046febf9d2 | 91a186e0a6f90a6e32cc4974299e1448883a335a | refs/heads/master | 2021-01-20T06:47:20.934711 | 2017-09-08T18:20:04 | 2017-09-08T18:20:04 | 101,518,553 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,929 | cpp | #include <iostream>
#include "Game.h"
#include "MenuButton.h"
#include "PlayState.h"
#include "HeliState.h"
#include "MainMenuState.h"
#include "StateParser.h"
const std::string MainMenuState::s_menuId = "MENU";
MainMenuState::MainMenuState()
{
}
MainMenuState::~MainMenuState()
{
}
void MainMenuState::update()
{
// todo
for (GameObject* pGameObject : m_gameObjects)
{
pGameObject->update();
}
}
void MainMenuState::render()
{
for (GameObject* pGameObject : m_gameObjects)
{
pGameObject->draw();
}
}
bool MainMenuState::onEnter()
{
StateParser stateParser;
stateParser.parseState("assets/data.xml", s_menuId, &m_gameObjects, &m_textureIdList);
m_callbacks.push_back(0);
m_callbacks.push_back(s_menuToPlay);
m_callbacks.push_back(s_menuToHeli);
m_callbacks.push_back(s_exitFromMenu);
setCallbacks(m_callbacks);
std::cout << "entering menuState\n";
return true;
}
bool MainMenuState::onExit()
{
for (GameObject* pGameObject : m_gameObjects)
{
pGameObject->clean();
}
m_gameObjects.clear();
for (int i = 0; i < m_textureIdList.size(); i++)
{
TextureManager::Instance()->clearFromTextureMap(m_textureIdList[i]);
}
std::cout << "exiting menuState\n";
return true;
}
void MainMenuState::s_menuToPlay()
{
std::cout << "play button clicked\n";
Game::Instance()->getStateMachine()->changeState(new PlayState());
}
void MainMenuState::s_exitFromMenu()
{
std::cout << "exit button clicked\n";
Game::Instance()->quit();
}
void MainMenuState::s_menuToHeli()
{
std::cout << "Heli button clicked\n";
Game::Instance()->getStateMachine()->changeState(new HeliState());
}
void MainMenuState::setCallbacks(const std::vector<Callback>& callbacks)
{
for (int i = 0; i < m_gameObjects.size(); i++)
{
if (dynamic_cast<MenuButton*>(m_gameObjects[i]))
{
MenuButton* pButton = dynamic_cast<MenuButton*>(m_gameObjects[i]);
pButton->setCallback(callbacks[pButton->getCallbackId()]);
}
}
}
| [
"[email protected]"
] | |
35d8bf466645d01e2a7ae12971c58d6c31a591a0 | 2baa02e126332491b6cbfd96f6f68b39dc6dab17 | /src/FFRooModelHist.cxx | 89379d9bf9323d94ce993207aa60727893ac3229 | [] | no_license | werthm/FooFit | c2441027468a6715608c2b3ae395efe839e42268 | 79ade7da98fc4187941b939f6a5f551c938c8593 | refs/heads/master | 2021-01-10T01:40:23.687754 | 2020-04-05T13:38:14 | 2020-04-05T13:38:14 | 47,331,402 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,557 | cxx | /*************************************************************************
* Author: Dominik Werthmueller, 2015-2019
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// FFRooModelHist //
// //
// Class representing a model from a histogram for RooFit. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TH2.h"
#include "TH3.h"
#include "TTree.h"
#include "RooRealVar.h"
#include "RooDataHist.h"
#include "RooHistPdf.h"
#include "RooGaussModel.h"
#include "RooFFTConvPdf.h"
#include "FFRooModelHist.h"
ClassImp(FFRooModelHist)
//______________________________________________________________________________
FFRooModelHist::FFRooModelHist(const Char_t* name, const Char_t* title, TH1* hist,
Bool_t gaussConvol, Int_t intOrder)
: FFRooModel(name, title, gaussConvol ? hist->GetDimension() * 2 : 0)
{
// Constructor.
// init members
fNDim = hist->GetDimension();
fHist = hist;
fTree = 0;
fWeightVar = "";
fInterpolOrder = intOrder;
fDataHist = 0;
fIsConvol = gaussConvol;
if (fIsConvol)
AddGaussConvolPars();
}
//______________________________________________________________________________
FFRooModelHist::FFRooModelHist(const Char_t* name, const Char_t* title, Int_t nDim, TTree* tree,
const Char_t* weightVar, Bool_t gaussConvol, Int_t intOrder)
: FFRooModel(name, title, gaussConvol ? nDim * 2 : 0)
{
// Constructor.
// init members
fNDim = nDim;
fHist = 0;
fTree = tree;
fWeightVar = "";
fInterpolOrder = intOrder;
if (weightVar)
fWeightVar = weightVar;
fDataHist = 0;
fIsConvol = gaussConvol;
if (fIsConvol)
AddGaussConvolPars();
}
//______________________________________________________________________________
FFRooModelHist::FFRooModelHist(const Char_t* name, const Char_t* title, Int_t nDim, TTree* tree,
RooAbsReal** convolPar, const Char_t* weightVar, Int_t intOrder)
: FFRooModel(name, title, nDim * 2)
{
// Constructor.
// init members
fNDim = nDim;
fHist = 0;
fTree = tree;
fWeightVar = "";
fInterpolOrder = intOrder;
if (weightVar)
fWeightVar = weightVar;
fDataHist = 0;
fIsConvol = kTRUE;
// set Gaussian convolution parameters
for (Int_t i = 0; i < fNPar; i++)
fPar[i] = convolPar[i];
}
//______________________________________________________________________________
FFRooModelHist::~FFRooModelHist()
{
// Destructor.
if (fHist)
delete fHist;
if (fTree)
delete fTree;
if (fDataHist)
delete fDataHist;
}
//______________________________________________________________________________
void FFRooModelHist::DetermineHistoBinning(RooRealVar* var, RooRealVar* par,
Int_t* nBin, Double_t* min, Double_t* max)
{
// Determine the binning of the histogram used to construct the pdf for
// the variable 'var' taking into account the parameter 'par'.
// Return the number of bins and the lower and upper bounds via 'nBin',
// 'min', and 'max', respectively.
// calculate the binning
RooAbsBinning& binning = var->getBinning();
Double_t binw = binning.averageBinWidth();
// different binning if convolution is used
if (fIsConvol)
{
// extend range due to bias parameter
Double_t lmin = TMath::Min(binning.lowBound(), TMath::Min(binning.lowBound() - par->getMin(), binning.lowBound() - par->getMax()));
Double_t lmax = TMath::Max(binning.highBound(), TMath::Max(binning.highBound() - par->getMin(), binning.highBound() - par->getMax()));
*min = binning.lowBound() - binw;
*max = binning.highBound() + binw;
// extend range to original binning
while (*min > lmin)
*min -= binw;
while (*max < lmax)
*max += binw;
*nBin = (*max - *min) / binw;
}
else
{
*min = binning.lowBound() - binw;
*max = binning.highBound() + binw;
*nBin = binning.numBins() + 2;
}
}
//______________________________________________________________________________
void FFRooModelHist::AddGaussConvolPars()
{
// Init the parameters for the Gaussian convolution.
// loop over dimensions
for (Int_t i = 0; i < fNDim; i++)
{
// add convolution parameters
TString tmp;
tmp = TString::Format("%s_%d_Conv_GMean", GetName(), i);
AddParameter(2*i, tmp.Data(), tmp.Data());
tmp = TString::Format("%s_%d_Conv_GSigma", GetName(), i);
AddParameter(2*i+1, tmp.Data(), tmp.Data());
}
}
//______________________________________________________________________________
void FFRooModelHist::BuildModel(RooAbsReal** vars)
{
// Build the model using the variables 'vars'.
// prepare variable set
RooArgSet varSet;
for (Int_t i = 0; i < fNDim; i++)
varSet.add(*vars[i]);
// check if variables can be down-casted
for (Int_t i = 0; i < fNDim; i++)
{
if (!vars[i]->InheritsFrom("RooRealVar"))
{
Error("BuildModel", "Variable '%s' is not of type RooRealVar!", vars[i]->GetName());
return;
}
}
// check if parameters can be down-casted
for (Int_t i = 0; i < fNPar; i++)
{
if (!fPar[i]->InheritsFrom("RooRealVar"))
{
Error("BuildModel", "Parameter '%s' is not of type RooRealVar!", fPar[i]->GetName());
return;
}
}
// create binned input data
if (!fHist && fTree)
{
// check dimension
if (fNDim == 1)
{
// calculate the binning
Int_t nbin_0 = 0;
Double_t min_0 = 0, max_0 = 0;
if (fIsConvol)
DetermineHistoBinning((RooRealVar*)vars[0], (RooRealVar*)fPar[0], &nbin_0, &min_0, &max_0);
else
DetermineHistoBinning((RooRealVar*)vars[0], 0, &nbin_0, &min_0, &max_0);
// create the histogram
fHist = new TH1F(TString::Format("hist_%s_%s",
vars[0]->GetName(),
GetName()).Data(),
TString::Format("Histogram variable '%s' of species '%s'",
vars[0]->GetTitle(), GetTitle()).Data(),
nbin_0, min_0, max_0);
// fill the histogram
fTree->Draw(TString::Format("%s>>hist_%s_%s",
vars[0]->GetName(),
vars[0]->GetName(),
GetName()).Data(),
fWeightVar.Data());
}
else if (fNDim == 2)
{
// calculate the binning
Int_t nbin_0 = 0;
Int_t nbin_1 = 0;
Double_t min_0 = 0, max_0 = 0;
Double_t min_1 = 0, max_1 = 0;
if (fIsConvol)
{
DetermineHistoBinning((RooRealVar*)vars[0], (RooRealVar*)fPar[0], &nbin_0, &min_0, &max_0);
DetermineHistoBinning((RooRealVar*)vars[1], (RooRealVar*)fPar[2], &nbin_1, &min_1, &max_1);
}
else
{
DetermineHistoBinning((RooRealVar*)vars[0], 0, &nbin_0, &min_0, &max_0);
DetermineHistoBinning((RooRealVar*)vars[1], 0, &nbin_1, &min_1, &max_1);
}
// create the histogram
fHist = new TH2F(TString::Format("hist_%s_%s_%s",
vars[0]->GetName(),
vars[1]->GetName(),
GetName()).Data(),
TString::Format("Histogram variables '%s' and '%s' of species '%s'",
vars[0]->GetTitle(), vars[1]->GetTitle(), GetTitle()).Data(),
nbin_0, min_0, max_0,
nbin_1, min_1, max_1);
// fill the histogram
fTree->Draw(TString::Format("%s:%s>>hist_%s_%s_%s",
vars[1]->GetName(),
vars[0]->GetName(),
vars[0]->GetName(),
vars[1]->GetName(),
GetName()).Data(),
fWeightVar.Data());
}
else if (fNDim == 3)
{
// calculate the binning
Int_t nbin_0 = 0;
Int_t nbin_1 = 0;
Int_t nbin_2 = 0;
Double_t min_0 = 0, max_0 = 0;
Double_t min_1 = 0, max_1 = 0;
Double_t min_2 = 0, max_2 = 0;
if (fIsConvol)
{
DetermineHistoBinning((RooRealVar*)vars[0], (RooRealVar*)fPar[0], &nbin_0, &min_0, &max_0);
DetermineHistoBinning((RooRealVar*)vars[1], (RooRealVar*)fPar[2], &nbin_1, &min_1, &max_1);
DetermineHistoBinning((RooRealVar*)vars[2], (RooRealVar*)fPar[4], &nbin_2, &min_2, &max_2);
}
else
{
DetermineHistoBinning((RooRealVar*)vars[0], 0, &nbin_0, &min_0, &max_0);
DetermineHistoBinning((RooRealVar*)vars[1], 0, &nbin_1, &min_1, &max_1);
DetermineHistoBinning((RooRealVar*)vars[2], 0, &nbin_2, &min_2, &max_2);
}
// create the histogram
fHist = new TH3F(TString::Format("hist_%s_%s_%s_%s",
vars[0]->GetName(),
vars[1]->GetName(),
vars[2]->GetName(),
GetName()).Data(),
TString::Format("Histogram variables '%s', '%s' and '%s' of species '%s'",
vars[0]->GetTitle(), vars[1]->GetTitle(), vars[2]->GetTitle(), GetTitle()).Data(),
nbin_0, min_0, max_0,
nbin_1, min_1, max_1,
nbin_2, min_2, max_2);
// fill the histogram
fTree->Draw(TString::Format("%s:%s:%s>>hist_%s_%s_%s_%s",
vars[2]->GetName(),
vars[1]->GetName(),
vars[0]->GetName(),
vars[0]->GetName(),
vars[1]->GetName(),
vars[2]->GetName(),
GetName()).Data(),
fWeightVar.Data());
}
else
{
Error("BuildModel", "Cannot convert unbinned input data of dimension %d!", fNDim);
return;
}
}
// backup binning of variables
Int_t vbins[fNDim];
Double_t vmin[fNDim];
Double_t vmax[fNDim];
for (Int_t i = 0; i < fNDim; i++)
{
vbins[i] = ((RooRealVar*)vars[i])->getBinning().numBins();
vmin[i] = ((RooRealVar*)vars[i])->getBinning().lowBound();
vmax[i] = ((RooRealVar*)vars[i])->getBinning().highBound();
}
// extend variables to range of histogram
TAxis* haxes[3] = { fHist->GetXaxis(), fHist->GetYaxis(), fHist->GetZaxis() };
for (Int_t i = 0; i < fNDim; i++)
{
((RooRealVar*)vars[i])->setBins(haxes[i]->GetNbins());
((RooRealVar*)vars[i])->setMin(haxes[i]->GetXmin());
((RooRealVar*)vars[i])->setMax(haxes[i]->GetXmax());
}
// create RooFit histogram
if (fDataHist) delete fDataHist;
fDataHist = new RooDataHist(TString::Format("%s_RooFit", fHist->GetName()),
TString::Format("%s (RooFit)", fHist->GetTitle()),
varSet, RooFit::Import(*fHist));
// restore binning of variables
for (Int_t i = 0; i < fNDim; i++)
{
((RooRealVar*)vars[i])->setBins(vbins[i]);
((RooRealVar*)vars[i])->setMin(vmin[i]);
((RooRealVar*)vars[i])->setMax(vmax[i]);
}
// create the model pdf
if (fPdf)
delete fPdf;
if (fIsConvol)
{
// delete old pdfs
if (fPdfIntr)
delete fPdfIntr;
if (fPdfConv)
delete fPdfConv;
// create pdfs
TString tmp;
tmp = TString::Format("%s_Conv_Intr", GetName());
fPdfIntr = new RooHistPdf(tmp.Data(), tmp.Data(), varSet, *fDataHist, fInterpolOrder);
tmp = TString::Format("%s_Conv_Gauss", GetName());
fPdfConv = new RooGaussModel(tmp.Data(), tmp.Data(), *((RooRealVar*)vars[0]), *fPar[0], *fPar[1]);
((RooRealVar*)vars[0])->setBins(10000, "cache");
fPdf = new RooFFTConvPdf(GetName(), GetTitle(), *((RooRealVar*)vars[0]), *fPdfIntr, *fPdfConv);
}
else
{
// create pdf
fPdf = new RooHistPdf(GetName(), GetTitle(), varSet, *fDataHist, fInterpolOrder);
}
}
| [
"[email protected]"
] | |
66da49ad572b5fdf8c0b62780cc903c1c96f7831 | ce1e8b29ffd9d97ffc5c693fe3bd4ee358b5e1d5 | /src/ExtFileHdf5/HDF5/HDF5_Array.cpp | 8a9b19e9d01f38757842bf33eddfcc6a871935a8 | [
"MIT"
] | permissive | voxie-viewer/voxie | d76fe7d3990b14dea34e654378d82ddeb48f6445 | 2b4f23116ab1c2fd44b134c4265a59987049dcdb | refs/heads/master | 2023-04-14T13:30:18.668070 | 2023-04-04T10:58:24 | 2023-04-04T10:58:24 | 60,341,017 | 6 | 1 | MIT | 2022-11-29T06:52:16 | 2016-06-03T10:50:54 | C++ | UTF-8 | C++ | false | false | 1,143 | cpp | /*
* Copyright (c) 2013 Steffen Kieß
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "Array.hpp"
| [
"[email protected]"
] | |
3af6453b01ad0855ef36be6cc2ee90ee2869e573 | 23c1284c85ee214ef18b81588a49d225f0e543f7 | /L4/matrix.cpp | ac581c928c600fcc3b69f8482575643e3763b3a6 | [] | no_license | mbolinas/220L4 | 1209a3e9abd7fe1c12703f46472890ef10f230a9 | 18d70d9c2df4d2121ac5d31770e6f2f76272b6eb | refs/heads/master | 2021-07-11T04:36:16.029672 | 2017-10-12T22:59:19 | 2017-10-12T22:59:19 | 106,753,704 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,002 | cpp | /*
* matrix.cpp
*
* Created on: Oct 11, 2017
* Author: Marc
*/
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
#include "matrix.hpp"
matrix::matrix(){
x = 0;
y = 0;
make();
}
matrix::matrix(int w, int l){
x = w;
y = l;
make();
}
void matrix::make(){
mat = new string*[x];
for(int c = 0; c < x; c++){
mat[c] = new string[y];
}
for(int i = 0; i < x; i++){
for(int j = 0; j < y; j++){
mat[i][j] = "0";
}
}
}
void matrix::print(){
for(int i = 0; i < x; i++){
for(int j = 0; j < y; j++){
cout << mat[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
void matrix::add_x(){
int how_many_x_to_give_to_ya = 5;
while(how_many_x_to_give_to_ya > 0){
int i = rand() % x;
int j = rand() % y;
if(mat[i][j] != "x"){
mat[i][j] = "x";
how_many_x_to_give_to_ya--;
}
}
}
matrix::~matrix(){
for(int i = 0; i < x; i++){
delete mat[i];
}
delete mat;
}
| [
"[email protected]"
] | |
8053924328b99e18b05ea488ae7eed67a785bb08 | ab0a8234e443a6aa152b9f7b135a1e2560e9db33 | /Server/CGSF/CGSFTest/BaseLayerTest/DataStructureTest.cpp | a219e13d3696891b41b832028b448a8a47be3987 | [] | no_license | zetarus/Americano | 71c358d8d12b144c8858983c23d9236f7d0e941b | b62466329cf6f515661ef9fb9b9d2ae90a032a60 | refs/heads/master | 2023-04-08T04:26:29.043048 | 2018-04-19T11:21:14 | 2018-04-19T11:21:14 | 104,159,178 | 9 | 2 | null | 2023-03-23T12:10:51 | 2017-09-20T03:11:44 | C++ | UHC | C++ | false | false | 1,333 | cpp | //////////////////////////////////////////////////////////////////////
//게임 프로그래머를 위한 자료구조와 알고리즘 소스 테스트
//////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "DataStructureTest.h"
#include "Array2D.h"
#include "Queue.h"
#include "Heap.h"
using namespace CGBase;
int CompareIntDescending( int left, int right )
{
if( left < right )
return 1;
if( left > right)
return -1;
return 0;
}
DataStructureTest::DataStructureTest(void)
{
}
DataStructureTest::~DataStructureTest(void)
{
}
bool DataStructureTest::Run()
{
/////////////////////////////////
//Array Test
/////////////////////////////////
Array2D<int> Array2D_( 5, 4 );
(*Array2D_.Get(4,3)) = 5;
int* ArrayValue = Array2D_.Get(4,3);
SFASSERT(*ArrayValue == 5);
/////////////////////////////////
//Queue Test
/////////////////////////////////
LQueue<int> Queue;
int Data = 5;
Queue.Enqueue(Data);
Queue.Enqueue(Data);
/////////////////////////////////
//Heap Test
/////////////////////////////////
Heap<int> IntHeap( 100, CompareIntDescending );
Data = 7;
IntHeap.Enqueue(Data);
Data = 10;
IntHeap.Enqueue(Data);
Data = 8;
IntHeap.Enqueue(Data);
int HeapTop = IntHeap.Item();
SFASSERT(HeapTop == 7);
return true;
}
| [
"[email protected]"
] | |
66536cf940bd5ef3a95d69e3f0ae9420fea01325 | 64dccd45009486beb7c7f9595bfaa16f9442dc05 | /BaseLib/task/sequence_manager/task_queue_selector.cpp | e450659c51504b2c08d9f90034da8a1a8c83fbcc | [] | no_license | xjyu007/BaseLib | cbb2d1baa32012a0bce1a33579336b8f93e722f2 | 46985fd2551f9e16619f361559c5a8c3a08c6ec5 | refs/heads/master | 2020-07-16T10:27:18.854060 | 2019-10-18T08:25:25 | 2019-10-18T08:25:25 | 205,770,219 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,381 | cpp | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "task/sequence_manager/task_queue_selector.h"
#include <utility>
#include "logging.h"
#include "task/sequence_manager/associated_thread_id.h"
#include "task/sequence_manager/task_queue_impl.h"
#include "task/sequence_manager/work_queue.h"
#include "threading/thread_checker.h"
#include "trace_event/traced_value.h"
namespace base::sequence_manager::internal {
constexpr const int64_t TaskQueueSelector::per_priority_starvation_tolerance_[];
TaskQueueSelector::TaskQueueSelector(
scoped_refptr<AssociatedThreadId> associated_thread,
const SequenceManager::Settings& settings)
: associated_thread_(std::move(associated_thread)),
#if DCHECK_IS_ON()
random_task_selection_(settings.random_task_selection_seed != 0),
#endif
anti_starvation_logic_for_priorities_disabled_(
settings.anti_starvation_logic_for_priorities_disabled),
delayed_work_queue_sets_("delayed", this, settings),
immediate_work_queue_sets_("immediate", this, settings) {}
TaskQueueSelector::~TaskQueueSelector() = default;
void TaskQueueSelector::AddQueue(TaskQueueImpl* queue) {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
DCHECK(queue->IsQueueEnabled());
AddQueueImpl(queue, TaskQueue::kNormalPriority);
}
void TaskQueueSelector::RemoveQueue(TaskQueueImpl* queue) {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
if (queue->IsQueueEnabled()) {
RemoveQueueImpl(queue);
}
}
void TaskQueueSelector::EnableQueue(TaskQueueImpl* queue) {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
DCHECK(queue->IsQueueEnabled());
AddQueueImpl(queue, queue->GetQueuePriority());
if (task_queue_selector_observer_)
task_queue_selector_observer_->OnTaskQueueEnabled(queue);
}
void TaskQueueSelector::DisableQueue(TaskQueueImpl* queue) {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
DCHECK(!queue->IsQueueEnabled());
RemoveQueueImpl(queue);
}
void TaskQueueSelector::SetQueuePriority(TaskQueueImpl* queue,
TaskQueue::QueuePriority priority) {
DCHECK_LT(priority, TaskQueue::kQueuePriorityCount);
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
if (queue->IsQueueEnabled()) {
ChangeSetIndex(queue, priority);
} else {
// Disabled queue is not in any set so we can't use ChangeSetIndex here
// and have to assign priority for the queue itself.
queue->delayed_work_queue()->AssignSetIndex(priority);
queue->immediate_work_queue()->AssignSetIndex(priority);
}
DCHECK_EQ(priority, queue->GetQueuePriority());
}
TaskQueue::QueuePriority TaskQueueSelector::NextPriority(
TaskQueue::QueuePriority priority) {
DCHECK(priority < TaskQueue::kQueuePriorityCount);
return static_cast<TaskQueue::QueuePriority>(static_cast<int>(priority) + 1);
}
void TaskQueueSelector::AddQueueImpl(TaskQueueImpl* queue,
TaskQueue::QueuePriority priority) {
#if DCHECK_IS_ON()
DCHECK(!CheckContainsQueueForTest(queue));
#endif
delayed_work_queue_sets_.AddQueue(queue->delayed_work_queue(), priority);
immediate_work_queue_sets_.AddQueue(queue->immediate_work_queue(), priority);
#if DCHECK_IS_ON()
DCHECK(CheckContainsQueueForTest(queue));
#endif
}
void TaskQueueSelector::ChangeSetIndex(TaskQueueImpl* queue,
TaskQueue::QueuePriority priority) {
#if DCHECK_IS_ON()
DCHECK(CheckContainsQueueForTest(queue));
#endif
delayed_work_queue_sets_.ChangeSetIndex(queue->delayed_work_queue(),
priority);
immediate_work_queue_sets_.ChangeSetIndex(queue->immediate_work_queue(),
priority);
#if DCHECK_IS_ON()
DCHECK(CheckContainsQueueForTest(queue));
#endif
}
void TaskQueueSelector::RemoveQueueImpl(TaskQueueImpl* queue) {
#if DCHECK_IS_ON()
DCHECK(CheckContainsQueueForTest(queue));
#endif
delayed_work_queue_sets_.RemoveQueue(queue->delayed_work_queue());
immediate_work_queue_sets_.RemoveQueue(queue->immediate_work_queue());
#if DCHECK_IS_ON()
DCHECK(!CheckContainsQueueForTest(queue));
#endif
}
int64_t TaskQueueSelector::GetSortKeyForPriority(
TaskQueue::QueuePriority priority) const {
switch (priority) {
case TaskQueue::kControlPriority:
return std::numeric_limits<int64_t>::min();
case TaskQueue::kBestEffortPriority:
return std::numeric_limits<int64_t>::max();
default:
if (anti_starvation_logic_for_priorities_disabled_)
return per_priority_starvation_tolerance_[priority];
return selection_count_ + per_priority_starvation_tolerance_[priority];
}
}
void TaskQueueSelector::WorkQueueSetBecameEmpty(size_t set_index) {
non_empty_set_counts_[set_index]--;
DCHECK_GE(non_empty_set_counts_[set_index], 0);
// There are no delayed or immediate tasks for |set_index| so remove from
// |active_priorities_|.
if (non_empty_set_counts_[set_index] == 0)
active_priorities_.erase(static_cast<TaskQueue::QueuePriority>(set_index));
}
void TaskQueueSelector::WorkQueueSetBecameNonEmpty(size_t set_index) {
non_empty_set_counts_[set_index]++;
DCHECK_LE(non_empty_set_counts_[set_index], kMaxNonEmptySetCount);
// There is now a delayed or an immediate task for |set_index|, so add to
// |active_priorities_|.
if (non_empty_set_counts_[set_index] == 1) {
const auto priority =
static_cast<TaskQueue::QueuePriority>(set_index);
active_priorities_.insert(GetSortKeyForPriority(priority), priority);
}
}
void TaskQueueSelector::CollectSkippedOverLowerPriorityTasks(
const WorkQueue* selected_work_queue,
std::vector<const Task*>* result) const {
delayed_work_queue_sets_.CollectSkippedOverLowerPriorityTasks(
selected_work_queue, result);
immediate_work_queue_sets_.CollectSkippedOverLowerPriorityTasks(
selected_work_queue, result);
}
#if DCHECK_IS_ON() || !defined(NDEBUG)
bool TaskQueueSelector::CheckContainsQueueForTest(
const TaskQueueImpl * queue) const {
bool contains_delayed_work_queue =
delayed_work_queue_sets_.ContainsWorkQueueForTest(
queue->delayed_work_queue());
bool contains_immediate_work_queue =
immediate_work_queue_sets_.ContainsWorkQueueForTest(
queue->immediate_work_queue());
DCHECK_EQ(contains_delayed_work_queue, contains_immediate_work_queue);
return contains_delayed_work_queue;
}
#endif
WorkQueue* TaskQueueSelector::SelectWorkQueueToService() {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
if (active_priorities_.empty())
return nullptr;
// Select the priority from which we will select a task. Usually this is
// the highest priority for which we have work, unless we are starving a lower
// priority.
const auto priority = active_priorities_.min_id();
bool chose_delayed_over_immediate;
// Control tasks are allowed to indefinitely stave out other work and any
// control tasks we run should not be counted for task starvation purposes.
if (priority != TaskQueue::kControlPriority)
selection_count_++;
WorkQueue* queue =
#if DCHECK_IS_ON()
random_task_selection_ ? ChooseWithPriority<SetOperationRandom>(
priority, &chose_delayed_over_immediate)
:
#endif
ChooseWithPriority<SetOperationOldest>(
priority, &chose_delayed_over_immediate);
// If we still have any tasks remaining for |set_index| then adjust it's
// sort key.
if (active_priorities_.IsInQueue(priority))
active_priorities_.ChangeMinKey(GetSortKeyForPriority(priority));
if (chose_delayed_over_immediate) {
immediate_starvation_count_++;
} else {
immediate_starvation_count_ = 0;
}
return queue;
}
void TaskQueueSelector::AsValueInto(trace_event::TracedValue* state) const {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
state->SetInteger("immediate_starvation_count", immediate_starvation_count_);
}
void TaskQueueSelector::SetTaskQueueSelectorObserver(Observer* observer) {
task_queue_selector_observer_ = observer;
}
std::optional<TaskQueue::QueuePriority>
TaskQueueSelector::GetHighestPendingPriority() const {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
if (active_priorities_.empty())
return std::nullopt;
return active_priorities_.min_id();
}
void TaskQueueSelector::SetImmediateStarvationCountForTest(
size_t immediate_starvation_count) {
immediate_starvation_count_ = immediate_starvation_count;
}
bool TaskQueueSelector::HasTasksWithPriority(
TaskQueue::QueuePriority priority) {
return !delayed_work_queue_sets_.IsSetEmpty(priority) ||
!immediate_work_queue_sets_.IsSetEmpty(priority);
}
TaskQueueSelector::SmallPriorityQueue::SmallPriorityQueue() {
for (size_t i = 0; i < TaskQueue::kQueuePriorityCount; i++) {
id_to_index_[i] = kInvalidIndex;
}
}
void TaskQueueSelector::SmallPriorityQueue::insert(
int64_t key,
TaskQueue::QueuePriority id) {
DCHECK_LE(size_, TaskQueue::kQueuePriorityCount);
DCHECK_LT(id, TaskQueue::kQueuePriorityCount);
DCHECK(!IsInQueue(id));
// Insert while keeping |keys_| sorted.
auto i = size_;
while (i > 0 && key < keys_[i - 1]) {
keys_[i] = keys_[i - 1];
auto moved_id = index_to_id_[i - 1];
index_to_id_[i] = moved_id;
id_to_index_[moved_id] = static_cast<uint8_t>(i);
i--;
}
keys_[i] = key;
index_to_id_[i] = id;
id_to_index_[id] = static_cast<uint8_t>(i);
size_++;
}
void TaskQueueSelector::SmallPriorityQueue::erase(TaskQueue::QueuePriority id) {
DCHECK_NE(size_, 0u);
DCHECK_LT(id, TaskQueue::kQueuePriorityCount);
DCHECK(IsInQueue(id));
// Erase while keeping |keys_| sorted.
size_--;
for (size_t i = id_to_index_[id]; i < size_; i++) {
keys_[i] = keys_[i + 1];
const auto moved_id = index_to_id_[i + 1];
index_to_id_[i] = moved_id;
id_to_index_[moved_id] = static_cast<uint8_t>(i);
}
id_to_index_[id] = kInvalidIndex;
}
void TaskQueueSelector::SmallPriorityQueue::ChangeMinKey(int64_t new_key) {
DCHECK_NE(size_, 0u);
const auto id = index_to_id_[0];
size_t i = 0;
while ((i + 1) < size_ && keys_[i + 1] < new_key) {
keys_[i] = keys_[i + 1];
const auto moved_id = index_to_id_[i + 1];
index_to_id_[i] = moved_id;
id_to_index_[moved_id] = static_cast<uint8_t>(i);
i++;
}
keys_[i] = new_key;
index_to_id_[i] = id;
id_to_index_[id] = static_cast<uint8_t>(i);
}
} // namespace base
| [
"[email protected]"
] | |
aa8dcb37ff5cfb58d8fc5582bff8ed3dcffa10fe | 43959ff8574c78b042d92081f9dec8e8c26d761f | /algo/상수.cpp | 1453072a4ebaf6875664cddc0331f56ba651e5d0 | [] | no_license | yunsangq/algo | 00579f827f724e9f9a267f3071f1762d32934116 | 01fecca52cc528c15dfaebe5fc4ba3d944b6333c | refs/heads/master | 2021-04-18T22:47:39.591786 | 2018-03-30T22:54:50 | 2018-03-30T22:54:50 | 126,771,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | cpp | #include <stdio.h>
int main() {
char s[10] = { 0 }, a[4] = { 0 }, b[4] = { 0 };
int _a = 0, _b = 0;
fgets(s, 10, stdin);
for (int i = 6; i >= 0; i--) {
if (i < 3) {
a[2 - i] = s[i];
}
else if (i > 3) {
b[6 - i] = s[i];
}
}
int mul = 100;
for (int i = 0; i < 3; i++) {
_a += (a[i]-'0') * mul;
_b += (b[i]-'0') * mul;
mul /= 10;
}
if (_a >= _b)
printf("%d\n", _a);
else
printf("%d\n", _b);
return 0;
} | [
"[email protected]"
] | |
043b80e060c942323a4ea4e27d7fb347e2b485d2 | cbb8caed772470637a6a8a576b3062239ce3a35d | /distribution/src/SliderJoint.cpp | 131d350d116281439106ef45ca1df714721ec4bc | [] | no_license | Exoamek/GaitSym2019 | 3c2e4950a572841187638668da4f9ac880b4331d | 9dc8c3086ca817f56bab530840c2a762e188261a | refs/heads/master | 2023-02-21T16:36:15.852242 | 2021-01-28T15:23:09 | 2021-01-28T15:23:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,781 | cpp | /*
* SliderJoint.cpp
* GaitSymODE
*
* Created by Bill Sellers on 25/05/2012.
* Copyright 2012 Bill Sellers. All rights reserved.
*
*/
#include "SliderJoint.h"
#include "Simulation.h"
#include "Body.h"
#include "ode/ode.h"
#include <iostream>
#include <cmath>
#include <sstream>
SliderJoint::SliderJoint(dWorldID worldID) : Joint()
{
setJointID(dJointCreateSlider(worldID, nullptr));
dJointSetData(JointID(), this);
dJointSetFeedback(JointID(), JointFeedback());
}
SliderJoint::~SliderJoint()
{
}
void SliderJoint::SetSliderAxis(double x, double y, double z)
{
dVector3 v;
v[0] = x; v[1] = y; v[2] = z;
dNormalize3(v);
dJointSetSliderAxis(JointID(), v[0], v[1], v[2]);
}
void SliderJoint::GetSliderAxis(dVector3 result)
{
dJointGetSliderAxis(JointID(), result);
}
double SliderJoint::GetSliderDistance()
{
return dJointGetSliderPosition(JointID()) + m_StartDistanceReference;
}
double SliderJoint::GetSliderDistanceRate()
{
return dJointGetSliderPositionRate(JointID());
}
void SliderJoint::SetStartDistanceReference(double startDistanceReference)
{
m_StartDistanceReference = startDistanceReference;
}
void SliderJoint::SetJointStops(double loStop, double hiStop)
{
if (loStop >= hiStop) throw(__LINE__);
// correct for m_StartDistanceReference
loStop -= m_StartDistanceReference;
hiStop -= m_StartDistanceReference;
// note there is safety feature that stops setting incompatible low and high
// stops which can cause difficulties. The safe option is to set them twice.
dJointSetSliderParam(JointID(), dParamLoStop, loStop);
dJointSetSliderParam(JointID(), dParamHiStop, hiStop);
dJointSetSliderParam(JointID(), dParamLoStop, loStop);
dJointSetSliderParam(JointID(), dParamHiStop, hiStop);
// we don't want bouncy stops
dJointSetSliderParam(JointID(), dParamBounce, 0);
}
void SliderJoint::SetStopCFM(double cfm)
{
dJointSetSliderParam (JointID(), dParamStopCFM, cfm);
}
void SliderJoint::SetStopERP(double erp)
{
dJointSetSliderParam (JointID(), dParamStopERP, erp);
}
void SliderJoint::SetStopSpringDamp(double springConstant, double dampingConstant, double integrationStep)
{
double ERP = integrationStep * springConstant/(integrationStep * springConstant + dampingConstant);
double CFM = 1/(integrationStep * springConstant + dampingConstant);
SetStopERP(ERP);
SetStopCFM(CFM);
}
void SliderJoint::SetStopSpringERP(double springConstant, double ERP, double integrationStep)
{
double CFM = ERP / (integrationStep * springConstant);
SetStopERP(ERP);
SetStopCFM(CFM);
}
void SliderJoint::SetStopBounce(double bounce)
{
dJointSetSliderParam (JointID(), dParamBounce, bounce);
}
void SliderJoint::Update()
{
}
std::string SliderJoint::dumpToString()
{
std::stringstream ss;
ss.precision(17);
ss.setf(std::ios::scientific);
if (firstDump())
{
setFirstDump(false);
ss << "Time\tXA\tYA\tZA\tDistance\tDistanceRate\tFX1\tFY1\tFZ1\tTX1\tTY1\tTZ1\tFX2\tFY2\tFZ2\tTX2\tTY2\tTZ2\n";
}
dVector3 a;
GetSliderAxis(a);
ss << simulation()->GetTime() << "\t" <<
a[0] << "\t" << a[1] << "\t" << a[2] << "\t" << GetSliderDistance() << "\t" << GetSliderDistanceRate() << "\t" <<
JointFeedback()->f1[0] << "\t" << JointFeedback()->f1[1] << "\t" << JointFeedback()->f1[2] << "\t" <<
JointFeedback()->t1[0] << "\t" << JointFeedback()->t1[1] << "\t" << JointFeedback()->t1[2] << "\t" <<
JointFeedback()->f2[0] << "\t" << JointFeedback()->f2[1] << "\t" << JointFeedback()->f2[2] << "\t" <<
JointFeedback()->t2[0] << "\t" << JointFeedback()->t2[1] << "\t" << JointFeedback()->t2[2] << "\t" <<
"\n";
return ss.str();
}
| [
"[email protected]"
] | |
d4deaf33912f2aa2f9a98a90b79be0ccd51c24fa | 2b4ce6a8d61cce6b2c063f6d5c2f6f8a6cbe23f9 | /include/Hawk/Math/Detail/Vector.hpp | 0c297ab9dd3bc9008dec6952302f7a7ba9896843 | [
"MIT"
] | permissive | MikhailGorobets/VolumeRender | ee82f70c2cb499638fefa50ef70c144d28dcbb40 | c85f23fe225d1e56e54910752be845b9d1e32860 | refs/heads/master | 2023-06-25T01:44:15.340185 | 2023-06-17T09:59:03 | 2023-06-17T10:49:12 | 189,657,415 | 48 | 17 | MIT | 2023-06-17T10:49:13 | 2019-05-31T20:55:59 | C++ | UTF-8 | C++ | false | false | 11,617 | hpp | /*
* MIT License
*
* Copyright(c) 2021 Mikhail Gorobets
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this softwareand 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 noticeand this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include <Hawk/Common/INumberArray.hpp>
namespace Hawk::Math::Detail {
template<typename T, U32 N>
class Vector final: public INumberArray<T, N> {
static_assert(std::is_same<T, F32>() || std::is_same<T, F64>() || std::is_same<T, I32>() || std::is_same<T, U32>(), "Invalid scalar type for Vector");
public:
constexpr Vector() noexcept = default;
constexpr Vector(T v) noexcept;
template <typename... Args> constexpr Vector(typename std::enable_if<sizeof...(Args) + 1 == N, T>::type const& head, Args... tail) noexcept;
private:
T m_Data[N];
};
template<typename T>
class Vector<T, 2> final: public INumberArray<T, 2> {
static_assert(std::is_same<T, F32>() || std::is_same<T, F64>() || std::is_same<T, I32>() || std::is_same<T, U32>(), "Invalid scalar type for Vector");
public:
union {
struct { T x, y; };
struct { T r, g; };
struct { T v[2]; };
};
public:
constexpr Vector() noexcept = default;
constexpr Vector(T v) noexcept;
template <typename... Args> constexpr Vector(typename std::enable_if<sizeof...(Args) + 1 == 2, T>::type const& head, Args... tail) noexcept;
};
template<typename T>
class Vector<T, 3> final: public INumberArray<T, 3> {
static_assert(std::is_same<T, F32>() || std::is_same<T, F64>() || std::is_same<T, I32>() || std::is_same<T, U32>(), "Invalid scalar type for Vector");
public:
union {
struct { T x, y, z; };
struct { T r, g, b; };
struct { T v[3]; };
};
public:
constexpr Vector() noexcept = default;
constexpr Vector(T v) noexcept;
constexpr Vector(Vector<T, 2> const& x, T y) noexcept;
template <typename... Args> constexpr Vector(typename std::enable_if<sizeof...(Args) + 1 == 3, T>::type const& head, Args... tail) noexcept;
};
template<typename T>
class Vector<T, 4> final: public INumberArray<T, 4> {
static_assert(std::is_same<T, F32>() || std::is_same<T, F64>() || std::is_same<T, I32>() || std::is_same<T, U32>() || std::is_same<T, I16>() || std::is_same<T, U16>() || std::is_same<T, U8>(), "Invalid scalar type for Vector");
public:
union {
struct { T x, y, z, w; };
struct { T r, g, b, a; };
struct { T v[4]; };
};
public:
constexpr Vector() noexcept = default;
constexpr Vector(T v) noexcept;
constexpr Vector(Vector<T, 3> const& x, T y) noexcept;
constexpr Vector(Vector<T, 2> const& x, T y, T z) noexcept;
template <typename... Args> constexpr Vector(typename std::enable_if<sizeof...(Args) + 1 == 4, T>::type const& head, Args... tail) noexcept;
};
template<typename T, U32 N> constexpr auto operator==(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept->bool;
template<typename T, U32 N> constexpr auto operator!=(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept->bool;
template<typename T, U32 N> constexpr auto operator+(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>;
template<typename T, U32 N> constexpr auto operator-(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>;
template<typename T, U32 N> constexpr auto operator*(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>;
template<typename T, U32 N> constexpr auto operator/(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>;
template<typename T, U32 N> constexpr auto operator-(Vector<T, N> const& rhs) noexcept->Vector<T, N>;
template<typename T, U32 N> constexpr auto operator*(Vector<T, N> const& lhs, T rhs) noexcept->Vector<T, N>;
template<typename T, U32 N> constexpr auto operator*(T lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>;
template<typename T, U32 N> constexpr auto operator/(Vector<T, N> const& lhs, T rhs) noexcept->Vector<T, N>;
template<typename T, U32 N> constexpr auto operator+=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>&;
template<typename T, U32 N> constexpr auto operator-=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>&;
template<typename T, U32 N> constexpr auto operator*=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>&;
template<typename T, U32 N> constexpr auto operator/=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept->Vector<T, N>&;
template<typename T, U32 N> constexpr auto operator*=(Vector<T, N>& lhs, T rhs) noexcept->Vector<T, N>&;
template<typename T, U32 N> constexpr auto operator/=(Vector<T, N>& lhs, T rhs) noexcept->Vector<T, N>&;
}
namespace Hawk::Math::Detail {
template<typename T, U32 N>
template<typename ...Args>
ILINE constexpr Vector<T, N>::Vector(typename std::enable_if<sizeof...(Args) + 1 == N, T>::type const& head, Args ...tail) noexcept : m_Data{head, T{ tail }...} {}
template<typename T, U32 N>
ILINE constexpr Vector<T, N>::Vector(T v) noexcept {
for (auto& e : *this) e = v;
}
template<typename T>
ILINE constexpr Vector<T, 2>::Vector(T v) noexcept : x{v}, y{v} {}
template<typename T>
ILINE constexpr Vector<T, 3>::Vector(T v) noexcept : x{v}, y{v}, z{v} {}
template<typename T>
ILINE constexpr Vector<T, 3>::Vector(Vector<T, 2> const& x, T y) noexcept : x{x.x}, y{x.y}, z{y} {}
template<typename T>
ILINE constexpr Vector<T, 4>::Vector(Vector<T, 3> const& x, T y) noexcept : x{x.x}, y{x.y}, z{x.z}, w{y} {}
template<typename T>
ILINE constexpr Vector<T, 4>::Vector(Vector<T, 2> const& x, T y, T z) noexcept : x{x.x}, y{x.y}, z{y}, w{z} {}
template<typename T>
ILINE constexpr Vector<T, 4>::Vector(T v) noexcept : x{v}, y{v}, z{v}, w{v} {}
template<typename T>
template<typename ...Args>
ILINE constexpr Vector<T, 2>::Vector(typename std::enable_if<sizeof...(Args) + 1 == 2, T>::type const& head, Args ...tail) noexcept : v{head, T{ tail }...} {}
template<typename T>
template<typename ...Args>
ILINE constexpr Vector<T, 3>::Vector(typename std::enable_if<sizeof...(Args) + 1 == 3, T>::type const& head, Args ...tail) noexcept : v{head, T{ tail }...} {}
template<typename T>
template<typename ...Args>
ILINE constexpr Vector<T, 4>::Vector(typename std::enable_if<sizeof...(Args) + 1 == 4, T>::type const& head, Args ...tail) noexcept : v{head, T{ tail }...} {}
template<typename T, U32 N>
[[nodiscard]] ILINE constexpr auto operator==(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept -> bool {
for (auto index = 0u; index < N; index++)
if (!(std::abs(lhs[index] - rhs[index]) <= std::numeric_limits<T>::epsilon()))
return false;
return true;
}
template<typename T, U32 N>
[[nodiscard]] ILINE constexpr auto operator!=(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept -> bool {
return !(lhs == rhs);
}
template<typename T, U32 N>
[[nodiscard]] ILINE constexpr auto operator+(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept-> Vector<T, N> {
auto result = Vector<T, N>{};
for (auto index = 0u; index < N; index++)
result[index] = lhs[index] + rhs[index];
return result;
}
template<typename T, U32 N>
[[nodiscard]] ILINE constexpr auto operator*(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept -> Vector<T, N> {
auto result = Vector<T, N>{};
for (auto index = 0; index < N; index++)
result[index] = lhs[index] * rhs[index];
return result;
}
template<typename T, U32 N>
[[nodiscard]] ILINE constexpr auto operator/(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept -> Vector<T, N> {
auto result = Vector<T, N>{};
for (auto index = 0; index < N; index++)
result[index] = lhs[index] / rhs[index];
return result;
}
template<typename T, U32 N>
[[nodiscard]] ILINE constexpr auto operator-(Vector<T, N> const& lhs, Vector<T, N> const& rhs) noexcept-> Vector<T, N> {
auto result = Vector<T, N>{};
for (auto index = 0u; index < N; index++)
result[index] = lhs[index] - rhs[index];
return result;
}
template<typename T, U32 N>
[[nodiscard]] ILINE constexpr auto operator-(Vector<T, N> const& rhs) noexcept -> Vector<T, N> {
auto result = Vector<T, N>{};
for (auto index = 0u; index < N; index++)
result[index] = -rhs[index];
return result;
}
template<typename T, U32 N>
[[nodiscard]] ILINE constexpr auto operator*(T lhs, Vector<T, N> const& rhs) noexcept-> Vector<T, N> {
auto result = Vector<T, N>{};
for (auto index = 0; index < N; index++)
result[index] = lhs * rhs[index];
return result;
}
template<typename T, U32 N>
[[nodiscard]] ILINE constexpr auto operator*(Vector<T, N> const& lhs, T rhs) noexcept-> Vector<T, N> {
return rhs * lhs;
}
template<typename T, U32 N>
[[nodiscard]] ILINE constexpr auto operator/(Vector<T, N> const& lhs, T rhs) noexcept -> Vector<T, N> {
return (T{1} / rhs) * lhs;
}
template<typename T, U32 N>
ILINE constexpr auto operator+=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept -> Vector<T, N>& {
lhs = lhs + rhs;
return lhs;
}
template<typename T, U32 N>
ILINE constexpr auto operator-=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept -> Vector<T, N>& {
lhs = lhs - rhs;
return lhs;
}
template<typename T, U32 N>
ILINE constexpr auto operator*=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept -> Vector<T, N>& {
lhs = lhs * rhs;
return lhs;
}
template<typename T, U32 N>
ILINE constexpr auto operator/=(Vector<T, N>& lhs, Vector<T, N> const& rhs) noexcept -> Vector<T, N>& {
lhs = lhs / rhs;
return lhs;
}
template<typename T, U32 N>
ILINE constexpr auto operator*=(Vector<T, N>& lhs, T rhs) noexcept -> Vector<T, N>& {
lhs = lhs * rhs;
return lhs;
}
template<typename T, U32 N>
ILINE constexpr auto operator/=(Vector<T, N>& lhs, T rhs) noexcept -> Vector<T, N>& {
lhs = lhs / rhs;
return lhs;
}
} | [
"[email protected]"
] | |
e51a9273650d20294496d17c8147533b97d84669 | c9d6cb1013c82eade42d7cdee1db78afec957c20 | /Sources/N-body/NBodyComputePrefs.h | 9094cf9488e3dadd0ca0a27aab498031b29d77ec | [] | no_license | ooper-shlab/MetalNBody-Swift | 0422add7d94b5f3cf2d1bc9abc57c5f5525ec886 | 621436876e1cffe675bfe0950ecb381408cb75bd | refs/heads/master | 2021-01-10T05:57:56.526638 | 2019-04-20T07:41:05 | 2019-04-20T07:41:05 | 48,329,901 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 618 | h | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
N-Body compute preferences common structure for the kernel and the utility class.
*/
#ifndef _NBODY_COMPUTE_PREFS_H_
#define _NBODY_COMPUTE_PREFS_H_
#ifdef __cplusplus
namespace NBody
{
namespace Compute
{
struct Prefs
{
float timestep;
float damping;
float softeningSqr;
unsigned int particles;
}; // Prefs
typedef Prefs Prefs;
} // Compute
} // NBody
#endif
#endif
| [
"[email protected]"
] | |
d72ee8c88a960c8c66e0d5edd680740dcb1651a8 | 2444e0dab75bedfb04fe630eb144e25350726d2a | /examples/SendMeasurement/SendMeasurement.ino | a1861f8b552cae1225d40516c91b046dfb37fd1c | [] | no_license | elpinjo/CumulocityClient | 5ccd3d50168d8e1f4a05124f0e148e24cf525972 | ae91ac49df1bb0def2042d60087e50f3d63eb57f | refs/heads/master | 2021-05-21T14:45:03.773960 | 2020-12-10T08:12:00 | 2020-12-10T08:12:00 | 252,685,057 | 4 | 4 | null | 2020-12-10T08:12:01 | 2020-04-03T09:15:24 | C++ | UTF-8 | C++ | false | false | 1,253 | ino | #include <CumulocityClient.h>
#ifdef ESP8266
#include <ESP8266WiFi.h>
#else //ESP32
#include <WiFi.h>
#endif
const char* ssid = "........";
const char* wifiPassword = "........";
char* host = "xxx.cumulocity.com";
char* username = "........"; // fixed credentials can be registered in the Administration section
char* c8yPassword = "........"; // create a user in usermanagement with the "device"role and fill the credentials here
char* tenant = "........"; //tenant ID can be found by clicking on your name in the top right corner of Cumulocity
char* clientId = "........."; //Should be a unique identifier for this device, e.g. IMEI, MAC address or SerialNumber
//uint64_t chipid = ESP.getEfuseMac();
WiFiClient wifiClient;
CumulocityClient c8yClient(wifiClient, clientId);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, wifiPassword);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("connected to wifi");
c8yClient.connect(host, tenant, username, c8yPassword);
c8yClient.registerDevice(clientId, "c8y_esp32");
}
void loop() {
delay(1000);
c8yClient.loop();
c8yClient.createMeasurement("Temperature", "T", "20.5", "*C");
}
| [
"[email protected]"
] | |
e7c92fe4cb3bd85b39b4193bd66879146016a9c6 | b273d8bc40df9e559d637102c4c2c646144c31ff | /src/String.h | 966d968e2ce8552cc47c3ba23cbf3a203e576859 | [] | no_license | chengfei1995121/ministl | b29f9de01513077718b666442f60dafbdeb17159 | 05261017d85dcd8897a132b186cb1b4f824fcff5 | refs/heads/master | 2021-05-12T18:53:25.671942 | 2018-01-17T09:31:30 | 2018-01-17T09:31:30 | 117,078,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,549 | h | #ifndef MINISTL_STRING_H
#define MINISTL_STRING_H
#include<memory>
#include<iostream>
using namespace std;
class String{
public:
typedef char value_type;
typedef char* iterator;
typedef const char* const_iterator;
typedef size_t size_type;
typedef char* pointer;
typedef char& reference;
friend ostream &operator<<(ostream &os,const String &s);
friend bool operator==(const String &s1,const String &s2);
friend bool operator<(const String &s1,const String &s2);
friend bool operator<=(const String &s1,const String &s2);
friend bool operator>(const String &s1,const String &s2);
friend bool operator>=(const String &s1,const String &s2);
friend bool operator!=(const String &s1,const String &s2);
friend String operator+(const String &s1,const String &s2);
friend String operator+(const String &s1,const char *c);
friend String operator+(const char *c,const String &s1);
String():sstart(nullptr),send(nullptr),scap(nullptr){}
String(const String &s1,size_t pos,size_t len=npos);
String(const char *c);
String(size_t n,char c);
String(const String &);
String(char *,size_t);
String& operator=(const String &);
size_t size() const;
iterator begin() const;
const_iterator cbegin() const noexcept;
const_iterator cend() const noexcept;
iterator end() const;
void free();
char &operator[](size_t n);
bool empty()const;
size_t capacity()const;
char at(size_t n);
String &operator+=(const String &);
String &operator+=(const char *);
String &operator+=(const char);
void check_size();
void push_back(char c);
String &replace(size_t pos,size_t len,const String &);
String &insert(size_t pos,const String&);
String &insert(size_t pos,const char *);
String &insert(size_t pos,size_t n,const char);
void clear();
String &erase(size_t pos=0,size_t len=npos);
size_t copy(char *,size_t len,size_t pos=0) const;
const char *data() const noexcept;
size_t find(char c,size_t pos=0) const;
size_t find(const String &,size_t pos=0)const;
size_t find(const char *,size_t pos=0) const;
char &back();
const char &back()const;
char &front();
const char &front() const;
String substr(size_t pos=0,size_t len=npos) const;
void swap(String &);
void swap(char *&,char *&);
~String(){
free();
}
private:
static const size_t npos=-1;
static allocator<char> alloc;
void reallocate();
char *sstart;
char *send;
char *scap;
};
//allocator<char> String::alloc;
#endif
| [
"[email protected]"
] | |
ab645fd0267761ac318a9360b7c0d3793d29bb97 | 43452fbcbe43bda467cd24e5f161c93535bc2bd5 | /src/geomega/src/MDGeometry.cxx | 4cd0c789ea1065005e4657dee8d22336cebff63e | [] | no_license | xtsinghua/megalib | cae2e256ad5ddf9d7b6cdb9d2b680a76dd902e4f | 0bd5c161c606c32a642efb34a963b6e2c07b81a0 | refs/heads/master | 2021-01-11T05:46:51.442857 | 2015-04-15T17:56:22 | 2015-04-15T17:56:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 218,124 | cxx | /*
* MDGeometry.cxx
*
*
* Copyright (C) by Andreas Zoglauer.
* All rights reserved.
*
*
* This code implementation is the intellectual property of
* Andreas Zoglauer.
*
* By copying, distributing or modifying the Program (or any work
* based on the Program) you indicate your acceptance of this statement,
* and all its terms.
*
*/
////////////////////////////////////////////////////////////////////////////////
//
// MDGeometry
//
////////////////////////////////////////////////////////////////////////////////
// Include the header:
#include "MDGeometry.h"
// Standard libs:
#include <iostream>
#include <fstream>
#include <limits>
#include <sstream>
#include <iomanip>
#include <cctype>
#include <cmath>
using namespace std;
// ROOT libs:
#include <TNode.h>
#include <TGeometry.h>
#include <TCanvas.h>
#include <TView.h>
#include <TROOT.h>
#include <TSystem.h>
#include <TObjString.h>
#include <TMath.h>
#include <TGeoOverlap.h>
#include <TObjArray.h>
// MEGAlib libs:
#include "MGlobal.h"
#include "MAssert.h"
#include "MStreams.h"
#include "MFile.h"
#include "MTokenizer.h"
#include "MDShape.h"
#include "MDShapeBRIK.h"
#include "MDShapeTRD1.h"
#include "MDShapeTRD2.h"
#include "MDShapeSPHE.h"
#include "MDShapeTUBS.h"
#include "MDShapeCONE.h"
#include "MDShapeCONS.h"
#include "MDShapeTRAP.h"
#include "MDShapeGTRA.h"
#include "MDShapePCON.h"
#include "MDShapePGON.h"
#include "MDShapeSubtraction.h"
#include "MDShapeUnion.h"
#include "MDShapeIntersection.h"
#include "MDCalorimeter.h"
#include "MDStrip2D.h"
#include "MDStrip3D.h"
#include "MDStrip3DDirectional.h"
#include "MDACS.h"
#include "MDDriftChamber.h"
#include "MDAngerCamera.h"
#include "MDVoxel3D.h"
#include "MDSystem.h"
#include "MTimer.h"
#include "MString.h"
////////////////////////////////////////////////////////////////////////////////
#ifdef ___CINT___
ClassImp(MDGeometry)
#endif
////////////////////////////////////////////////////////////////////////////////
MDGeometry::MDGeometry()
{
// default constructor
m_GeometryScanned = false;
m_WorldVolume = 0;
m_StartVolume = "";
m_ShowVolumes = true;
m_DefaultColor = -1;
m_IgnoreShortNames = false;
m_DoSanityChecks = true;
m_ComplexER = true;
m_NodeList = new TObjArray();
m_IncludeList = new TObjArray();
m_Name = "\"Geometry, which was not worth a name...\"" ;
m_Version = "0.0.0.0";
m_SphereRadius = DBL_MAX;
m_SpherePosition = MVector(DBL_MAX, DBL_MAX, DBL_MAX);
m_DistanceToSphereCenter = DBL_MAX;
m_GeoView = 0;
m_Geometry = 0;
m_LastVolumes.clear();
m_LastVolumePosition = 0;
m_TriggerUnit = new MDTriggerUnit(this);
m_System = new MDSystem("NoName");
// Make sure we ignore the default ROOT geometry...
// BUG: In case we are multi-threaded and some one interact with the geometry
// before the gGeoManager is reset during new, we will get a seg-fault!
gGeoManager = 0;
// ... before
m_Geometry = new TGeoManager("Geomega geometry", "Geomega");
}
////////////////////////////////////////////////////////////////////////////////
MDGeometry::~MDGeometry()
{
// default destructor
Reset();
delete m_TriggerUnit;
delete m_System;
}
////////////////////////////////////////////////////////////////////////////////
void MDGeometry::Reset()
{
// Reset this class to default values
for (unsigned int i = 0; i < m_VolumeList.size(); ++i) {
delete m_VolumeList[i];
}
m_VolumeList.clear();
for (unsigned int i = 0; i < m_MaterialList.size(); ++i) {
delete m_MaterialList[i];
}
m_MaterialList.clear();
for (unsigned int i = 0; i < m_DetectorList.size(); ++i) {
delete m_DetectorList[i];
}
m_DetectorList.clear();
m_NDetectorTypes.clear();
m_NDetectorTypes.resize(MDDetector::c_MaxDetector+1);
for (unsigned int i = 0; i < m_TriggerList.size(); ++i) {
delete m_TriggerList[i];
}
m_TriggerList.clear();
for (unsigned int i = 0; i < m_ShapeList.size(); ++i) {
delete m_ShapeList[i];
}
m_ShapeList.clear();
for (unsigned int i = 0; i < m_OrientationList.size(); ++i) {
delete m_OrientationList[i];
}
m_OrientationList.clear();
for (unsigned int i = 0; i < m_VectorList.size(); ++i) {
delete m_VectorList[i];
}
m_VectorList.clear();
m_ConstantList.clear();
m_ConstantMap.clear();
m_WorldVolume = 0;
// m_StartVolume = ""; // This is a start option of geomega, so do not reset!
m_IncludeList->Delete();
m_NodeList->Delete();
if (m_GeoView != 0) {
if (gROOT->FindObject("MainCanvasGeomega") != 0) {
delete m_GeoView;
}
m_GeoView = 0;
}
// Create a new geometry
// BUG: In case we are multi-threaded and some one interact with the geometry
// before the gGeoManager is reset during new, we will get a seg-fault!
gGeoManager = 0;
delete m_Geometry;
m_Geometry = new TGeoManager("Give it a good name", "MissingName");
delete m_System;
m_System = new MDSystem("NoName");
m_IgnoreShortNames = false;
m_DoSanityChecks = true;
m_ComplexER = true;
m_VirtualizeNonDetectorVolumes = false;
m_LastVolumes.clear();
m_LastVolumePosition = 0;
m_DetectorSearchTolerance = 0.000001;
m_CrossSectionFileDirectory = g_MEGAlibPath + "/resource/geometries/materials";
MDVolume::ResetIDs();
MDDetector::ResetIDs();
MDMaterial::ResetIDs();
m_GeometryScanned = false;
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::IsScanned()
{
// Return true if the geometry setup-file has been scanned/read successfully
return m_GeometryScanned;
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::ScanSetupFile(MString FileName, bool CreateNodes, bool VirtualizeNonDetectorVolumes, bool AllowCrossSectionCreation)
{
// Scan the setup-file and create the geometry
//if (IsScanned() == false) {
// mout<<"Loading geometry file: "<<FileName<<endl;
//}
int Stage = 1;
MTimer Timer;
double TimeLimit = 10;
bool FoundDepreciated = false;
// First clean the geometry ...
Reset();
// Save if we want to virtualize non detector volumes for speed increase:
// If the file contains such a statement, this one is overwritten
m_VirtualizeNonDetectorVolumes = VirtualizeNonDetectorVolumes;
// If the is set the visibility of everything but the sensitive volume to zero
bool ShowOnlySensitiveVolumes = false;
m_FileName = FileName;
if (m_FileName == "") {
mout<<" *** Error: No geometry file name given"<<endl;
return false;
}
MFile::ExpandFileName(m_FileName);
if (gSystem->IsAbsoluteFileName(m_FileName) == false) {
m_FileName = gSystem->WorkingDirectory() + MString("/") + m_FileName;
}
if (gSystem->AccessPathName(m_FileName) == 1) {
mgui<<"Geometry file \""<<m_FileName<<"\" does not exist. Aborting."<<error;
return false;
}
m_CrossSectionFileDirectory = MFile::GetDirectoryName(m_FileName);
m_CrossSectionFileDirectory += "/auxiliary";
mdebug<<"Started scanning of geometry... This may take a while..."<<endl;
MDMaterial* M = 0;
MDMaterial* MCopy = 0;
MDVolume* V = 0;
MDVolume* VCopy = 0;
MDDetector* D = 0;
MDTrigger* T = 0;
MDSystem* S = 0;
MDVector* Vector = 0;
MDShape* Shape = 0;
MDOrientation* Orientation = 0;
// For scaling some volumes:
map<MDVolume*, double> ScaledVolumes;
// Since the geometry-file can include other geometry files,
// we have to store the whole file in memory
vector<MDDebugInfo> FileContent;
if (AddFile(m_FileName, FileContent) == false) {
mout<<" *** Error reading included files. Aborting!"<<endl;
return false;
}
// Now scan the data and search for "Include" files and add them
// to the original stored file content
MTokenizer Tokenizer;
for (unsigned int i = 0; i < FileContent.size(); i++) {
m_DebugInfo = FileContent[i];
if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) {
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() == 0) continue;
if (Tokenizer.IsTokenAt(0, "Include") == true) {
// Test for old material path
if (Tokenizer.GetTokenAt(1).EndsWith("resource/geometries/materials/Materials.geo") == true) {
mout<<" *** Deprectiated *** "<<endl;
mout<<"You are using the old MEGAlib material path:"<<endl;
mout<<m_DebugInfo.GetText()<<endl;
mout<<"Please update to the new path now!"<<endl;
mout<<"Change: resource/geometries To: resource/examples/geomega "<<endl;
mout<<endl;
FoundDepreciated = true;
}
MString FileName = Tokenizer.GetTokenAt(1);
MFile::ExpandFileName(FileName, m_FileName);
if (MFile::Exists(FileName) == false) {
mout<<" *** Error finding file "<<FileName<<endl;
Typo("File IO error");
return false;
}
vector<MDDebugInfo> AddFileContent;
if (AddFile(FileName, AddFileContent) == false) {
mout<<" *** Error reading file "<<FileName<<endl;
Typo("File IO error");
return false;
}
for (unsigned int j = 0; j < AddFileContent.size(); ++j) {
//FileContent.push_back(AddFileContent[j]);
FileContent.insert(FileContent.begin() + (i+1) + j, AddFileContent[j]);
}
}
}
if (FileContent.size() == 0) {
mgui<<"File is \""<<m_FileName<<"\" empty or binary!"<<error;
return false;
}
++Stage;
if (Timer.ElapsedTime() > TimeLimit) {
mout<<"Stage "<<Stage<<" (reading of file(s)) finished after "<<Timer.ElapsedTime()<<" sec"<<endl;
}
// Find lines which are continued in a second line by the "\\" keyword
for (unsigned int i = 0; i < FileContent.size(); i++) {
m_DebugInfo = FileContent[i];
if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) {
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() == 0) continue;
// Of course the real token is "\\"
if (Tokenizer.IsTokenAt(Tokenizer.GetNTokens()-1, "\\\\") == true) {
//cout<<"Found \\\\: "<<Tokenizer.ToString()<<endl;
// Prepend this text to the next line
if (FileContent.size() > i+1) {
//cout<<"Next: "<<FileContent[i+1].GetText()<<endl;
MString Prepend = "";
for (unsigned int t = 0; t < Tokenizer.GetNTokens()-1; ++t) {
Prepend += Tokenizer.GetTokenAt(t);
Prepend += " ";
}
FileContent[i+1].Prepend(Prepend);
FileContent[i].SetText("");
//cout<<"Prepended: "<< FileContent[i+1].GetText()<<endl;
}
}
}
// Find constants
//
for (unsigned int i = 0; i < FileContent.size(); i++) {
m_DebugInfo = FileContent[i];
if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) {
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() == 0) continue;
// Constants
if (Tokenizer.IsTokenAt(0, "Constant") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain three entries, e.g. \"Constant Distance 10.5\"");
return false;
}
map<MString, MString>::iterator Iter = m_ConstantMap.find(Tokenizer.GetTokenAt(1));
if (Iter != m_ConstantMap.end()) {
if (m_ConstantMap[Tokenizer.GetTokenAt(1)] != Tokenizer.GetTokenAt(2)) {
Typo("Constant has already been defined and both are not identical!");
return false;
}
}
m_ConstantMap[Tokenizer.GetTokenAt(1)] = Tokenizer.GetTokenAt(2);
m_ConstantList.push_back(Tokenizer.GetTokenAt(1));
}
}
// Take care of maths and constants containing constants, containing constants...
bool ConstantChanged = true;
while (ConstantChanged == true) {
// Step 1: Solve maths:
for (map<MString, MString>::iterator Iter1 = m_ConstantMap.begin();
Iter1 != m_ConstantMap.end();
++Iter1) {
if (MTokenizer::IsMaths((*Iter1).second) == true) {
bool ContainsConstant = false;
for (map<MString, MString>::iterator Iter2 = m_ConstantMap.begin();
Iter2 != m_ConstantMap.end();
++Iter2) {
if (ContainsReplacableConstant((*Iter1).second, (*Iter2).first) == true) {
ContainsConstant = true;
//cout<<"Replaceable constant: "<<(*Iter1).second<<" (namely:"<<(*Iter2).first<<")"<<endl;
break;
} else {
//cout<<"No replaceable constant: "<<(*Iter1).second<<" (test:"<<(*Iter2).first<<")"<<endl;
}
}
if (ContainsConstant == false) {
MString Constant = (*Iter1).second;
MTokenizer::EvaluateMaths(Constant);
(*Iter1).second = Constant;
}
}
}
// Step 2: Replace constants in constants
bool ConstantChangableWithMath = false;
ConstantChanged = false;
for (map<MString, MString>::iterator Iter1 = m_ConstantMap.begin();
Iter1 != m_ConstantMap.end();
++Iter1) {
//cout<<(*Iter1).first<<" - "<<(*Iter1).second<<" Pos: "<<i++<<" of "<<m_ConstantMap.size()<<endl;
for (map<MString, MString>::iterator Iter2 = m_ConstantMap.begin();
Iter2 != m_ConstantMap.end();
++Iter2) {
//cout<<"Map size: "<<m_ConstantMap.size()<<endl;
if (ContainsReplacableConstant((*Iter1).second, (*Iter2).first) == true) {
//cout<<" ---> "<<(*Iter2).first<<" - "<<(*Iter2).second<<endl;
//cout<<(*Iter1).second<<" contains "<<(*Iter2).first<<endl;
if (MTokenizer::IsMaths((*Iter2).second) == false) {
MString Constant = (*Iter1).second;
ReplaceWholeWords(Constant, (*Iter2).first, (*Iter2).second);
(*Iter1).second = Constant;
ConstantChanged = true;
} else {
ConstantChangableWithMath = true;
}
}
}
}
if (ConstantChanged == false && ConstantChangableWithMath == true) {
mout<<" *** Error ***"<<endl;
mout<<"Recursively defined constant found!"<<endl;
return false;
}
}
// Do the final replace:
for (unsigned int i = 0; i < FileContent.size(); i++) {
m_DebugInfo = FileContent[i];
if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) { // No maths since we are not yet ready for it...
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() == 0) continue;
MString Init = Tokenizer.GetTokenAt(0);
if (Init == "Volume" ||
Init == "Material" ||
Init == "Trigger" ||
Init == "System" ||
Init == "Strip2D" ||
Init == "MDStrip2D" ||
Init == "Strip3D" ||
Init == "MDStrip3D" ||
Init == "Strip3DDirectional" ||
Init == "MDStrip3DDirectional" ||
Init == "DriftChamber" ||
Init == "MDDriftChamber" ||
Init == "AngerCamera" ||
Init == "MDAngerCamera" ||
Init == "Simple" ||
Init == "Scintillator" ||
Init == "ACS" ||
Init == "MDACS" ||
Init == "Calorimeter" ||
Init == "MDCalorimeter" ||
Init == "Voxel3D" ||
Init == "MDVoxel3D") {
continue;
}
for (map<MString, MString>::iterator Iter = m_ConstantMap.begin();
Iter != m_ConstantMap.end(); ++Iter) {
FileContent[i].Replace((*Iter).first, (*Iter).second, true);
}
}
++Stage;
if (Timer.ElapsedTime() > TimeLimit) {
mout<<"Stage "<<Stage<<" (analyzing constant) finished after "<<Timer.ElapsedTime()<<" sec"<<endl;
}
// Check for Vectors FIRST since those are used in ForVector loops...
for (unsigned int i = 0; i < FileContent.size(); i++) {
m_DebugInfo = FileContent[i];
if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) { // No maths since we are not yet ready for it...
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() == 0) continue;
if (Tokenizer.IsTokenAt(0, "Vector") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"Vector MyMatrix\"");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(1)) == false) {
return false;
}
if (NameExists(Tokenizer.GetTokenAt(1)) == true) {
return false;
}
}
AddVector(new MDVector(Tokenizer.GetTokenAt(1)));
continue;
}
}
for (unsigned int i = 0; i < FileContent.size(); i++) {
m_DebugInfo = FileContent[i];
if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) { // No maths since we are not yet ready for it...
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() == 0) continue;
if ((Vector = GetVector(Tokenizer.GetTokenAt(0))) != 0) {
Tokenizer.Analyse(m_DebugInfo.GetText()); // let's do some maths...
if (Tokenizer.IsTokenAt(1, "Matrix") == true) {
// We need at least 9 keywords:
if (Tokenizer.GetNTokens() < 9) {
Typo("Vector.Matrix must contain at least nine keywords,"
" e.g. \"MaskMatrix.Matrix 3 1.0 3 1.0 1 0.0 1 0 1 0 1 0 1 0 1\"");
return false;
}
unsigned int x_max = Tokenizer.GetTokenAtAsUnsignedInt(2);
unsigned int y_max = Tokenizer.GetTokenAtAsUnsignedInt(4);
unsigned int z_max = Tokenizer.GetTokenAtAsUnsignedInt(6);
double dx = Tokenizer.GetTokenAtAsDouble(3);
double dy = Tokenizer.GetTokenAtAsDouble(5);
double dz = Tokenizer.GetTokenAtAsDouble(7);
// Now we know the real number of keywords:
if (Tokenizer.GetNTokens() != 8+x_max*y_max*z_max) {
Typo("This version of Vector.Matrix does not contain the right amount of numbers\"");
return false;
}
for (unsigned int z = 0; z < z_max; ++z) {
for (unsigned int y = 0; y < y_max; ++y) {
for (unsigned int x = 0; x < x_max; ++x) {
Vector->Add(MVector(x*dx, y*dy, z*dz), Tokenizer.GetTokenAtAsDouble(8 + x + y*x_max + z*x_max*y_max));
}
}
}
} else {
Typo("Unrecognized vector option");
return false;
}
}
}
++Stage;
if (Timer.ElapsedTime() > TimeLimit) {
mout<<"Stage "<<Stage<<" (evaluating vectors) finished after "<<Timer.ElapsedTime()<<" sec"<<endl;
}
// Check for "For"-loops as well as the special "ForVector"-loop
int ForDepth = 0;
int CurrentDepth = 0;
vector<MDDebugInfo>::iterator Iter;
for (Iter = FileContent.begin();
Iter != FileContent.end();
/* ++Iter erase */) {
m_DebugInfo = (*Iter);
if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) {
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() == 0) {
++Iter;
continue;
}
if (Tokenizer.IsTokenAt(0, "For") == true) {
Tokenizer.Analyse(m_DebugInfo.GetText(), true); // redo for math's evaluation just here
CurrentDepth = ForDepth;
ForDepth++;
if (Tokenizer.GetNTokens() != 5) {
Typo("Line must contain five entries, e.g. \"For I 3 -11.0 11.0\"");
return false;
}
MString Index = Tokenizer.GetTokenAt(1);
if (Tokenizer.GetTokenAtAsDouble(2) <= 0 || std::isnan(Tokenizer.GetTokenAtAsDouble(2))) { // std:: is required
mout<<"Loop number: "<<Tokenizer.GetTokenAtAsDouble(2)<<endl;
Typo("Loop number in for loop must be a positive integer");
return false;
}
unsigned int Loops = Tokenizer.GetTokenAtAsUnsignedInt(2);
double Start = Tokenizer.GetTokenAtAsDouble(3);
double Step = Tokenizer.GetTokenAtAsDouble(4);
// Remove for line
Iter = FileContent.erase(Iter++);
// Store content of for loop:
vector<MDDebugInfo> ForLoopContent;
for (; Iter != FileContent.end(); /* ++Iter erase */) {
m_DebugInfo = (*Iter);
if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) {
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() == 0) {
Iter++;
continue;
}
if (Tokenizer.IsTokenAt(0, "For") == true) {
ForDepth++;
}
if (Tokenizer.IsTokenAt(0, "Done") == true) {
ForDepth--;
if (ForDepth == CurrentDepth) {
Iter = FileContent.erase(Iter++);
break;
}
}
ForLoopContent.push_back(m_DebugInfo);
Iter = FileContent.erase(Iter++);
}
// Add new content at the same place:
vector<MDDebugInfo>::iterator LastIter = Iter;
int Position = 0;
for (unsigned int l = 1; l <= Loops; ++l) {
MString LoopString;
LoopString += l;
MString ValueString;
ValueString += (Start + (l-1)*Step);
vector<MDDebugInfo>::iterator ForIter;
for (ForIter = ForLoopContent.begin();
ForIter != ForLoopContent.end();
++ForIter) {
m_DebugInfo = (*ForIter);
m_DebugInfo.Replace(MString("%") + Index, LoopString);
m_DebugInfo.Replace(MString("$") + Index, ValueString);
LastIter = FileContent.insert(LastIter, m_DebugInfo);
LastIter++;
Position++;
}
}
Iter = LastIter - Position;
continue;
}
if (Tokenizer.IsTokenAt(0, "ForVector") == true) {
// Take care of nesting
CurrentDepth = ForDepth;
ForDepth++;
if (Tokenizer.GetNTokens() != 6) {
Typo("The ForVector-line must contain six entries, e.g. \"ForVector MyVector X Y Z V\"");
return false;
}
// Retrieve data:
Vector = GetVector(Tokenizer.GetTokenAt(1));
if (Vector == 0) {
Typo("ForVector-line: cannot find vector\"");
return false;
}
MString XIndex = Tokenizer.GetTokenAt(2);
MString YIndex = Tokenizer.GetTokenAt(3);
MString ZIndex = Tokenizer.GetTokenAt(4);
MString VIndex = Tokenizer.GetTokenAt(5);
// Remove for line
Iter = FileContent.erase(Iter++);
// Store content of ForVector loop:
vector<MDDebugInfo> ForLoopContent;
for (; Iter != FileContent.end(); /* ++Iter erase */) {
m_DebugInfo = (*Iter);
if (Tokenizer.Analyse(m_DebugInfo.GetText(), false) == false) {
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() == 0) {
Iter++;
continue;
}
if (Tokenizer.IsTokenAt(0, "ForVector") == true) {
ForDepth++;
}
if (Tokenizer.IsTokenAt(0, "DoneVector") == true) {
ForDepth--;
if (ForDepth == CurrentDepth) {
Iter = FileContent.erase(Iter++);
break;
}
}
ForLoopContent.push_back(m_DebugInfo);
Iter = FileContent.erase(Iter++);
}
// Add new content at the same place:
vector<MDDebugInfo>::iterator LastIter = Iter;
int Position = 0;
for (unsigned int l = 1; l <= Vector->GetSize(); ++l) {
MString LoopString;
LoopString += l;
MString XValueString;
XValueString += Vector->GetPosition(l-1).X();
MString YValueString;
YValueString += Vector->GetPosition(l-1).Y();
MString ZValueString;
ZValueString += Vector->GetPosition(l-1).Z();
MString ValueString;
ValueString += Vector->GetValue(l-1);
vector<MDDebugInfo>::iterator ForIter;
for (ForIter = ForLoopContent.begin();
ForIter != ForLoopContent.end();
++ForIter) {
m_DebugInfo = (*ForIter);
m_DebugInfo.Replace(MString("%") + XIndex, LoopString);
m_DebugInfo.Replace(MString("$") + XIndex, XValueString);
m_DebugInfo.Replace(MString("%") + YIndex, LoopString);
m_DebugInfo.Replace(MString("$") + YIndex, YValueString);
m_DebugInfo.Replace(MString("%") + ZIndex, LoopString);
m_DebugInfo.Replace(MString("$") + ZIndex, ZValueString);
m_DebugInfo.Replace(MString("%") + VIndex, LoopString);
m_DebugInfo.Replace(MString("$") + VIndex, ValueString);
LastIter = FileContent.insert(LastIter, m_DebugInfo);
LastIter++;
Position++;
}
}
Iter = LastIter - Position;
continue;
}
++Iter;
}
++Stage;
if (Timer.ElapsedTime() > TimeLimit) {
mout<<"Stage "<<Stage<<" (evaluating for loops) finished after "<<Timer.ElapsedTime()<<" sec"<<endl;
}
// Find random numbers
TRandom3 R;
R.SetSeed(11031879); // Do never modify!!!!
for (unsigned int i = 0; i < FileContent.size(); i++) {
while (FileContent[i].Contains("RandomDouble") == true) {
//cout<<"Before: "<<FileContent[i].GetText()<<endl;
FileContent[i].ReplaceFirst("RandomDouble", R.Rndm());
//cout<<"after: "<<FileContent[i].GetText()<<endl;
}
}
// // All constants and for loops are expanded, let's print some text ;-)
// for (unsigned int i = 0; i < FileContent.size(); i++) {
// cout<<FileContent[i].GetText()<<endl;
// }
++Stage;
if (Timer.ElapsedTime() > TimeLimit) {
mout<<"Stage "<<Stage<<" (evaluating random numbers) finished after "<<Timer.ElapsedTime()<<" sec"<<endl;
}
// Check for "If"-clauses
int IfDepth = 0;
int CurrentIfDepth = 0;
for (unsigned int i = 0; i < FileContent.size(); i++) {
m_DebugInfo = FileContent[i];
if (Tokenizer.Analyse(FileContent[i].GetText()) == false) {
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() == 0) {
continue;
}
if (Tokenizer.IsTokenAt(0, "If") == true) {
// Take care of nesting
CurrentIfDepth = IfDepth;
IfDepth++;
if (Tokenizer.GetNTokens() != 2) {
Typo("The If-line must contain two entries, the last one must be math, e.g. \"If { 1 == 2 } or If { $Value > 0 } \"");
return false;
}
// Retrieve data:
bool Bool = Tokenizer.GetTokenAtAsBoolean(1);
// Clear the if line
FileContent[i].SetText("");
// Forward its endif:
for (unsigned int j = i+1; j < FileContent.size(); ++j) {
if (Tokenizer.Analyse(FileContent[j].GetText(), false) == false) {
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() == 0) {
continue;
}
if (Tokenizer.IsTokenAt(0, "If") == true) {
IfDepth++;
}
if (Tokenizer.IsTokenAt(0, "EndIf") == true) {
IfDepth--;
if (IfDepth == CurrentIfDepth) {
FileContent[j].SetText("");
break;
}
}
if (Bool == false) {
FileContent[j].SetText("");
}
}
} // Is if
} // global loop
++Stage;
if (Timer.ElapsedTime() > TimeLimit) {
mout<<"Stage "<<Stage<<" (evaluating if clauses) finished after "<<Timer.ElapsedTime()<<" sec"<<endl;
}
// All constants and for loops are expanded, let's print some text ;-)
for (unsigned int i = 0; i < FileContent.size(); i++) {
m_DebugInfo = FileContent[i];
if (Tokenizer.Analyse(m_DebugInfo.GetText(), true) == false) {
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() == 0) continue;
if (Tokenizer.IsTokenAt(0, "Print") == true ||
Tokenizer.IsTokenAt(0, "Echo") == true) {
if (Tokenizer.GetNTokens() < 2) {
Typo("Line must contain at least two entries, e.g. \"Print Me!\"");
return false;
}
//mout<<" *** User Info start ***"<<endl;
mout<<" *** User Info: ";
for (unsigned int t = 1; t < Tokenizer.GetNTokens(); ++t) {
mout<<Tokenizer.GetTokenAt(t)<<" ";
}
mout<<endl;
//mout<<" *** User Info end ***"<<endl;
}
}
// First loop:
// Find the master keyword, volumes, material, detectors
//
for (unsigned int i = 0; i < FileContent.size(); i++) {
m_DebugInfo = FileContent[i];
if (Tokenizer.Analyse(m_DebugInfo.GetText()) == false) {
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() == 0) continue;
// Let's scan for first order keywords:
// Here we have:
// - Name
// - Version
// - Material
// - Volume
// - Detector
// - Trigger
// - System
// - Vector
// - Shape
// - Orientation
// Volume (Most frequent, so start with this one)
if (Tokenizer.IsTokenAt(0, "Volume") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"Volume D1Main\"");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(1)) == false) {
return false;
}
if (NameExists(Tokenizer.GetTokenAt(1)) == true) {
return false;
}
}
AddVolume(new MDVolume(Tokenizer.GetTokenAt(1),
CreateShortName(Tokenizer.GetTokenAt(1))));
continue;
}
// Name
else if (Tokenizer.IsTokenAt(0, "Name") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"Name MEGA\"");
return false;
}
m_Name = Tokenizer.GetTokenAt(1);
m_Geometry->SetNameTitle(m_Name, "A Geomega geometry");
continue;
}
// Version
else if (Tokenizer.IsTokenAt(0, "Version") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"Version 1.1.123\"");
return false;
}
m_Version = Tokenizer.GetTokenAt(1);
continue;
}
// Surrounding sphere
else if (Tokenizer.IsTokenAt(0, "SurroundingSphere") == true) {
if (Tokenizer.GetNTokens() != 6) {
Typo("Line must contain five values: Radius, xPos, yPos, zPos of sphere center, Distance to sphere center");
return false;
}
m_SphereRadius = Tokenizer.GetTokenAtAsDouble(1);
m_SpherePosition = MVector(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4));
m_DistanceToSphereCenter = Tokenizer.GetTokenAtAsDouble(5);
if (m_SphereRadius != m_DistanceToSphereCenter) {
Typo("Limitation: Concerning your surrounding sphere: The sphere radius must equal the distance to the sphere for the time being. Sorry.");
return false;
}
continue;
}
// Show volumes
else if (Tokenizer.IsTokenAt(0, "ShowVolumes") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two values: ShowVolumes false");
return false;
}
m_ShowVolumes = Tokenizer.GetTokenAtAsBoolean(1);
continue;
}
// Show volumes
else if (Tokenizer.IsTokenAt(0, "ShowOnlySensitiveVolumes") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two values: ShowVolumes false");
return false;
}
ShowOnlySensitiveVolumes = Tokenizer.GetTokenAtAsBoolean(1);
continue;
}
// Do Sanity checks
else if (Tokenizer.IsTokenAt(0, "DoSanityChecks") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two values: DoSanityChecks false");
return false;
}
m_DoSanityChecks = Tokenizer.GetTokenAtAsBoolean(1);
continue;
}
// Virtualize all non detector volumes
else if (Tokenizer.IsTokenAt(0, "VirtualizeNonDetectorVolumes") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two values: VirtualizeNonDetectorVolumes false");
return false;
}
m_VirtualizeNonDetectorVolumes = Tokenizer.GetTokenAtAsBoolean(1);
continue;
}
// Complex event reconstruction
else if (Tokenizer.IsTokenAt(0, "ComplexER") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two values: ComplexER false");
return false;
}
m_ComplexER = Tokenizer.GetTokenAtAsBoolean(1);
continue;
}
// Ignore short names
else if (Tokenizer.IsTokenAt(0, "IgnoreShortNames") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two values: IgnoreShortNames true");
return false;
}
m_IgnoreShortNames = Tokenizer.GetTokenAtAsBoolean(1);
continue;
}
// Default color
else if (Tokenizer.IsTokenAt(0, "DefaultColor") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two values: DefaultColor 3");
return false;
}
m_DefaultColor = Tokenizer.GetTokenAtAsInt(1);
continue;
}
// Detector search tolerance
else if (Tokenizer.IsTokenAt(0, "DetectorSearchTolerance") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two values: DetectorSearchTolerance 0.000001");
return false;
}
m_DetectorSearchTolerance = Tokenizer.GetTokenAtAsDouble(1);
continue;
}
// General absorption file directory
else if (Tokenizer.IsTokenAt(0, "AbsorptionFileDirectory") == true ||
Tokenizer.IsTokenAt(0, "CrossSectionFilesDirectory") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two values: CrossSectionFilesDirectory auxiliary");
return false;
}
m_CrossSectionFileDirectory = Tokenizer.GetTokenAtAsString(1);
MFile::ExpandFileName(m_CrossSectionFileDirectory);
if (gSystem->IsAbsoluteFileName(m_CrossSectionFileDirectory) == false) {
m_CrossSectionFileDirectory =
MString(MFile::GetDirectoryName(m_FileName)) + "/" + m_CrossSectionFileDirectory;
}
continue;
}
// Material
else if (Tokenizer.IsTokenAt(0, "Material") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"Material Aluminimum\"");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(1)) == false) {
return false;
}
if (NameExists(Tokenizer.GetTokenAt(1)) == true) {
return false;
}
}
AddMaterial(new MDMaterial(Tokenizer.GetTokenAt(1),
CreateShortName(Tokenizer.GetTokenAt(1)),
CreateShortName(Tokenizer.GetTokenAt(1), 19, false, true)));
continue;
}
// Shape
else if (Tokenizer.IsTokenAt(0, "Shape") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain three strings, e.g. \"Shape BOX RedBox\"");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(2)) == false) {
return false;
}
if (NameExists(Tokenizer.GetTokenAt(2)) == true) {
return false;
}
}
AddShape(Tokenizer.GetTokenAt(1), Tokenizer.GetTokenAt(2));
continue;
}
// Orientation
else if (Tokenizer.IsTokenAt(0, "Orientation") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"Orientation RedBoxOrientation\"");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(1)) == false) {
return false;
}
if (NameExists(Tokenizer.GetTokenAt(1)) == true) {
return false;
}
}
AddOrientation(new MDOrientation(Tokenizer.GetTokenAt(1)));
continue;
}
// Trigger
else if (Tokenizer.IsTokenAt(0, "Trigger") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"Trigger D1D2\"");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(1)) == false) {
return false;
}
if (NameExists(Tokenizer.GetTokenAt(1)) == true) {
return false;
}
}
AddTrigger(new MDTrigger(Tokenizer.GetTokenAt(1)));
continue;
}
// System
else if (Tokenizer.IsTokenAt(0, "System") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"System D1D2\"");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(1)) == false) {
return false;
}
if (NameExists(Tokenizer.GetTokenAt(1)) == true) {
return false;
}
}
m_System = new MDSystem(Tokenizer.GetTokenAt(1));
continue;
}
// Detectors: Strip2D
else if (Tokenizer.IsTokenAt(0, "Strip2D") == true ||
Tokenizer.IsTokenAt(0, "MDStrip2D") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"Strip2D Tracker\"");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(1)) == false) {
return false;
}
if (NameExists(Tokenizer.GetTokenAt(1)) == true) {
return false;
}
}
AddDetector(new MDStrip2D(Tokenizer.GetTokenAt(1)));
continue;
}
// Detectors: Strip3D
else if (Tokenizer.IsTokenAt(0, "Strip3D") == true ||
Tokenizer.IsTokenAt(0, "MDStrip3D") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"Strip3D Germanium\"");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(1)) == false) {
return false;
}
if (NameExists(Tokenizer.GetTokenAt(1)) == true) {
return false;
}
}
AddDetector(new MDStrip3D(Tokenizer.GetTokenAt(1)));
continue;
}
// Detectors: Strip3DDirectional
else if (Tokenizer.IsTokenAt(0, "Strip3DDirectional") == true ||
Tokenizer.IsTokenAt(0, "MDStrip3DDirectional") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"Strip3DDirectional ThickSiliconWafer\"");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(1)) == false) {
return false;
}
if (NameExists(Tokenizer.GetTokenAt(1)) == true) {
return false;
}
}
AddDetector(new MDStrip3DDirectional(Tokenizer.GetTokenAt(1)));
continue;
}
// Detectors: DriftChamber
else if (Tokenizer.IsTokenAt(0, "DriftChamber") == true ||
Tokenizer.IsTokenAt(0, "MDDriftChamber") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"DriftChamber Xenon\"");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(1)) == false) {
return false;
}
if (NameExists(Tokenizer.GetTokenAt(1)) == true) {
return false;
}
}
AddDetector(new MDDriftChamber(Tokenizer.GetTokenAt(1)));
continue;
}
// Detectors: AngerCamera
else if (Tokenizer.IsTokenAt(0, "AngerCamera") == true ||
Tokenizer.IsTokenAt(0, "MDAngerCamera") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"AngerCamera Angers\"");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(1)) == false) {
return false;
}
if (NameExists(Tokenizer.GetTokenAt(1)) == true) {
return false;
}
}
AddDetector(new MDAngerCamera(Tokenizer.GetTokenAt(1)));
continue;
}
// Detectors: ACS
else if (Tokenizer.IsTokenAt(0, "Scintillator") == true ||
Tokenizer.IsTokenAt(0, "Simple") == true ||
Tokenizer.IsTokenAt(0, "ACS") == true ||
Tokenizer.IsTokenAt(0, "MDACS") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"Scintillator ACS1\"");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(1)) == false) {
return false;
}
if (NameExists(Tokenizer.GetTokenAt(1)) == true) {
return false;
}
}
AddDetector(new MDACS(Tokenizer.GetTokenAt(1)));
continue;
}
// Detectors: Calorimeter
else if (Tokenizer.IsTokenAt(0, "Calorimeter") == true ||
Tokenizer.IsTokenAt(0, "MDCalorimeter") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"Calorimeter athena\"");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(1)) == false) {
return false;
}
if (NameExists(Tokenizer.GetTokenAt(1)) == true) {
return false;
}
}
AddDetector(new MDCalorimeter(Tokenizer.GetTokenAt(1)));
continue;
}
// Detectors: Voxel3D
else if (Tokenizer.IsTokenAt(0, "Voxel3D") == true ||
Tokenizer.IsTokenAt(0, "MDVoxel3D") == true) {
if (Tokenizer.GetNTokens() != 2) {
Typo("Line must contain two strings, e.g. \"Voxel3D MyVoxler\"");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(1)) == false) {
return false;
}
if (NameExists(Tokenizer.GetTokenAt(1)) == true) {
return false;
}
}
AddDetector(new MDVoxel3D(Tokenizer.GetTokenAt(1)));
continue;
}
}
// Now we can do some basic evaluation of the input:
if (m_SphereRadius == DBL_MAX) {
Typo("You have to define a surrounding sphere!");
return false;
}
++Stage;
if (Timer.ElapsedTime() > TimeLimit) {
mout<<"Stage "<<Stage<<" (analyzing primary keywords) finished after "<<Timer.ElapsedTime()<<" sec"<<endl;
}
//
// Second loop:
// Search for copies/clones of different volumes and named detectors
//
//
for (unsigned int i = 0; i < FileContent.size(); i++) {
m_DebugInfo = FileContent[i];
if (Tokenizer.Analyse(m_DebugInfo.GetText()) == false) {
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() < 3) continue;
// Check for volumes with copies
if (Tokenizer.IsTokenAt(1, "Copy") == true) {
if ((V = GetVolume(Tokenizer.GetTokenAt(0))) != 0) {
if (GetVolume(Tokenizer.GetTokenAt(2)) != 0) {
Typo("A volume of this name already exists!");
return false;
}
VCopy = new MDVolume(Tokenizer.GetTokenAt(2));
AddVolume(VCopy);
V->AddClone(VCopy);
} else if ((M = GetMaterial(Tokenizer.GetTokenAt(0))) != 0) {
if (GetMaterial(Tokenizer.GetTokenAt(2)) != 0) {
Typo("A material of this name already exists!");
return false;
}
MCopy = new MDMaterial(Tokenizer.GetTokenAt(2),
CreateShortName(Tokenizer.GetTokenAt(2)),
CreateShortName(Tokenizer.GetTokenAt(2), 19));
AddMaterial(MCopy);
M->AddClone(MCopy);
}
} else if (Tokenizer.IsTokenAt(1, "NamedDetector") == true || Tokenizer.IsTokenAt(1, "Named") == true) {
if ((D = GetDetector(Tokenizer.GetTokenAt(0))) != 0) {
if (D->IsNamedDetector() == true) {
Typo("You cannot add a named detector to a named detector!");
return false;
}
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain three strings, e.g. MyStripDetector.Named Strip1. Are you using the old NamedDetector format?");
return false;
}
if (m_DoSanityChecks == true) {
if (ValidName(Tokenizer.GetTokenAt(2)) == false) {
Typo("You don't have a valid detector name!");
return false;
}
if (NameExists(Tokenizer.GetTokenAt(2)) == true) {
Typo("The name alreday exists!");
return false;
}
}
MDDetector* Clone = D->Clone();
Clone->SetName(Tokenizer.GetTokenAt(2));
if (D->AddNamedDetector(Clone) == false) {
Typo("Unable to add a named detector!");
return false;
}
AddDetector(Clone);
}
}
// Umdrehen: Copy gefunden, dann Volumen/ Detector zuordnen
// --> Fehler falls kein Volumen vorhanden
}
++Stage;
if (Timer.ElapsedTime() > TimeLimit) {
mout<<"Stage "<<Stage<<" (analyzing \"Copies\") finished after "<<Timer.ElapsedTime()<<" sec"<<endl;
}
////////////////////////////////////////////////////////////////////////////////////////////
// Third loop:
// Fill the volumes, materials with life...
for (unsigned int i = 0; i < FileContent.size(); i++) {
m_DebugInfo = FileContent[i];
if (Tokenizer.Analyse(m_DebugInfo.GetText()) == false) {
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() < 2) continue;
// Now the first token is some kind of name, so we have to find the
// according object and fill it
// Check for Materials:
if ((M = GetMaterial(Tokenizer.GetTokenAt(0))) != 0) {
if (Tokenizer.IsTokenAt(1, "Density") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and 3 doubles,"
" e.g. \"Alu.Density 2.77\"");
return false;
}
M->SetDensity(Tokenizer.GetTokenAtAsDouble(2));
} else if (Tokenizer.IsTokenAt(1, "RadiationLength") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and 3 doubles,"
" e.g. \"Alu.RadiationLength 8.9\"");
return false;
}
M->SetRadiationLength(Tokenizer.GetTokenAtAsDouble(2));
} else if (Tokenizer.IsTokenAt(1, "Component") == true ||
Tokenizer.IsTokenAt(1, "ComponentByAtoms") == true) {
if (Tokenizer.GetNTokens() < 4 || Tokenizer.GetNTokens() > 5) {
Typo("Line must contain two strings and 3 doubles,"
" e.g. \"Alu.ComponentByAtoms 27.0 13.0 1.0\""
" or three string and one double\""
" e.g. \"Alu.ComponentByAtoms Al 1.0\"");
return false;
}
if (Tokenizer.GetNTokens() == 4) {
if (M->SetComponent(Tokenizer.GetTokenAtAsString(2),
Tokenizer.GetTokenAtAsDouble(3),
MDMaterialComponent::c_ByAtoms) == false) {
Typo("Element not found!");
return false;
}
} else {
M->SetComponent(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4),
MDMaterialComponent::c_ByAtoms);
}
} else if (Tokenizer.IsTokenAt(1, "ComponentByMass") == true) {
if (Tokenizer.GetNTokens() < 4 || Tokenizer.GetNTokens() > 5) {
Typo("Line must contain two strings and 3 doubles,"
" e.g. \"Alu.ComponentByMass 27.0 13.0 1.0\""
" or three string and one double\""
" e.g. \"Alu.ComponentByMass Al 1.0\"");
return false;
}
if (Tokenizer.GetNTokens() == 4) {
if (M->SetComponent(Tokenizer.GetTokenAtAsString(2),
Tokenizer.GetTokenAtAsDouble(3),
MDMaterialComponent::c_ByMass) == false) {
Typo("Element not found!");
return false;
}
} else {
M->SetComponent(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4),
MDMaterialComponent::c_ByMass);
}
} else if (Tokenizer.IsTokenAt(1, "Sensitivity") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and one int,"
" e.g. \"Alu.Sensitivity 1\"");
return false;
}
M->SetSensitivity(Tokenizer.GetTokenAtAsInt(2));
// }
// // Check for total absorption coefficients:
// else if (Tokenizer.IsTokenAt(1, "TotalAbsorptionFile") == true) {
// if (Tokenizer.GetNTokens() < 3) {
// Typo("Line must contain three strings"
// " e.g. \"Wafer.TotalAbsorptionFile MyFile.abs");
// return false;
// }
// M->SetAbsorptionFileName(Tokenizer.GetTokenAfterAsString(2));
} else if (Tokenizer.IsTokenAt(1, "Copy") == true) {
// No warning...
} else {
Typo("Unrecognized material option");
return false;
}
} // end materials
// Check for orientations:
else if ((Orientation = GetOrientation(Tokenizer.GetTokenAt(0))) != 0) {
if (Orientation->Parse(Tokenizer, m_DebugInfo) == false) {
Reset();
return false;
}
} // end orientations
// Check for shapes:
else if ((Shape = GetShape(Tokenizer.GetTokenAt(0))) != 0) {
if (Shape->GetType() == "Subtraction") {
if (Tokenizer.IsTokenAt(1, "Parameters") == true) {
if (Tokenizer.GetNTokens() < 4 || Tokenizer.GetNTokens() > 5) {
Typo("The shape subtraction needs 4-5 parameters");
return false;
}
MDShape* Minuend = GetShape(Tokenizer.GetTokenAt(2));
MDShape* Subtrahend = GetShape(Tokenizer.GetTokenAt(3));
MDOrientation* Orientation = 0;
if (Tokenizer.GetNTokens() == 5) {
Orientation = GetOrientation(Tokenizer.GetTokenAt(4));
if (Orientation == 0) {
Typo("The orientation was not found!");
return false;
}
} else {
Orientation = new MDOrientation(Shape->GetName() + "_Orientation");
AddOrientation(Orientation);
}
if (Minuend == 0) {
Typo("The minuend shape was not found!");
return false;
}
if (Subtrahend == 0) {
Typo("The subtrahend shape was not found!");
return false;
}
if (dynamic_cast<MDShapeSubtraction*>(Shape)->Set(Minuend, Subtrahend, Orientation) == false) {
Typo("Unable to parse the shape correctly");
return false;
}
}
} else if (Shape->GetType() == "Union") {
if (Tokenizer.IsTokenAt(1, "Parameters") == true) {
if (Tokenizer.GetNTokens() < 4 || Tokenizer.GetNTokens() > 5) {
Typo("The shape Union needs 4-5 parameters");
return false;
}
MDShape* Augend = GetShape(Tokenizer.GetTokenAt(2));
MDShape* Addend = GetShape(Tokenizer.GetTokenAt(3));
MDOrientation* Orientation = 0;
if (Tokenizer.GetNTokens() == 5) {
Orientation = GetOrientation(Tokenizer.GetTokenAt(4));
if (Orientation == 0) {
Typo("The orientation was not found!");
return false;
}
} else {
Orientation = new MDOrientation(Shape->GetName() + "_Orientation");
AddOrientation(Orientation);
}
if (Augend == 0) {
Typo("The augend shape was not found!");
return false;
}
if (Addend == 0) {
Typo("The addend shape was not found!");
return false;
}
if (dynamic_cast<MDShapeUnion*>(Shape)->Set(Augend, Addend, Orientation) == false) {
Typo("Unable to parse the shape Union correctly");
return false;
}
}
} else if (Shape->GetType() == "Intersection") {
if (Tokenizer.IsTokenAt(1, "Parameters") == true) {
if (Tokenizer.GetNTokens() < 4 || Tokenizer.GetNTokens() > 5) {
Typo("The shape Intersection needs 4-5 parameters");
return false;
}
MDShape* Left = GetShape(Tokenizer.GetTokenAt(2));
MDShape* Right = GetShape(Tokenizer.GetTokenAt(3));
MDOrientation* Orientation = 0;
if (Tokenizer.GetNTokens() == 5) {
Orientation = GetOrientation(Tokenizer.GetTokenAt(4));
if (Orientation == 0) {
Typo("The orientation was not found!");
return false;
}
} else {
Orientation = new MDOrientation(Shape->GetName() + "_Orientation");
AddOrientation(Orientation);
}
if (Left == 0) {
Typo("The left shape was not found!");
return false;
}
if (Right == 0) {
Typo("The right shape was not found!");
return false;
}
if (dynamic_cast<MDShapeIntersection*>(Shape)->Set(Left, Right, Orientation) == false) {
Typo("Unable to parse the shape Intersection correctly");
return false;
}
}
} else {
if (Shape->Parse(Tokenizer, m_DebugInfo) == false) {
Reset();
return false;
}
}
} // end shapes
// Check for triggers:
else if ((T = GetTrigger(Tokenizer.GetTokenAt(0))) != 0) {
if (Tokenizer.IsTokenAt(1, "PositiveDetectorType") == true) {
mout<<" *** Deprectiated *** "<<endl;
mout<<"The \"PositiveDetectorType\" keyword is no longer supported!"<<endl;
mout<<"Replace it with:"<<endl;
mout<<T->GetName()<<".Veto false"<<endl;
mout<<T->GetName()<<".TriggerByChannel true"<<endl;
mout<<T->GetName()<<".DetectorType "
<<MDDetector::GetDetectorTypeName(Tokenizer.GetTokenAtAsInt(2))
<<" "<<Tokenizer.GetTokenAtAsInt(3)<<endl;
mout<<"Using the above..."<<endl;
mout<<endl;
FoundDepreciated = true;
if (Tokenizer.GetNTokens() != 4) {
Typo("Line must contain two strings and 2 integer,"
" e.g. \"D1D2Trigger.DetectorType 1 2\"");
return false;
}
// Check if such a detector type exists:
bool Found = false;
for (unsigned int d = 0; d < GetNDetectors(); ++d) {
if (GetDetectorAt(d)->GetType() == Tokenizer.GetTokenAtAsInt(2)) {
Found = true;
break;
}
}
if (Found == false) {
Typo("Line contains a not defined detector type!");
return false;
}
T->SetVeto(false);
T->SetTriggerByChannel(true);
T->SetDetectorType(Tokenizer.GetTokenAtAsInt(2), Tokenizer.GetTokenAtAsInt(3));
} else if (Tokenizer.IsTokenAt(1, "TriggerByChannel") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and one boolean,"
" e.g. \"D1D2Trigger.TriggerByChannel true\"");
return false;
}
T->SetTriggerByChannel(Tokenizer.GetTokenAtAsBoolean(2));
} else if (Tokenizer.IsTokenAt(1, "TriggerByDetector") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and one boolean,"
" e.g. \"D1D2Trigger.TriggerByDetector true\"");
return false;
}
T->SetTriggerByDetector(Tokenizer.GetTokenAtAsBoolean(2));
} else if (Tokenizer.IsTokenAt(1, "Veto") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and one boolean,"
" e.g. \"D1D2Trigger.Veto true\"");
return false;
}
T->SetVeto(Tokenizer.GetTokenAtAsBoolean(2));
} else if (Tokenizer.IsTokenAt(1, "DetectorType") == true) {
if (Tokenizer.GetNTokens() != 4) {
Typo("Line must contain three strings and one int,"
" e.g. \"D1D2Trigger.DetectorType Strip3D 1\"");
return false;
}
if (MDDetector::IsValidDetectorType(Tokenizer.GetTokenAtAsString(2)) == false) {
Typo("Line must contain a valid detector type, e.g. Strip2D, DriftChamber, etc.");
return false;
}
// Check if such a detector type exists:
bool Found = false;
for (unsigned int d = 0; d < GetNDetectors(); ++d) {
if (GetDetectorAt(d)->GetTypeName() == Tokenizer.GetTokenAtAsString(2)) {
Found = true;
break;
}
}
if (Found == false) {
Typo("Line contains a not defined detector type!");
return false;
}
T->SetDetectorType(MDDetector::GetDetectorType(Tokenizer.GetTokenAtAsString(2)),
Tokenizer.GetTokenAtAsInt(3));
} else if (Tokenizer.IsTokenAt(1, "Detector") == true) {
if (Tokenizer.GetNTokens() != 4) {
Typo("Line must contain three strings and one int,"
" e.g. \"D1D2Trigger.Detector MyStrip2D 1\"");
return false;
}
MDDetector* TriggerDetector;
if ((TriggerDetector = GetDetector(Tokenizer.GetTokenAt(2))) == 0) {
Typo("A detector of this name does not exist!");
return false;
}
T->SetDetector(TriggerDetector, Tokenizer.GetTokenAtAsInt(3));
} else if (Tokenizer.IsTokenAt(1, "GuardringDetectorType") == true) {
if (Tokenizer.GetNTokens() != 4) {
Typo("Line must contain three strings and one int,"
" e.g. \"D1D2Trigger.GuardringDetectorType Strip3D 1\"");
return false;
}
if (MDDetector::IsValidDetectorType(Tokenizer.GetTokenAtAsString(2)) == false) {
Typo("Line must contain a valid detector type, e.g. Strip2D, DriftChamber, etc.");
return false;
}
T->SetGuardringDetectorType(MDDetector::GetDetectorType(Tokenizer.GetTokenAtAsString(2)),
Tokenizer.GetTokenAtAsInt(3));
} else if (Tokenizer.IsTokenAt(1, "GuardringDetector") == true) {
if (Tokenizer.GetNTokens() != 4) {
Typo("Line must contain three strings and one int,"
" e.g. \"D1D2Trigger.GuardringDetector MyStrip2D 1\"");
return false;
}
MDDetector* TriggerDetector;
if ((TriggerDetector = GetDetector(Tokenizer.GetTokenAt(2))) == 0) {
Typo("A detector of this name does not exist!");
return false;
}
T->SetGuardringDetector(TriggerDetector, Tokenizer.GetTokenAtAsInt(3));
} else if (Tokenizer.IsTokenAt(1, "NegativeDetectorType") == true) {
mout<<" *** Outdated *** "<<endl;
mout<<"The \"NegativeDetectorType\" keyword is no longer supported!"<<endl;
return false;
} else {
Typo("Unrecognized trigger option");
return false;
}
}
// Check for volumes
else if ((S = GetSystem(Tokenizer.GetTokenAt(0))) != 0) {
if (Tokenizer.IsTokenAt(1, "TimeResolution") == true) {
if (Tokenizer.GetNTokens() >= 3) {
MString Type = Tokenizer.GetTokenAt(2);
Type.ToLower();
if (Type == "ideal" || Type == "none" || Type == "no" || Type == "nix" || Type == "perfect") {
m_System->SetTimeResolutionType(MDSystem::c_TimeResolutionTypeIdeal);
} else if (Type == "gauss" || Type == "gaus") {
if (Tokenizer.GetNTokens() == 4) {
m_System->SetTimeResolutionType(MDSystem::c_TimeResolutionTypeGauss);
m_System->SetTimeResolutionGaussSigma(Tokenizer.GetTokenAtAsDouble(3));
} else {
Typo("Line must contain three strings and one double,"
" e.g. \"MEGA.TimeResolution Gauss 2.0E-6\"");
return false;
}
} else {
Typo("Unrecognized time resolution type.");
return false;
}
} else {
Typo("Not enough tokens.");
return false;
}
} else {
Typo("Unrecognized system option");
return false;
}
}
// Check for volumes
else if ((V = GetVolume(Tokenizer.GetTokenAt(0))) != 0) {
if (Tokenizer.IsTokenAt(1, "Material") == true) {
if ((M = GetMaterial(Tokenizer.GetTokenAt(2))) == 0) {
Typo("Unknown material found!");
return false;
}
V->SetMaterial(M);
} else if (Tokenizer.IsTokenAt(1, "Shape") == true) {
if (Tokenizer.GetNTokens() < 3) {
Typo("Not enough input parameters for this shape!");
return false;
}
MString ShapeID = Tokenizer.GetTokenAtAsString(2);
ShapeID.ToLowerInPlace();
if (ShapeID.AreIdentical("brik") == true || ShapeID.AreIdentical("box") == true) {
MDShapeBRIK* BRIK = new MDShapeBRIK(V->GetName() + "_Shape");
if (BRIK->Parse(Tokenizer, m_DebugInfo) == false) {
Reset();
return false;
}
V->SetShape(BRIK);
AddShape(BRIK);
} else if (ShapeID.AreIdentical("pcon") == true) {
MDShapePCON* PCON = new MDShapePCON(V->GetName() + "_Shape");
if (PCON->Parse(Tokenizer, m_DebugInfo) == false) {
Reset();
return false;
}
V->SetShape(PCON);
AddShape(PCON);
} else if (ShapeID.AreIdentical("pgon") == true) {
MDShapePGON* PGON = new MDShapePGON(V->GetName() + "_Shape");
if (PGON->Parse(Tokenizer, m_DebugInfo) == false) {
Reset();
return false;
}
V->SetShape(PGON);
AddShape(PGON);
}
// Sphere:
else if (ShapeID.AreIdentical("sphe") == true || ShapeID.AreIdentical("sphere") == true) {
MDShapeSPHE* SPHE = new MDShapeSPHE(V->GetName() + "_Shape");
if (SPHE->Parse(Tokenizer, m_DebugInfo) == false) {
Reset();
return false;
}
V->SetShape(SPHE);
AddShape(SPHE);
}
// Cylinder:
else if (ShapeID.AreIdentical("tubs") == true || ShapeID.AreIdentical("tube") == true) {
MDShapeTUBS* TUBS = new MDShapeTUBS(V->GetName() + "_Shape");
if (TUBS->Parse(Tokenizer, m_DebugInfo) == false) {
Reset();
return false;
}
V->SetShape(TUBS);
AddShape(TUBS);
}
// Cone:
else if (ShapeID.AreIdentical("cone") == true) {
MDShapeCONE* CONE = new MDShapeCONE(V->GetName() + "_Shape");
if (CONE->Parse(Tokenizer, m_DebugInfo) == false) {
Typo("Shape of CONE not ok");
return false;
}
V->SetShape(CONE);
AddShape(CONE);
}
// CONS:
else if (ShapeID.AreIdentical("cons") == true) {
MDShapeCONS* CONS = new MDShapeCONS(V->GetName() + "_Shape");
if (CONS->Parse(Tokenizer, m_DebugInfo) == false) {
Reset();
return false;
}
V->SetShape(CONS);
AddShape(CONS);
}
// General trapezoid:
else if (ShapeID.AreIdentical("trap") == true) {
MDShapeTRAP* TRAP = new MDShapeTRAP(V->GetName() + "_Shape");
if (TRAP->Parse(Tokenizer, m_DebugInfo) == false) {
Reset();
return false;
}
V->SetShape(TRAP);
AddShape(TRAP);
}
// General twisted trapezoid:
else if (ShapeID.AreIdentical("gtra") == true) {
MDShapeGTRA* GTRA = new MDShapeGTRA(V->GetName() + "_Shape");
if (GTRA->Parse(Tokenizer, m_DebugInfo) == false) {
Reset();
return false;
}
V->SetShape(GTRA);
AddShape(GTRA);
}
// Simple trapezoid
else if (ShapeID.AreIdentical("trd1") == true) {
MDShapeTRD1* TRD1 = new MDShapeTRD1(V->GetName() + "_Shape");
if (TRD1->Parse(Tokenizer, m_DebugInfo) == false) {
Reset();
return false;
}
V->SetShape(TRD1);
AddShape(TRD1);
}
// Simple trapezoid
else if (ShapeID.AreIdentical("trd2") == true) {
MDShapeTRD2* TRD2 = new MDShapeTRD2(V->GetName() + "_Shape");
if (TRD2->Parse(Tokenizer, m_DebugInfo) == false) {
Reset();
return false;
}
V->SetShape(TRD2);
AddShape(TRD2);
}
// Simple union of two shapes
else if (ShapeID.AreIdentical("union") == true) {
MDShapeUnion* Union = new MDShapeUnion(V->GetName() + "_Shape");
if (Tokenizer.GetNTokens() != 6) {
Typo("The shape Union needs 6 parameters");
return false;
}
MDShape* Augend = GetShape(Tokenizer.GetTokenAt(3));
MDShape* Addend = GetShape(Tokenizer.GetTokenAt(4));
MDOrientation* Orientation = GetOrientation(Tokenizer.GetTokenAt(5));
if (Augend == 0) {
Typo("The augend shape was not found!");
return false;
}
if (Addend == 0) {
Typo("The addend shape was not found!");
return false;
}
if (Orientation == 0) {
Typo("The orientation was not found!");
return false;
}
if (Union->Set(Augend, Addend, Orientation) == false) {
Typo("Unable to parse the shape Union correctly");
return false;
}
V->SetShape(Union);
AddShape(Union);
}
// Subtraction
else if (ShapeID.AreIdentical("subtraction") == true) {
MDShapeSubtraction* Subtraction = new MDShapeSubtraction(V->GetName() + "_Shape");
if (Tokenizer.GetNTokens() != 6) {
Typo("The shape subtraction needs 6 parameters");
return false;
}
MDShape* Minuend = GetShape(Tokenizer.GetTokenAt(3));
MDShape* Subtrahend = GetShape(Tokenizer.GetTokenAt(4));
MDOrientation* Orientation = GetOrientation(Tokenizer.GetTokenAt(5));
if (Minuend == 0) {
Typo("The minuend shape was not found!");
return false;
}
if (Subtrahend == 0) {
Typo("The subtrahend shape was not found!");
return false;
}
if (Orientation == 0) {
Typo("The orientation was not found!");
return false;
}
if (Subtraction->Set(Minuend, Subtrahend, Orientation) == false) {
Typo("Unable to parse the shape correctly");
return false;
}
V->SetShape(Subtraction);
AddShape(Subtraction);
}
// Intersection
else if (ShapeID.AreIdentical("intersection") == true) {
MDShapeIntersection* Intersection = new MDShapeIntersection(V->GetName() + "_Shape");
if (Tokenizer.GetNTokens() != 6) {
Typo("The shape Intersection needs 6 parameters");
return false;
}
MDShape* Left = GetShape(Tokenizer.GetTokenAt(3));
MDShape* Right = GetShape(Tokenizer.GetTokenAt(4));
MDOrientation* Orientation = GetOrientation(Tokenizer.GetTokenAt(5));
if (Left == 0) {
Typo("The left shape was not found!");
return false;
}
if (Right == 0) {
Typo("The right shape was not found!");
return false;
}
if (Orientation == 0) {
Typo("The orientation was not found!");
return false;
}
if (Intersection->Set(Left, Right, Orientation) == false) {
Typo("Unable to parse the shape Intersection correctly");
return false;
}
V->SetShape(Intersection);
AddShape(Intersection);
}
// Now check if it is in the list
else {
MDShape* Shape = GetShape(Tokenizer.GetTokenAt(2));
if (Shape != 0) {
V->SetShape(Shape);
} else {
Typo("Unknown shape found!");
return false;
}
}
} else if (Tokenizer.IsTokenAt(1, "Mother") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain three strings"
" e.g. \"Triangle.Mother WorldVolume\"");
return false;
}
if (Tokenizer.IsTokenAt(2, "0")) {
V->SetWorldVolume();
if (m_WorldVolume != 0) {
Typo("You are only allowed to have one world volume!");
return false;
}
m_WorldVolume = V;
} else {
if (GetVolume(Tokenizer.GetTokenAt(2)) == 0) {
Typo("A volume of this name does not exist!");
return false;
}
if (GetVolume(Tokenizer.GetTokenAt(2)) == V) {
Typo("A volume can't be its own mother!");
return false;
}
if (GetVolume(Tokenizer.GetTokenAt(2))->IsClone() == true) {
Typo("You are not allowed to set a volume as mother which is created via \"Copy\". Use the original volume!");
return false;
}
if (V->SetMother(GetVolume(Tokenizer.GetTokenAt(2))) == false) {
Typo("Mother could not be set (Do you have some cyclic mother-relations defined?)");
return false;
}
}
} else if (Tokenizer.IsTokenAt(1, "Color") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and one integer"
" e.g. \"Triangle.Color 2\"");
return false;
}
if (Tokenizer.GetTokenAtAsInt(2) < 0) {
Typo("The color value needs to be positive");
return false;
}
V->SetColor(Tokenizer.GetTokenAtAsInt(2));
} else if (Tokenizer.IsTokenAt(1, "LineStyle") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and one integer"
" e.g. \"Triangle.LineStyle 1\"");
return false;
}
if (Tokenizer.GetTokenAtAsInt(2) < 0) {
Typo("The line style value needs to be positive");
return false;
}
V->SetLineStyle(Tokenizer.GetTokenAtAsInt(2));
} else if (Tokenizer.IsTokenAt(1, "LineWidth") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and one integer"
" e.g. \"Triangle.LineWidth 1\"");
return false;
}
if (Tokenizer.GetTokenAtAsInt(2) < 0) {
Typo("The line width value needs to be positive");
return false;
}
V->SetLineWidth(Tokenizer.GetTokenAtAsInt(2));
} else if (Tokenizer.IsTokenAt(1, "Scale") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and one integer"
" e.g. \"Triangle.Scale 2.0\"");
return false;
}
if (Tokenizer.GetTokenAtAsDouble(2) <= 0) {
Typo("The color value needs to be positive");
return false;
}
ScaledVolumes[V] = Tokenizer.GetTokenAtAsDouble(2);
} else if (Tokenizer.IsTokenAt(1, "Virtual") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and one boolean"
" e.g. \"Triangle.Virtual true\"");
return false;
}
V->SetVirtual(Tokenizer.GetTokenAtAsBoolean(2));
} else if (Tokenizer.IsTokenAt(1, "Many") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and one boolean"
" e.g. \"Triangle.Many true\"");
return false;
}
V->SetMany(Tokenizer.GetTokenAtAsBoolean(2));
} else if (Tokenizer.IsTokenAt(1, "Visibility") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and one integer"
" e.g. \"Triangle.Visibility 1\"");
return false;
}
if (Tokenizer.GetTokenAtAsInt(2) < -1 || Tokenizer.GetTokenAtAsInt(2) > 3) {
Typo("The visibility needs to be -1, 0, 1, 2, or 3");
return false;
}
V->SetVisibility(Tokenizer.GetTokenAtAsInt(2));
} else if (Tokenizer.IsTokenAt(1, "Absorptions") == true) {
mout<<" *** Deprectiated *** "<<endl;
mout<<"The \"Absorptions\" keyword is no longer supported"<<endl;
mout<<"All cross section files have fixed file names, and can be found in the directory given by"<<endl;
mout<<"the keyword CrossSectionFilesDirectory or in \"auxiliary\" as default"<<endl;
mout<<endl;
FoundDepreciated = true;
} else if (Tokenizer.IsTokenAt(1, "Orientation") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain three strings,"
" e.g. \"Wafer.Orientation WaferOrientation\"");
return false;
}
Orientation = GetOrientation(Tokenizer.GetTokenAtAsString(2));
if (Orientation == 0) {
Typo("Cannot find the requested orientation. Did you define it?");
return false;
}
V->SetPosition(Orientation->GetPosition());
V->SetRotation(Orientation->GetRotationMatrix());
} else if (Tokenizer.IsTokenAt(1, "Position") == true) {
if (Tokenizer.GetNTokens() != 5) {
Typo("Line must contain two strings and 3 doubles,"
" e.g. \"Wafer.Position 3.5 1.0 0.0\"");
return false;
}
V->SetPosition(MVector(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4)));
} else if (Tokenizer.IsTokenAt(1, "Rotation") == true ||
Tokenizer.IsTokenAt(1, "Rotate") == true) {
if (Tokenizer.GetNTokens() != 5 && Tokenizer.GetNTokens() != 8) {
Typo("Line must contain two strings and 3 doubles,"
" e.g. \"Wafer.Rotation 60.0 0.0 0.0\"");
return false;
}
if (Tokenizer.GetNTokens() == 5) {
V->SetRotation(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4));
} else {
double theta1 = Tokenizer.GetTokenAtAsDouble(2);
double theta2 = Tokenizer.GetTokenAtAsDouble(4);
double theta3 = Tokenizer.GetTokenAtAsDouble(6);
if (theta1 < 0 || theta1 > 180) {
Typo("Theta1 of Rotation needs per definition to be within [0;180]");
return false;
}
if (theta2 < 0 || theta2 > 180) {
Typo("Theta2 of Rotation needs per definition to be within [0;180]");
return false;
}
if (theta3 < 0 || theta3 > 180) {
Typo("Theta3 of Rotation needs per definition to be within [0;180]");
return false;
}
V->SetRotation(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4),
Tokenizer.GetTokenAtAsDouble(5),
Tokenizer.GetTokenAtAsDouble(6),
Tokenizer.GetTokenAtAsDouble(7));
}
} else if (Tokenizer.IsTokenAt(1, "Copy") == true) {
// No warning...
} else {
Typo("Unrecognized volume option!");
return false;
}
} // end Volume
} // end third loop...
/////////////////////////////////////////////////////////////////////////////////////
// Fourth loop:
// Fill the detector not before everything else is done!
for (unsigned int i = 0; i < FileContent.size(); i++) {
m_DebugInfo = FileContent[i];
if (Tokenizer.Analyse(m_DebugInfo.GetText()) == false) {
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() < 2) continue;
// Check for detectors:
if ((D = GetDetector(Tokenizer.GetTokenAt(0))) != 0) {
// Check for global tokens
// Check for simulation in voxels instead of a junk volume
if (Tokenizer.IsTokenAt(1, "VoxelSimulation") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and 1 boolean,"
" e.g. \"Wafer.VoxelSimulation true\"");
return false;
}
if (Tokenizer.GetTokenAtAsBoolean(2) == true) {
D->UseDivisions(CreateShortName(MString("X" + D->GetName())),
CreateShortName(MString("Y" + D->GetName())),
CreateShortName(MString("Z" + D->GetName())));
}
}
// Check for sensitive volume
else if (Tokenizer.IsTokenAt(1, "SensitiveVolume") == true) {
// Check and reject named detector
if (D->IsNamedDetector() == true) {
Typo("SensitiveVolume cannot be used with a named detector! It's inherited from its template detector.");
return false;
}
// Test if volume exists:
if ((V = GetVolume(Tokenizer.GetTokenAt(2))) == 0) {
Typo("A volume of this name does not exist!");
return false;
}
D->AddSensitiveVolume(V);
}
// Check for detector volume
else if (Tokenizer.IsTokenAt(1, "DetectorVolume") == true) {
// Check and reject named detector
if (D->IsNamedDetector() == true) {
Typo("DetectorVolume cannot be used with a named detector! It's inherited from its template detector.");
return false;
}
// Test if volume exists:
if ((V = GetVolume(Tokenizer.GetTokenAt(2))) == 0) {
Typo("A volume of this name does not exist!");
return false;
}
D->SetDetectorVolume(V);
}
// Check for NoiseThresholdEqualsTriggerThreshold
else if (Tokenizer.IsTokenAt(1, "NoiseThresholdEqualsTriggerThreshold") == true ||
Tokenizer.IsTokenAt(1, "NoiseThresholdEqualTriggerThreshold") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain one string and one bool,"
" e.g. \"Wafer.NoiseThresholdEqualsTriggerThreshold true\"");
return false;
}
D->SetNoiseThresholdEqualsTriggerThreshold(Tokenizer.GetTokenAtAsBoolean(2));
}
// Check for noise threshold
else if (Tokenizer.IsTokenAt(1, "NoiseThreshold") == true) {
if (Tokenizer.GetNTokens() < 3 || Tokenizer.GetNTokens() > 4) {
Typo("Line must contain one string and 2 doubles,"
" e.g. \"Wafer.NoiseThreshold 30 10\"");
return false;
}
D->SetNoiseThreshold(Tokenizer.GetTokenAtAsDouble(2));
if (Tokenizer.GetNTokens() == 4) {
D->SetNoiseThresholdSigma(Tokenizer.GetTokenAtAsDouble(3));
}
}
// Check for trigger threshold
else if (Tokenizer.IsTokenAt(1, "TriggerThreshold") == true) {
if (Tokenizer.GetNTokens() < 3 || Tokenizer.GetNTokens() > 4) {
Typo("Line must contain one string and 2 double,"
" e.g. \"Wafer.TriggerThreshold 30 10\"");
return false;
}
D->SetTriggerThreshold(Tokenizer.GetTokenAtAsDouble(2));
if (Tokenizer.GetNTokens() == 4) {
D->SetTriggerThresholdSigma(Tokenizer.GetTokenAtAsDouble(3));
}
}
// Check for failure rate
else if (Tokenizer.IsTokenAt(1, "FailureRate") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain one string and 1 double,"
" e.g. \"Wafer.FailureRate 0.01\"");
return false;
}
D->SetFailureRate(Tokenizer.GetTokenAtAsDouble(2));
}
// Check for minimum and maximum overflow
else if (Tokenizer.IsTokenAt(1, "Overflow") == true) {
if (Tokenizer.GetNTokens() < 3 || Tokenizer.GetNTokens() > 4) {
Typo("Line must contain one string and 2 doubles,"
" e.g. \"Wafer.Overflow 350 100\"");
return false;
}
D->SetOverflow(Tokenizer.GetTokenAtAsDouble(2));
if (Tokenizer.GetNTokens() == 4) {
D->SetOverflowSigma(Tokenizer.GetTokenAtAsDouble(3));
} else {
D->SetOverflowSigma(0.0);
}
}
// Check for energy loss maps
else if (Tokenizer.IsTokenAt(1, "EnergyLossMap") == true) {
// Check and reject named detector
if (D->IsNamedDetector() == true) {
Typo("EnergyLossMap cannot be used with a named detector! It's inherited from its template detector.");
return false;
}
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings,"
" e.g. \"Wafer.EnergyLossMap MyEnergyLoss\"");
return false;
}
MString FileName = Tokenizer.GetTokenAt(2);
MFile::ExpandFileName(FileName, m_FileName);
if (MFile::Exists(FileName) == false) {
Typo("File does not exist.");
return false;
}
D->SetEnergyLossMap(FileName);
}
// Check for energy resolution
else if (Tokenizer.IsTokenAt(1, "EnergyResolutionAt") == true ||
Tokenizer.IsTokenAt(1, "EnergyResolution") == true) {
if (Tokenizer.GetNTokens() < 3) {
Typo("EnergyResolution keyword not correct.");
return false;
}
MString Type = Tokenizer.GetTokenAt(2);
char* Tester;
double d = strtod(Type.Data(), &Tester); if (d != 0) d = 0; // Just to prevent the compiler from complaining
if (Tester != Type.Data()) {
// We have a number - do it the old way
if (Tokenizer.GetNTokens() < 4 || Tokenizer.GetNTokens() > 6) {
Typo("Line must contain one string and 2-4 doubles,"
" e.g. \"Wafer.EnergyResolutionAt 662 39 (20 -2)\"");
return false;
}
mout<<" *** Deprectiated *** "<<endl;
mout<<"The \"EnergyResolution\" keyword format has changed. Please see the geomega manual."<<endl;
mout<<"Using a Gaussian resolution in compatibility mode."<<endl;
mout<<endl;
//FoundDepreciated = true;
D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeGauss);
if (Tokenizer.GetNTokens() == 4) {
D->SetEnergyResolution(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3));
} else if (Tokenizer.GetNTokens() == 5) {
D->SetEnergyResolution(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3));
} else if (Tokenizer.GetNTokens() == 6) {
D->SetEnergyResolution(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(2) + Tokenizer.GetTokenAtAsDouble(5),
Tokenizer.GetTokenAtAsDouble(3));
}
} else {
// New way:
Type.ToLower();
if (Type == "ideal" || Type == "perfect") {
D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeIdeal);
} else if (Type == "none" || Type == "no") {
D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeNone);
} else if (Type == "gauss" || Type == "gaus") {
if (Tokenizer.GetNTokens() != 6 ) {
Typo("EnergyResolution keyword not correct. Example:"
"\"Wafer.EnergyResolution Gauss 122 122 2.0\"");
return false;
}
if (D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeGauss &&
D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeUnknown) {
Typo("The energy resolution type cannot change!");
return false;
}
D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeGauss);
D->SetEnergyResolution(Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4),
Tokenizer.GetTokenAtAsDouble(5));
} else if (Type == "lorentz" || Type == "lorenz") {
if (Tokenizer.GetNTokens() != 6 ) {
Typo("EnergyResolution keyword not correct. Example:"
"\"Wafer.EnergyResolution Lorentz 122 122 2.0\"");
return false;
}
if (D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeLorentz &&
D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeUnknown) {
Typo("The energy resolution type cannot change!");
return false;
}
D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeLorentz);
D->SetEnergyResolution(Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4),
Tokenizer.GetTokenAtAsDouble(5));
} else if (Type == "gauslandau" || Type == "gausslandau" || Type == "gauss-landau") {
if (Tokenizer.GetNTokens() != 9 ) {
Typo("EnergyResolution keyword not correct. Example:"
"\"Wafer.EnergyResolution GaussLandau 122 122 2.0 122 3.0 0.2\"");
return false;
}
if (D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeGaussLandau &&
D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeUnknown) {
Typo("The energy resolution type cannot change!");
return false;
}
D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeGaussLandau);
D->SetEnergyResolution(Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4),
Tokenizer.GetTokenAtAsDouble(5),
Tokenizer.GetTokenAtAsDouble(6),
Tokenizer.GetTokenAtAsDouble(7),
Tokenizer.GetTokenAtAsDouble(8));
} else {
Typo("Unknown EnergyResolution parameters.");
return false;
}
}
}
// Check for energy resolution type
else if (Tokenizer.IsTokenAt(1, "EnergyResolutionType") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings,"
" e.g. \"Wafer.EnergyResolutionType Gauss\"");
return false;
}
if (Tokenizer.GetTokenAtAsString(2) == "Gauss" ||
Tokenizer.GetTokenAtAsString(2) == "Gaus") {
D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeGauss);
} else if (Tokenizer.GetTokenAtAsString(2) == "Lorentz") {
D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeLorentz);
} else {
Typo("Unkown energy resolution type!");
return false;
}
}
// Check for energy resolution type
else if (Tokenizer.IsTokenAt(1, "EnergyCalibration") == true) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings,"
" e.g. \"Wafer.EnergyCalibration File.dat\"");
return false;
}
MString FileName = Tokenizer.GetTokenAtAsString(2);
MFile::ExpandFileName(FileName, m_FileName);
MFunction Calibration;
if (Calibration.Set(FileName, "DP") == false) {
Typo("Unable to read file");
return false;
}
D->SetEnergyCalibration(Calibration);
}
// Check for time resolution
else if (Tokenizer.IsTokenAt(1, "TimeResolution") == true ||
Tokenizer.IsTokenAt(1, "TimeResolutionAt") == true) {
if (Tokenizer.GetNTokens() != 4) {
Typo("Line must contain one string and 2 doubles,"
" e.g. \"Wafer.TimeResolutionAt 662 0.0000001\"");
return false;
}
D->SetTimeResolution(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3));
}
// Check for pulse-form:
else if (Tokenizer.IsTokenAt(1, "PulseShape") == true) {
if (Tokenizer.GetNTokens() != 14) {
Typo("Line must contain one string and 12 doubles,"
" e.g. \"Wafer.PulseShape <10xFitParameter> FitStart FitStop\"");
return false;
}
D->SetPulseShape(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4),
Tokenizer.GetTokenAtAsDouble(5),
Tokenizer.GetTokenAtAsDouble(6),
Tokenizer.GetTokenAtAsDouble(7),
Tokenizer.GetTokenAtAsDouble(8),
Tokenizer.GetTokenAtAsDouble(9),
Tokenizer.GetTokenAtAsDouble(10),
Tokenizer.GetTokenAtAsDouble(11),
Tokenizer.GetTokenAtAsDouble(12),
Tokenizer.GetTokenAtAsDouble(13));
}
// Check for structural size
else if (Tokenizer.IsTokenAt(1, "StructuralSize") == true) {
mout<<" *** Deprectiated *** "<<endl;
mout<<"The \"StructuralSize\" keyword is no longer supported, since it contained redundant information"<<endl;
mout<<endl;
FoundDepreciated = true;
// if (Tokenizer.GetNTokens() != 5) {
// Typo("Line must contain one string and 3 doubles,"
// " e.g. \"Wafer.StructuralSize 0.0235, 3.008, 0.5\"");
// return false;
// }
// D->SetStructuralSize(MVector(Tokenizer.GetTokenAtAsDouble(2),
// Tokenizer.GetTokenAtAsDouble(3),
// Tokenizer.GetTokenAtAsDouble(4)));
}
// Check for structural offset
else if (Tokenizer.IsTokenAt(1, "StructuralOffset") == true) {
// Check and reject named detector
if (D->IsNamedDetector() == true) {
Typo("StructuralOffset cannot be used with a named detector! It's inherited from its template detector.");
return false;
}
if (Tokenizer.GetNTokens() != 5) {
Typo("Line must contain one string and 3 doubles,"
" e.g. \"Wafer.StructuralOffset 0.142, 0.142, 0.0\"");
return false;
}
D->SetStructuralOffset(MVector(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4)));
}
// Check for structural pitch
else if (Tokenizer.IsTokenAt(1, "StructuralPitch") == true) {
// Check and reject named detector
if (D->IsNamedDetector() == true) {
Typo("StructuralPitch cannot be used with a named detector! It's inherited from its template detector.");
return false;
}
if (Tokenizer.GetNTokens() != 5) {
Typo("Line must contain one string and 3 doubles,"
" e.g. \"Wafer.StructuralPitch 0.0, 0.0, 0.0\"");
return false;
}
D->SetStructuralPitch(MVector(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4)));
}
// Check for SiStrip specific tokens:
else if (Tokenizer.IsTokenAt(1, "Width") == true) {
mout<<" *** Deprectiated *** "<<endl;
mout<<"The \"Width\" keyword is no longer supported, since it contained redundant information"<<endl;
mout<<endl;
FoundDepreciated = true;
// if (D->GetDetectorType() != MDDetector::c_Strip2D &&
// D->GetDetectorType() != MDDetector::c_DriftChamber &&
// D->GetDetectorType() != MDDetector::c_Strip3D) {
// Typo("Option Width only supported for StripxD & DriftChamber");
// return false;
// }
// if (Tokenizer.GetNTokens() != 4) {
// Typo("Line must contain one string and 2 doubles,"
// " e.g. \"Wafer.Width 6.3, 6.3\"");
// return false;
// }
// dynamic_cast<MDStrip2D*>(D)->SetWidth(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3));
} else if (Tokenizer.IsTokenAt(1, "Pitch") == true) {
mout<<" *** Deprectiated *** "<<endl;
mout<<"The \"Pitch\" keyword is no longer supported, since it contained redundant information"<<endl;
mout<<endl;
FoundDepreciated = true;
// if (D->GetDetectorType() != MDDetector::c_Strip2D &&
// D->GetDetectorType() != MDDetector::c_Strip3D &&
// D->GetDetectorType() != MDDetector::c_DriftChamber) {
// Typo("Option Pitch only supported for StripxD & DriftChamber");
// return false;
// }
// if (Tokenizer.GetNTokens() != 4) {
// Typo("Line must contain one string and 2 doubles,"
// " e.g. \"Wafer.Pitch 0.047 0.047\"");
// return false;
// }
// dynamic_cast<MDStrip2D*>(D)->SetPitch(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3));
} else if (Tokenizer.IsTokenAt(1, "Offset") == true) {
// Check and reject named detector
if (D->IsNamedDetector() == true) {
Typo("Offset cannot be used with a named detector! It's inherited from its template detector.");
return false;
}
if (D->GetDetectorType() != MDDetector::c_Strip2D &&
D->GetDetectorType() != MDDetector::c_Strip3D &&
D->GetDetectorType() != MDDetector::c_Strip3DDirectional &&
D->GetDetectorType() != MDDetector::c_Voxel3D &&
D->GetDetectorType() != MDDetector::c_DriftChamber) {
Typo("Option Offset only supported for StripxD & DriftChamber");
return false;
}
if (D->GetDetectorType() == MDDetector::c_Voxel3D) {
if (Tokenizer.GetNTokens() != 5) {
Typo("Line must contain one string and 3 doubles,"
" e.g. \"Voxler.Offset 0.2 0.2 0.2\"");
return false;
}
dynamic_cast<MDVoxel3D*>(D)->SetOffset(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3), Tokenizer.GetTokenAtAsDouble(4));
} else {
if (Tokenizer.GetNTokens() != 4) {
Typo("Line must contain one string and 2 doubles,"
" e.g. \"Wafer.Offset 0.2 0.2\"");
return false;
}
dynamic_cast<MDStrip2D*>(D)->SetOffset(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3));
}
} else if (Tokenizer.IsTokenAt(1, "StripNumber") == true ||
Tokenizer.IsTokenAt(1, "Strip") == true ||
Tokenizer.IsTokenAt(1, "Strips") == true) {
// Check and reject named detector
if (D->IsNamedDetector() == true) {
Typo("StripNumber cannot be used with a named detector! It's inherited from its template detector.");
return false;
}
if (D->GetDetectorType() != MDDetector::c_Strip2D &&
D->GetDetectorType() != MDDetector::c_Strip3D &&
D->GetDetectorType() != MDDetector::c_Strip3DDirectional &&
D->GetDetectorType() != MDDetector::c_DriftChamber) {
Typo("Option StripNumber only supported for StripxD & DriftChamber");
return false;
}
if (Tokenizer.GetNTokens() != 4) {
Typo("Line must contain one string and 2 doubles,"
" e.g. \"Wafer.StripNumber 128 128\"");
return false;
}
dynamic_cast<MDStrip2D*>(D)->SetNStrips(Tokenizer.GetTokenAtAsInt(2), Tokenizer.GetTokenAtAsInt(3));
} else if (Tokenizer.IsTokenAt(1, "PixelNumber") == true ||
Tokenizer.IsTokenAt(1, "Pixels") == true ||
Tokenizer.IsTokenAt(1, "Pixel") == true ||
Tokenizer.IsTokenAt(1, "VoxelNumber") == true ||
Tokenizer.IsTokenAt(1, "Voxels") == true ||
Tokenizer.IsTokenAt(1, "Voxel") == true) {
if (D->GetDetectorType() != MDDetector::c_Voxel3D) {
Typo("Option Strip/Voxel number only supported for Voxel3D");
return false;
}
// Check and reject named detector
if (D->IsNamedDetector() == true) {
Typo("Pixels/voxels cannot be used with a named detector! It's inherited from its template detector.");
return false;
}
if (Tokenizer.GetNTokens() != 5) {
Typo("Line must contain one string and 3 doubles,"
" e.g. \"Voxler.StripNumber 128 128 128\"");
return false;
}
dynamic_cast<MDVoxel3D*>(D)->SetNVoxels(Tokenizer.GetTokenAtAsInt(2), Tokenizer.GetTokenAtAsInt(3), Tokenizer.GetTokenAtAsInt(4));
} else if (Tokenizer.IsTokenAt(1, "StripLength") == true) {
mout<<" *** Deprectiated *** "<<endl;
mout<<"The \"StripLength\" keyword is no longer supported, since it contained redundant information"<<endl;
mout<<endl;
FoundDepreciated = true;
// if (D->GetDetectorType() != MDDetector::c_Strip2D &&
// D->GetDetectorType() != MDDetector::c_Strip3D &&
// D->GetDetectorType() != MDDetector::c_DriftChamber) {
// Typo("Option StripLength only supported for StripxD & DriftChamber");
// return false;
// }
// if (Tokenizer.GetNTokens() != 4) {
// Typo("Line must contain one string and 2 doubles,"
// " e.g. \"Wafer.StripLength 6.016 6.016\"");
// return false;
// }
// dynamic_cast<MDStrip2D*>(D)->SetStripLength(Tokenizer.GetTokenAtAsDouble(2), Tokenizer.GetTokenAtAsDouble(3));
} else if (Tokenizer.IsTokenAt(1, "Orientation") == true) {
mout<<" *** Deprectiated *** "<<endl;
mout<<"The \"Orientation\" keyword is no longer supported, since it contained redundant information"<<endl;
mout<<endl;
FoundDepreciated = true;
// if (D->GetDetectorType() != MDDetector::c_Strip2D &&
// D->GetDetectorType() != MDDetector::c_Strip3D &&
// D->GetDetectorType() != MDDetector::c_DriftChamber) {
// Typo("Option StripLength only supported for StripxD & DriftChamber");
// return false;
// }
// if (Tokenizer.GetNTokens() != 3) {
// Typo("Line must contain one string and one integer,"
// " e.g. \"Wafer.Orientation 2\"");
// return false;
// }
// dynamic_cast<MDStrip2D*>(D)->SetOrientation(Tokenizer.GetTokenAtAsInt(2));
}
// Check for guard ring threshold
else if (Tokenizer.IsTokenAt(1, "GuardringTriggerThreshold") == true) {
if (D->GetDetectorType() != MDDetector::c_Strip2D &&
D->GetDetectorType() != MDDetector::c_Strip3D &&
D->GetDetectorType() != MDDetector::c_Voxel3D &&
D->GetDetectorType() != MDDetector::c_Strip3DDirectional &&
D->GetDetectorType() != MDDetector::c_DriftChamber) {
Typo("Option GuardRingTriggerThreshold only supported for StripxD & DriftChamber");
return false;
}
if (Tokenizer.GetNTokens() < 3 || Tokenizer.GetNTokens() > 4) {
Typo("Line must contain two strings and 2 double,"
" e.g. \"Wafer.GuardringTriggerThreshold 30 10\"");
return false;
}
if (D->GetDetectorType() == MDDetector::c_Voxel3D) {
dynamic_cast<MDVoxel3D*>(D)->SetGuardringTriggerThreshold(Tokenizer.GetTokenAtAsDouble(2));
if (Tokenizer.GetNTokens() == 4) {
dynamic_cast<MDVoxel3D*>(D)->SetGuardringTriggerThresholdSigma(Tokenizer.GetTokenAtAsDouble(3));
}
} else {
dynamic_cast<MDStrip2D*>(D)->SetGuardringTriggerThreshold(Tokenizer.GetTokenAtAsDouble(2));
if (Tokenizer.GetNTokens() == 4) {
dynamic_cast<MDStrip2D*>(D)->SetGuardringTriggerThresholdSigma(Tokenizer.GetTokenAtAsDouble(3));
}
}
}
// Check for guard ring energy resolution
else if (Tokenizer.IsTokenAt(1, "GuardringEnergyResolution") == true ||
Tokenizer.IsTokenAt(1, "GuardringEnergyResolutionAt") == true) {
if (D->GetDetectorType() != MDDetector::c_Strip2D &&
D->GetDetectorType() != MDDetector::c_Strip3D &&
D->GetDetectorType() != MDDetector::c_Voxel3D &&
D->GetDetectorType() != MDDetector::c_Strip3DDirectional &&
D->GetDetectorType() != MDDetector::c_DriftChamber) {
Typo("Option GuardringEnergyResolutionAt only supported for StripxD & DriftChamber");
return false;
}
if (Tokenizer.GetNTokens() != 4) {
Typo("Line must contain two strings and 2 doubles,"
" e.g. \"Wafer.GuardringEnergyResolutionAt 30 10\"");
return false;
}
if (D->GetDetectorType() == MDDetector::c_Voxel3D) {
if (dynamic_cast<MDVoxel3D*>(D)->SetGuardringEnergyResolution(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3)) == false) {
Typo("Incorrect input");
return false;
}
} else {
if (dynamic_cast<MDStrip2D*>(D)->SetGuardringEnergyResolution(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3)) == false) {
Typo("Incorrect input");
return false;
}
}
}
// Check for Calorimeter specific tokens:
else if (Tokenizer.IsTokenAt(1, "NoiseAxis") == true) {
mout<<" *** Unsupported *** "<<endl;
mout<<"The \"NoiseAxis\" keyword is no longer supported!"<<endl;
mout<<"For all detectors, the z-axis is by default the depth-noised axis"<<endl;
mout<<"For the depth resolution, use the \"DepthResolution\" keyword"<<endl;
mout<<endl;
FoundDepreciated = true;
}
else if (Tokenizer.IsTokenAt(1, "DepthResolution") == true ||
Tokenizer.IsTokenAt(1, "DepthResolutionAt") == true) {
bool Return = true;
if (D->GetDetectorType() == MDDetector::c_Calorimeter) {
if (Tokenizer.GetNTokens() == 4) {
Return = dynamic_cast<MDCalorimeter*>(D)->SetDepthResolutionAt(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3),
0);
} else if (Tokenizer.GetNTokens() == 5) {
Return = dynamic_cast<MDCalorimeter*>(D)->SetDepthResolutionAt(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4));
}
} else if (D->GetDetectorType() == MDDetector::c_Strip3D ||
D->GetDetectorType() == MDDetector::c_Strip3DDirectional ||
D->GetDetectorType() == MDDetector::c_DriftChamber) {
if (Tokenizer.GetNTokens() == 4) {
Return = dynamic_cast<MDStrip3D*>(D)->SetDepthResolutionAt(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3),
0);
} else if (Tokenizer.GetNTokens() == 5) {
Return = dynamic_cast<MDStrip3D*>(D)->SetDepthResolutionAt(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4));
}
} else {
Typo("Option DepthResolution only supported for Calorimeter, Strip3D, Strip3DDirectional, DriftChamber");
return false;
}
if (Return == false) {
Typo("Incorrect input");
return false;
}
}
else if (Tokenizer.IsTokenAt(1, "DepthResolutionThreshold") == true) {
if (D->GetDetectorType() == MDDetector::c_Strip3D ||
D->GetDetectorType() == MDDetector::c_Strip3DDirectional ||
D->GetDetectorType() == MDDetector::c_DriftChamber) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and 1 doubles,"
" e.g. \"Wafer.DepthResolutionThreshold 25.0\"");
return false;
}
dynamic_cast<MDStrip3D*>(D)->SetDepthResolutionThreshold(Tokenizer.GetTokenAtAsDouble(2));
} else {
Typo("Option DepthResolutionThreshold only supported for Strip3D, Strip3DDirectional, DriftChamber");
return false;
}
}
// Check for Scintillator specific tokens:
else if (Tokenizer.IsTokenAt(1, "HitPosition") == true) {
mout<<" *** Obsolete *** "<<endl;
mout<<"The \"HitPosition\" keyword is no longer necessary in the current version and thus not used - please delete it!"<<endl;
}
// Check for Strip3D and higher specific tokens:
else if (Tokenizer.IsTokenAt(1, "EnergyResolutionDepthCorrection") == true ||
Tokenizer.IsTokenAt(1, "EnergyResolutionDepthCorrectionAt") == true) {
if (D->GetDetectorType() != MDDetector::c_Strip3D &&
D->GetDetectorType() != MDDetector::c_Strip3DDirectional &&
D->GetDetectorType() != MDDetector::c_DriftChamber) {
Typo("Option EnergyResolutionDepthCorrectionAt only supported for StripxD & DriftChamber");
return false;
}
if (Tokenizer.GetNTokens() < 3) {
Typo("EnergyResolution keyword not correct.");
return false;
}
MString Type = Tokenizer.GetTokenAt(2);
char* Tester;
double d = strtod(Type.Data(), &Tester); if (d != 0) d = 0; // Just to prevent the compiler from complaining
if (Tester != Type.Data()) {
// We have a number - do it the old way
if (Tokenizer.GetNTokens() != 4) {
Typo("Line must contain one string and 2,"
" e.g. \"Wafer.EnergyResolutionDeothCorrection 0.0 1.0\"");
return false;
}
if (dynamic_cast<MDStrip3D*>(D)->SetEnergyResolutionDepthCorrection(Tokenizer.GetTokenAtAsDouble(2),
1.0,
Tokenizer.GetTokenAtAsDouble(3)) == false) {
Typo("Incorrect input");
return false;
}
} else {
// New way:
Type.ToLower();
if (Type == "gauss" || Type == "gaus") {
if (Tokenizer.GetNTokens() != 6 ) {
Typo("EnergyResolution keyword not correct. Example:"
"\"Wafer.EnergyResolutionDepthCorrection Gauss 1.0 122 2.0\"");
return false;
}
if (D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeGauss &&
D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeUnknown) {
Typo("The energy resolution type cannot change!");
return false;
}
D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeGauss);
dynamic_cast<MDStrip3D*>(D)->SetEnergyResolutionDepthCorrection(Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4),
Tokenizer.GetTokenAtAsDouble(5));
} else if (Type == "lorentz" || Type == "lorenz") {
if (Tokenizer.GetNTokens() != 6 ) {
Typo("EnergyResolution keyword not correct. Example:"
"\"Wafer.EnergyResolution Lorentz 122 122 2.0\"");
return false;
}
if (D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeLorentz &&
D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeUnknown) {
Typo("The energy resolution type cannot change!");
return false;
}
D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeLorentz);
dynamic_cast<MDStrip3D*>(D)->SetEnergyResolutionDepthCorrection(Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4),
Tokenizer.GetTokenAtAsDouble(5));
} else if (Type == "gauslandau" || Type == "gausslandau" || Type == "gauss-landau") {
if (Tokenizer.GetNTokens() != 9 ) {
Typo("EnergyResolution keyword not correct. Example:"
"\"Wafer.EnergyResolution GaussLandau 122 122 2.0 122 3.0 0.2\"");
return false;
}
if (D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeGaussLandau &&
D->GetEnergyResolutionType() != MDDetector::c_EnergyResolutionTypeUnknown) {
Typo("The energy resolution type cannot change!");
return false;
}
D->SetEnergyResolutionType(MDDetector::c_EnergyResolutionTypeGaussLandau);
dynamic_cast<MDStrip3D*>(D)->SetEnergyResolutionDepthCorrection(Tokenizer.GetTokenAtAsDouble(3),
Tokenizer.GetTokenAtAsDouble(4),
Tokenizer.GetTokenAtAsDouble(5),
Tokenizer.GetTokenAtAsDouble(6),
Tokenizer.GetTokenAtAsDouble(7),
Tokenizer.GetTokenAtAsDouble(8));
} else {
Typo("Unknown EnergyResolutionDepthCorrection parameters.");
return false;
}
}
}
else if (Tokenizer.IsTokenAt(1, "TriggerThresholdDepthCorrection") == true ||
Tokenizer.IsTokenAt(1, "TriggerThresholdDepthCorrectionAt") == true) {
if (D->GetDetectorType() != MDDetector::c_Strip3D &&
D->GetDetectorType() != MDDetector::c_Strip3DDirectional &&
D->GetDetectorType() != MDDetector::c_DriftChamber) {
Typo("Option TriggerThresholdDepthCorrectionAt only supported for StripxD & DriftChamber");
return false;
}
if (Tokenizer.GetNTokens() != 4) {
Typo("Line must contain two strings and 2 doubles,"
" e.g. \"Wafer.TriggerThresholdDepthCorrectionGuardringTriggerThresholdAt 30 10\"");
return false;
}
if (dynamic_cast<MDStrip3D*>(D)->SetTriggerThresholdDepthCorrection(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3)) == false) {
Typo("Incorrect input");
return false;
}
}
else if (Tokenizer.IsTokenAt(1, "NoiseThresholdDepthCorrection") == true ||
Tokenizer.IsTokenAt(1, "NoiseThresholdDepthCorrectionAt") == true) {
if (D->GetDetectorType() != MDDetector::c_Strip3D &&
D->GetDetectorType() != MDDetector::c_Strip3DDirectional &&
D->GetDetectorType() != MDDetector::c_DriftChamber) {
Typo("Option NoiseThresholdDepthCorrectionAt only supported for StripxD & DriftChamber");
return false;
}
if (Tokenizer.GetNTokens() != 4) {
Typo("Line must contain two strings and 2 doubles,"
" e.g. \"Wafer.NoiseThresholdDepthCorrectionGuardringNoiseThresholdAt 30 10\"");
return false;
}
if (dynamic_cast<MDStrip3D*>(D)->SetNoiseThresholdDepthCorrection(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3)) == false) {
Typo("Incorrect input");
return false;
}
}
// Check for Strip3DDirectional specific tokens:
else if (Tokenizer.IsTokenAt(1, "DirectionalResolution") == true ||
Tokenizer.IsTokenAt(1, "DirectionalResolutionAt") == true) {
if (D->GetDetectorType() == MDDetector::c_Strip3DDirectional) {
if (Tokenizer.GetNTokens() < 4 || Tokenizer.GetNTokens() > 5) {
Typo("Line must contain two strings and 2 doubles,"
" e.g. \"Wafer.DirectionResolutionAt 662 39\"");
return false;
}
if (Tokenizer.GetNTokens() == 4) {
dynamic_cast<MDStrip3DDirectional*>(D)
->SetDirectionalResolutionAt(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3)*c_Rad,
1E-6);
} else if (Tokenizer.GetNTokens() == 5) {
dynamic_cast<MDStrip3DDirectional*>(D)
->SetDirectionalResolutionAt(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3)*c_Rad,
Tokenizer.GetTokenAtAsDouble(4));
}
} else {
Typo("Option DirectionResolution only supported for Strip3DDirectional");
return false;
}
}
// Check for Anger camera specific tokens
else if (Tokenizer.IsTokenAt(1, "PositionResolution") == true ||
Tokenizer.IsTokenAt(1, "PositionResolutionAt") == true) {
if (D->GetDetectorType() != MDDetector::c_AngerCamera) {
Typo("Option PositionResolution only supported for AngerCamera");
return false;
}
if (Tokenizer.GetNTokens() != 4) {
Typo("Line must contain two strings and 2 doubles,"
" e.g. \"Wafer.PositionResolutionAt 30 10\"");
return false;
}
dynamic_cast<MDAngerCamera*>(D)->SetPositionResolution(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3));
} else if (Tokenizer.IsTokenAt(1, "Positioning") == true) {
if (D->GetDetectorType() == MDDetector::c_AngerCamera) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and 1 double:"
" e.g. \"Anger.Postioning XYZ\"");
return false;
}
if (Tokenizer.GetTokenAtAsString(2) == "XYZ") {
dynamic_cast<MDAngerCamera*>(D)->SetPositioning(MDGridPoint::c_XYZAnger);
} else if (Tokenizer.GetTokenAtAsString(2) == "XY") {
dynamic_cast<MDAngerCamera*>(D)->SetPositioning(MDGridPoint::c_XYAnger);
} else {
Typo("Unknown positioning type");
return false;
}
} else {
Typo("Option Positioning only supported for AngerCamera");
return false;
}
// Check for DriftChamber specific tokens:
} else if (Tokenizer.IsTokenAt(1, "LightSpeed") == true) {
if (D->GetDetectorType() == MDDetector::c_DriftChamber) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two string and 3 doubles:,"
" e.g. \"Chamber.LightSpeed 18E+9\"");
return false;
}
dynamic_cast<MDDriftChamber*>(D)->SetLightSpeed(Tokenizer.GetTokenAtAsDouble(2));
} else {
Typo("Option LightSpeed only supported for DriftChamber");
return false;
}
} else if (Tokenizer.IsTokenAt(1, "LightDetectorPosition") == true) {
if (D->GetDetectorType() == MDDetector::c_DriftChamber) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and 1 double:"
" e.g. \"Chamber.LightDetectorPosition 3\"");
return false;
}
dynamic_cast<MDDriftChamber*>(D)->SetLightDetectorPosition(Tokenizer.GetTokenAtAsInt(2));
} else {
Typo("Option LightDetectorPosition only supported for DriftChamber");
return false;
}
} else if (Tokenizer.IsTokenAt(1, "DriftConstant") == true) {
if (D->GetDetectorType() == MDDetector::c_DriftChamber) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two string and 1 double:"
" e.g. \"Chamber.DriftConstant 3\"");
return false;
}
dynamic_cast<MDDriftChamber*>(D)->SetDriftConstant(Tokenizer.GetTokenAtAsDouble(2));
} else {
Typo("Option DriftConstant only supported for DriftChamber");
return false;
}
} else if (Tokenizer.IsTokenAt(1, "EnergyPerElectron") == true) {
if (D->GetDetectorType() == MDDetector::c_DriftChamber) {
if (Tokenizer.GetNTokens() != 3) {
Typo("Line must contain two strings and 1 double:"
" e.g. \"Chamber.EnergyPerElectron 3\"");
return false;
}
dynamic_cast<MDDriftChamber*>(D)->SetEnergyPerElectron(Tokenizer.GetTokenAtAsDouble(2));
} else {
Typo("Option EnergyPerElectron only supported for DriftChamber");
return false;
}
} else if (Tokenizer.IsTokenAt(1, "LightEnergyResolution") == true ||
Tokenizer.IsTokenAt(1, "LightEnergyResolutionAt") == true) {
if (D->GetDetectorType() == MDDetector::c_DriftChamber) {
if (Tokenizer.GetNTokens() != 4) {
Typo("Line must contain two strings and 2 doubles,"
" e.g. \"Wafer.LightEnergyResolutionAt 662 39\"");
return false;
}
dynamic_cast<MDDriftChamber*>(D)
->SetLightEnergyResolution(Tokenizer.GetTokenAtAsDouble(2),
Tokenizer.GetTokenAtAsDouble(3));
} else {
Typo("Option LightEnergyResolution only supported for DriftChamber");
return false;
}
} else if (Tokenizer.IsTokenAt(1, "Assign") == true) {
// Handle this one after the volume tree is completed
} else if (Tokenizer.IsTokenAt(1, "BlockTrigger") == true) {
// Handle this one after validation of the detector
} else if (Tokenizer.IsTokenAt(1, "NamedDetector") == true || Tokenizer.IsTokenAt(1, "Named")) {
// Already handled
} else {
Typo("Unrecognized detector option");
return false;
}
} // end detector
// Now we have some unassigned token ...
else{
//Typo("Unrecognized option...");
//return false;
}
} // end fourth loop
++Stage;
if (Timer.ElapsedTime() > TimeLimit) {
mout<<"Stage "<<Stage<<" (analyzing all properties) finished after "<<Timer.ElapsedTime()<<" sec"<<endl;
}
if (m_WorldVolume == 0) {
mout<<" *** Error *** No world volume"<<endl;
mout<<"One volume needs to be the world volume!"<<endl;
mout<<"It is charcterized by e.g. \"WorldVolume.Mother 0\" (0 = nil)"<<endl;
mout<<"Stopping to scan geometry file!"<<endl;
Reset();
return false;
}
// The world volume is not allowed to have copies/clones
if (m_WorldVolume->GetNClones() > 0) {
mout<<" *** Error *** World volume"<<endl;
mout<<"World volume is not allowed to have copies/clones!"<<endl;
mout<<"Stopping to scan geometry file!"<<endl;
Reset();
return false;
}
if (m_WorldVolume->GetCloneTemplate() != 0) {
mout<<" *** Error *** World volume"<<endl;
mout<<"World volume is not allowed to be cloned/copied!"<<endl;
mout<<"Stopping to scan geometry file!"<<endl;
Reset();
return false;
}
//
if (ShowOnlySensitiveVolumes == true) {
for (unsigned int i = 0; i < GetNVolumes(); i++) {
if (GetVolumeAt(i)->IsSensitive() == true) {
GetVolumeAt(i)->SetVisibility(1);
} else {
GetVolumeAt(i)->SetVisibility(0);
}
}
}
// Validate the orientations
for (unsigned int s = 0; s < GetNOrientations(); ++s) {
if (m_OrientationList[s]->Validate() == false) {
Reset();
return false;
}
}
// Validate the shapes (attention: some shapes are valuated multiple times internally)...
for (unsigned int s = 0; s < GetNShapes(); ++s) {
if (m_ShapeList[s]->Validate() == false) {
Reset();
return false;
}
}
// Set a possible default color for all volumes:
if (m_DefaultColor >= 0) {
for (unsigned int i = 0; i < GetNVolumes(); i++) {
m_VolumeList[i]->SetColor(m_DefaultColor);
}
}
// Fill the clones with life:
for (unsigned int i = 0; i < GetNVolumes(); i++) {
if (m_VolumeList[i]->CopyDataToClones() == false) {
return false;
}
}
for (unsigned int i = 0; i < GetNMaterials(); i++) {
if (m_MaterialList[i]->CopyDataToClones() == false) {
return false;
}
}
for (unsigned int i = 0; i < GetNDetectors(); i++) {
if (m_DetectorList[i]->CopyDataToNamedDetectors() == false) {
return false;
}
}
if (m_ShowVolumes == false) {
for (unsigned int i = 0; i < GetNVolumes(); i++) {
if (m_VolumeList[i]->GetVisibility() <= 1) {
m_VolumeList[i]->SetVisibility(0);
}
}
}
// Scale some volumes:
map<MDVolume*, double>::iterator ScaleIter;
for (ScaleIter = ScaledVolumes.begin();
ScaleIter != ScaledVolumes.end(); ++ScaleIter) {
if ((*ScaleIter).first->IsClone() == false) {
(*ScaleIter).first->Scale((*ScaleIter).second);
} else {
mout<<" *** Error *** Scaling is not applicable to clones/copies"<<endl;
Reset();
return false;
}
}
m_WorldVolume->ResetCloneTemplateFlags();
++Stage;
if (Timer.ElapsedTime() > TimeLimit) {
mout<<"Stage "<<Stage<<" (generating clones) finished after "<<Timer.ElapsedTime()<<" sec"<<endl;
}
for (unsigned int i = 0; i < GetNVolumes(); i++) {
if (m_VolumeList[i] != 0) {
//cout<<(int) m_VolumeList[i]<<"!"<<m_VolumeList[i]->GetName()<<endl;
//cout<<m_VolumeList[i]->ToString()<<endl;
}
}
if (m_WorldVolume->Validate() == false) {
return false;
}
// Virtualize non-detector volumes
if (m_VirtualizeNonDetectorVolumes == true) {
mout<<" *** Info *** "<<endl;
mout<<"Non-detector volumes are virtualized --- you cannot calculate absorptions!"<<endl;
m_WorldVolume->VirtualizeNonDetectorVolumes();
}
m_WorldVolume->RemoveVirtualVolumes();
// mimp<<"Error if there are not positioned volumes --> otherwise GetRandomPosition() fails"<<endl;
if (m_WorldVolume->Validate() == false) {
return false;
}
if (VirtualizeNonDetectorVolumes == false) {
if (m_WorldVolume->ValidateClonesHaveSameMotherVolume() == false) {
return false;
}
}
// A final loop over the data checks for the detector keyword "Assign"
// We need a final volume tree, thus this is really the final loop
for (unsigned int i = 0; i < FileContent.size(); i++) {
m_DebugInfo = FileContent[i];
if (Tokenizer.Analyse(m_DebugInfo.GetText()) == false) {
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() < 2) continue;
// Check for detectors:
if ((D = GetDetector(Tokenizer.GetTokenAt(0))) != 0) {
// Check for global tokens
// Check for simulation in voxels instead of a junk volume
if (Tokenizer.IsTokenAt(1, "Assign") == true) {
if (D->IsNamedDetector() == false) {
Typo("The Assign keyword can only be used with named detectors");
return false;
}
MVector Pos;
if (Tokenizer.GetNTokens() == 3) {
vector<MString> VolumeNames = Tokenizer.GetTokenAtAsString(2).Tokenize(".");
if (VolumeNames.size() == 0) {
Typo("The volume sequence is empty!");
return false;
}
if (m_WorldVolume->GetName() != VolumeNames[0]) {
Typo("The volume sequence must start with the world volume!");
return false;
}
MDVolumeSequence Seq;
MDVolume* Start = m_WorldVolume;
Seq.AddVolume(Start);
for (unsigned int i = 1; i < VolumeNames.size(); ++i) {
bool Found = false;
for (unsigned int v = 0; v < Start->GetNDaughters(); ++v) {
//cout<<"Looking for "<<VolumeNames[i]<<" in "<<Start->GetDaughterAt(v)->GetName()<<endl;
if (Start->GetDaughterAt(v)->GetName() == VolumeNames[i]) {
Found = true;
Start = Start->GetDaughterAt(v);
Seq.AddVolume(Start);
//cout<<"Found: "<<VolumeNames[i]<<endl;
break;
}
}
if (Found == false) {
Typo("Cannot find all volumes in the volume sequence! Make sure you placed the right volumes!");
return false;
}
}
if (Start->GetDetector() == 0) {
Typo("The volume sequence does not point to a detector!");
return false;
}
if (Start->GetDetector() != D->GetNamedAfterDetector()) {
Typo("The volume sequence does not point to the right detector!");
return false;
}
if (Start->IsSensitive() == 0) {
Typo("The volume sequence does not point to a sensitive volume!");
return false;
}
Pos = Start->GetShape()->GetRandomPositionInside();
Pos = Seq.GetPositionInFirstVolume(Pos, Start);
}
else if (Tokenizer.GetNTokens() == 5) {
Pos[0] = Tokenizer.GetTokenAtAsDouble(2);
Pos[1] = Tokenizer.GetTokenAtAsDouble(3);
Pos[2] = Tokenizer.GetTokenAtAsDouble(4);
}
else {
Typo("Line must contain two strings and one volume sequence (\"NamedWafer.Assign WorldVolume.Tracker.Wafer1\")"
" or two strings and three numbers as absolute position (\"NamedWafer.Assign 12.0 0.0 0.0\")");
return false;
}
MDVolumeSequence* VS = new MDVolumeSequence();
m_WorldVolume->GetVolumeSequence(Pos, VS);
D->SetVolumeSequence(*VS);
delete VS;
}
}
}
// Take care of the start volume:
if (m_StartVolume != "") {
MDVolume* SV = 0;
mout<<"Trying to set start volume as world volume ... ";
if ((SV = GetVolume(m_StartVolume)) != 0) {
if (SV->IsVirtual() == true) {
mout<<"impossible, it's a virtual volume..."<<endl;
mgui<<"Start volume cannot be shown, because it's a virtual volume. Showing whole geometry."<<error;
} else if (SV->GetMother() == 0 && SV != m_WorldVolume) {
mout<<"impossible, it's not a regular positioned volume, but a clone template..."<<endl;
mgui<<"Start volume cannot be shown, because it's not a regular positioned volume, but a clone template. Showing whole geometry."<<error;
} else {
// Determine the correct rotation and position of this volume, to keep all positions correct:
MVector Position(0, 0, 0);
TMatrixD Rotation;
Rotation.ResizeTo(3,3);
Rotation(0,0) = 1;
Rotation(1,1) = 1;
Rotation(2,2) = 1;
MDVolume* Volume = SV;
while (Volume->GetMother() != 0) {
Position = Volume->GetInvRotationMatrix()*Position;
Position += Volume->GetPosition();
Rotation *= Volume->GetInvRotationMatrix();
Volume = Volume->GetMother();
}
if (Volume != m_WorldVolume) {
mout<<"impossible, it doesn't have a regular volume tree..."<<endl;
mgui<<"Start volume cannot be shown, because it doesn't have a regular volume tree. Showing whole geometry."<<error;
} else {
m_WorldVolume->RemoveAllDaughters();
SV->SetMother(m_WorldVolume);
SV->SetPosition(Position);
SV->SetRotation(Rotation);
mout<<"done"<<endl;
}
}
} else {
mout<<"failed!"<<endl;
mgui<<"Start volume not found in volume tree."<<error;
}
}
// Take care of preferred visible volumes
if (m_PreferredVisibleVolumeNames.size() > 0) {
// Take care of preferred visible volumes - make everything not visible
if (m_PreferredVisibleVolumeNames.size() > 0) {
for (unsigned int i = 0; i < GetNVolumes(); i++) {
m_VolumeList[i]->SetVisibility(0);
for (unsigned int c = 0; c < GetVolumeAt(i)->GetNClones(); ++c) {
GetVolumeAt(i)->GetCloneAt(c)->SetVisibility(0);
}
}
}
bool FoundOne = false;
for (auto N: m_PreferredVisibleVolumeNames) {
for (unsigned int i = 0; i < GetNVolumes(); i++) {
if (GetVolumeAt(i)->GetName() == N) {
GetVolumeAt(i)->SetVisibility(1);
FoundOne = true;
}
for (unsigned int c = 0; c < GetVolumeAt(i)->GetNClones(); ++c) {
if (GetVolumeAt(i)->GetCloneAt(c)->GetName() == N) {
GetVolumeAt(i)->GetCloneAt(c)->SetVisibility(1);
FoundOne = true;
}
}
}
}
if (FoundOne == false) {
mout<<"ERROR: None of your preferred visible volumes has been found!"<<endl;
}
}
//
// Validation routines for the detectors:
//
// Determine the common volume for all sensitive volumes of all detectors
for (unsigned int i = 0; i < GetNDetectors(); i++) {
if (m_DetectorList[i]->GetNSensitiveVolumes() > 1) {
// Check that the sensitive volumes are no copies
for (unsigned int l = 0; l < m_DetectorList[i]->GetNSensitiveVolumes(); ++l) {
//cout<<"clone test for "<<m_DetectorList[i]->GetSensitiveVolume(l)->GetName()<<endl;
if (m_DetectorList[i]->GetSensitiveVolume(l)->IsClone() == true || m_DetectorList[i]->GetSensitiveVolume(l)->IsCloneTemplate() == true ) {
Typo("If your detector has multiple sensitive volumes, then those cannot by copies or a template for copies.");
return false;
}
}
vector<vector<MDVolume*> > Volumes;
for (unsigned int l = 0; l < m_DetectorList[i]->GetNSensitiveVolumes(); ++l) {
vector<MDVolume*> MotherVolumes;
MotherVolumes.push_back(m_DetectorList[i]->GetSensitiveVolume(l));
//cout<<"Tree "<<l<<": "<<MotherVolumes.back()->GetName()<<endl;
while (MotherVolumes.back() != 0 && MotherVolumes.back()->GetMother()) {
MotherVolumes.push_back(MotherVolumes.back()->GetMother());
//cout<<"Tree "<<l<<": "<<MotherVolumes.back()->GetName()<<endl;
}
Volumes.push_back(MotherVolumes);
}
// Replace volumes by mother volumes until we have a common mother, or reached the end of the volume tree
// Loop of all mothers of the first volume --- those are the test volumes
for (unsigned int m = 0; m < Volumes[0].size(); ++m) {
MDVolume* Test = Volumes[0][m];
if (Test == 0) break;
//cout<<"Testing: "<<Test->GetName()<<endl;
bool FoundTest = true;
for (unsigned int l = 1; l < Volumes.size(); ++l) {
bool Found = false;
for (unsigned int m = 0; m < Volumes[l].size(); ++m) {
//cout<<"Comparing to: "<<Volumes[l][m]->GetName()<<" of tree "<<Volumes[l][0]->GetName()<<endl;
if (Test == Volumes[l][m]) {
//cout<<"Found sub"<<endl;
Found = true;
break;
}
}
if (Found == false) {
FoundTest = false;
break;
}
}
if (FoundTest == true) {
m_DetectorList[i]->SetCommonVolume(Test);
mout<<"Common mother volume for sensitive detectors of "<<m_DetectorList[i]->GetName()<<": "<<Test->GetName()<<endl;
break;
}
}
if (m_DetectorList[i]->GetCommonVolume() == 0) {
mout<<" *** Error *** Multiple sensitive volumes per detector restriction"<<endl;
mout<<"If your detector has multiple sensitive volumes, those must have a common volume and there are no copies allowed starting with the sensitive volume up to the common volume."<<endl;
mout<<"Stopping to scan geometry file!"<<endl;
Reset();
return false;
}
}
// The common volume is automatically set to the detector volume in MDetector::Validate(), if there is only one sensitive volume
// Make sure there is always only one sensitive volume of a certain type in the common volume
// Due to the above checks it is enough to simply check the number of sensitive volumes in the common volume
if (m_DetectorList[i]->GetNSensitiveVolumes() > 1 && m_DetectorList[i]->GetNSensitiveVolumes() != m_DetectorList[i]->GetCommonVolume()->GetNSensitiveVolumes()) {
mout<<" *** Error *** Multiple sensitive volumes per detector restriction"<<endl;
mout<<"If your detector has multiple sensitive volumes, those must have a common volume, in which exactly one of those volumes is positioned, and in addition no other sensitive volume. The latter is not the case."<<endl;
mout<<"Stopping to scan geometry file!"<<endl;
Reset();
return false;
}
}
bool IsValid = true;
for (unsigned int i = 0; i < GetNDetectors(); i++) {
if (m_DetectorList[i]->Validate() == false) {
IsValid = false;
}
m_NDetectorTypes[m_DetectorList[i]->GetDetectorType()]++;
}
// Special detector loop for blocked channels:
for (unsigned int i = 0; i < FileContent.size(); i++) {
m_DebugInfo = FileContent[i];
if (Tokenizer.Analyse(m_DebugInfo.GetText()) == false) {
Typo("Tokenizer error");
return false;
}
if (Tokenizer.GetNTokens() < 2) continue;
// Check for detectors:
if ((D = GetDetector(Tokenizer.GetTokenAt(0))) != 0) {
// Check for simulation in voxels instead of a junk volume
if (Tokenizer.IsTokenAt(1, "BlockTrigger") == true) {
if (Tokenizer.GetNTokens() != 4) {
Typo("Line must contain two strings and 2 integerd,"
" e.g. \"Wafer.BlockTrigger 0 0 \"");
return false;
}
D->BlockTriggerChannel(Tokenizer.GetTokenAtAsInt(2),
Tokenizer.GetTokenAtAsInt(3));
}
}
}
// Trigger sanity checks:
for (unsigned int i = 0; i < GetNTriggers(); i++) {
if (m_TriggerList[i]->Validate() == false) {
IsValid = false;
}
}
// Make sure that all detectors which have only veto triggers have NoiseThresholdEqualsTriggerThreshold setf
for (unsigned int d = 0; d < GetNDetectors(); ++d) {
int NVetoes = 0;
int NTriggers = 0;
for (unsigned int t = 0; t < GetNTriggers(); ++t) {
if (GetTriggerAt(t)->Applies(GetDetectorAt(d)) == true) {
if (GetTriggerAt(t)->IsVeto() == true) {
NVetoes++;
} else {
NTriggers++;
}
}
}
if (NVetoes > 0 && NTriggers == 0 && GetDetectorAt(d)->GetNoiseThresholdEqualsTriggerThreshold() == false) {
mout<<" *** Error *** Triggers with vetoes"<<endl;
mout<<"A detector (here: "<<GetDetectorAt(d)->GetName()<<"), which only has veto triggers, must have the flag \"NoiseThresholdEqualsTriggerThreshold true\"!"<<endl;
Reset();
return false;
}
}
// Material sanity checks
for (unsigned int i = 0; i < GetNMaterials(); i++) {
m_MaterialList[i]->SetCrossSectionFileDirectory(m_CrossSectionFileDirectory);
if (m_MaterialList[i]->Validate() == false) {
IsValid = false;
}
}
// Check if all cross sections are present if not try to create them
bool CrossSectionsPresent = true;
for (unsigned int i = 0; i < GetNMaterials(); i++) {
if (m_MaterialList[i]->AreCrossSectionsPresent() == false) {
CrossSectionsPresent = false;
break;
}
}
if (CrossSectionsPresent == false && AllowCrossSectionCreation == true) {
if (CreateCrossSectionFiles() == false) {
mout<<" *** Warning *** "<<endl;
mout<<"Not all cross section files are present!"<<endl;
}
}
// Check if we can apply the keyword komplex ER
// Does not cover all possibilities (e.g. rotated detector etc.)
if (m_ComplexER == false) {
int NTrackers = 0;
for (unsigned int i = 0; i < GetNDetectors(); i++) {
if (m_DetectorList[i]->GetDetectorType() == MDDetector::c_Strip2D) {
if (dynamic_cast<MDStrip2D*>(m_DetectorList[i])->GetOrientation() != 2) {
mout<<" *** Error *** ComplexER"<<endl;
mout<<"This keyword can only be applied for tracker which are oriented in z-axis!"<<endl;
Reset();
return false;
} else {
NTrackers++;
}
}
}
if (NTrackers > 1) {
mout<<" *** Error *** ComplexER"<<endl;
mout<<"This keyword can only be applied if only one or none tracker is available!"<<endl;
Reset();
return false;
}
}
// We need a trigger criteria
if (GetNTriggers() == 0) {
mout<<" *** Warning *** "<<endl;
mout<<"You have not defined any trigger criteria!!"<<endl;
} else {
// Check if each detector has a trigger criterion:
vector<MDDetector*> Detectors;
for (unsigned int i = 0; i < GetNDetectors(); ++i) Detectors.push_back(m_DetectorList[i]);
for (unsigned int t = 0; t < GetNTriggers(); ++t) {
vector<MDDetector*> TriggerDetectors = m_TriggerList[t]->GetDetectors();
for (unsigned int d1 = 0; d1 < Detectors.size(); ++d1) {
for (unsigned int d2 = 0; d2 < TriggerDetectors.size(); ++d2) {
if (Detectors[d1] == 0) continue;
if (Detectors[d1] == TriggerDetectors[d2]) {
Detectors[d1] = 0;
break;
}
// If we have a named detectors, in case the "named after detector" has a trigger criteria, we are fine
if (Detectors[d1]->IsNamedDetector() == true) {
if (Detectors[d1]->GetNamedAfterDetector() == TriggerDetectors[d2]) {
Detectors[d1] = 0;
break;
}
}
}
}
vector<int> TriggerDetectorTypes = m_TriggerList[t]->GetDetectorTypes();
for (unsigned int d1 = 0; d1 < Detectors.size(); ++d1) {
if (Detectors[d1] == 0) continue;
for (unsigned int d2 = 0; d2 < TriggerDetectorTypes.size(); ++d2) {
if (Detectors[d1]->GetDetectorType() == TriggerDetectorTypes[d2]) {
Detectors[d1] = 0;
break;
}
}
}
}
for (unsigned int i = 0; i < Detectors.size(); ++i) {
if (Detectors[i] != 0) {
mout<<" *** Warning *** "<<endl;
mout<<"You have not defined any trigger criterion for detector: "<<Detectors[i]->GetName()<<endl;
}
}
}
if (IsValid == false) {
mout<<" *** Error *** "<<endl;
mout<<"There were errors while scanning this file. Correct them first!!"<<endl;
Reset();
return false;
}
++Stage;
if (Timer.ElapsedTime() > TimeLimit) {
mout<<"Stage "<<Stage<<" (validation & post-processing) finished after "<<Timer.ElapsedTime()<<" sec"<<endl;
}
// Geant4 requires that the world volume is the first volume in the list
// Thus resort the list
m_VolumeList.erase(find(m_VolumeList.begin(), m_VolumeList.end(), m_WorldVolume));
m_VolumeList.insert(m_VolumeList.begin(), m_WorldVolume);
// The last stage is to optimize the geometry for hit searches:
m_WorldVolume->OptimizeVolumeTree();
m_GeometryScanned = true;
++Stage;
if (Timer.ElapsedTime() > TimeLimit) {
mout<<"Stage "<<Stage<<" (volume tree optimization) finished after "<<Timer.ElapsedTime()<<" sec"<<endl;
}
mdebug<<"Geometry "<<m_FileName<<" successfully scanned within "<<Timer.ElapsedTime()<<"s"<<endl;
mdebug<<"It contains "<<GetNVolumes()<<" volumes"<<endl;
if (FoundDepreciated == true) {
mgui<<"Your geometry contains depreciated information (see console output for details)."<<endl;
mgui<<"Please update it now to the latest conventions!"<<show;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::AddFile(MString FileName, vector<MDDebugInfo>& FileContent)
{
FileContent.clear();
MFile::ExpandFileName(FileName);
// First edit the file name:
if (gSystem->IsAbsoluteFileName(FileName) == false) {
FileName = MFile::GetDirectoryName(m_FileName) + MString("/") + FileName;
}
if (gSystem->AccessPathName(FileName) == 1) {
mout<<" *** Error *** "<<endl;
mout<<"Included file \""<<FileName<<"\" does not exist."<<endl;
return false;
}
if (IsIncluded(FileName) == true) {
//mout<<" *** Warning *** "<<endl;
//mout<<"The file has been included multiple times: "<<FileName<<endl;
return true;
}
int LineCounter = 0;
int LineLength = 10000;
char* LineBuffer = new char[LineLength];
ifstream FileStream;
FileStream.open(FileName);
if (FileStream.is_open() == 0) {
mout<<" *** Error *** "<<endl;
mout<<"Can't open file "<<FileName<<endl;
delete [] LineBuffer;
return false;
}
int Comment = 0;
MTokenizer Tokenizer;
MDDebugInfo Info;
while (FileStream.getline(LineBuffer, LineLength, '\n')) {
Info = MDDebugInfo(LineBuffer, FileName, LineCounter++);
Tokenizer.Analyse(Info.GetText(), false);
if (Tokenizer.GetNTokens() >=1 && Tokenizer.GetTokenAt(0) == "Exit") {
mout<<"Found \"Exit\" in file "<<FileName<<endl;
break;
}
if (Tokenizer.GetNTokens() >= 1 && Tokenizer.GetTokenAt(0) == "EndComment") {
//mout<<"Found \"EndComment\" in file "<<FileName<<endl;
Comment--;
if (Comment < 0) {
mout<<" *** Error *** "<<endl;
mout<<"Found \"EndComment\" without \"BeginComment\" in file "<<FileName<<endl;
FileContent.clear();
delete [] LineBuffer;
return false;
}
continue;
}
if (Tokenizer.GetNTokens() >= 1 && Tokenizer.GetTokenAt(0) == "BeginComment") {
//mout<<"Found \"BeginComment\" in file "<<FileName<<endl;
Comment++;
continue;
}
if (Comment == 0) {
FileContent.push_back(Info);
}
}
// Add an empty line, just in case the file didn't end with a new line
FileContent.push_back(MDDebugInfo(" ", FileName, LineCounter++));
AddInclude(FileName);
delete [] LineBuffer;
FileStream.close();
return true;
}
////////////////////////////////////////////////////////////////////////////////
void MDGeometry::Typo(MString Typo)
{
// Print an error message
mout<<" *** Error *** in setup file "<<m_DebugInfo.GetFileName()<<" at line "<<m_DebugInfo.GetLine()<<":"<<endl;
mout<<"\""<<m_DebugInfo.GetText()<<"\""<<endl;
mout<<Typo<<endl;
mout<<"Stopping to scan geometry file!"<<endl;
Reset();
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::NameExists(MString Name)
{
// Return true if the name Name already exists
// Since all new names pass through this function (because we have to check
// if it already exists), we can make sure that we are case insensitive!
for (unsigned int i = 0; i < GetNVolumes(); i++) {
if (Name.AreIdentical(m_VolumeList[i]->GetName(), true)) {
Typo("A volume of this name (case insensitive) already exists!");
return true;
}
}
for (unsigned int i = 0; i < GetNMaterials(); i++) {
if (Name.AreIdentical(m_MaterialList[i]->GetName(), true)) {
Typo("A material of this name (case insensitive) already exists!");
return true;
}
}
for (unsigned int i = 0; i < GetNDetectors(); i++) {
if (Name.AreIdentical(m_DetectorList[i]->GetName(), true)) {
Typo("A detector of this name (case insensitive) already exists!");
return true;
}
}
for (unsigned int i = 0; i < GetNTriggers(); i++) {
if (Name.AreIdentical(m_TriggerList[i]->GetName(), true)) {
Typo("A trigger of this name (case insensitive) already exists!");
return true;
}
}
for (unsigned int i = 0; i < GetNVectors(); i++) {
if (Name.AreIdentical(m_VectorList[i]->GetName(), true)) {
Typo("A vector of this name (case insensitive) already exists!");
return true;
}
}
for (unsigned int i = 0; i < m_ConstantList.size(); i++) {
if (Name.AreIdentical(m_ConstantList[i], true)) {
Typo("A constant of this name (case insensitive) already exists!");
return true;
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::DrawGeometry(TCanvas* Canvas)
{
// The geometry must have been loaded previously
// You cannot display 2 geometries at once!
if (m_GeometryScanned == false) {
mgui<<"Geometry has to be scanned before it can be drawn!"<<endl;
return false;
}
// Start by deleting the old windows:
if (m_GeoView != 0) {
if (gROOT->FindObject("MainCanvasGeomega") != 0) {
delete m_GeoView;
}
m_GeoView = 0;
}
mdebug<<"NVolumes: "<<m_WorldVolume->GetNVisibleVolumes()<<endl;
// Only draw the new windows if there are volumes to be drawn:
if (m_WorldVolume->GetNVisibleVolumes() == 0) {
mgui<<"There are no visible volumes in your geometry!"<<warn;
return false;
}
MTimer Timer;
double TimerLimit = 5;
if (Canvas == 0) {
m_GeoView = new TCanvas("MainCanvasGeomega","MainCanvasGeomega",800,800);
} else {
Canvas->cd();
}
m_WorldVolume->CreateRootGeometry(m_Geometry, 0);
// m_Geometry->CloseGeometry(); // we do not close the geometry,
m_Geometry->SetMultiThread(true);
m_Geometry->SetVisLevel(1000);
m_Geometry->SetNsegments(2*m_Geometry->GetNsegments());
m_Geometry->SetVisDensity(-1.0);
//m_Geometry->Voxelize("ALL");
// Make sure we use the correct geometry for interactions
gGeoManager = m_Geometry;
if (m_Geometry->GetTopVolume() != 0) m_Geometry->GetTopVolume()->Draw("ogle");
if (m_Geometry->GetListOfNavigators() == nullptr) {
m_Geometry->AddNavigator();
}
m_Geometry->SetCurrentNavigator(0);
if (Timer.ElapsedTime() > TimerLimit) {
mout<<"Geometry drawn within "<<Timer.ElapsedTime()<<"s"<<endl;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::AreCrossSectionsPresent()
{
// Check if all absorption files are present:
for (unsigned int i = 0; i < m_MaterialList.size(); ++i) {
if (m_MaterialList[i]->AreCrossSectionsPresent() == false) {
return false;
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::TestIntersections()
{
// Test for intersections
// Attention: Not all can be found!
cout<<"Testing intersections!"<<endl;
if (IsScanned() == false) {
Error("bool MDGeometry::TestIntersections()",
"You have to scan the geometry file first!");
return false;
}
if (m_WorldVolume->ValidateIntersections() == false) {
return false;
}
cout<<"Testing intersections finished!"<<endl;
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::CheckOverlaps()
{
// Check for overlaps using the ROOT overlap checker
if (IsScanned() == false) {
Error("bool MDGeometry::TestIntersections()",
"You have to scan the geometry file first!");
return false;
}
m_WorldVolume->CreateRootGeometry(m_Geometry, 0);
m_Geometry->CloseGeometry();
m_Geometry->CheckOverlaps(0.000001);
TObjArray* Overlaps = m_Geometry->GetListOfOverlaps();
if (Overlaps->GetEntries() > 0) {
mout<<"List of extrusions and overlaps: "<<endl;
for (int i = 0; i < Overlaps->GetEntries(); ++i) {
TGeoOverlap* O = (TGeoOverlap*) (Overlaps->At(i));
if (O->IsOverlap() == true) {
mout<<"Overlap: "<<O->GetFirstVolume()->GetName()<<" with "<<O->GetSecondVolume()->GetName()<<" by "<<O->GetOverlap()<<" cm"<<endl;
}
if (O->IsExtrusion() == true) {
mout<<"Extrusion: "<<O->GetSecondVolume()->GetName()<<" extrudes "<<O->GetFirstVolume()->GetName()<<" by "<<O->GetOverlap()<<" cm"<<endl;
}
}
} else {
mout<<endl;
mout<<"No extrusions and overlaps detected with ROOT (ROOT claims to be able to detect 95% of them)"<<endl;
}
return Overlaps->GetEntries() > 0 ? false : true;
}
////////////////////////////////////////////////////////////////////////////////
void MDGeometry::DumpInformation()
{
// Dump the geometry information:
if (IsScanned() == false) {
Error("bool MDGeometry::DumpInformation()",
"You have to scan the geometry file first!");
return;
}
cout<<ToString()<<endl;
}
////////////////////////////////////////////////////////////////////////////////
void MDGeometry::CalculateMasses()
{
// Calculate the masses of the geometry
if (IsScanned() == false) {
Error("bool MDGeometry::DumpInformation()",
"You have to scan the geometry file first!");
return;
}
double Total = 0;
map<MDMaterial*, double> Masses;
map<MDMaterial*, double>::iterator MassesIter;
m_WorldVolume->GetMasses(Masses);
size_t NameWidth = 0;
for (MassesIter = (Masses.begin());
MassesIter != Masses.end(); MassesIter++) {
if ((*MassesIter).first->GetName().Length() > NameWidth) {
NameWidth = (*MassesIter).first->GetName().Length();
}
}
ostringstream out;
out.setf(ios_base::fixed, ios_base::floatfield);
out.precision(3);
out<<endl;
out<<"Mass summary by material: "<<endl;
out<<endl;
for (MassesIter = (Masses.begin());
MassesIter != Masses.end(); MassesIter++) {
out<<setw(NameWidth+2)<<(*MassesIter).first->GetName()<<" : "<<setw(12)<<(*MassesIter).second<<" g"<<endl;
Total += (*MassesIter).second;
}
out<<endl;
out<<setw(NameWidth+2)<<"Total"<<" : "<<setw(12)<<Total<<" g"<<endl;
out<<endl;
out<<"No warranty for this information!"<<endl;
out<<"This information is only valid, if "<<endl;
out<<"(a) No volume intersects any volume which is not either its mother or daughter."<<endl;
out<<"(b) All daughters lie completely inside their mothers"<<endl;
out<<"(c) The material information is correct"<<endl;
out<<"(d) tbd."<<endl;
mout<<out.str()<<endl;
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::WriteGeant3Files()
{
// Create GEANT3 files
if (m_GeometryScanned == false) {
Error("bool MDGeometry::WriteGeant3Files()",
"Geometry has to be scanned first");
return false;
}
// Some sanity checks:
if (GetNMaterials() > 200) {
mout<<"Error: GMega only supports 200 materials at the moment!"<<endl;
return false;
}
// open the geometry-file:
fstream FileStream; // = new fstream();
// gcc 2.95.3: FileStream.open("ugeom.f", ios::out, 0664);
FileStream.open("ugeom.f", ios_base::out);
// Write header:
ostringstream Text;
Text<<
"************************************************************************\n"
"*\n"
"* Copyright (C) by the MEGA-team.\n"
"* All rights reserved.\n"
"*\n"
"*\n"
"* This code implementation is the intellectual property of the \n"
"* MEGA-team at MPE.\n"
"*\n"
"* By copying, distributing or modifying the Program (or any work\n"
"* based on the Program) you indicate your acceptance of this \n"
"* statement, and all its terms.\n"
"*\n"
"************************************************************************\n"
"\n"
"\n"
" SUBROUTINE UGEOM\n"
"\n"
"************************************************************************\n"
"*\n"
"* Initializes the geometry\n"
"*\n"
"* Author: This file has been automatically generated by the \n"
"* geometry-program GeoMega "<<g_VersionString<<"\n"
"*\n"
"************************************************************************\n"
"\n"
" IMPLICIT NONE\n"
"\n"
"\n"
" INCLUDE 'common.f'\n"
"\n"
"\n"
"\n"
" INTEGER IVOL\n"
" DIMENSION IVOL("<<MDVolume::m_IDCounter<<")\n"
" REAL UBUF\n"
" DIMENSION UBUF(2)\n\n"<<endl;
FileStream<<WFS(Text.str().c_str());
Text.str("");
for (unsigned int i = 0; i < GetNMaterials(); i++) {
FileStream<<WFS(m_MaterialList[i]->GetGeant3DIM());
}
for (unsigned int i = 0; i < GetNVolumes(); i++) {
FileStream<<WFS(m_VolumeList[i]->GetGeant3DIM());
}
for (unsigned int i = 0; i < GetNMaterials(); i++) {
FileStream<<WFS(m_MaterialList[i]->GetGeant3DATA());
}
for (unsigned int i = 0; i < GetNVolumes(); i++) {
FileStream<<WFS(m_VolumeList[i]->GetGeant3DATA());
}
Text<<endl<<
" ZNMAT = "<<GetNMaterials()<<endl;
FileStream<<WFS(Text.str().c_str());
Text.str("");
for (unsigned int i = 0; i < GetNMaterials(); i++) {
FileStream<<WFS(m_MaterialList[i]->GetGeant3());
}
Text<<endl<<
" CALL GPART"<<endl<<
" CALL GPHYSI"<<endl<<endl;
FileStream<<WFS(Text.str().c_str());
Text.str("");
FileStream<<WFS(m_WorldVolume->GetGeant3())<<endl;
//FileStream.setf(ios_base::fixed, ios_base::floatfield);
FileStream.setf(ios::fixed, ios::floatfield);
//FileStream.precision(3);
// Finally position the volumes
MString Name, MotherName, CopyName;
// Scan through the tree...
int IDCounter = 1;
FileStream<<WFS(m_WorldVolume->GetGeant3Position(IDCounter))<<endl;
Text<<endl;
Text<<" CALL GGCLOS"<<endl;
Text<<" GEONAM = \""<<m_FileName<<"\""<<endl;
double MinDist;
MVector RSize = m_WorldVolume->GetSize();
MinDist = RSize.X();
if (RSize.Y() < MinDist) MinDist = RSize.Y();
if (RSize.Z() < MinDist) MinDist = RSize.Z();
Text<<" MDIST = "<<MinDist<<endl;
Text<<endl;
Text<<" SPHR = "<<m_SphereRadius<<endl;
Text<<" SPHX = "<<m_SpherePosition.X()<<endl;
Text<<" SPHY = "<<m_SpherePosition.Y()<<endl;
Text<<" SPHZ = "<<m_SpherePosition.Z()<<endl;
Text<<" SPHD = "<<m_DistanceToSphereCenter<<endl;
Text<<endl;
Text<<" RETURN"<<endl;
Text<<" END"<<endl;;
FileStream<<WFS(Text.str().c_str());
Text.str("");
FileStream.close();
// open the geometry-file:
// gcc 2.95.3: FileStream.open("detinit.f", ios::out, 0664);
FileStream.open("detinit.f", ios_base::out);
Text<<
"************************************************************************\n"
"*\n"
"* Copyright (C) by the MEGA-team.\n"
"* All rights reserved.\n"
"*\n"
"*\n"
"* This code implementation is the intellectual property of the \n"
"* MEGA-team at MPE.\n"
"*\n"
"* By copying, distributing or modifying the Program (or any work\n"
"* based on the Program) you indicate your acceptance of this \n"
"* statement, and all its terms.\n"
"*\n"
"************************************************************************\n"
"\n"
"\n"
" SUBROUTINE DETINIT\n"
"\n"
"************************************************************************\n"
"*\n"
"* Initializes the detectors\n"
"*\n"
"* Author: This file has been automatically generated by the \n"
"* geometry-program GeoMega "<<g_VersionString<<"\n"
"*\n"
"************************************************************************\n"
"\n"
" IMPLICIT NONE\n"
"\n"
" INCLUDE 'common.f'\n"
"\n"<<endl;
Text<<" NDET = "<<GetNDetectors()<<endl<<endl;
if (GetNDetectors() > 0) {
Text<<" NSENS = "<<GetDetectorAt(0)->GetGlobalNSensitiveVolumes()<<endl<<endl;
}
// Write detectors
for(unsigned int i = 0; i < GetNDetectors(); i++) {
Text<<m_DetectorList[i]->GetGeant3();
}
// Write trigger conditions
Text<<" TNTRIG = "<<GetNTriggers()<<endl<<endl;
for(unsigned int i = 0; i < GetNTriggers(); i++) {
Text<<m_TriggerList[i]->GetGeant3(i+1);
}
Text<<endl;
Text<<" EVINFO = 1"<<endl;
Text<<" SNAM = '"<<m_Name<<"_"<<m_Version<<"'"<<endl<<endl;
Text<<" RETURN"<<endl;
Text<<" END"<<endl;
FileStream<<WFS(Text.str().c_str());
Text.str("");
FileStream.close();
// Clean up...
m_WorldVolume->ResetCloneTemplateFlags();
return true;
}
////////////////////////////////////////////////////////////////////////////////
MString MDGeometry::WFS(MString Text)
{
// Real name: WrapFortranStrings
// A line in a FORTRAN77 file is not allowed to be larger than 72 characters
// This functions cuts the lines appropriately:
size_t CutLength = 72;
if (Text.Length() <= CutLength) return Text;
MString Cut;
MString PreCut;
MString Beyond;
MString Formated;
while (Text.Length() > 0) {
int NextRet = Text.First('\n');
if (NextRet == -1) {
NextRet = Text.Length();
} else {
NextRet += 1;
}
Cut = Text.GetSubString(0, NextRet);
Text.Remove(0, NextRet);
if (Cut.Length() <= CutLength || Cut.BeginsWith("*") == true) {
Formated += Cut;
} else {
Beyond = Cut.GetSubString(CutLength+1 , Cut.Length());
bool BeyondHasText = false;
for (size_t c = 0; c < Beyond.Length(); ++c) {
char t = Beyond[c];
if (t != ' ' || t != '\n') {
BeyondHasText = true;
break;
}
}
if (BeyondHasText == true) {
// Check if we can wrap the line at a comma...
PreCut = Cut.GetSubString(0, CutLength-1);
size_t NiceLength = PreCut.Last(',')+1;
if (NiceLength < CutLength/2) NiceLength = CutLength;
Formated += Cut.GetSubString(0, NiceLength) + "\n";
Cut.Remove(0, NiceLength);
while (Cut.Length() > 0) {
// Check if we can wrap the line at a comma...
PreCut = Cut.GetSubString(0, CutLength-7);
size_t NiceLength2 = PreCut.Last(',')+1;
if (NiceLength2 < CutLength/2) NiceLength2 = CutLength-6;
Formated += " &" + Cut.GetSubString(0, NiceLength2);
Cut.Remove(0, NiceLength2);
if (Cut.Length() > 0) Formated += MString("\n");
}
} else {
Formated += Cut;
}
}
}
return Formated + Text;
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::WriteMGeantFiles(MString FilePrefix, bool StoreIAs, bool StoreVetoes)
{
// This routine generates an intermediate geometry-file, which can be decoded
// by MGEANT or MGGPOD
//
// Guest author: RMK
MString FileName;
fstream FileStream;
if (m_GeometryScanned == false) {
Error("bool MDGeometry::WriteMGeantFiles()",
"Geometry has to be scanned first");
return false;
}
// Extract file part of pathname
MString theFile = m_FileName;
if (theFile.Contains("/")) {
theFile.Remove(0,theFile.Last('/')+1);
}
// ---------------------------------------------------------------------------
// Create the materials file: MEGA_materials.mat
// ---------------------------------------------------------------------------
//
if (FilePrefix == "") {
FileName = "materials.mat";
} else {
FileName = FilePrefix + ".mat";
}
// gcc 2.95.3: FileStream.open("MEGA_materials.mat", ios::out, 0664);
FileStream.open(FileName, ios_base::out);
FileStream<<
"! +============================================================================+"<<endl<<
"! MEGA_materials.mat MGEANT/MGGPOD materials list file "<<endl<<
"! "<<endl<<
"! Based on setup file: "<< theFile << endl <<
"! "<<endl<<
"! Copyright (C) by the MEGA-team. "<<endl<<
"! All rights reserved. "<<endl<<
"! "<<endl<<
"! Author: This file has been automatically generated by the "<<endl<<
"! geometry-program GeoMega (Version: "<<g_VersionString<<")"<<endl<<
"! +============================================================================+"<<endl<<
"! Built-in Materials (numbers 1-16) --> "<<endl<<
"! hydrogen, deuterium, helium, lithium, beryllium, carbon, nitrogen, "<<endl<<
"! neon, aluminum, iron, copper, tungsten, lead, uranium, air, vacuum "<<endl<<
"! "<<endl<<
"! Format for User Materials --> "<<endl<<
"! mate imate chmat A Z dens radl absl(=1.0) nwbuf <CR> "<<endl<<
"! [ubuf] "<<endl<<
"! mixt imate chmat nlmat dens <CR> "<<endl<<
"! A(1) Z(1) wmat(1) "<<endl<<
"! ... "<<endl<<
"! A(N) Z(N) wmat(N) "<<endl<<
"! (wmat = prop by number(nlmat<0) or weight(nlmat>0); N = abs(nlmat)) "<<endl<<
"! "<<endl<<
"! umix imate chmat nlmat dens <CR> "<<endl<<
"! A(1) elenam(1) wmat(1) "<<endl<<
"! ... "<<endl<<
"! A(N) elenam(N) wmat(N) "<<endl<<
"! (wmat = prop by number(nlmat<0) or weight(nlmat>0); N = abs(nlmat), "<<endl<<
"! use A(i) == 0.0 to select natural isotopic abundance mixture) "<<endl<<
"! "<<endl<<
"! +============================================================================+"<<endl;
FileStream<<endl<<endl;
for (unsigned int i = 0; i < GetNMaterials(); i++) {
FileStream << m_MaterialList[i]->GetMGeant();
}
FileStream << endl << "end" << endl;
FileStream.close();
// ---------------------------------------------------------------------------
// Create the tracking media file: MEGA_media.med
// ---------------------------------------------------------------------------
if (FilePrefix == "") {
FileName = "media.med";
} else {
FileName = FilePrefix + ".med";
}
// gcc 2.95.3: FileStream.open("MEGA_media.med", ios::out, 0664);
FileStream.open(FileName, ios_base::out);
FileStream<<
"! +============================================================================+"<<endl<<
"! MEGA_media.med MGEANT/MGGPOD tracking media list file "<<endl<<
"! "<<endl<<
"! Based on setup file: " << theFile << endl <<
"! "<<endl<<
"! Copyright (C) by the MEGA-team. "<<endl<<
"! All rights reserved. "<<endl<<
"! "<<endl<<
"! Author: This file has been automatically generated by the "<<endl<<
"! geometry-program GeoMega (Version: "<<g_VersionString<<")"<<endl<<
"! +============================================================================+"<<endl<<
"! Format for User Media --> "<<endl<<
"! tmed itmed chmed chmat pass/dete/shld/mask -> "<<endl<<
"! ->ifield fieldm *tmaxfd *stemax *deemax epsil *stmin nwbuf <CR> "<<endl<<
"! [ubuf] "<<endl<<
"! (* set negative for automatic calculation of tracking parameter) "<<endl<<
"! tpar chmed chpar parval "<<endl<<
"! +============================================================================+"<<endl;
FileStream<<endl<<endl;
FileStream<<"! Some additional comments:"<<endl;
FileStream<<"! Adjust material sorting by hand to dete, pass, shld, or mask"<<endl;
FileStream<<"! as required - see MGEANT manual!"<<endl;
FileStream<<endl<<endl;
for (unsigned int i = 0; i < GetNMaterials(); i++) {
// Check if a detector consists of this material:
int Sensitivity = 0;
for (unsigned int d = 0; d < GetNDetectors(); ++d) {
for (unsigned int v = 0; v < GetDetectorAt(d)->GetNSensitiveVolumes(); ++v) {
if (GetDetectorAt(d)->GetSensitiveVolume(v)->GetMaterial()->GetName() == GetMaterialAt(i)->GetName()) {
if (GetDetectorAt(d)->GetDetectorType() == MDDetector::c_ACS) {
Sensitivity = 2;
} else {
Sensitivity = 1;
}
}
}
}
FileStream << m_MaterialList[i]->GetMGeantTmed(Sensitivity);
}
FileStream << endl << "end" << endl;
FileStream.close();
// ---------------------------------------------------------------------------
// Create the geometry file: MEGA_setup.geo
// ---------------------------------------------------------------------------
if (FilePrefix == "") {
FileName = "setup.geo";
} else {
FileName = FilePrefix + ".geo";
}
// gcc 2.95.3: FileStream.open("MEGA_setup.geo", ios::out, 0664);
FileStream.open(FileName, ios_base::out);
FileStream<<
"! +============================================================================+"<<endl<<
"! MEGA_setup.geo MGEANT/MGGPOD geometry list file "<<endl<<
"! "<<endl<<
"! Based on setup file: " << theFile << endl <<
"! "<<endl<<
"! Copyright (C) by the MEGA-team. "<<endl<<
"! All rights reserved. "<<endl<<
"! "<<endl<<
"! Author: This file has been automatically generated by the "<<endl<<
"! geometry-program GeoMega (Version: "<<g_VersionString<<")"<<endl<<
"! +============================================================================+"<<endl<<
"! Format for Shape and Position Parameters Input --> "<<endl<<
"! rotm irot theta1 phi1 theta2 phi2 theta3 phi3 "<<endl<<
"! volu chname chshap chmed npar <CR> "<<endl<<
"! [parms] "<<endl<<
"! posi chname copy chmoth x y z irot chonly "<<endl<<
"! posp chname copy chmoth x y z irot chonly npar <CR> "<<endl<<
"! parms "<<endl<<
"! divn chname chmoth ndiv iaxis "<<endl<<
"! dvn2 chname chmoth ndiv iaxis co chmed "<<endl<<
"! divt chname chmoth step iaxis chmed ndvmx "<<endl<<
"! dvt2 chname chmoth step iaxis co chmed ndvmx "<<endl<<
"! divx chname chmoth ndiv iaxis step co chmed ndvmx "<<endl<<
"! satt chname chiatt ival "<<endl<<
"! tree ndets firstdetnum detlvl shldlvl masklvl "<<endl<<
"! Euclid support => "<<endl<<
"! eucl filename "<<endl<<
"! ROTM irot theta1 phi1 theta2 phi2 theta3 phi3 "<<endl<<
"! VOLU 'chname' 'chshap' numed npar <CR> "<<endl<<
"! [parms] "<<endl<<
"! POSI 'chname' copy 'chmoth' x y z irot 'chonly' "<<endl<<
"! POSP 'chname' copy 'chmoth' x y z irot 'chonly' npar <CR> "<<endl<<
"! parms "<<endl<<
"! DIVN 'chname' 'chmoth' ndiv iaxis "<<endl<<
"! DVN2 'chname' 'chmoth' ndiv iaxis co numed "<<endl<<
"! DIVT 'chname' 'chmoth' step iaxis numed ndvmx "<<endl<<
"! DVT2 'chname' 'chmoth' step iaxis co numed ndvmx "<<endl<<
"! +============================================================================+"<<endl;
FileStream<<endl<<endl;
// Tree command - not needed for ACT / INIT - but do not delete
// FileStream << "! Tree Structure (must be modified manually!)" << endl;
// FileStream << "tree 1 1 1 1 1" << endl << endl;
// Volume tree data
FileStream << m_WorldVolume->GetMGeant() << endl;
// Volume position data
int IDCounter = 1;
FileStream << m_WorldVolume->GetMGeantPosition(IDCounter) << endl;
FileStream << endl << "end" << endl;
FileStream.close();
// ---------------------------------------------------------------------------
// Create the detector initialization file: detector.det
// ---------------------------------------------------------------------------
if (FilePrefix == "") {
FileName = "detector.det";
} else {
FileName = FilePrefix + "_detector.det";
}
// open the geometry-file:
FileStream.open(FileName, ios_base::out);
FileStream<<
"! +============================================================================+"<<endl<<
"! detector.det MGGPOD-MEGALIB-extension detector & trigger description "<<endl<<
"! "<<endl<<
"! Based on setup file: " << theFile << endl <<
"! "<<endl<<
"! Copyright (C) by the MEGA-team. "<<endl<<
"! All rights reserved. "<<endl<<
"! "<<endl<<
"! Author: This file has been automatically generated by the "<<endl<<
"! geometry-program GeoMega (Version: "<<g_VersionString<<")"<<endl<<
"! +============================================================================+"<<endl<<
"\n"<<endl;
FileStream<<"NDET "<<GetNDetectors()<<endl<<endl;
if (GetNDetectors() > 0) {
FileStream<<"NSEN "<<GetDetectorAt(0)->GetGlobalNSensitiveVolumes()<<endl<<endl;
}
// Write detectors
for(unsigned int i = 0; i < GetNDetectors(); i++) {
FileStream<<m_DetectorList[i]->GetMGeant();
}
// Write trigger conditions
FileStream<<"NTRG "<<GetNTriggers()<<endl<<endl;
for(unsigned int i = 0; i < GetNTriggers(); i++) {
FileStream<<m_TriggerList[i]->GetMGeant(i+1);
}
FileStream<<endl;
FileStream<<"END"<<endl;
FileStream.close();
if (FilePrefix == "") {
FileName = "megalib.ini";
} else {
FileName = FilePrefix + "_megalib.ini";
}
// open the geometry-file:
FileStream.open(FileName, ios_base::out);
FileStream<<
"! +============================================================================+"<<endl<<
"! megalib.ini MGGPOD-MEGALIB-extension setup input file "<<endl<<
"! "<<endl<<
"! Based on setup file: " << theFile << endl <<
"! "<<endl<<
"! Copyright (C) by the MEGA-team. "<<endl<<
"! All rights reserved. "<<endl<<
"! "<<endl<<
"! Author: This file has been automatically generated by the "<<endl<<
"! geometry-program GeoMega (Version: "<<g_VersionString<<")"<<endl<<
"! +============================================================================+"<<endl<<
"\n"<<endl;
FileStream<<endl;
FileStream<<"GNAM "<<theFile<<endl;
FileStream<<endl;
FileStream<<"VERS 24"<<endl;
FileStream<<endl;
if (StoreIAs == true) {
FileStream<<"EIFO 1"<<endl;
} else {
FileStream<<"EIFO 0"<<endl;
}
if (StoreVetoes == true) {
FileStream<<"VIFO 1"<<endl;
} else {
FileStream<<"VIFO 0"<<endl;
}
FileStream<<endl;
FileStream<<"END"<<endl;
FileStream.close();
// Clean up...
m_WorldVolume->ResetCloneTemplateFlags();
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::ValidName(MString Name)
{
// Return true if name is a valid name, i.e. only contains alphanumeric
// characters as well as "_"
for (size_t i = 0; i < Name.Length(); ++i) {
if (isalnum(Name[i]) == 0 &&
Name[i] != '_') {
mout<<" *** Error *** in Name \""<<Name<<"\""<<endl;
mout<<"Names are only allowed to contain alphanumeric characters as well as \"_\""<<endl;
return false;
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
MString MDGeometry::MakeValidName(MString Name)
{
// Makes a valid name out of "Name"
// If the returned string is empty this task was impossible
MString ValidName;
for (size_t i = 0; i < Name.Length(); ++i) {
if (isalnum(Name[i]) != 0 ||
Name[i] == '_' ||
Name[i] == '-') {
ValidName += Name[i];
}
}
return ValidName;
}
////////////////////////////////////////////////////////////////////////////////
MString MDGeometry::CreateShortName(MString Name, unsigned int Length, bool Fill, bool KeepKeywords)
{
// Create a Length character short name out of name, which is not in one of
// the lists (detectors, materials, volumes)
// e.g. if there exist two volumes, TrackerBox and TrackerStalk,
// the first one is called TRAC, the second TRA0
if (m_IgnoreShortNames == true) {
return "IGNO";
}
MString SN;
Name.ToLower();
bool FoundMicsetKeyword = false;
MString MicsetKeyword = "_micset";
if (KeepKeywords == true && Name.Contains(MicsetKeyword) == true) {
//mout<<" *** Info ***"<<endl;
//mout<<"Special MGGPOD material keyword "<<MicsetKeyword<<" found!"<<endl;
FoundMicsetKeyword = true;
Name.ReplaceAll(MicsetKeyword, "");
Length -= MicsetKeyword.Length();
}
bool FoundGeRecoilKeyword = false;
MString GeRecoilKeyword = "_ge_recoil";
if (KeepKeywords == true && Name.Contains(GeRecoilKeyword) == true) {
//mout<<" *** Info ***"<<endl;
//mout<<"Special MGGPOD material keyword "<<GeRecoilKeyword<<" found!"<<endl;
FoundGeRecoilKeyword = true;
Name.ReplaceAll(GeRecoilKeyword, "");
Length -= GeRecoilKeyword.Length();
}
bool FoundSiRecoilKeyword = false;
MString SiRecoilKeyword = "_si_recoil";
if (KeepKeywords == true && Name.Contains(SiRecoilKeyword) == true) {
//mout<<" *** Info ***"<<endl;
//mout<<"Special MGGPOD material keyword "<<SiRecoilKeyword<<" found!"<<endl;
FoundSiRecoilKeyword = true;
Name.ReplaceAll(SiRecoilKeyword, "");
Length -= SiRecoilKeyword.Length();
}
bool FoundCZTRecoilKeyword = false;
MString CZTRecoilKeyword = "_czt_recoil";
if (KeepKeywords == true && Name.Contains(CZTRecoilKeyword) == true) {
//mout<<" *** Info ***"<<endl;
//mout<<"Special MGGPOD material keyword "<<CZTRecoilKeyword<<" found!"<<endl;
FoundCZTRecoilKeyword = true;
Name.ReplaceAll(CZTRecoilKeyword, "");
Length -= CZTRecoilKeyword.Length();
}
bool FoundAddRecoilKeyword = false;
MString AddRecoilKeyword = "_addrec";
if (KeepKeywords == true && Name.Contains(AddRecoilKeyword) == true) {
mout<<" *** Info ***"<<endl;
mout<<"Special MGGPOD material keyword "<<AddRecoilKeyword<<" found!"<<endl;
FoundAddRecoilKeyword = true;
Name.ReplaceAll(AddRecoilKeyword, "");
Length -= AddRecoilKeyword.Length();
}
// Remove everything which is not alphanumerical from the name:
for (size_t i = 0; i < Name.Length(); ++i) {
if (isalnum(Name[i]) == false &&
Name[i] != '_' &&
Name[i] != '-') {
Name.Remove(i, 1);
}
}
// Keep only first "Length" charcters:callgrind.out.16396
Name = Name.GetSubString(0, Length);
if (Length < 4) Length = 4;
// if we are smaller, we can try to expand the name:
if (Name.Length() < Length) {
if (ShortNameExists(Name) == true) {
unsigned int MaxExpand = 0;
if (pow(10.0, (int) (Length-Name.Length())) - 1 > numeric_limits<unsigned int>::max()) {
MaxExpand = numeric_limits<unsigned int>::max();
} else {
MaxExpand = (unsigned int) (pow(10.0, (int) (Length-Name.Length())) - 1.0);
}
for (unsigned int i = 1; i < MaxExpand; ++i) {
SN = Name;
SN += i;
if (ShortNameExists(SN) == false) {
Name = SN;
break;
}
}
}
}
// If we still haven't found a suited short name:
if (ShortNameExists(Name) == true) {
// Step one: test the first "Length" letters
SN = Name.Replace(Length, Name.Length() - Length, "");
if (ShortNameExists(SN) == true) {
// Step three: Replace the last character by a number ...
for (int j = (int) '0'; j < (int) '9'; j++) {
SN[Length-1] = (char) j;
if (ShortNameExists(SN) == false) {
break;
}
}
}
if (ShortNameExists(SN) == true) {
// Step four: Replace the last two characters by a numbers ...
for (int i = (int) '0'; i < (int) '9'; i++) {
for (int j = (int) '0'; j < (int) '9'; j++) {
SN[Length-2] = (char) i;
SN[Length-1] = (char) j;
if (ShortNameExists(SN) == false) {
break;
}
}
if (ShortNameExists(SN) == false) {
break;
}
}
}
if (ShortNameExists(SN) == true) {
// Step five: Replace the last three characters by a numbers ...
for (int k = (int) '0'; k < (int) '9'; k++) {
for (int i = (int) '0'; i < (int) '9'; i++) {
for (int j = (int) '0'; j < (int) '9'; j++) {
SN[Length-3] = (char) k;
SN[Length-2] = (char) i;
SN[Length-1] = (char) j;
if (ShortNameExists(SN) == false) {
break;
}
}
if (ShortNameExists(SN) == false) {
break;
}
}
if (ShortNameExists(SN) == false) {
break;
}
}
}
if (ShortNameExists(SN) == true) {
// That's too much:
merr<<"You have too many volumes starting with "<<Name<<endl;
merr<<"Please add \"IgnoreShortNames true\" into your geometry file!"<<endl;
merr<<"As a result you are not able to do Geant3/MGEANT/MGGPOS simulations"<<endl;
m_IgnoreShortNames = true;
return "IGNO";
}
Name = SN;
}
if (KeepKeywords == true && FoundMicsetKeyword == true) {
Name += MicsetKeyword;
Length += MicsetKeyword.Length();
}
if (KeepKeywords == true && FoundGeRecoilKeyword == true) {
Name += GeRecoilKeyword;
Length += GeRecoilKeyword.Length();
}
if (KeepKeywords == true && FoundSiRecoilKeyword == true) {
Name += SiRecoilKeyword;
Length += SiRecoilKeyword.Length();
}
if (KeepKeywords == true && FoundCZTRecoilKeyword == true) {
Name += CZTRecoilKeyword;
Length += CZTRecoilKeyword.Length();
}
if (KeepKeywords == true && FoundAddRecoilKeyword == true) {
Name += AddRecoilKeyword;
Length += AddRecoilKeyword.Length();
}
// We always need a name which has exactly Length characters
while (Name.Length() < Length) {
if (Fill == true) {
Name += '_';
} else {
Name += ' ';
}
}
return Name;
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::ShortNameExists(MString Name)
{
// Check all lists if "Name" is already listed
MString ObjectName;
MString ShortName;
MString OriginalMGeantShortName;
MString ShortNameDivisionX;
MString ShortNameDivisionY;
MString ShortNameDivisionZ;
Name.ToLower();
// Test volumes
for (unsigned int i = 0; i < GetNVolumes(); i++) {
ObjectName = m_VolumeList[i]->GetName();
ObjectName.ToLower();
ShortName = m_VolumeList[i]->GetShortName();
ShortName.ToLower();
if (Name == ObjectName ||
Name == ShortName) {
return true;
}
}
// Test materials
for (unsigned int i = 0; i < GetNMaterials(); i++) {
ObjectName = m_MaterialList[i]->GetName();
ObjectName.ToLower();
ShortName = m_MaterialList[i]->GetShortName();
ShortName.ToLower();
OriginalMGeantShortName = m_MaterialList[i]->GetOriginalMGeantShortName();
OriginalMGeantShortName.ToLower();
if (Name == ObjectName ||
Name == ShortName ||
Name == OriginalMGeantShortName) {
return true;
}
}
// Test detectors
for (unsigned int i = 0; i < GetNDetectors(); i++) {
ObjectName = m_DetectorList[i]->GetName();
ObjectName.ToLower();
ShortNameDivisionX = m_DetectorList[i]->GetShortNameDivisionX();
ShortNameDivisionX.ToLower();
ShortNameDivisionY = m_DetectorList[i]->GetShortNameDivisionY();
ShortNameDivisionY.ToLower();
ShortNameDivisionZ = m_DetectorList[i]->GetShortNameDivisionZ();
ShortNameDivisionZ.ToLower();
if (Name == ObjectName ||
Name == ShortNameDivisionX ||
Name == ShortNameDivisionY ||
Name == ShortNameDivisionZ) {
return true;
}
}
// Test triggers
for (unsigned int i = 0; i < GetNTriggers(); i++) {
ObjectName = m_TriggerList[i]->GetName();
ObjectName.ToLower();
if (Name == ObjectName) {
return true;
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
void MDGeometry::AddVolume(MDVolume* Volume)
{
// Add a volume to the list
m_VolumeList.push_back(Volume);
}
////////////////////////////////////////////////////////////////////////////////
MDVolume* MDGeometry::GetWorldVolume()
{
// return the world volume
return m_WorldVolume;
}
////////////////////////////////////////////////////////////////////////////////
MDVolume* MDGeometry::GetVolumeAt(const unsigned int i) const
{
// return the volume at position i in the list. Counting starts with zero!
if (i < m_VolumeList.size()) {
return m_VolumeList[i];
} else {
merr<<"Index ("<<i<<") out of bounds (0, "<<GetNVolumes()-1<<")"<<endl;
return 0;
}
}
////////////////////////////////////////////////////////////////////////////////
MDVolume* MDGeometry::GetVolume(const MString& Name)
{
// Return the volume with name Name or 0 if it does not exist
// This function is not reentrant!!!!
// ---> begin extremely time critical
const unsigned int Size = 20;
list<MDVolume*>::iterator I;
for (I = m_LastVolumes.begin(); I != m_LastVolumes.end(); ++I) {
if ((*I)->GetName().AreIdentical(Name)) {
return (*I);
}
}
unsigned int i, i_max = m_VolumeList.size();
for (i = m_LastVolumePosition; i < i_max; ++i) {
if (m_VolumeList[i]->GetName().AreIdentical(Name)) {
m_LastVolumes.push_front(m_VolumeList[i]);
if (m_LastVolumes.size() > Size) m_LastVolumes.pop_back();
m_LastVolumePosition = i;
return m_VolumeList[i];
}
}
for (i = 0; i < m_LastVolumePosition; ++i) {
if (m_VolumeList[i]->GetName().AreIdentical(Name)) {
m_LastVolumes.push_front(m_VolumeList[i]);
if (m_LastVolumes.size() > Size) m_LastVolumes.pop_back();
m_LastVolumePosition = i;
return m_VolumeList[i];
}
}
// Not optimized:
//unsigned int i, i_max = m_VolumeList.size();
//for (i = 0; i < i_max; ++i) {
// if (Name == m_VolumeList[i]->GetName()) {
// return m_VolumeList[i];
// }
//}
// Infos: CompareTo is faster than ==
// <--- end extremely time critical
return 0;
}
////////////////////////////////////////////////////////////////////////////////
unsigned int MDGeometry::GetVolumeIndex(const MString& Name)
{
// Return the index of volume with name Name or g_UnsignedIntNotDefined if it does not exist
unsigned int i, i_max = m_VolumeList.size();
for (i = 0; i < i_max; ++i) {
if (Name == m_VolumeList[i]->GetName()) {
return i;
}
}
return g_UnsignedIntNotDefined;
}
////////////////////////////////////////////////////////////////////////////////
unsigned int MDGeometry::GetNVolumes() const
{
// Return the number of volumes in the list
return m_VolumeList.size();
}
////////////////////////////////////////////////////////////////////////////////
void MDGeometry::AddDetector(MDDetector* Detector)
{
// Add a volume to the list
m_DetectorList.push_back(Detector);
}
////////////////////////////////////////////////////////////////////////////////
MDDetector* MDGeometry::GetDetectorAt(unsigned int i)
{
// return the volume at position i in the list. Counting starts with zero!
if (i < GetNDetectors()) {
return m_DetectorList[i];
} else {
merr<<"Index ("<<i<<") out of bounds (0, "<<GetNDetectors()-1<<")"<<endl;
return 0;
}
}
////////////////////////////////////////////////////////////////////////////////
MDDetector* MDGeometry::GetDetector(const MString& Name)
{
// Return the detector with name Name or 0 if it does not exist
for (unsigned int i = 0; i < GetNDetectors(); i++) {
if (Name == m_DetectorList[i]->GetName()) {
return m_DetectorList[i];
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
unsigned int MDGeometry::GetDetectorIndex(const MString& Name)
{
// Return the index of material with name Name or g_UnsignedIntNotDefined if it does not exist
unsigned int i, i_max = GetNDetectors();
for (i = 0; i < i_max; i++) {
if (Name == m_DetectorList[i]->GetName()) {
return i;
}
}
return g_UnsignedIntNotDefined;
}
////////////////////////////////////////////////////////////////////////////////
unsigned int MDGeometry::GetNDetectors()
{
// Return the number of volumes in the list
return m_DetectorList.size();
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::AddShape(const MString& Type, const MString& Name)
{
// Add a shape to the list
MString S = Type;
S.ToLowerInPlace();
if (S == "box" || S == "brik") {
AddShape(new MDShapeBRIK(Name));
} else if (S == "sphe" || S == "sphere") {
AddShape(new MDShapeSPHE(Name));
} else if (S == "cone") {
AddShape(new MDShapeCONE(Name));
} else if (S == "cons") {
AddShape(new MDShapeCONS(Name));
} else if (S == "pcon") {
AddShape(new MDShapePCON(Name));
} else if (S == "pgon") {
AddShape(new MDShapePGON(Name));
} else if (S == "tubs" || S == "tube") {
AddShape(new MDShapeTUBS(Name));
} else if (S == "trap") {
AddShape(new MDShapeTRAP(Name));
} else if (S == "trd1") {
AddShape(new MDShapeTRD1(Name));
} else if (S == "trd2") {
AddShape(new MDShapeTRD2(Name));
} else if (S == "gtra") {
AddShape(new MDShapeGTRA(Name));
} else if (S == "subtraction") {
AddShape(new MDShapeSubtraction(Name));
} else if (S == "union") {
AddShape(new MDShapeUnion(Name));
} else if (S == "intersection") {
AddShape(new MDShapeIntersection(Name));
} else {
Typo("Line does not contain a known shape type!");
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
void MDGeometry::AddShape(MDShape* Shape)
{
// Add a shape to the list
m_ShapeList.push_back(Shape);
}
////////////////////////////////////////////////////////////////////////////////
MDShape* MDGeometry::GetShapeAt(unsigned int i)
{
// return the shape at position i in the list. Counting starts with zero!
if (i < GetNShapes()) {
return m_ShapeList[i];
} else {
merr<<"Index ("<<i<<") out of bounds (0, "<<GetNShapes()-1<<")"<<endl;
return 0;
}
}
////////////////////////////////////////////////////////////////////////////////
MDShape* MDGeometry::GetShape(const MString& Name)
{
// Return the shape with name Name or 0 if it does not exist
for (unsigned int i = 0; i < GetNShapes(); i++) {
if (Name == m_ShapeList[i]->GetName()) {
return m_ShapeList[i];
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
unsigned int MDGeometry::GetShapeIndex(const MString& Name)
{
// Return the index of the shape with name Name or g_UnsignedIntNotDefined if it does not exist
unsigned int i, i_max = GetNShapes();
for (i = 0; i < i_max; i++) {
if (Name == m_ShapeList[i]->GetName()) {
return i;
}
}
return g_UnsignedIntNotDefined;
}
////////////////////////////////////////////////////////////////////////////////
unsigned int MDGeometry::GetNShapes()
{
// Return the number of shapes in the list
return m_ShapeList.size();
}
////////////////////////////////////////////////////////////////////////////////
void MDGeometry::AddOrientation(MDOrientation* Orientation)
{
// Add an orientation to the list
m_OrientationList.push_back(Orientation);
}
////////////////////////////////////////////////////////////////////////////////
MDOrientation* MDGeometry::GetOrientationAt(unsigned int i)
{
// return the orientation at position i in the list. Counting starts with zero!
if (i < GetNOrientations()) {
return m_OrientationList[i];
} else {
merr<<"Index ("<<i<<") out of bounds (0, "<<GetNOrientations()-1<<")"<<endl;
return 0;
}
}
////////////////////////////////////////////////////////////////////////////////
MDOrientation* MDGeometry::GetOrientation(const MString& Name)
{
// Return the orientation with name Name or 0 if it does not exist
for (unsigned int i = 0; i < GetNOrientations(); i++) {
if (Name == m_OrientationList[i]->GetName()) {
return m_OrientationList[i];
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
unsigned int MDGeometry::GetOrientationIndex(const MString& Name)
{
// Return the index of the orientation with name Name or g_UnsignedIntNotDefined if it does not exist
unsigned int i, i_max = GetNOrientations();
for (i = 0; i < i_max; i++) {
if (Name == m_OrientationList[i]->GetName()) {
return i;
}
}
return g_UnsignedIntNotDefined;
}
////////////////////////////////////////////////////////////////////////////////
unsigned int MDGeometry::GetNOrientations()
{
// Return the number of orientations in the list
return m_OrientationList.size();
}
////////////////////////////////////////////////////////////////////////////////
void MDGeometry::AddMaterial(MDMaterial* Material)
{
// Add a material to the list
m_MaterialList.push_back(Material);
}
////////////////////////////////////////////////////////////////////////////////
MDMaterial* MDGeometry::GetMaterialAt(unsigned int i)
{
// return the material at position i in the list. Counting starts with zero!
if (i < GetNMaterials()) {
return m_MaterialList[i];
} else {
merr<<"Index ("<<i<<") out of bounds (0, "<<GetNMaterials()-1<<")"<<endl;
return 0;
}
}
////////////////////////////////////////////////////////////////////////////////
MDMaterial* MDGeometry::GetMaterial(const MString& Name)
{
// Return the material with name Name or 0 if it does not exist
for (unsigned int i = 0; i < GetNMaterials(); i++) {
if (Name == m_MaterialList[i]->GetName()) {
return m_MaterialList[i];
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
unsigned int MDGeometry::GetMaterialIndex(const MString& Name)
{
// Return the material with name Name or 0 if it does not exist
unsigned int i, i_max = GetNMaterials();
for (i = 0; i < i_max; i++) {
if (Name == m_MaterialList[i]->GetName()) {
return i;
}
}
return g_UnsignedIntNotDefined;
}
////////////////////////////////////////////////////////////////////////////////
unsigned int MDGeometry::GetNMaterials()
{
// Return the number of materials in the list
return m_MaterialList.size();
}
////////////////////////////////////////////////////////////////////////////////
void MDGeometry::AddTrigger(MDTrigger* Trigger)
{
// Add a material to the list
m_TriggerList.push_back(Trigger);
}
////////////////////////////////////////////////////////////////////////////////
MDTrigger* MDGeometry::GetTriggerAt(unsigned int i)
{
// return the material at position i in the list. Counting starts with zero!
if (i < GetNTriggers()) {
return m_TriggerList[i];
} else {
merr<<"Index ("<<i<<") out of bounds (0, "<<GetNTriggers()-1<<")"<<endl;
return 0;
}
}
////////////////////////////////////////////////////////////////////////////////
MDTrigger* MDGeometry::GetTrigger(const MString& Name)
{
// Return the material with name Name or 0 if it does not exist
unsigned int i;
for (i = 0; i < GetNTriggers(); i++) {
if (Name == m_TriggerList[i]->GetName()) {
return m_TriggerList[i];
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
unsigned int MDGeometry::GetTriggerIndex(const MString& Name)
{
// Return the material with name Name or 0 if it does not exist
unsigned int i, i_max = GetNTriggers();
for (i = 0; i < i_max; i++) {
if (Name == m_TriggerList[i]->GetName()) {
return i;
}
}
return g_UnsignedIntNotDefined;
}
////////////////////////////////////////////////////////////////////////////////
unsigned int MDGeometry::GetNTriggers()
{
// Return the number of materials in the list
return m_TriggerList.size();
}
////////////////////////////////////////////////////////////////////////////////
MDSystem* MDGeometry::GetSystem(const MString& Name)
{
// Return the system with name Name or 0 if it does not exist
if (m_System->GetName() == Name) {
return m_System;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
void MDGeometry::AddVector(MDVector* Vector)
{
// Add a vector to the list
m_VectorList.push_back(Vector);
}
////////////////////////////////////////////////////////////////////////////////
MDVector* MDGeometry::GetVectorAt(unsigned int i)
{
// return the vector at position i in the list. Counting starts with zero!
if (i < GetNVectors()) {
return m_VectorList[i];
} else {
merr<<"Index ("<<i<<") out of bounds (0, "<<GetNVectors()-1<<")"<<endl;
return 0;
}
}
////////////////////////////////////////////////////////////////////////////////
MDVector* MDGeometry::GetVector(const MString& Name)
{
// Return the vector with name Name or 0 if it does not exist
unsigned int i;
for (i = 0; i < GetNVectors(); i++) {
if (Name == m_VectorList[i]->GetName()) {
return m_VectorList[i];
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
unsigned int MDGeometry::GetVectorIndex(const MString& Name)
{
// Return the vector with name Name or 0 if it does not exist
unsigned int i, i_max = GetNVectors();
for (i = 0; i < i_max; i++) {
if (Name == m_VectorList[i]->GetName()) {
return i;
}
}
return g_UnsignedIntNotDefined;
}
////////////////////////////////////////////////////////////////////////////////
unsigned int MDGeometry::GetNVectors()
{
// Return the number of vectors in the list
return m_VectorList.size();
}
////////////////////////////////////////////////////////////////////////////////
void MDGeometry::AddInclude(MString FileName)
{
// Add the name of an included file
if (IsIncluded(FileName) == false) {
m_IncludeList->AddLast(new TObjString(FileName));
}
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::IsIncluded(MString FileName)
{
// Check if the file has already been included
for (int i = 0; i < GetNIncludes(); i++) {
if (dynamic_cast<TObjString*>(m_IncludeList->At(i))->GetString().CompareTo(FileName) == 0) {
return true;
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
int MDGeometry::GetNIncludes()
{
// Get the number of included files:
return m_IncludeList->GetLast()+1;
}
////////////////////////////////////////////////////////////////////////////////
MString MDGeometry::ToString()
{
//
unsigned int i;
ostringstream out;
out<<endl<<"Description of geometry: "<<m_Name<<", version: "<<m_Version<<endl;
out<<endl<<endl<<"Description of volumes:"<<endl;
for (i = 0; i < m_VolumeList.size(); ++i) {
out<<m_VolumeList[i]->GetName()<<endl;;
out<<m_VolumeList[i]->ToString()<<endl;;
}
out<<endl<<endl<<"Description of volume-tree:"<<endl;
if (m_WorldVolume != 0) {
out<<m_WorldVolume->ToStringVolumeTree(0)<<endl;
}
out<<endl<<endl<<"Description of materials:"<<endl<<endl;
for (i = 0; i < m_MaterialList.size(); ++i) {
out<<m_MaterialList[i]->ToString();
}
out<<endl<<endl<<"Description of detectors:"<<endl<<endl;
for (i = 0; i < m_DetectorList.size(); ++i) {
out<<m_DetectorList[i]->ToString()<<endl;
}
out<<endl<<endl<<"Description of triggers:"<<endl<<endl;
for (i = 0; i < m_TriggerList.size(); ++i) {
out<<m_TriggerList[i]->ToString()<<endl;
}
return out.str().c_str();
}
////////////////////////////////////////////////////////////////////////////////
MString MDGeometry::GetName()
{
//
return m_Name;
}
////////////////////////////////////////////////////////////////////////////////
MString MDGeometry::GetFileName()
{
//
return m_FileName;
}
////////////////////////////////////////////////////////////////////////////////
double MDGeometry::GetStartSphereRadius() const
{
return m_SphereRadius;
}
////////////////////////////////////////////////////////////////////////////////
double MDGeometry::GetStartSphereDistance() const
{
return m_DistanceToSphereCenter;
}
////////////////////////////////////////////////////////////////////////////////
MVector MDGeometry::GetStartSpherePosition() const
{
return m_SpherePosition;
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::HasComplexER()
{
// Return true if the co0mplex geometry is used for event reconstrcution,
// i.e. if volume sequences are necessary
return m_ComplexER;
}
////////////////////////////////////////////////////////////////////////////////
vector<MDMaterial*> MDGeometry::GetListOfUnusedMaterials()
{
// Return a list of unused materials
// First create a list of used materials:
vector<MDMaterial*> Used;
for (unsigned int v = 0; v < m_VolumeList.size(); ++v) {
MDMaterial* M = m_VolumeList[v]->GetMaterial();
if (find(Used.begin(), Used.end(), M) == Used.end()) {
Used.push_back(M);
}
}
// Now create a list of not used materials:
vector<MDMaterial*> Unused;
for (unsigned int m = 0; m < m_MaterialList.size(); ++m) {
if (find(Used.begin(), Used.end(), m_MaterialList[m]) == Used.end()) {
Unused.push_back(m_MaterialList[m]);
}
}
return Unused;
}
////////////////////////////////////////////////////////////////////////////////
MDVolumeSequence MDGeometry::GetVolumeSequence(MVector Pos, bool ForceDetector, bool ForceSensitiveVolume)
{
// Return the volume sequence for this position...
MDVolumeSequence* VSpointer = GetVolumeSequencePointer(Pos, ForceDetector, ForceSensitiveVolume);
MDVolumeSequence VS = *VSpointer;
delete VSpointer;
return VS;
}
////////////////////////////////////////////////////////////////////////////////
MDVolumeSequence* MDGeometry::GetVolumeSequencePointer(MVector Pos, bool ForceDetector, bool ForceSensitiveVolume)
{
// Return the volume sequence for this position...
MDVolumeSequence* VS = new MDVolumeSequence();
m_WorldVolume->GetVolumeSequence(Pos, VS);
if ((ForceDetector == true && VS->GetDetector() == 0) ||
(ForceSensitiveVolume == true && VS->GetSensitiveVolume() == 0)) {
MVector OrigPos = Pos;
double Tolerance = m_DetectorSearchTolerance;
ostringstream out;
out<<endl;
out<<" Warning:"<<endl;
if (VS->GetDetector() == 0) {
out<<" No detector volume could be found for the hit at position ";
} else {
out<<" No sensitive volume could be found for the hit at position ";
}
out<<setprecision(20)<<OrigPos[0]<<", "<<OrigPos[1]<<", "<<OrigPos[2]<<setprecision(6)<<endl;
if (VS->GetDeepestVolume() != 0) {
out<<" The deepest volume is: "<<VS->GetDeepestVolume()->GetName()<<endl;
}
out<<" Possible reasons are: "<<endl;
out<<" * The hit is just (+-"<<Tolerance<<" cm) outside the border of the volume:" <<endl;
out<<" -> Make sure you have stored your simulation file with enough digits"<<endl;
out<<" (cosima keyword \"StoreScientific\") so that the volume borders can be separated"<<endl;
out<<" -> Make sure your search tolerance given in the geometry file (geomega keyword"<<endl;
out<<" \"DetectorSearchTolerance\") is not too small"<<endl;
out<<" * The current and the simulation geometry are not identical"<<endl;
out<<" * There are overlaps in your geometry:"<<endl;
// Check for overlaps:
vector<MDVolume*> OverlappingVolumes;
m_WorldVolume->FindOverlaps(Pos, OverlappingVolumes);
if (OverlappingVolumes.size() > 1) {
out<<" The following volumes overlap:"<<endl;
for (unsigned int i = 0; i < OverlappingVolumes.size(); ++i) {
out<<" "<<OverlappingVolumes[i]->GetName()<<endl;
}
} else {
out<<" -> No simple overlaps found, but you might do a full overlap check anyway..."<<endl;
}
// Start the search within a tolerance limit
if (VS->GetDetector() == 0) {
out<<" Searching for a detector within "<<Tolerance<<" cm around the given position..."<<endl;
} else {
out<<" Searching for a sensitive volume within "<<Tolerance<<" cm around the given position..."<<endl;
}
Pos = OrigPos;
Pos[0] += Tolerance;
VS->Reset();
m_WorldVolume->GetVolumeSequence(Pos, VS);
if (VS->GetDeepestVolume() != 0) {
if (VS->GetSensitiveVolume() != 0 && VS->GetDetector() != 0) {
out<<" --> Successfully guessed the correct sensitive volume: "<<VS->GetDeepestVolume()->GetName()<<endl;
return VS;
} else if (VS->GetSensitiveVolume() == 0 && ForceSensitiveVolume == false && VS->GetDetector() != 0) {
out<<" --> Successfully guessed the correct detector volume: "<<VS->GetDeepestVolume()->GetName()<<endl;
return VS;
}
}
Pos = OrigPos;
Pos[0] -= Tolerance;
VS->Reset();
m_WorldVolume->GetVolumeSequence(Pos, VS);
if (VS->GetDeepestVolume() != 0) {
if (VS->GetSensitiveVolume() != 0 && VS->GetDetector() != 0) {
out<<" --> Successfully guessed the correct sensitive volume: "<<VS->GetDeepestVolume()->GetName()<<endl;
return VS;
} else if (VS->GetSensitiveVolume() == 0 && ForceSensitiveVolume == false && VS->GetDetector() != 0) {
out<<" --> Successfully guessed the correct detector volume: "<<VS->GetDeepestVolume()->GetName()<<endl;
return VS;
}
}
Pos = OrigPos;
Pos[1] += Tolerance;
VS->Reset();
m_WorldVolume->GetVolumeSequence(Pos, VS);
if (VS->GetDeepestVolume() != 0) {
if (VS->GetSensitiveVolume() != 0 && VS->GetDetector() != 0) {
out<<" --> Successfully guessed the correct sensitive volume: "<<VS->GetDeepestVolume()->GetName()<<endl;
return VS;
} else if (VS->GetSensitiveVolume() == 0 && ForceSensitiveVolume == false && VS->GetDetector() != 0) {
out<<" --> Successfully guessed the correct detector volume: "<<VS->GetDeepestVolume()->GetName()<<endl;
return VS;
}
}
Pos = OrigPos;
Pos[1] -= Tolerance;
VS->Reset();
m_WorldVolume->GetVolumeSequence(Pos, VS);
if (VS->GetDeepestVolume() != 0) {
if (VS->GetSensitiveVolume() != 0 && VS->GetDetector() != 0) {
out<<" --> Successfully guessed the correct sensitive volume: "<<VS->GetDeepestVolume()->GetName()<<endl;
return VS;
} else if (VS->GetSensitiveVolume() == 0 && ForceSensitiveVolume == false && VS->GetDetector() != 0) {
out<<" --> Successfully guessed the correct detector volume: "<<VS->GetDeepestVolume()->GetName()<<endl;
return VS;
}
}
Pos = OrigPos;
Pos[2] += Tolerance;
VS->Reset();
m_WorldVolume->GetVolumeSequence(Pos, VS);
if (VS->GetDeepestVolume() != 0) {
if (VS->GetSensitiveVolume() != 0 && VS->GetDetector() != 0) {
out<<" --> Successfully guessed the correct sensitive volume: "<<VS->GetDeepestVolume()->GetName()<<endl;
return VS;
} else if (VS->GetSensitiveVolume() == 0 && ForceSensitiveVolume == false && VS->GetDetector() != 0) {
out<<" --> Successfully guessed the correct detector volume: "<<VS->GetDeepestVolume()->GetName()<<endl;
return VS;
}
}
Pos = OrigPos;
Pos[2] -= Tolerance;
VS->Reset();
m_WorldVolume->GetVolumeSequence(Pos, VS);
if (VS->GetDeepestVolume() != 0) {
if (VS->GetSensitiveVolume() != 0 && VS->GetDetector() != 0) {
out<<" --> Successfully guessed the correct sensitive volume: "<<VS->GetDeepestVolume()->GetName()<<endl;
return VS;
} else if (VS->GetSensitiveVolume() == 0 && ForceSensitiveVolume == false && VS->GetDetector() != 0) {
out<<" --> Successfully guessed the correct detector volume: "<<VS->GetDeepestVolume()->GetName()<<endl;
return VS;
}
}
out<<" --> No suitable volume found!"<<endl;
// Only print the warning if we did not find anything
mout<<out.str()<<endl;
}
return VS;
}
////////////////////////////////////////////////////////////////////////////////
MVector MDGeometry::GetGlobalPosition(const MVector& PositionInDetector, const MString& NamedDetector)
{
//! Use this function to convert a position within a NAMED detector
//! (i.e. uniquely identifyable) into a position in the global coordinate system
MVector Position = g_VectorNotDefined;
// Find the detector (class) which contains the given named detector
bool Found = false;
for (unsigned d = 0; d < m_DetectorList.size(); ++d) {
if (m_DetectorList[d]->HasNamedDetector(NamedDetector) == true) {
Position = m_DetectorList[d]->GetGlobalPosition(PositionInDetector, NamedDetector);
Found = true;
break;
}
}
if (Found == false) {
mout<<" *** Error *** Named detector not found: "<<NamedDetector<<endl;
}
return Position;
}
////////////////////////////////////////////////////////////////////////////////
MVector MDGeometry::GetRandomPositionInVolume(const MString& Name)
{
//! Return a random position in the given volume --- excluding daughter volumes!
//! Any of the clone templates!!! (needed by Cosima)
if (m_GeometryScanned == false) {
merr<<"Geometry has to be scanned first!"<<endl;
return g_VectorNotDefined;
}
MDVolume* Volume = GetVolume(Name);
if (Volume == 0) {
merr<<"No volume of this name exists: "<<Name<<endl;
return g_VectorNotDefined;
}
if (Volume->IsClone()) {
Volume = Volume->GetCloneTemplate();
}
//cout<<"Volume: "<<Name<<endl;
// First find out how many placements we have:
vector<int> Placements;
int TreeDepth = -1;
m_WorldVolume->GetNPlacements(Volume, Placements, TreeDepth);
int Total = 1;
//cout<<"Placements"<<endl;
for (unsigned int i = 0; i < Placements.size(); ++i) {
//cout<<Placements[i]<<endl;
if (Placements[i] != 0) {
Total *= Placements[i];
}
}
//cout<<"Total: "<<Total<<endl;
int Random = gRandom->Integer(Total);
//cout<<"Random: "<<Random<<endl;
// Update the placements to reflect the ID of the random volume
vector<int> NewPlacements;
for (unsigned int i = 0; i < Placements.size(); ++i) {
if (Placements[i] != 0) {
Total = Total/Placements[i];
NewPlacements.push_back(Random / Total);
Random = Random % Total;
} else {
//NewPlacements[i] = 0;
}
}
//cout<<"New placements"<<endl;
//for (unsigned int i = 0; i < NewPlacements.size(); ++i) {
// cout<<NewPlacements[i]<<endl;
//}
TreeDepth = -1;
MVector Pos = m_WorldVolume->GetRandomPositionInVolume(Volume, NewPlacements, TreeDepth);
//cout<<Pos<<endl;
return Pos;
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::CreateCrossSectionFiles()
{
// Create the x-section files if cosima is present
mout<<endl;
mout<<"Cross sections have changed or are missing. Starting calculation using cosima (Geant4)!"<<endl;
mout<<endl;
if (MFile::Exists(g_MEGAlibPath + "/bin/cosima") == false) {
mout<<" *** Warning ***"<<endl;
mout<<"Cannot create cross section files since cosima is not present."<<endl;
return false;
}
// (1) Create a mimium cosima file:
MString FileName = gSystem->TempDirectory();
FileName += "/DelMe.source";
ofstream out;
out.open(FileName);
if (out.is_open() == false) {
mout<<" *** Error ***"<<endl;
mout<<"Unable to create cosima source file for cross section creation"<<endl;
return false;
}
out<<"Version 1"<<endl;
out<<"Geometry "<<m_FileName<<endl;
out<<"PhysicsListEM Standard"<<endl;
out<<"CreateCrossSectionFiles "<<m_CrossSectionFileDirectory<<endl;
out.close();
// (2) Run cosima
mout<<"-------- Cosima output start --------"<<endl;
MString WorkingDirectory = gSystem->WorkingDirectory();
gSystem->ChangeDirectory(gSystem->TempDirectory());
gSystem->Exec(MString("cosima ") + FileName);
gSystem->Exec(MString("rm -f DelMe.*.sim ") + FileName);
gSystem->ChangeDirectory(WorkingDirectory);
mout<<"-------- Cosima output stop ---------"<<endl;
// (3) Check if cross sections are loaded could be created
bool Success = true;
for (unsigned int i = 0; i < GetNMaterials(); i++) {
if (m_MaterialList[i]->LoadCrossSections(true) == false) {
Success = false;
}
}
if (Success == false) {
mout<<" *** Warning ***"<<endl;
mout<<"Cannot load create cross section files correctly."<<endl;
mout<<"Please read the above error output for a possible fix..."<<endl;
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
void MDGeometry::ReplaceWholeWords(MString& Text, const MString& OldWord, const MString& NewWord)
{
// In "Text" replace all occurances of OldWord with NewWord if the character
// after "OldWord is not alphanumerical or "_"
// This algorithm also appears MDDebugInfo::Replace
if (Text.Length() > 0) {
size_t Pos = 0;
while ((Pos = Text.Index(OldWord, Pos)) != MString::npos) {
//cout<<Text<<":"<<Pos<<endl;
if (Text.Length() > Pos + OldWord.Length()) {
//cout<<"i: "<<Text[Pos + OldWord.Length()]<<endl;
if (isalnum(Text[Pos + OldWord.Length()]) != 0 ||
Text[Pos + OldWord.Length()] == '_') {
//cout<<"cont."<<endl;
Pos += OldWord.Length();
continue;
}
}
if (Pos > 0) {
if (isalnum(Text[Pos - 1]) != 0 ||
Text[Pos - 1] == '_') {
//cout<<"cont."<<endl;
Pos += OldWord.Length();
continue;
}
}
Text.Replace(Pos, OldWord.Length(), NewWord);
Pos += NewWord.Length();
}
}
}
////////////////////////////////////////////////////////////////////////////////
bool MDGeometry::ContainsReplacableConstant(const MString& Text, const MString& Constant)
{
// Check if "Text" contains Constant as a real keyword
if (Text.Contains(Constant) == false) return false;
if (Text.Length() > 0) {
size_t Pos = 0;
while ((Pos = Text.Index(Constant, Pos)) != MString::npos) {
// Found it!
// The characters immediately before and after are not allowed to be alphanumerical or "_"
if (Text.Length() > Pos + Constant.Length()) {
//cout<<"i: "<<Text[Pos + OldWord.Length()]<<endl;
if (isalnum(Text[Pos + Constant.Length()]) || Text[Pos + Constant.Length()] == '_') {
return false;
}
}
if (Pos > 0) {
if (isalnum(Text[Pos - 1]) || Text[Pos - 1] == '_') {
return false;
}
}
Pos += Constant.Length();
}
}
return true;
}
// MDGeometry.cxx: the end...
////////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
] | |
c31c089c4eb1d1f09853fd781063a391de8c9f1f | ad006f5c883debb2687436be23e3c096be5bec35 | /LeetCode/pass/add_two_numbers.cpp | a397f418bc82480795c9bbd98aa2fd46f4d56748 | [] | no_license | Haoson/leetcode | 540021a6ac01886f2887b1399eae9d79b081b9ee | d0bf550a360f9b13112cd27029b4ca758d1045ad | refs/heads/master | 2021-01-25T03:49:17.411295 | 2015-03-12T18:22:43 | 2015-03-12T18:22:43 | 31,490,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,445 | cpp | /*************************************************************************
> File Name: add_two_numbers.cpp
> Author:Haoson
> Created Time: Mon 09 Mar 2015 09:13:11 AM PDT
> Description:
************************************************************************/
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode dummy(-1);//辅助dummy节点
ListNode *res = &dummy;
ListNode* ptr1 = l1,*ptr2 = l2;
int carry = 0;
while(ptr1||ptr2){
int num = carry+(ptr1?ptr1->val:0)+(ptr2?ptr2->val:0);
carry = num/10;
num = num%10;
res->next = new ListNode(num);
res = res->next;
if(ptr1)ptr1 = ptr1->next;
if(ptr2)ptr2 = ptr2->next;
}
if(carry>0)res->next = new ListNode(carry);//进位导致位数增多情况
return dummy.next;
}
};
int main(int argc,char* argv[]){
Solution s;
ListNode a(2);ListNode a1(4);ListNode a2(3);
a.next = &a1;
a1.next = &a2;
ListNode b(5);ListNode b1(6);ListNode b2(4);
b.next = &b1;
b1.next = &b2;
ListNode * res = s.addTwoNumbers(&a,&b);
while(res){
cout<<res->val<<" ";
res = res->next;
}
cout<<endl;
return 0;
}
| [
"[email protected]"
] | |
823e04b79fdae967ccd89d475aa8181988c2710f | 1354c730933ce135496f3e6bd50a30983dc81e39 | /Ch_8/Ch8_Rev9and10.cpp | 033d7450c9133f81b3ce9f51a964c3543b78bf40 | [] | no_license | slorello89/PracticeProblems | 0ce0dc350ae3417448a53d436ad6bb33fcd946c4 | f70e47bee63f8c8488baf8fcd8066d729fc43a7d | refs/heads/master | 2022-08-24T07:29:21.575171 | 2020-05-21T18:19:34 | 2020-05-21T18:19:34 | 265,920,529 | 0 | 0 | null | 2020-05-21T18:16:46 | 2020-05-21T18:16:45 | null | UTF-8 | C++ | false | false | 1,150 | cpp | //chapter 8 review 9 and 10 works and works :) (work on uppercase sensititvity)
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string Reverse (string phrase)
//reverses a string using arrays
{
string word;
for(int Letter = phrase.length()-1; Letter>=0; Letter --){
word+=phrase[Letter];
}
return(word);
}
string Uppercase(string S)
//determines if strings are the same regaurdless of case
{
for(int Letter=0; Letter<S.length(); Letter++){
if ((S[Letter]>='a')&&(S[Letter]<='z')){
S[Letter] = S[Letter] - 'a' + 'A';
}
}
return(S);
}
bool isPalendrom(string word)
//determines if something is a palidrome
{
string reversed = Reverse(word);
if(Uppercase(word)==word){
word = Uppercase(word);
}
return word == reversed;
}
int main()
//calls function
{
string phrase;
cout << "Enter a word to be reversed: ";
cin >> phrase;
// cout << Reverse(phrase);
if(isPalendrom(phrase)){
cout << phrase << " is a palendrome";
}
else{
cout << phrase << " is not a palendrome";
}
return(0);
} | [
"[email protected]"
] | |
4e819acf146f27409a91823959b917c370f3fac9 | 65588b3f0d822485522c820b25e8d2583061027e | /ModularTwoChoice/ModularTwoChoice.ino | 762f61c806d27883e6f49be3ba82e5c6e61250b6 | [] | no_license | cxrodgers/ArduFSM | 7847af6f5b28f9aaf26fa069180474344b6a8bb2 | 7c582867f5229a1b6f1abd4d58a82cbc360fdcad | refs/heads/master | 2022-01-17T13:03:48.802929 | 2020-04-03T16:05:04 | 2020-04-03T16:05:04 | 17,423,002 | 3 | 6 | null | 2016-12-14T20:59:05 | 2014-03-05T00:52:21 | Python | UTF-8 | C++ | false | false | 11,376 | ino | /* A two-alternative choice behavior with left and right lick ports.
TODO
----
* Move the required states, like TRIAL_START and WAIT_FOR_NEXT_TRIAL,
as well as all required variables like flag_start_trial, into TrialSpeak.cpp.
* move definitions of trial_params to header file, so can be auto-generated
* diagnostics: which state it is in on each call (or subset of calls)
Here are the things that the user should have to change for each protocol:
* Enum of states
* User-defined states in switch statement
* param_abbrevs, param_values, tpidx_*, N_TRIAL_PARAMS
*/
#include "chat.h"
#include "hwconstants.h"
#include <Servo.h>
#ifndef __HWCONSTANTS_H_USE_STEPPER_DRIVER
#include <Stepper.h>
#endif
#include "TimedState.h"
#include "States.h"
#ifndef __HWCONSTANTS_H_USE_IR_DETECTOR
#include "mpr121.h"
#include <Wire.h> // also for mpr121
#endif
#ifdef __HWCONSTANTS_H_USE_IR_DETECTOR
#include "ir_detector.h"
#endif
// Make this true to generate random responses for debugging
#define FAKE_RESPONDER 0
extern char* param_abbrevs[N_TRIAL_PARAMS];
extern long param_values[N_TRIAL_PARAMS];
extern bool param_report_ET[N_TRIAL_PARAMS];
extern char* results_abbrevs[N_TRIAL_RESULTS];
extern long results_values[N_TRIAL_RESULTS];
extern long default_results_values[N_TRIAL_RESULTS];
//// Miscellaneous globals
// flag to remember whether we've received the start next trial signal
// currently being used in both setup() and loop() so it can't be staticked
bool flag_start_trial = 0;
//// Declarations
int take_action(char *protocol_cmd, char *argument1, char *argument2);
//// User-defined variables, etc, go here
/// these should all be staticked into loop()
STATE_TYPE next_state;
// touched monitor
uint16_t sticky_touched = 0;
// initial position of stim arm .. user must ensure this is correct
extern long sticky_stepper_position;
/// not sure how to static these since they are needed by both loop and setup
// Servo
Servo linServo;
// Stepper
// We won't assign till we know if it's 2pin or 4pin
#ifndef __HWCONSTANTS_H_USE_STEPPER_DRIVER
Stepper *stimStepper = 0;
#endif
//// Setup function
void setup()
{
unsigned long time = millis();
int status = 1;
Serial.begin(115200);
Serial.print(time);
Serial.println(" DBG begin setup");
//// Begin user protocol code
//// Put this in a user_setup1() function?
// MPR121 touch sensor setup
#ifndef __HWCONSTANTS_H_USE_IR_DETECTOR
pinMode(TOUCH_IRQ, INPUT);
digitalWrite(TOUCH_IRQ, HIGH); //enable pullup resistor
Wire.begin();
#endif
// output pins
pinMode(L_REWARD_VALVE, OUTPUT);
pinMode(R_REWARD_VALVE, OUTPUT);
pinMode(__HWCONSTANTS_H_HOUSE_LIGHT, OUTPUT);
pinMode(__HWCONSTANTS_H_BACK_LIGHT, OUTPUT);
// initialize the house light to ON
digitalWrite(__HWCONSTANTS_H_HOUSE_LIGHT, HIGH);
digitalWrite(__HWCONSTANTS_H_BACK_LIGHT, HIGH);
// random number seed
randomSeed(analogRead(3));
// attach servo
linServo.attach(LINEAR_SERVO);
//linServo.write(1850); // move close for measuring
//// Run communications until we've received all setup info
// Later make this a new flag. For now wait for first trial release.
while (!flag_start_trial)
{
status = communications(time);
if (status != 0)
{
Serial.println("comm error in setup");
delay(1000);
}
}
//// Now finalize the setup using the received initial parameters
// user_setup2() function?
#ifdef __HWCONSTANTS_H_USE_STEPPER_DRIVER
pinMode(__HWCONSTANTS_H_STEP_ENABLE, OUTPUT);
pinMode(__HWCONSTANTS_H_STEP_PIN, OUTPUT);
pinMode(__HWCONSTANTS_H_STEP_DIR, OUTPUT);
// Make sure it's off
digitalWrite(__HWCONSTANTS_H_STEP_ENABLE, LOW);
digitalWrite(__HWCONSTANTS_H_STEP_PIN, LOW);
digitalWrite(__HWCONSTANTS_H_STEP_DIR, LOW);
#endif
#ifndef __HWCONSTANTS_H_USE_STEPPER_DRIVER
pinMode(TWOPIN_ENABLE_STEPPER, OUTPUT);
pinMode(TWOPIN_STEPPER_1, OUTPUT);
pinMode(TWOPIN_STEPPER_2, OUTPUT);
// Make sure it's off
digitalWrite(TWOPIN_ENABLE_STEPPER, LOW);
// Initialize
stimStepper = new Stepper(__HWCONSTANTS_H_NUMSTEPS,
TWOPIN_STEPPER_1, TWOPIN_STEPPER_2);
#endif
// Opto (collides with one of the 4-pin setups)
pinMode(__HWCONSTANTS_H_OPTO, OUTPUT);
digitalWrite(__HWCONSTANTS_H_OPTO, HIGH);
// thresholds for MPR121
#ifndef __HWCONSTANTS_H_USE_IR_DETECTOR
mpr121_setup(TOUCH_IRQ, param_values[tpidx_TOU_THRESH],
param_values[tpidx_REL_THRESH]);
#endif
#ifndef __HWCONSTANTS_H_USE_STEPPER_DRIVER
// Set the speed of the stepper
stimStepper->setSpeed(param_values[tpidx_STEP_SPEED]);
#endif
// initial position of the stepper
sticky_stepper_position = param_values[tpidx_STEP_INITIAL_POS];
// linear servo setup
linServo.write(param_values[tpidx_SRV_FAR]);
delay(param_values[tpidx_SERVO_SETUP_T]);
}
//// Loop function
void loop()
{ /* Called over and over again. On each call, the behavior is determined
by the current state.
*/
//// Variable declarations
// get the current time as early as possible in this function
unsigned long time = millis();
static STATE_TYPE current_state = WAIT_TO_START_TRIAL;
// The next state, by default the same as the current state
next_state = current_state;
// misc
int status = 1;
//// User protocol variables
uint16_t touched = 0;
//// Run communications
status = communications(time);
//// User protocol code
// could put other user-specified every_loop() stuff here
// Poll touch inputs
#ifndef __HWCONSTANTS_H_USE_IR_DETECTOR
touched = pollTouchInputs();
#endif
#ifdef __HWCONSTANTS_H_USE_IR_DETECTOR
if (time % 500 == 0) {
touched = pollTouchInputs(time, 1);
} else {
touched = pollTouchInputs(time, 0);
}
#endif
// announce sticky
if (touched != sticky_touched)
{
Serial.print(time);
Serial.print(" TCH ");
Serial.println(touched);
sticky_touched = touched;
}
//// Begin state-dependent operations
// Try to replace every case with a single function or object call
// Ultimately this could be a dispatch table.
// Also, eventually we'll probably want them to return next_state,
// but currently it's generally passed by reference.
stateDependentOperations(current_state, time);
//// Update the state variable
if (next_state != current_state)
{
Serial.print(time);
Serial.print(" ST_CHG ");
Serial.print(current_state);
Serial.print(" ");
Serial.println(next_state);
Serial.print(millis());
Serial.print(" ST_CHG2 ");
Serial.print(current_state);
Serial.print(" ");
Serial.println(next_state);
}
current_state = next_state;
return;
}
//// Take protocol action based on user command (ie, setting variable)
int take_action(char *protocol_cmd, char *argument1, char *argument2)
{ /* Protocol action.
Currently two possible actions:
if protocol_cmd == 'SET':
argument1 is the variable name. argument2 is the data.
if protocol_cmd == 'ACT':
argument1 is converted into a function based on a dispatch table.
REWARD_L : reward the left valve
REWARD_R : reward the right valve
REWARD : reward the current valve
This logic could be incorporated in TrialSpeak, but we would need to provide
the abbreviation, full name, datatype, and optional handling logic for
each possible variable. So it seems to make more sense here.
Return values:
0 - command parsed successfully
2 - unimplemented protocol_cmd
4 - unknown variable on SET command
5 - data conversion error
6 - unknown asynchronous action
*/
int status;
//~ Serial.print("DBG take_action ");
//~ Serial.print(protocol_cmd);
//~ Serial.print("-");
//~ Serial.print(argument1);
//~ Serial.print("-");
//~ Serial.println(argument2);
if (strncmp(protocol_cmd, "SET\0", 4) == 0)
{
// Find index into param_abbrevs
int idx = -1;
for (int i=0; i < N_TRIAL_PARAMS; i++)
{
if (strcmp(param_abbrevs[i], argument1) == 0)
{
idx = i;
break;
}
}
// Error if not found, otherwise set
if (idx == -1)
{
Serial.print("ERR param not found ");
Serial.println(argument1);
return 4;
}
else
{
// Convert to int
status = safe_int_convert(argument2, param_values[idx]);
// Debug
//~ Serial.print("DBG setting var ");
//~ Serial.print(idx);
//~ Serial.print(" to ");
//~ Serial.println(argument2);
// Error report
if (status != 0)
{
Serial.println("ERR can't set var");
return 5;
}
}
}
else if (strncmp(protocol_cmd, "ACT\0", 4) == 0)
{
// Dispatch
if (strncmp(argument1, "REWARD_L\0", 9) == 0) {
asynch_action_reward_l();
} else if (strncmp(argument1, "REWARD_R\0", 9) == 0) {
asynch_action_reward_r();
} else if (strncmp(argument1, "REWARD\0", 7) == 0) {
asynch_action_reward();
} else if (strncmp(argument1, "THRESH\0", 7) == 0) {
asynch_action_set_thresh();
} else if (strncmp(argument1, "HLON\0", 5) == 0) {
asynch_action_light_on();
}
else
return 6;
}
else
{
// unknown command
return 2;
}
return 0;
}
int safe_int_convert(char *string_data, long &variable)
{ /* Check that string_data can be converted to long before setting variable.
Returns 1 if string data could not be converted to %d.
*/
long conversion_var = 0;
int status;
// Parse into %d
// Returns number of arguments successfully parsed
status = sscanf(string_data, "%ld", &conversion_var);
//~ Serial.print("DBG SIC ");
//~ Serial.print(string_data);
//~ Serial.print("-");
//~ Serial.print(conversion_var);
//~ Serial.print("-");
//~ Serial.print(status);
//~ Serial.println(".");
if (status == 1) {
// Good, we converted one variable
variable = conversion_var;
return 0;
}
else {
// Something went wrong, probably no variables converted
Serial.print("ERR SIC cannot parse -");
Serial.print(string_data);
Serial.println("-");
return 1;
}
}
void asynch_action_reward_l()
{
unsigned long time = millis();
Serial.print(time);
Serial.println(" EV AAR_L");
digitalWrite(L_REWARD_VALVE, HIGH);
delay(param_values[tpidx_REWARD_DUR_L]);
digitalWrite(L_REWARD_VALVE, LOW);
}
void asynch_action_reward_r()
{
unsigned long time = millis();
Serial.print(time);
Serial.println(" EV AAR_R");
digitalWrite(R_REWARD_VALVE, HIGH);
delay(param_values[tpidx_REWARD_DUR_R]);
digitalWrite(R_REWARD_VALVE, LOW);
}
void asynch_action_reward()
{
if (param_values[tpidx_REWSIDE] == LEFT)
asynch_action_reward_l();
else if (param_values[tpidx_REWSIDE] == RIGHT)
asynch_action_reward_r();
else
Serial.println("ERR unknown rewside");
}
void asynch_action_set_thresh()
{
unsigned long time = millis();
Serial.print(time);
Serial.println(" EV AAST");
#ifndef __HWCONSTANTS_H_USE_IR_DETECTOR
mpr121_setup(TOUCH_IRQ, param_values[tpidx_TOU_THRESH],
param_values[tpidx_REL_THRESH]);
#endif
}
void asynch_action_light_on()
{
unsigned long time = millis();
Serial.print(time);
Serial.println(" EV HLON");
digitalWrite(__HWCONSTANTS_H_HOUSE_LIGHT, HIGH);
}
| [
"[email protected]"
] | |
233edd190ed154c2aa075ddba767fafdcecee3d3 | d0ff2c67da042ebfe6b0cd3f7fbbfdd24999e0c4 | /specFW2/cmdmd.cpp | 97b9ab6fd27c1eb4e90f2345df2bfaa662e334ff | [] | no_license | Pkijoe/specFW2 | ed8e0b9a595faf57dfc345c4647196494fffd257 | 053a8c32ea481fc23a523e1249c55a574f808e2f | refs/heads/master | 2020-04-07T00:03:15.362800 | 2018-11-15T18:45:17 | 2018-11-15T18:45:17 | 157,889,646 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,968 | cpp | //===========================================================================
//
// Module Name: cmdMD.cpp
//
// Function: This routine selects the mode of operation:
// SETUP-0,NOT_ON-1,COLD-2,HOT-A,READY-R,DIAG-X,AUTO-Z
//
// Original Author: T Frazzini
//
// Copyright (c) 2005, PerkinElmer, LAS. All rights reserved.
//
//===========================================================================
#include "StdAfx.h"
#include "SpecFW2.h"
#include "ParserThread.h"
unsigned int CParserThread::cmdMD()
{
WORD status(NO_ERRORS);
char cMode;
theApp.EnterCriticalSection1(&m_CriticalSection); // Protect critical parameters
strcpy(m_nDataOutBuf, "MD00");
cMode = *m_pCmdPtr++;
m_nBytesRead++;
if (m_cStartupMode > NOT_ON && m_cStartupMode < READY)
{
status = ERR_CMD;
memcpy(&m_nDataOutBuf[2], "01", 2);
}
else
{
switch (cMode)
{
// case SETUP:
// case AUTO:
case DIAG:
m_cOperationMode = cMode;
m_cStartupMode = cMode;
break;
case MFG:
//...........................................................
// Mfg mode entry placed into the Spectrometer log.
{
char* szStr = new char[40];
GetDateTimeStamp(szStr);
sprintf(&szStr[19], " Mode: Mfg (DCM)\0");
AddToSpecLog(szStr);
}
//...........................................................
m_cOperationMode = cMode;
m_cStartupMode = cMode;
break;
case READY:
//...........................................................
// Ready mode entry placed into the Spectrometer log.
{
char* szStr = new char[40];
GetDateTimeStamp(szStr);
sprintf(&szStr[19], " Mode: Ready (DCM)\0");
AddToSpecLog(szStr);
}
//...........................................................
m_cOperationMode = cMode;
m_cStartupMode = cMode;
break;
case COLD:
//...........................................................
// Cold mode entry placed into the Spectrometer log.
{
char* szStr = new char[40];
GetDateTimeStamp(szStr);
sprintf(&szStr[19], " Mode: Cold (DCM)\0");
AddToSpecLog(szStr);
}
//...........................................................
m_cInitFlag = YES; /* Intialization to start */
if ( m_bCCDPower ) /* DETECTOR POWER OFF IF ON */
{
m_bCCDPower = false;
}
m_cOperationMode = READY;
m_cStartupMode = cMode;
break;
case HOT:
//...........................................................
// Hot mode entry placed into the Spectrometer log.
{
char* szStr = new char[40];
GetDateTimeStamp(szStr);
sprintf(&szStr[19], " Mode: Hot (DCM)\0");
AddToSpecLog(szStr);
}
//...........................................................
m_cInitFlag = YES; /* Intialization to start */
if ( m_bCCDPower ) /* DETECTOR POWER OFF IF ON */
{
m_bCCDPower = false;
}
m_cOperationMode = READY;
m_cStartupMode = cMode;
break;
default:
status = ERR_PARA;
memcpy(&m_nDataOutBuf[2], "07", 2);
break;
}
}
if (status == NO_ERRORS)
{
// Just in case system is in Sleep mode - disable checking
m_bSleepFlag = false;
m_nWarning = 0; // Clear ALL Warnings
m_nFatal = 0; // Clear ALL Fatal messages
if (m_cOperationMode == AUTO)
{
m_nOPmode = TEST; // TEST MODE
m_nTestMode = NORMAL; // TEST MODE, NORMAL
m_bTestMode = false;
m_bOverscanMode = false;
}
else
{
m_nOPmode = NORMAL; // NORMAL MODE, NOT TESTING
m_nTestMode = NORMAL; // NORMAL
m_bTestMode = false;
m_bOverscanMode = false;
}
}
theApp.LeaveCriticalSection1(&m_CriticalSection); // Remove protection
return status;
}
//===========================================================================
/*** Revision History ***
01/28/17 KR CBF-143 - Remove unwanted thermal commands
$Log: /IcarusBased/SpecFW/cmdmd.cpp $
*
* 8 4/07/08 5:09p Nashth
* Added Mfg mode to History log.
*
* 7 4/07/08 10:41a Nashth
* Second attempt at Spectrometer history log.
*
* 6 3/31/08 5:31p Nashth
* Implementation of spectrometer history log... First pass.
*
* 5 11/29/05 11:30a Nashth
* Trace printfs added to Main critical section for Enter/Leave for
* debugging.
*
* 4 9/30/05 9:23a Frazzitl
* Changed variable names to make more readable
*
* 3 8/18/05 13:49 Frazzitl
* Implemented Sleep mode. Time is checked in CommandServer if enabled.
* At correct time, the system must be restarted - not yet implemented.
* Disabled if any legal Mode Command is accepted.
*
* 2 8/01/05 3:11p Nashth
* Protected critical parameters via critical section to allow the HW Init
* thread to run. Also, started the HW Init thread. However the system
* continues to come up READY.
*
* 1 3/17/05 11:17 Frazzitl
* Initial version of Optima Spectrometer firmware using the Icarus board,
* TcpIp, and the new Sarnoff detector.
$NoKeywords: $
** End of Rev History **/
| [
"[email protected]"
] | |
a64ca0915344d733241503014b6e420aa4c49653 | e99b3e5153bc6865be1d9a1f592f15599901ae54 | /catkin_ws/src/motor_communication/include/motor_communication/motor_communication.h | bcca1143bfd4e806cd3c8518d93ed4f2b9dfcfb7 | [] | no_license | AutoModelCar/model_car | dfdc6ac48ade56ee6ca0ac7b477ef85edcb3f091 | fed4cef394e412ec1f3aaa51586a6eb7689b4cc7 | refs/heads/version-1 | 2021-01-20T18:19:36.983343 | 2018-03-29T12:08:02 | 2018-03-29T12:08:02 | 62,126,597 | 8 | 27 | null | 2017-09-11T16:04:30 | 2016-06-28T09:07:07 | Makefile | UTF-8 | C++ | false | false | 1,066 | h | #include <ros/ros.h>
#include <ros/message_operations.h>
#include <std_msgs/String.h>
#include <std_msgs/Int16.h>
#include <std_msgs/Bool.h>
#include <string>
#include <iostream>
#include <cstdio>
#include <unistd.h>
#include "serial/serial.h"
#include <sstream>
#include <ros/console.h>
#include <sstream>
using std::string;
using std::exception;
using std::cout;
using std::cerr;
using std::endl;
using std::vector;
typedef int16_t speed_MMpS_t;
class motor_communication
{
private:
//! Node handle in the private namespace
ros::NodeHandle priv_nh_;
std::string serial_port_;//="/dev/ttySAC2";
int baud_rate_;//=115200;
std::string result;
size_t bytes_wrote;
serial::Serial my_serial;
//serial::Serial my_serial;
//my_serial(serial_port_, 115200, serial::Timeout::simpleTimeout(1000));
public:
motor_communication();
~motor_communication();
void init();
void run(int speed);
void my_sleep(unsigned long milliseconds);
void stop();
void start();
double getSpeed();
};
| [
"[email protected]"
] | |
bfe0083495af299a41cad0f48a1d23d0cc04d21e | 2a02d8873c8825eb3fef2b352fcda238961831c9 | /more/codeforces/1662H.cpp | 6cf00eba608e60208a56f739ea47b768d577edab | [] | no_license | Stypox/olympiad-exercises | eb42b93a10ae566318317dfa3daaa65b7939621b | 70c6e83a6774918ade532855e818b4822d5b367b | refs/heads/master | 2023-04-13T22:30:55.122026 | 2023-04-10T15:09:17 | 2023-04-10T15:09:17 | 168,403,900 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 587 | cpp | #include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a%b);
}
void tryAll(int g, set<int>& res) {
for(int i=1;i<=sqrt(g)+5;++i){
if (g%i==0) {
res.insert(i);
res.insert(g/i);
}
}
}
int main() {
int T;
cin>>T;
while(T--){
int W,L;
cin>>W>>L;
set<int> res;
tryAll(gcd(W-1, L-1), res);
tryAll(gcd(W-2, L), res);
tryAll(gcd(W, L-2), res);
tryAll(gcd(W, 2), res);
tryAll(gcd(2, L), res);
cout<<res.size();
for(auto i=res.begin();i!=res.end();++i){
cout<<" "<<*i;
}
cout<<"\n";
}
} | [
"[email protected]"
] | |
6216176ab7a139296c7d6a179f86c421abe5b309 | 575c265b54bbb7f20b74701753174678b1d5ce2c | /lottery/Classes/lottery/dzpk/utils/RoomOtherPlayer.cpp | 8731d364b511cbc223a64d29afb1eccb8f5202aa | [] | no_license | larryzen/Project3.x | c8c8a0be1874647909fcb1a0eb453c46d6d674f1 | cdc2bf42ea737c317fe747255d2ff955f80dbdae | refs/heads/master | 2020-12-04T21:27:46.777239 | 2019-03-02T06:30:26 | 2019-03-02T06:30:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,155 | cpp | #include "RoomOtherPlayer.h"
#include "RoomPlayer.h"
#include "Sound.h"
#include "PlayerModel.h"
#include "Venue.h"
#include "StringFormat.h"
#include "Players.h"
//#include "RoomCardAction.h"
//#include "RoomScene.h"
//#include "RoomInfo.h"
//#include "RoomPopFrame.h"
//#include "RoomOtherInfo.h"
//#include "GlobalHttpReq.h"
RoomOtherPlayer::RoomOtherPlayer():
click_index(0),
my_sound_id(-1),
seatAction(false)
{
}
RoomOtherPlayer::~RoomOtherPlayer()
{
do{
CC_BREAK_IF(my_sound_id==-1);
Sound::getInstance()->stopEffect(my_sound_id);
}while(0);
}
bool RoomOtherPlayer::init()
{
if (!Layer::init())
{
return false;
}
return true;
}
CCPoint RoomOtherPlayer::getPostBySeatID(int id , bool bvar)
{
int x,y;
CCSize WinSize = CCDirector::sharedDirector()->getVisibleSize();
int X[9] = {
WinSize.width/2+0,
WinSize.width/2-173,
WinSize.width/2-340,
WinSize.width/2-340,
WinSize.width/2-173,
WinSize.width/2+173,
WinSize.width/2+340,
WinSize.width/2+340,
WinSize.width/2+173,
};
int Y[9] = {
WinSize.height/2-110,
WinSize.height/2-110,
WinSize.height/2-33,
WinSize.height/2+107,
WinSize.height/2+165,
WinSize.height/2+165,
WinSize.height/2+107,
WinSize.height/2-33,
WinSize.height/2-110,
};
int mySeatID =0;//RoomScene::getMySeatID();
if (bvar)
mySeatID = -1;
if (mySeatID!=-1)
{
if (mySeatID==id)
{
x=X[0];
y=Y[0];
}else if ( mySeatID<id )
{
x=X[id-mySeatID];
y=Y[id-mySeatID];
}else
{
x=X[9-mySeatID+id];
y=Y[9-mySeatID+id];
}
}
else
{
x=X[id];
y=Y[id];
}
return ccp(x,y);
}
CCSprite *RoomOtherPlayer::getPlayerAvatar(int seatid)
{
////玩家头像
//const char* genderPicName = RoomScene::getRff()[seatid].sex==1 ? "rooms/photo/room_photo_1.png" : "rooms/photo/room_photo_2.png";
//std::string headerFile = "no_custom_head";
//CCHttpAgent::getInstance()->getImagePath(RoomScene::getRff()[seatid].user_id,headerFile);
//CCSprite* photo = CCSprite::create(genderPicName);
//
//CCLog("座位id:%d , uid: %d , headerFile = %s " , seatid , RoomScene::getRff()[seatid].user_id , headerFile.c_str());
//if (headerFile.compare("no_custom_head")==0 )
//{
// return photo;
//}else{
// do{
// CCLOG("headPath=%s",CCHttpAgent::getInstance()->getImagePath(RoomScene::getRff()[seatid].user_id).c_str());
//
// CCSize sc_sz = photo->getContentSize();
// CCSprite *header = CCSprite::create(CCHttpAgent::getInstance()->getImagePath(RoomScene::getRff()[seatid].user_id).c_str());
// CC_BREAK_IF(!header);
// CCSize tx_sz = header->getContentSize();
// header->setScaleX(sc_sz.width/tx_sz.width);
// header->setScaleY(sc_sz.height/tx_sz.height);
//
// return header;
// }while(0);
//}
return NULL;
}
void RoomOtherPlayer::updateOtherPlayerUI(int seatid)
{
if (seatAction)
return;
int begin=seatid;
int end=seatid+1;
CCLOG("update UI");
if (seatid==10) //刷新全部ui
{
begin=0;
end=9;
}
for (int i=begin;i<end;i++)
{
if (this->getChildByTag(i))
{
this->removeChildByTag(i,true);
}
if (this->getChildByTag(100+i))
{
this->removeChildByTag(100+i,true);
}
}
if (seatid>=0 && seatid<9){ //清除操作警告!
updateWarnning(seatid);
}
//for (int i=begin;i<end;i++)
//{
// if ( RoomScene::getMySeatID()==-1 && RoomScene::getRff()[i].player_status==12) //12表示没人,则播放坐下动画
// {
// Scale9Sprite* sitBtn_normal = Scale9Sprite::createWithSpriteFrameName("sit_down_frame.png");
// Scale9Sprite* sitBtn_selected = Scale9Sprite::createWithSpriteFrameName("sit_down_frame.png");
// Scale9Sprite* sitBtn_highLight = Scale9Sprite::createWithSpriteFrameName("sit_down_frame.png");
// Scale9Sprite* sitBtn_disabled = Scale9Sprite::createWithSpriteFrameName("sit_down_frame.png");
//
// sitBtn_highLight->setColor(ccc3(131,131,131));
// CCSize sitBtn_size = sitBtn_normal->getContentSize();
// ControlButton* sitBtn = ControlButton::create(sitBtn_normal);
// sitBtn->setPreferredSize(sitBtn_size);
//
// sitBtn->setZoomOnTouchDown(false);
// sitBtn->setBackgroundSpriteForState(sitBtn_normal,CCControlStateNormal);
// sitBtn->setBackgroundSpriteForState(sitBtn_selected,CCControlStateSelected);
// sitBtn->setBackgroundSpriteForState(sitBtn_highLight,CCControlStateHighlighted);
// sitBtn->setBackgroundSpriteForState(sitBtn_disabled,CCControlStateDisabled);
// sitBtn->setAnchorPoint(ccp(0.5f,0.5f));
// sitBtn->setPosition(getPostBySeatID(i));
// sitBtn->setTag(100+i);
// this->addChild(sitBtn,2);
// sitBtn->addTargetWithActionForControlEvents(this, cccontrol_selector(RoomOtherPlayer::ctrlBtnCallback), CCControlEventTouchDown);
//
// CCLabelTTF *status_label = CCLabelTTF::create("","Arial-BoldMT",18);
// status_label->setAnchorPoint(ccp(0.5f,0.5f));
// status_label->setPosition(ccp(sitBtn_size.width/2,78));
// sitBtn->addChild(status_label);
// string title = "就坐";
// status_label->setString(title.c_str());
// }
// else if (RoomScene::getRff()[i].player_status!=12 )
// {
// if ( 13 == RoomScene::getRff()[i].player_status || 3 == RoomScene::getRff()[i].player_status ) //13等待下一场的玩家,3弃牌
// {
// //头像框
// do{
// Scale9Sprite* player_icon_normal = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png");
// Scale9Sprite* player_icon_selected = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png");
// Scale9Sprite* player_icon_highLight = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png");
// Scale9Sprite* player_icon_disabled = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png");
//
// player_icon_normal->setColor(ccc3(131,131,131));
// player_icon_highLight->setColor(ccc3(131,131,131));
// CCSize player_icon_size = player_icon_normal->getContentSize();
// ControlButton* player_icon = ControlButton::create(player_icon_normal);
// CC_BREAK_IF(!player_icon);
// player_icon->setPreferredSize(player_icon_size);
//
// player_icon->setZoomOnTouchDown(false);
// player_icon->setBackgroundSpriteForState(player_icon_normal,CCControlStateNormal);
// player_icon->setBackgroundSpriteForState(player_icon_selected,CCControlStateSelected);
// player_icon->setBackgroundSpriteForState(player_icon_highLight,CCControlStateHighlighted);
// player_icon->setBackgroundSpriteForState(player_icon_disabled,CCControlStateDisabled);
// player_icon->setAnchorPoint(ccp(0.5f,0.5f));
// player_icon->setPosition(getPostBySeatID(i));
// player_icon->setTag(i);
// this->addChild(player_icon,2);
// player_icon->addTargetWithActionForControlEvents(this, cccontrol_selector(RoomOtherPlayer::ctrlBtnCallback), CCControlEventTouchDown);
// CCLabelTTF *status_label = CCLabelTTF::create("","Arial-BoldMT",14);
// CC_BREAK_IF(!status_label);
// status_label->setAnchorPoint(ccp(0.5f,0.5f));
// status_label->setPosition(ccp(player_icon_size.width/2,player_icon_size.height-10));
// status_label->setTag(0);
// player_icon->addChild(status_label);
// string title = RoomPlayer::getTitleByStatus(RoomScene::getRff()[i].player_status,RoomScene::getRff()[i].name);
// status_label->setString(title.c_str());
//
// CCLabelTTF *chipNum = CCLabelTTF::create(Players::getInstance()->convertToChipNum(RoomScene::getRff()[i].own_gold),"Arial-BoldMT",14);
// CC_BREAK_IF(!chipNum);
// chipNum->setAnchorPoint(ccp(0.5f,0.5f));
// chipNum->setPosition(ccp(player_icon_size.width/2,10));
// chipNum->setTag(1);
// player_icon->addChild(chipNum);
//
// CCSprite *photo = getPlayerAvatar(i);
// CC_BREAK_IF(!photo);
// photo->setColor(ccc3(131,131,131));
// photo->setPosition(ccp(player_icon_size.width/2, player_icon_size.height/2));
// player_icon->addChild(photo);
// }while (0);
// }
// else
// {
// do{
// //头像
// Scale9Sprite* player_icon_normal = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png");
// Scale9Sprite* player_icon_selected = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png");
// Scale9Sprite* player_icon_highLight = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png");
// Scale9Sprite* player_icon_disabled = Scale9Sprite::createWithSpriteFrameName("player_frame_1.png");
//
// player_icon_highLight->setColor(ccc3(131,131,131));
// CCSize player_icon_size = player_icon_normal->getContentSize();
// ControlButton* player_icon = ControlButton::create(player_icon_normal);
// CC_BREAK_IF(!player_icon);
// player_icon->setPreferredSize(player_icon_size);
//
// player_icon->setZoomOnTouchDown(false);
// player_icon->setBackgroundSpriteForState(player_icon_normal,CCControlStateNormal);
// player_icon->setBackgroundSpriteForState(player_icon_selected,CCControlStateSelected);
// player_icon->setBackgroundSpriteForState(player_icon_highLight,CCControlStateHighlighted);
// player_icon->setBackgroundSpriteForState(player_icon_disabled,CCControlStateDisabled);
// player_icon->setAnchorPoint(ccp(0.5f,0.5f));
// player_icon->setPosition(getPostBySeatID(i));
// player_icon->setTag(i);
// this->addChild(player_icon,2);
// player_icon->addTargetWithActionForControlEvents(this, cccontrol_selector(RoomOtherPlayer::ctrlBtnCallback), CCControlEventTouchDown);
//
// CCLabelTTF *status_label = CCLabelTTF::create("","Arial-BoldMT",14,CCSizeMake(80, 20) , kCCTextAlignmentCenter);
// CC_BREAK_IF(!status_label);
// status_label->setAnchorPoint(ccp(0.5f,0.5f));
// status_label->setPosition(ccp(player_icon_size.width/2,player_icon_size.height-10));
// status_label->setTag(0);
// player_icon->addChild(status_label);
//
// if (RoomScene::getRff()[i].bborsb==0)
// {
// string title = RoomPlayer::getTitleByStatus(RoomScene::getRff()[i].player_status,RoomScene::getRff()[i].name);
// status_label->setString(title.c_str());
// }else if (RoomScene::getRff()[i].bborsb==1){
// status_label->setString("小盲注");
// }else if (RoomScene::getRff()[i].bborsb==2){
// status_label->setString("大盲注");
// }
// CCLabelTTF *chipNum = CCLabelTTF::create(Players::getInstance()->convertToChipNum(RoomScene::getRff()[i].own_gold),"Arial-BoldMT",14);
// CC_BREAK_IF(!chipNum);
// chipNum->setAnchorPoint(ccp(0.5f,0.5f));
// chipNum->setPosition(ccp(player_icon_size.width/2,10));
// chipNum->setTag(1);
// player_icon->addChild(chipNum);
//
// //玩家头像
// CCSprite *photo = getPlayerAvatar(i);
// CC_BREAK_IF(!photo);
// photo->setPosition(ccp(player_icon_size.width/2, player_icon_size.height/2));
// player_icon->addChild(photo);
//
//
// if ( 10 == RoomScene::getRff()[i].player_status )
// {
// status_label->setString("下注中..");
//
// m_index = i;
// CCSprite *time_sp = CCSprite::createWithSpriteFrameName("player_frame_3.png");
// time_bar = CusProgressTimer::createWith(time_sp , 20.0f);
// CC_BREAK_IF(!time_bar);
// time_bar->setPosition(ccp(player_icon_size.width/2, player_icon_size.height/2));
// float left_time = RoomScene::getRff()[i].left_time-getServerTime()>20? 20:RoomScene::getRff()[i].left_time-getServerTime();
// time_bar->setLeftTime(left_time);
// time_bar->setSelector(this, common_selector(RoomOtherPlayer::updateStatus));
// time_bar->setSelector3(this, common_selector(RoomOtherPlayer::timeWarnning));
// player_icon->addChild(time_bar);
//
// if (i==RoomScene::getMySeatID()){
// time_bar->setSelector2(this, common_selector(RoomOtherPlayer::cardCallBack));
// }
// }
// }while(0);
// }
// }
//}
}
void RoomOtherPlayer::ctrlBtnCallback(CCObject *sender,cocos2d::extension::Control::EventType controlEvent)
{
ControlButton* ctrl_btn = (ControlButton*)sender;
int btn_tag = ctrl_btn->getTag();
//if (PlayerModel::getInstance()->money<RoomInfo::getInstance()->min_take && btn_tag>=100)
//{
// //自身筹码小于最小携带
// if (RoomScene::isExistPromote())
// {
// return;
// }
//
// CCString *str = CCString::createWithFormat("很遗憾,筹码达不到该房间的最小限制,当然您也可以充值获得更多筹码。");
//
// CCScene *scene = CCDirector::sharedDirector()->getRunningScene();
// RoomPopFrame *popFrame = RoomPopFrame::create();
// popFrame->setAnchorPoint(ccp(0,0));
// popFrame->setAnchorPoint(ccp(0,0));
// scene->addChild(popFrame,6);
//
// popFrame->createDialog(str->getCString(),"继续旁观","进入房间");
// popFrame->setClickOnce(true);
// popFrame->setReturnSelector(this, common_selector(RoomOtherPlayer::quicklyEnterRoom));
//
// return;
//}
//
//if (RoomInfo::getInstance()->max_limit!=-1)
//{
// if (PlayerModel::getInstance()->money>RoomInfo::getInstance()->max_limit && btn_tag>=100)
// {
// //自身筹码大于最大携带
// if (RoomScene::isExistPromote())
// {
// return;
// }
//
// CCString *str = CCString::createWithFormat("你的筹码已超过该场的最大上限,可以去更高档的桌子比赛了!");
//
// CCScene *scene = CCDirector::sharedDirector()->getRunningScene();
// RoomPopFrame *popFrame = RoomPopFrame::create();
// popFrame->setAnchorPoint(ccp(0,0));
// popFrame->setAnchorPoint(ccp(0,0));
// scene->addChild(popFrame,6);
//
// popFrame->createDialog(str->getCString(),"继续旁观","进入房间");
// popFrame->setClickOnce(true);
// popFrame->setReturnSelector(this, common_selector(RoomOtherPlayer::quicklyEnterRoom));
//
// return;
// }
//}
//
//
//if (btn_tag>=100)
//{
// CCScene *scene = CCDirector::sharedDirector()->getRunningScene();
// if (!scene->getChildByTag(10))
// {
// return;
// }
// RoomFastBuy *roomFastBuy = (RoomFastBuy*)scene->getChildByTag(10)->getChildByTag(4);
// if (roomFastBuy)
// {
// roomFastBuy->openDialog(btn_tag-100,"携带筹码");
// }
//}else{
//
// CCScene *scene = CCDirector::sharedDirector()->getRunningScene();
//
// int index=-1;
// for (int i=0;i<50;i++)
// {
// if (Players::getInstance()[i].seatid==btn_tag)
// {
// index=i;
// break;
// }
// }
// if (index==-1)
// return;
// RoomOtherInfo *otherPlayerInfo = RoomOtherInfo::create();
// otherPlayerInfo->setAnchorPoint(CCPointZero);
// otherPlayerInfo->setPosition(CCPointZero);
// otherPlayerInfo->initUI(index);
// scene->addChild(otherPlayerInfo,5);
//}
}
void RoomOtherPlayer::ctrlbtn_scheduler(float dt)
{
ControlButton *player = dynamic_cast<ControlButton*>(getChildByTag(click_index));
player->setTouchEnabled(true);
}
void RoomOtherPlayer::quicklyEnterRoom(bool bvar)
{
this->getParent()->unscheduleAllSelectors();
//RoomScene::setIsExit(true);
//
//JPacket jpacket;
//jpacket.val["cmd"] = CMD_LOGOUT_REQUEST;
//jpacket.end();
//CCTcpClient::getInstance()->send_data(jpacket.tostring());
for (int i=0;i<50;i++)
{
Players::getInstance()[i].init();
}
for (int i=0;i<9;i++)
{
//RoomScene::getRff()[i].reset();
}
//RoomInfo::getInstance()->init(); //初始化房间
enterOtherRoom();
Sound::getInstance()->playEffect("sound/sound_gangjinru.ogg");
}
void RoomOtherPlayer::enterOtherRoom()
{
std::vector<Venue> allList;
for (int i=1; i<=5; ++i)
{
std::vector<Venue> tempList;
if (i==1)
{
tempList = PlayerModel::getInstance()->venueList_1;
}
else if (i==2)
{
tempList = PlayerModel::getInstance()->venueList_2;
}
else if (i==3)
{
tempList = PlayerModel::getInstance()->venueList_3;
}
else if (i==4)
{
tempList = PlayerModel::getInstance()->venueList_4;
}
else if (i==5)
{
tempList = PlayerModel::getInstance()->venueList_5;
}
for (std::vector<Venue>::iterator iter=tempList.begin(); iter!=tempList.end(); ++iter)
{
allList.push_back(*iter);
}
}
//用于保存可以进入的桌子id
std::vector<int> room_id;
room_id.clear();
for (std::vector<Venue>::iterator iter=allList.begin(); iter!=allList.end(); ++iter)
{
if (PlayerModel::getInstance()->money>=(*iter).min_money)
{
if ((*iter).limit==-1){
room_id.push_back((*iter).room_id);
}else if (PlayerModel::getInstance()->money<=(*iter).limit)
{
room_id.push_back((*iter).room_id);
}
}
}
if (room_id.empty())
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
showToast("筹码不足,没有可进入的房间!");
#else
//CCMessageBox("筹码不足,没有可进入的房间!","错误提示");
#endif
return;
}
//随机一个桌子id
int index = rand()%room_id.size();
int table_id = room_id[index];
//取出房间信息
for (std::vector<Venue>::iterator iter=allList.begin(); iter!=allList.end(); ++iter)
{
if ((*iter).room_id==table_id)
{
//RoomInfo::getInstance()->s_bet=(*iter).sblind;
//RoomInfo::getInstance()->b_bet=(*iter).bblind;
//RoomInfo::getInstance()->min_take=(*iter).min_money;
//RoomInfo::getInstance()->max_take=(*iter).max_money;
//RoomInfo::getInstance()->port = (*iter).port;
//RoomInfo::getInstance()->ip = (*iter).ip;
//RoomInfo::getInstance()->max_limit = (*iter).limit;
//RoomInfo::getInstance()->tid = 0;
//RoomInfo::getInstance()->rmid = (*iter).showVenueId;
CCArray* vect = CCArray::create();
StringFormat::Split((*iter).quickRefuelItems.c_str(), ",", vect);
for (int i=0; i<vect->count(); ++i)
{
//RoomInfo::getInstance()->quick_addBet[i] = StringFormat::strToInt(((CCString*)vect->objectAtIndex(i))->getCString());
//DLog::showLog("-------quick_addBet[%d]: %d",i,RoomInfo::getInstance()->quick_addBet[i]);
}
break;
}
}
CCTextureCache::purgeSharedTextureCache();
CCSpriteFrameCache::purgeSharedSpriteFrameCache();
//CCTransitionScene* reScene = CCTransitionFade::create(0.5f, RoomScene::scene(),ccBLACK);
//CCDirector::sharedDirector()->replaceScene(reScene);
}
void RoomOtherPlayer::timer_bar_scheduler(float dt)
{
}
void RoomOtherPlayer::updateStatus(int status)
{
//RoomScene::getRff()[m_index].player_status = status;
//RoomScene::getRff()[m_index].bborsb = 0;
}
void RoomOtherPlayer::timeWarnning(float dt)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
if (CCUserDefault::sharedUserDefault()->getBoolForKey(SYSTEM_VOLUME_SNAKE_SWITCH_KEY,false)) {
setVibrate();
}
#endif
//RoomWarnning *roomWarnning = dynamic_cast<RoomWarnning*>(this->getParent()->getChildByTag(7));
//do{
// CC_BREAK_IF(!roomWarnning);
// roomWarnning->addWarnning(m_index);
//
// if(m_index==RoomScene::getMySeatID()){
// my_sound_id=Sound::getInstance()->playEffect("sound/sound_daojishi.ogg",true);
// }
//}while (0);
}
void RoomOtherPlayer::updateWarnning(int seatid)
{
//RoomWarnning *roomWarnning = dynamic_cast<RoomWarnning*>(this->getParent()->getChildByTag(7));
//do{
// CC_BREAK_IF(!roomWarnning);
// roomWarnning->removeWarnning(seatid);
//
// CC_BREAK_IF(my_sound_id==-1);
// Sound::getInstance()->stopEffect(my_sound_id);
//}while (0);
}
void RoomOtherPlayer::cardCallBack(float dt)
{
//int mySeatID =0;//RoomScene::getMySeatID();
//RoomCardAction* roomCardAction = dynamic_cast<RoomCardAction*>(this->getParent()->getChildByTag(2));
//roomCardAction->cardAction(10*mySeatID+1);
//roomCardAction->cardAction(10*mySeatID+2);
}
int RoomOtherPlayer::getNextPlayerSeatidOfGaming(int seatid)
{
int nextSeatid;
int index=0;
for (int i=0;i<9;i++)
{
//if ( RoomScene::getRff()[i].player_status<=11 && RoomScene::getRff()[i].player_status!=3 )
//{
// index++;
//}
}
if ( 1==index )
{
return -1;
}
for (int i=seatid+1;i<9;i++)
{
//if (RoomScene::getRff()[i].player_status<=11 && RoomScene::getRff()[i].player_status!=3 )
//{
// nextSeatid = i;
// return nextSeatid;
//}
}
for (int i=0;i<seatid;i++)
{
//if (RoomScene::getRff()[i].player_status<=11 && RoomScene::getRff()[i].player_status!=3 )
//{
// nextSeatid = i;
// return nextSeatid;
//}
}
return -1;
}
void RoomOtherPlayer::sitAction(int seatid)
{
int index = seatid;
for (int i=100 ; i<109;i++)
{
if (this->getChildByTag(i))
{
this->removeChildByTag(i,true);
}
}
for (int i=0;i!=9;++i){
if (getChildByTag(i)){
ControlButton *palyer = dynamic_cast<ControlButton*>(getChildByTag(i));
palyer->setTouchEnabled(false);
}
}
CCScene *scene = CCDirector::sharedDirector()->getRunningScene();
if (!scene->getChildByTag(10))
{
return;
}
//RoomCardAction *roomCardAction = (RoomCardAction*)scene->getChildByTag(10)->getChildByTag(2);
//RoomTag *roomTag = (RoomTag*)scene->getChildByTag(10)->getChildByTag(5);
//RoomChip *roomChip = (RoomChip*)scene->getChildByTag(10)->getChildByTag(3);
//RoomWarnning *roomWarnning = (RoomWarnning*)scene->getChildByTag(10)->getChildByTag(7);
//RoomLight *roomLight = (RoomLight*)scene->getChildByTag(10)->getChildByTag(8);
if (index==0)
{
}
else if (index<5)
{
seatAction=true;
//if (roomCardAction)
//{
// roomCardAction->hidePlayerCards();
//}
//if (roomTag)
//{
// roomTag->hideTag();
//}
//if (roomChip)
//{
// roomChip->hideAllChips();
//}
//if (roomWarnning)
//{
// roomWarnning->hideWarnning();
//}
//if (roomLight) {
// roomLight->hideLight();
//}
int controlNum = index+1;
for (int i=0;i<9;i++)
{
if (this->getChildByTag(i))
{
CCPointArray *array = CCPointArray::create(10);
int seat_id_pos = i;
for (int j=i;j<i+controlNum;j++)
{
array->addControlPoint(getPostBySeatID(seat_id_pos,true));
seat_id_pos--;
if (seat_id_pos<0)
{
seat_id_pos=8;
}
}
CCCatmullRomTo *action = CCCatmullRomTo::create(1, array);
this->getChildByTag(i)->runAction(action);
}
}
}else{
seatAction=true;
//if (roomCardAction)
//{
// roomCardAction->hidePlayerCards();
//}
//if (roomTag)
//{
// roomTag->hideTag();
//}
//if (roomChip)
//{
// roomChip->hideAllChips();
//}
//if (roomWarnning)
//{
// roomWarnning->hideWarnning();
//}
//if (roomLight) {
// roomLight->hideLight();
//}
int controlNum = 10-index;
for (int i=0;i<9;i++)
{
if (this->getChildByTag(i))
{
CCPointArray *array = CCPointArray::create(10);
int seat_id_pos = i;
for (int j=i;j<i+controlNum;j++)
{
array->addControlPoint(getPostBySeatID(seat_id_pos,true));
seat_id_pos++;
if (seat_id_pos>8)
{
seat_id_pos=0;
}
}
CCCatmullRomTo *action = CCCatmullRomTo::create(1, array);
this->getChildByTag(i)->runAction(action);
}
}
}
CCCallFuncN *cf = CCCallFuncN::create(this, callfuncN_selector(RoomOtherPlayer::showActionTag));
this->runAction(CCSequence::create(CCDelayTime::create(1.0f),cf,NULL));
if (!scene->getChildByTag(10))
{
return;
}
//RoomBottom *roomBottom = (RoomBottom*)scene->getChildByTag(10)->getChildByTag(1);
//roomBottom->updateMyPlayerUI(seatid);
//坐下音效
Sound::getInstance()->playEffect("sound/sound_gangjinru.ogg");
}
void RoomOtherPlayer::showActionTag(CCNode *pSender)
{
for (int i=0; i!=9; ++i) {
if (getChildByTag(i)){
ControlButton *palyer = dynamic_cast<ControlButton*>(getChildByTag(i));
palyer->setTouchEnabled(true);
}
}
CCScene *scene = CCDirector::sharedDirector()->getRunningScene();
if (!scene->getChildByTag(10))
{
return;
}
//RoomCardAction *roomCardAction = (RoomCardAction*)scene->getChildByTag(10)->getChildByTag(2);
//if (roomCardAction)
//{
// roomCardAction->showPlayerCards();
//}
if (!scene->getChildByTag(10))
{
return;
}
//RoomTag *roomTag = (RoomTag*)scene->getChildByTag(10)->getChildByTag(5);
//if (roomTag)
//{
// roomTag->showTag();
//}
if (!scene->getChildByTag(10))
{
return;
}
//RoomChip *roomChip = (RoomChip*)scene->getChildByTag(10)->getChildByTag(3);
//if (roomChip)
//{
// roomChip->showAllChips();
//}
if (!scene->getChildByTag(10))
{
return;
}
//RoomWarnning *roomWarnning = (RoomWarnning*)scene->getChildByTag(10)->getChildByTag(7);
//if (roomWarnning)
//{
// roomWarnning->showWarnning();
//}
if (!scene->getChildByTag(10))
{
return;
}
//RoomLight *roomLight = (RoomLight*)scene->getChildByTag(10)->getChildByTag(8);
//if (roomLight) {
// roomLight->showLight();
//}
if (seatAction){
seatAction=false;
updateOtherPlayerUI(10);
}
}
void RoomOtherPlayer::addWinFrame(int seatid)
{
do{
CC_BREAK_IF(!getChildByTag(seatid));
CC_BREAK_IF(getChildByTag(seatid)->getChildByTag(321));
CCSprite *frame = CCSprite::createWithSpriteFrameName("room_win_frame.png");
CC_BREAK_IF(!frame);
frame->setPosition(ccp(getChildByTag(seatid)->getContentSize().width/2,
getChildByTag(seatid)->getContentSize().height/2));
frame->setTag(321);
getChildByTag(seatid)->addChild(frame,5);
vector<CCPoint> vecPos;
vecPos.push_back(ccp(21,3));
vecPos.push_back(ccp(3,107));
vecPos.push_back(ccp(65,117));
vecPos.push_back(ccp(83,13));
float delay=0.5f;
CCCallFuncN *cf = CCCallFuncN::create(this, callfuncN_selector(RoomOtherPlayer::removeWinStar));
for (int i=0; i!=4; ++i) {
CCSprite *star = CCSprite::createWithSpriteFrameName("room_win_star.png");
star->setPosition(vecPos[i]);
star->setOpacity(0);
frame->addChild(star);
star->runAction(CCSequence::create(CCDelayTime::create(delay),CCFadeIn::create(0.5f),CCFadeOut::create(0.5f),cf,NULL));
delay+=1.0f;
}
}while(0);
}
void RoomOtherPlayer::removeWinStar(CCNode *pSender)
{
do{
CCSprite *sp = dynamic_cast<CCSprite*>(pSender);
CC_BREAK_IF(!sp);
sp->removeFromParentAndCleanup(true);
}while (0);
}
| [
"[email protected]"
] | |
c940a681d180a60eb17cfc861ba1f29f3b711180 | ac7707d2c5e1c286593305cd5a9b63f66cacaf20 | /CS 142/Chapter Quizzes/Chapter Quizzes/Chapter Quizzes.cpp | b400a40ecb44f868d6991625f42220ba222844c1 | [] | no_license | jacobparry/CS142_IntroToProgramming | 73e715e88376a58ca451d4264366b02019f9da52 | 488da02361b73429b36c98088527b1a599fcefe9 | refs/heads/master | 2020-03-10T03:17:30.238152 | 2018-04-11T22:23:54 | 2018-04-11T22:23:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 841 | cpp | #include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
const int NOT_FOUND = -1;
const int times_to_shuffle = 100;
const int EVEN = 0;
const int POW_OF_2 = 2;
const int TRUE_POW = 1;
int main()
{
bool power = false;
vector<string> restaurants(8);
int number_of_restaurants = 0;
for (int i = 0; i < restaurants.size(); i++)
{
number_of_restaurants++;
}
double true_power = number_of_restaurants;
int number_of_rounds = 0;
if ((number_of_restaurants % 2) == EVEN)
{
bool trial = true;
while (trial)
{
true_power = true_power / POW_OF_2;
number_of_rounds++;
if (true_power == TRUE_POW)
{
trial = false;
}
else if (true_power < TRUE_POW)
{
trial = false;
}
}
}
else
{
}
system("pause");
return 0;
} | [
"[email protected]"
] | |
31b1eaf261f7244551a344a64dd046bd47567283 | f0f0cdbc587382a25941bfbed229f0057492696d | /olivia/bytearray.h | 63c6026decef16efec41e6382947eddcd69d6edc | [] | no_license | YuyiLin-Oliva/tinyServer | 428b796a9c8d4ce738cea34ec4b4658f3c850413 | 9e632dda6954c97fba3d8e4a73a1f2042edf1685 | refs/heads/master | 2021-03-17T21:03:16.953237 | 2020-03-13T10:33:54 | 2020-03-13T10:33:54 | 247,017,865 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,330 | h | //二进制数组(序列化/反序列化)
#ifndef __BYTEARRAY_H__
#define __BYTEARRAY_H__
#include <memory>
#include <string>
#include <stdint.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <vector>
namespace olivia {
/**
* @brief 二进制数组,提供基础类型的序列化,反序列化功能
*/
class ByteArray {
public:
typedef std::shared_ptr<ByteArray> ptr;
//ByteArray的存储节点
struct Node {
/**
* @brief 构造指定大小的内存块
* @param[in] s 内存块字节数
*/
Node(size_t s);
Node();
//析构函数,释放内存
~Node();
//内存块地址指针
char* ptr;
//下一个内存块地址
Node* next;
/// 内存块大小
size_t size;
};
/**
* @brief 使用指定长度的内存块构造ByteArray
* @param[in] base_size 内存块大小
*/
ByteArray(size_t base_size = 4096);
~ByteArray();
/**
* @brief 写入固定长度int8_t类型的数据
* @post m_position += sizeof(value)
* 如果m_position > m_size 则 m_size = m_position
*/
void writeFint8 (int8_t value);
void writeFuint8 (uint8_t value);
//写入固定长度int16_t类型的数据(大端/小端)
void writeFint16 (int16_t value);
void writeFuint16(uint16_t value);
/**
* @brief 写入固定长度int32_t类型的数据(大端/小端)
* @post m_position += sizeof(value)
* 如果m_position > m_size 则 m_size = m_position
*/
void writeFint32 (int32_t value);
void writeFuint32(uint32_t value);
void writeFint64 (int64_t value);
void writeFuint64(uint64_t value);
// /**
// * @brief 写入有符号Varint32类型的数据
// * @post m_position += 实际占用内存(1 ~ 5)
// * 如果m_position > m_size 则 m_size = m_position
// */
// void writeInt32 (int32_t value);
// void writeUint32 (uint32_t value);
/**
// * @brief 写入有符号Varint64类型的数据
// * @post m_position += 实际占用内存(1 ~ 10)
// * 如果m_position > m_size 则 m_size = m_position
// */
// void writeInt64 (int64_t value);
// void writeUint64 (uint64_t value);
/**
* @brief 写入float类型的数据
* @post m_position += sizeof(value)
* 如果m_position > m_size 则 m_size = m_position
*/
void writeFloat (float value);
void writeDouble (double value);
/**
* @brief 写入std::string类型的数据,用uint16_t作为长度类型
* @post m_position += 2 + value.size()
* 如果m_position > m_size 则 m_size = m_position
*/
void writeStringF16(const std::string& value);
/**
* @brief 写入std::string类型的数据,用uint32_t作为长度类型
* @post m_position += 4 + value.size()
* 如果m_position > m_size 则 m_size = m_position
*/
void writeStringF32(const std::string& value);
/**
* @brief 写入std::string类型的数据,用uint64_t作为长度类型
* @post m_position += 8 + value.size()
* 如果m_position > m_size 则 m_size = m_position
*/
void writeStringF64(const std::string& value);
// /**
// * @brief 写入std::string类型的数据,用无符号Varint64作为长度类型
// * @post m_position += Varint64长度 + value.size()
// * 如果m_position > m_size 则 m_size = m_position
// */
// void writeStringVint(const std::string& value);
/**
* @brief 写入std::string类型的数据,无长度
* @post m_position += value.size()
* 如果m_position > m_size 则 m_size = m_position
*/
void writeStringWithoutLength(const std::string& value);
/**
* @brief 读取int8_t类型的数据
* @pre getReadSize() >= sizeof(int8_t)
* @post m_position += sizeof(int8_t);
* @exception 如果getReadSize() < sizeof(int8_t) 抛出 std::out_of_range
*/
int8_t readFint8();
uint8_t readFuint8();
/**
* @brief 读取int16_t类型的数据
* @pre getReadSize() >= sizeof(int16_t)
* @post m_position += sizeof(int16_t);
* @exception 如果getReadSize() < sizeof(int16_t) 抛出 std::out_of_range
*/
int16_t readFint16();
uint16_t readFuint16();
/**
* @brief 读取int32_t类型的数据
* @pre getReadSize() >= sizeof(int32_t)
* @post m_position += sizeof(int32_t);
* @exception 如果getReadSize() < sizeof(int32_t) 抛出 std::out_of_range
*/
int32_t readFint32();
uint32_t readFuint32();
/**
* @brief 读取int64_t类型的数据
* @pre getReadSize() >= sizeof(int64_t)
* @post m_position += sizeof(int64_t);
* @exception 如果getReadSize() < sizeof(int64_t) 抛出 std::out_of_range
*/
int64_t readFint64();
uint64_t readFuint64();
// /**
// * @brief 读取有符号Varint32类型的数据
// * @pre getReadSize() >= 有符号Varint32实际占用内存
// * @post m_position += 有符号Varint32实际占用内存
// * @exception 如果getReadSize() < 有符号Varint32实际占用内存 抛出 std::out_of_range
// */
// int32_t readInt32();
// uint32_t readUint32();
// /**
// * @brief 读取有符号Varint64类型的数据
// * @pre getReadSize() >= 有符号Varint64实际占用内存
// * @post m_position += 有符号Varint64实际占用内存
// * @exception 如果getReadSize() < 有符号Varint64实际占用内存 抛出 std::out_of_range
// */
// int64_t readInt64();
// uint64_t readUint64();
/**
* @brief 读取float类型的数据
* @pre getReadSize() >= sizeof(float)
* @post m_position += sizeof(float);
* @exception 如果getReadSize() < sizeof(float) 抛出 std::out_of_range
*/
float readFloat();
/**
* @brief 读取double类型的数据
* @pre getReadSize() >= sizeof(double)
* @post m_position += sizeof(double);
* @exception 如果getReadSize() < sizeof(double) 抛出 std::out_of_range
*/
double readDouble();
/**
* @brief 读取std::string类型的数据,用uint16_t作为长度
* @pre getReadSize() >= sizeof(uint16_t) + size
* @post m_position += sizeof(uint16_t) + size;
* @exception 如果getReadSize() < sizeof(uint16_t) + size 抛出 std::out_of_range
*/
std::string readStringF16();
/**
* @brief 读取std::string类型的数据,用uint32_t作为长度
* @pre getReadSize() >= sizeof(uint32_t) + size
* @post m_position += sizeof(uint32_t) + size;
* @exception 如果getReadSize() < sizeof(uint32_t) + size 抛出 std::out_of_range
*/
std::string readStringF32();
/**
* @brief 读取std::string类型的数据,用uint64_t作为长度
* @pre getReadSize() >= sizeof(uint64_t) + size
* @post m_position += sizeof(uint64_t) + size;
* @exception 如果getReadSize() < sizeof(uint64_t) + size 抛出 std::out_of_range
*/
std::string readStringF64();
// /**
// * @brief 读取std::string类型的数据,用无符号Varint64作为长度
// * @pre getReadSize() >= 无符号Varint64实际大小 + size
// * @post m_position += 无符号Varint64实际大小 + size;
// * @exception 如果getReadSize() < 无符号Varint64实际大小 + size 抛出 std::out_of_range
// */
// std::string readStringVint();
/**
* @brief 清空ByteArray
* @post m_position = 0, m_size = 0
*/
void clear();
/**
* @brief 写入size长度的数据
* @param[in] buf 内存缓存指针
* @param[in] size 数据大小
* @post m_position += size, 如果m_position > m_size 则 m_size = m_position
*/
void write(const void* buf, size_t size);
/**
* @brief 读取size长度的数据
* @param[out] buf 内存缓存指针
* @param[in] size 数据大小
* @post m_position += size, 如果m_position > m_size 则 m_size = m_position
* @exception 如果getReadSize() < size 则抛出 std::out_of_range
*/
void read(void* buf, size_t size);
/**
* @brief 读取size长度的数据
* @param[out] buf 内存缓存指针
* @param[in] size 数据大小
* @param[in] position 读取开始位置
* @exception 如果 (m_size - position) < size 则抛出 std::out_of_range
*/
void read(void* buf, size_t size, size_t position) const;
//返回ByteArray当前位置
size_t getPosition() const { return m_position;}
/**
* @brief 设置ByteArray当前位置
* @post 如果m_position > m_size 则 m_size = m_position
* @exception 如果m_position > m_capacity 则抛出 std::out_of_range
*/
void setPosition(size_t v);
/**
* @brief 把ByteArray的数据写入到文件中
* @param[in] name 文件名
*/
bool writeToFile(const std::string& name) const;
/**
* @brief 从文件中读取数据
* @param[in] name 文件名
*/
bool readFromFile(const std::string& name);
//返回内存块的大小
size_t getBaseSize() const { return m_baseSize;}
//返回可读取数据大小
size_t getReadSize() const { return m_size - m_position;}
//是否是小端
bool isLittleEndian() const;
//设置是否为小端
void setIsLittleEndian(bool val);
//将ByteArray里面的数据[m_position, m_size)转成std::string
std::string toString() const;
//将ByteArray里面的数据[m_position, m_size)转成16进制的std::string(格式:FF FF FF)
std::string toHexString() const;
/**
* @brief 获取可读取的缓存,保存成iovec数组
* @param[out] buffers 保存可读取数据的iovec数组
* @param[in] len 读取数据的长度,如果len > getReadSize() 则 len = getReadSize()
* @return 返回实际数据的长度
*/
uint64_t getReadBuffers(std::vector<iovec>& buffers, uint64_t len = ~0ull) const;
//获取可读取的缓存,保存成iovec数组,从position位置开始
uint64_t getReadBuffers(std::vector<iovec>& buffers, uint64_t len, uint64_t position) const;
/**
* @brief 获取可写入的缓存,保存成iovec数组
* @param[out] buffers 保存可写入的内存的iovec数组
* @param[in] len 写入的长度
* @return 返回实际的长度
* @post 如果(m_position + len) > m_capacity 则 m_capacity扩容N个节点以容纳len长度
*/
uint64_t getWriteBuffers(std::vector<iovec>& buffers, uint64_t len);
//返回数据的长度
size_t getSize() const { return m_size;}
private:
//扩容ByteArray,使其可以容纳size个数据(如果原本可以可以容纳,则不扩容)
void addCapacity(size_t size);
//获取当前的可写入容量
size_t getCapacity() const { return m_capacity - m_position;}
private:
// 内存块的大小
size_t m_baseSize;
// 当前操作位置
size_t m_position;
// 当前的总容量
size_t m_capacity;
// 当前数据的大小
size_t m_size;
// 字节序,默认大端
int8_t m_endian;
/// 第一个内存块指针
Node* m_root;
// 当前操作的内存块指针
Node* m_cur;
};
}
#endif
| [
"[email protected]"
] | |
83466580cca2ad63126661a09ee4acecd135c2d8 | 8bb53a4764186cca14296b405fbced488b303794 | /Course.cpp | 9b7e9cf156ac33610149386b9d27498a4051bb95 | [] | no_license | mbooali/CourseManagementSystem_Simulation | 62f7c32dbc54e990f66f319fb8268e0cd0353aef | 198ecb9e5a542b555dfb7898e0e431c48db21278 | refs/heads/master | 2021-01-17T11:58:12.973362 | 2015-03-15T05:00:06 | 2015-03-15T05:00:06 | 32,245,814 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 736 | cpp | // ourse.cpp: implementation of the Course class.
//
//////////////////////////////////////////////////////////////////////
#include "Course.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
string Course::GiveName()
{
return name;
}
Course::Course () //class Constructor for Course
{
zarfiat = vahed = term = status = mark = 0;
}
void Course::SetVars( int v, int z, string n )
{
vahed = v;
zarfiat = z;
name = n;
}
Course* Course::Next()
{
return next;
}
void Course::SetNext( Course *next2 )
{
next = next2;
}
void Course::Show()
{
cout << name << endl << vahed<< endl << zarfiat << endl;
}
| [
"[email protected]"
] | |
da99729ecea2e077622c5363bf8ed655e6ed6dbf | 1d8d4257b1af9217c5bf36367c38f04fcf475698 | /RayTracingDemo/GeometricObjects/Triangles/SmoothUVMeshTriangle.h | ed4ea4bf226d854919b5a6a7fb1fb988339beae9 | [] | no_license | kagtag/RayTracingDemo | ed53780fdc91163cbe45d277efa01f14f21b4944 | 9e0660e31859afd0126e93761331a05b3d8fa831 | refs/heads/master | 2020-04-13T01:09:52.738823 | 2019-02-05T14:31:10 | 2019-02-05T14:31:10 | 162,866,164 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 271 | h | #pragma once
#include "SmoothMeshTriangle.h"
class SmoothUVMeshTriangle : public SmoothMeshTriangle
{
public:
SmoothUVMeshTriangle();
SmoothUVMeshTriangle(Mesh* mesh, int v0, int v1, int v2);
virtual bool
hit(const Ray& ray, double& tmin, ShadeRec& sr) const;
}; | [
"[email protected]"
] | |
95002ba9a183a5a01ea48372d05aceb0a90a39d6 | f6e5e55a6e206a850ee5382fb420aa5ae2dc4c7b | /25_1_Template/25_1_Template/Pessoa.cpp | 2fada3ab4e36830fffb8646d29b4630b8fdaa69c | [] | no_license | rodrigo-prado/CursoCPlusPlus | a76f672152eb6111a643f6d2ff1030e7e04a167e | 784890712d6041414d37c294a54e18eea7ce7dea | refs/heads/master | 2023-01-22T14:33:44.738964 | 2020-11-27T22:01:57 | 2020-11-27T22:01:57 | 315,754,784 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 490 | cpp | #include "Pessoa.h"
#include <iostream>
using namespace std;
Pessoa::Pessoa(string first,string last,
int arbitrary) : primeiro_nome_(first),ultimo_nome_(last),
idade_(arbitrary)
{
}
Pessoa::~Pessoa()
{
}
string Pessoa::GetName()
{
return primeiro_nome_ + " " + ultimo_nome_;
}
bool Pessoa::operator<(Pessoa const& p) const
{
return idade_ < p.idade_;
}
bool Pessoa::operator<(int i) const
{
return idade_ < i;
}
bool operator<(int i, Pessoa const& p)
{
return i < p.idade_;
}
| [
"[email protected]"
] | |
4eb5c32754ef2223d725d5d175d5e2fa735db957 | 5e3854a39930f676bedc35bd01a0aebf3fb431c6 | /algorithm/leetcode10_regular-expression-matching.cpp | ffbba9ae6a89f91d211897b89ca352147ea4309e | [] | no_license | kobe24o/LeetCode | a6f17f71f456055b0f740e9f5a91626c5885212f | 519145d4c27e60ff001154df8d0e258508a2039f | refs/heads/master | 2022-08-04T12:44:33.841722 | 2022-07-30T06:55:47 | 2022-07-30T06:55:47 | 198,562,034 | 36 | 17 | null | null | null | null | UTF-8 | C++ | false | false | 1,441 | cpp | class Solution {
public:
bool isMatch(string s, string p) {
int m = s.size(), n = p.size(), i, j;
vector<vector<int>> dp(m+1, vector<int>(n+1, false));
dp[0][0] = true;
for(i = 0; i <= m; ++i)
{
for(j = 1; j <= n; ++j)
{
if(p[j-1] == '*')//p第j个字符为*
{
dp[i][j] |= dp[i][j-2];//*匹配0次前面的字符
if(match(s,p,i,j-1))
//s第i个和p的第j-1个可以匹配, *匹配再多匹配一次i-1
dp[i][j] |= dp[i-1][j];
}
else//p第j个字符不为*
{
if(match(s,p,i,j))//必须是i、j能够匹配
dp[i][j] |= dp[i-1][j-1];
}
}
}
return dp[m][n];
}
bool match(string &s, string &p, int i, int j)
{ //第i,j个字符能匹配
return i>0 && (p[j-1]=='.' || p[j-1]==s[i-1]);
}
};
class Solution {
public:
bool isMatch(string s, string p) {
if(p.empty())
return s.empty();
if(p[1]=='*')
{
return isMatch(s, p.substr(2)) ||
((!s.empty() && (s[0]==p[0] || p[0]=='.')) && isMatch(s.substr(1),p));
}
else
return (!s.empty() && (s[0]==p[0]||p[0]=='.')) && isMatch(s.substr(1),p.substr(1));
}
};
| [
"[email protected]"
] |
Subsets and Splits