text
stringlengths 8
6.88M
|
|---|
#ifndef ORDER_H
#define ORDER_H
#include "Drink.h"
#include <iostream>
using namespace std;
class Order
{
public:
Order();
virtual ~Order();
friend istream& operator >>(istream& in, Drink drink);
friend ostream& operator <<(ostream& out, Drink drink);
protected:
private:
};
#endif // ORDER_H
|
#include <cstdio>
#include <algorithm>
#include <iostream>
using namespace std;
int ara[500009];
int again[500009];
int bapke(int n)
{
if(ara[n]==n)
return n;
else
bapke(ara[n]);
}
int main()
{
int n,m,i,A,B,t,maxi;
scanf("%d",&t);
while(t--){
scanf("%d %d",&n,&m);
maxi=-1;
for(i=0;i<=n;i++)
{
ara[i]=i;
again[i]=0;
}
for(i=1;i<=m;i++)
{
scanf("%d %d",&A,&B);
if(A>B)
swap(A,B);
A=bapke(A);
B=bapke(B);
if(A!=B)
{
ara[B]=A;
}
}
for(i=1;i<=n;i++)
{
int x=bapke(i);
again[x]=again[x]+1;
if(maxi<again[x])
{
maxi=again[x];
}
}
printf("%d\n",maxi);
}
return 0;
}
|
#include "audio\Singularity.Audio.h"
namespace Singularity
{
namespace Audio
{
#pragma region Constructors and Finalizers
AdaptiveParameter::AdaptiveParameter(String name, float min, float max) : m_pName(name), m_fMin(min), m_fMax(max), m_fCurrent(min)
{
}
AdaptiveParameter::~AdaptiveParameter()
{
}
String AdaptiveParameter::GetName()
{
return m_pName;
}
float AdaptiveParameter::GetMin()
{
return m_fMin;
}
float AdaptiveParameter::GetMax()
{
return m_fMax;
}
float AdaptiveParameter::GetCurrentValue()
{
return m_fCurrent;
}
void AdaptiveParameter::SetName(String name)
{
this->m_pName = name;
}
void AdaptiveParameter::SetMin(float min)
{
this->m_fMin = min;
this->m_fCurrent = min;
}
void AdaptiveParameter::SetMax(float max)
{
this->m_fMax = max;
}
void AdaptiveParameter::SetCurrentValue(float value)
{
this->m_fCurrent = value;
if (m_fCurrent > m_fMax)
{
m_fCurrent = m_fMax;
}
if (m_fCurrent < m_fMin)
{
m_fCurrent = m_fMin;
}
}
#pragma endregion
}
}
|
// shared project unit tests
// (c) 2020 Michael Fink
// https://github.com/vividos/OldStuff/
// Unit tests for shared project files
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define STRINGIFY2(x) #x
#define STRINGIFY(x) STRINGIFY2(x)
#define Assert(condition, text) \
if (!(condition)) \
{ \
printf("%s(%i): Assert! Error in condition: %s\nMessage: %s", \
__FILE__, __LINE__, \
STRINGIFY(condition), text); \
getch(); \
exit(-1); \
}
#include "defs.h"
#include "linmap.h"
// tests linear_mapping class
void TestLinearMapping()
{
linear_mapping m1, m2(0.f, -1.f, 100L, 0L);
Assert(m1.float2long(0.0) == 0L, "mapped long value must be 0");
Assert(m1.float2long(0.5) == 50L, "mapped long value must be 50");
Assert(m1.float2long(1.0) == 100L, "mapped long value must be 100");
Assert(m1.float2long(42.0) == 4200L, "mapped long value must be 4200");
Assert(m1.long2float(0L) == 0.f, "mapped float value must be 0.f");
Assert(m1.long2float(42L) == 0.42f, "mapped float value must be 0.42f");
Assert(m2.float2long(0.0) == 100L, "mapped long value must be 100");
Assert(m2.float2long(-0.5) == 50L, "mapped long value must be 50");
Assert(m2.float2long(1.0) == 200L, "mapped long value must be 200");
}
#include "cstring.h"
// this tests adding to a string with a fixed buffer size; since
// the buffer is not automatically resized, only a part of the
// added text appears in the string.
void TestStringAdd()
{
string n("test1", 7);
n.add("test2");
Assert(n == "test1t", "string must be added partially");
}
void TestStringFormat()
{
string s(32); // note that initial buffer is large enough
s.format("%i + %3.1f = %s", 42, 64.f, "106");
Assert(s == "42 + 64.0 = 106", "formatted text must match");
}
#include "app.h"
#include "keyboard.h"
class testapp: public app
{
int count;
public:
virtual void init()
{
count = 0;
}
virtual void show_screen();
virtual void handle_key(keycode kc)
{
if (kc == kbF1 &&
keyboard::is_special_key(skAlt))
count++;
}
};
void testapp::show_screen()
{
point min = {20, 5}, max = {40, 55};
textwindow* wnd = sc.openwindow(min, max);
wnd->setattr(white, blue);
wnd->clear();
wnd->gotoxy(2, 2);
wnd->outstr("Hello World!");
wnd->gotoxy(4, 6);
string text(40);
text.format("Count is: %i", count);
wnd->outstr(text);
wnd->setattr(white, blue, true);
wnd->gotoxy(6, 10);
wnd->outstr("Increase count by pressing Alt+F1!");
}
void TestApp()
{
testapp app;
app.run();
}
void main()
{
clrscr();
TestLinearMapping();
TestStringAdd();
TestStringFormat();
TestApp();
printf("All tests OK!");
getch();
};
|
/*
프로그램 설명
1~10 까지 덧셈하여 출력
기존에 지니던 문제점 해결
*/
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
int _tmain(int argc, TCHAR* argv[])
{
STARTUPINFO si1 = { 0, };
STARTUPINFO si2 = { 0, };
PROCESS_INFORMATION pi1;
PROCESS_INFORMATION pi2;
DWORD return_val1;
DWORD return_val2;
TCHAR command1[] = _T("PartAdder.exe 1 5");
TCHAR command2[] = _T("PartAdder.exe 6 10");
DWORD sum = 0;
si1.cb = sizeof(si1);
si2.cb = sizeof(si2);
CreateProcess(NULL, command1,
NULL, NULL, TRUE,
0, NULL, NULL,
&si1, &pi1);
CreateProcess(NULL, command2,
NULL, NULL, TRUE,
0, NULL, NULL,
&si2, &pi2);
CloseHandle(pi1.hThread);
CloseHandle(pi2.hThread);
/**********문제 해결을 위해 추가되는 두줄의 코드 ****************/
WaitForSingleObject(pi1.hProcess, INFINITE);
WaitForSingleObject(pi2.hProcess, INFINITE);
GetExitCodeProcess(pi1.hProcess, &return_val1);
GetExitCodeProcess(pi2.hProcess, &return_val2);
if (return_val1 == -1 || return_val2 == -1)
return -1; //비정상적 종료
sum += return_val1;
sum += return_val2;
_tprintf(_T("total: %d \n"), sum);
CloseHandle(pi1.hProcess);
CloseHandle(pi2.hProcess);
return 0;
}
|
//#include <stdio.h>
//#include <stdlib.h>
//
//int main()
//{
// printf("hello world\n");
// system("pause");
//}
//#include <stdio.h>
//#include <stdlib.h>
////void insertSort(int *num, int len)
////{
//// int i, j, temp;
//// for (i = 0; i < len - 1; i++) {
//// j = i + 1;
//// temp = num[j]; //temp存储新元素
//// while(temp < num[--j] && j >= 0) {//升序排序,降序排序需要num[j] < temp
//// num[j + 1] = num[j];
//// }
//// num[j + 1] = temp;
//// }
////}
//void insertSort(int *arr, int len)
//{
// int i, j, temp;
//
// for (i = 0; i < len; i++) {
// j = i;
// temp = arr[j];
// while(temp < arr[--j] && j >= 0) {
// arr[j + 1] = arr[j];
// }
// arr[j + 1] = temp;
// }
//}
//void test(int arr[], int sz)
//{
// for (int i = 0; i < sz; ++i)
// printf("%d ", arr[i]);
// printf("\n");
//}
//int main()
//{
// int arr[] = { 2, 5, 6, 1, 8, 0, 4, 6, 8, 7, 9, 6};
// int sz = sizeof(arr) / sizeof(arr[0]);
// printf("未排序的数组:> ");
// test(arr,sz);//输出数组中的元素
// insertSort(arr, sz);//选择排序
// printf("已经排好序的数组:> ");
// test(arr, sz);
// system("pause");
// return 0;
//}
//#include <stdio.h>
//#include <stdlib.h>
//
//void selectSort(int *arr, int len)
//{
// int i, j, temp, minIndex;
//
// for (i = 0; i < len; i++) {
// minIndex = i;
// for (j = i; j < len; j++) {
// if( arr[j] < arr[minIndex]) {
// minIndex = j;
// }
// }
// if (minIndex != i) {
// temp = arr[i];
// arr[i] = arr[minIndex];
// arr[minIndex] = temp;
// }
// }
//}
//void test(int arr[], int sz)
//{
// for (int i = 0; i < sz; ++i)
// printf("%d ", arr[i]);
// printf("\n");
//}
//int main()
//{
// int arr[] = { 2, 5, 6, 1, 8, 0, 4, 6, 8, 7, 9, 6};
// int sz = sizeof(arr) / sizeof(arr[0]);
// printf("未排序的数组:> ");
// test(arr,sz);//输出数组中的元素
// selectSort(arr, sz);//选择排序
// printf("已经排好序的数组:> ");
// test(arr, sz);
// system("pause");
// return 0;
//}
//#include <stdio.h>
//#include <stdlib.h>
//#include <time.h>
//
//void quickSort(int *arr, int l, int r)
//{
// int i = l, j = r, temp, k;
// if (i < j) {
// k = rand() % (j - i + 1) + i - 1;
// temp = arr[k];
// while(i < j) {
// while(arr[j] >= temp && j > k) {
// j--;
// }
// if (j > k) {
// arr[k] = arr[j];
// k = j;
// }
//
// while(arr[i] <= temp && i < k) {
// i++;
// }
// if (i < k) {
// arr[k] = arr[i];
// k = i;
// }
// }
//
// arr[k] = temp;
// quickSort(arr, l , k - 1);
// quickSort(arr, k + 1, r);
// }
//
//}
//void test(int arr[], int sz)
//{
// for (int i = 0; i < sz; ++i)
// printf("%d ", arr[i]);
// printf("\n");
//}
//int main()
//{
// srand((unsigned int) time(NULL));
// int arr[] = { 2, 5, 6, 1, 8, 0, 4, 6, 8, 7, 9, 6};
// int sz = sizeof(arr) / sizeof(arr[0]);
// printf("未排序的数组:> ");
// test(arr,sz); //输出数组中的元素
// quickSort(arr, 0, sz - 1); //快速排序 = 快排
// printf("已经排好序的数组:> ");
// test(arr, sz);
// system("pause");
// return 0;
//}
//#include <stdio.h>
//#include <stdlib.h>
//
//void quickSort(int *arr, int l, int r)
//{
// int i = l, j = r, temp;
//
// if (i < j) {
// temp = arr[i];
// while(i < j) {
// while(arr[j] >= temp && j > i) {
// j--;
// }
// if (j > i) {
// arr[i++] = arr[j];
// }
//
// while(arr[i] <= temp && j > i) {
// i++;
// }
// if (j > i) {
// arr[j--] = arr[i];
// }
// }
//
// arr[i] = temp;
// quickSort(arr, l, i - 1);
// quickSort(arr, i + 1, r);
// }
//}
//void test(int arr[], int sz)
//{
// for (int i = 0; i < sz; ++i)
// printf("%d ", arr[i]);
// printf("\n");
//}
//int main()
//{
// int arr[] = { 2, 5, 6, 1, 8, 0, 4, 6, 8, 7, 9, 6};
// int sz = sizeof(arr) / sizeof(arr[0]);
// printf("未排序的数组:> ");
// test(arr,sz); //输出数组中的元素
// quickSort(arr, 0, sz - 1); //快速排序 = 快排
// printf("已经排好序的数组:> ");
// test(arr, sz);
// system("pause");
// return 0;
//}
//#include <stdio.h>
//#include <stdlib.h>
//
//void bubbleSort(int *arr, int len)
//{
// int i, j, temp;
//
// for (i = 0; i < len - 1; i++) {
// for ( j = 0; j < len - 1 - i; j++) {
// if (arr[j] > arr[j + 1]) {
// temp = arr[j];
// arr[j] = arr[j + 1];
// arr[j + 1] = temp;
// }
// }
// }
//}
//int main()
//{
// int arr1[] = {34, 27, 55, 8, 97, 67, 35, 43, 22, 101, 78, 96, 35, 99};
// int i;
// int len = sizeof(arr1) / sizeof(*arr1);
//
// bubbleSort(arr1, len);
// printf("len = %d \n", len);
// printf("use bubble sort asc the arrary is: ");
//
// for(i = 0; i < len; i++){
// printf("%d ", arr1[i]);
// }
// printf("\n");
// system("pause");
// return 0;
//}
//#include <stdio.h>
//#include <stdlib.h>
//
//void selectSort(int *arr, int len)
//{
// int i, j, temp, max, count;
//
// for (i = 0; i < len; i++) {
// count = i;
// max = arr[count];
// for (j = i; j < len; j++) {
// if (arr[j] > max) {
// max = arr[j];
// count = j;
// }
// }
// temp = arr[count];
// arr[count] = arr[i];
// arr[i] = temp;
// }
//}
////void selectionSort(int *num, int len) //选择排序升序排列
////{
//// int i, j, temp, minIndex;
////
//// for (i = 0; i < len - 1; i++) {
//// minIndex = i;
//// for (j = i + 1; j < len; j++) {
//// if (num[j] < num[minIndex]) { //降序>
//// minIndex = j;
//// }
//// }
//// if (num[minIndex] < num[i]) { //降序>
//// temp = num[minIndex];
//// num[minIndex] = num[i];
//// num[i] = temp;
//// }
//// }
////}
//void test(int arr[], int sz)
//{
// for (int i = 0; i < sz; ++i)
// printf("%d ", arr[i]);
// printf("\n");
//}
//int main()
//{
// int arr[] = { 2, 5, 6, 1, 8, 0, 4, 6, 8, 7, 9, 6};
// int sz = sizeof(arr) / sizeof(arr[0]);
// printf("未排序的数组:> ");
// test(arr,sz);//输出数组中的元素
// selectSort(arr, sz);//选择排序
// printf("已经排好序的数组:> ");
// test(arr, sz);
// system("pause");
// return 0;
//}
//#include <stdio.h>
//#include <time.h>
//#include <stdlib.h>
//
//void quickSort(int *arr, int r, int l)
//{
// int i = r, j = l, temp, k;
//
// if (i < j) {
// k = rand() % (j - i + 1) + i - 1;
// temp = arr[k];
// while(i < j) {
// while(arr[j] >= temp && k < j) {
// j--;
// }
// if (k < j) {
// arr[k] = arr[j];
// k = j;
// }
// while(arr[i] <= temp && i < k) {
// i++;
// }
// if (i < k) {
// arr[k] = arr[i];
// k = i;
// }
// }
// arr[k] = temp;
// quickSort(arr, r, k - 1);
// quickSort(arr, k + 1, l);
// }
//}
//void test(int arr[], int sz)
//{
// for (int i = 0; i < sz; ++i)
// printf("%d ", arr[i]);
// printf("\n");
//}
//int main()
//{
// srand((unsigned)time(NULL));
// int arr[] = { 2, 5, 6, 1, 8, 0, 4, 6, 8, 7, 9, 6};
// int sz = sizeof(arr) / sizeof(arr[0]);
// printf("未排序的数组:> ");
// test(arr,sz); //输出数组中的元素
// quickSort(arr, 0, sz - 1); //快速排序 = 快排
// printf("已经排好序的数组:> ");
// test(arr, sz);
// system("pause");
// return 0;
//}
//#include <stdio.h>
//#include <stdlib.h>
//
//void swap(int *a, int *b) {
// int temp = *b;
// *b = *a;
// *a = temp;
//}
//
//void max_heapify(int arr[], int start, int end) { //
// // 建立父节点指标和子节点指标
// int dad = start;
// int son = dad * 2 + 1;
// while (son <= end) { // 若子节点指标在范围内才做比较
// if (son + 1 <= end && arr[son] < arr[son + 1]) // 先比较两个子节点大小,选择最大的
// son++;
// if (arr[dad] > arr[son]) // 如果父节点大于子节点代表调整完毕,直接跳出函数
// return;
// else { // 否则交换父子内容再继续子节点和孙节点比较
// swap(&arr[dad], &arr[son]);
// dad = son;
// son = dad * 2 + 1;
// }
// }
//}
//
//void heap_sort(int arr[], int len) {
// int i;
// // 初始化,i从最后一个父节点开始调整
// for (i = len / 2 - 1; i >= 0; i--)
// max_heapify(arr, i, len - 1);
// // 先将第一个元素和已排好元素前一位做交换,再重新调整,直到排序完毕
// for (i = len - 1; i > 0; i--) {
// swap(&arr[0], &arr[i]);
// max_heapify(arr, 0, i - 1);
// }
//}
//
//int main() {
// int arr[] = { 3, 5, 3, 0, 8, 6, 1, 5, 8, 6, 2, 4, 9, 4, 7, 0, 1, 8, 9, 7, 3, 1, 2, 5, 9, 7, 4, 0, 2, 6 };
// int len = (int) sizeof(arr) / sizeof(*arr);
// printf("sizeof(arr) / sizeof(*arr)=%d\n", sizeof(arr) / sizeof(*arr));
// heap_sort(arr, len);
// int i;
// for (i = 0; i < len; i++)
// printf("%d ", arr[i]);
// printf("\n");
// return 0;
//}
///*快速排序(Quick Sort)使用分治法策略。
//它的基本思想是:选择一个基准数,通过一趟排序将要排序的数据分割成独立的两部分;
//其中一部分的所有数据都比另外一部分的所有数据都要小。
//然后,再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,
//以此达到整个数据变成有序序列。
//
//快速排序流程:
//(1) 从数列中挑出一个基准值。
//(2) 将所有比基准值小的摆放在基准前面,所有比基准值大的摆在基准的后面(相同的数可以到任一边);
// 在这个分区退出之后,该基准就处于数列的中间位置。
//(3) 递归地把"基准值前面的子数列"和"基准值后面的子数列"进行排序。
//*/
//#include <stdio.h>
//
////void quickSort(int *arr, int l, int r)
////{
//// int i = l, j = r, temp = arr[i];
////
//// if(i < j)
//// {
//// while (i < j) {
//// while (temp < arr[j] && i < j)
//// j--;
//// if(i < j)
//// arr[i++] = arr[j];
//// while (temp > arr[i] && i < j)
//// i++;
//// if(i < j)
//// arr[j--] = arr[i];
//// }
////
//// arr[i] = temp;
//// quickSort(arr, l, i - 1);
//// quickSort(arr, i + 1, r);
//// }
////}
//void quickSort(int *arr, int l, int r)
//{
// if(l < r) {
// int i = l, j = r, temp;
//
// temp = arr[i]; //基准值
// while (i < j) {
// while (arr[j] > temp && i < j) { //从右往左找小于基准值的下标;降序找大于基准值
// j--;
// }
// if(i < j) {
// arr[i++] = arr[j];
// }
// while (arr[i] < temp && i < j) { //从左往右找大于基准值的下标;降序找小于基准值
// i++;
// }
// if(i < j) {
// arr[j--] = arr[i];
// }
// }
// arr[i] = temp;
// quickSort(arr, l, i - 1);
// quickSort(arr, i + 1, r);
// }
//}
//
//void test(int arr[], int sz)
//{
// for (int i = 0; i < sz; ++i)
// printf("%d ", arr[i]);
// printf("\n");
//}
//int main()
//{
// int arr[] = { 2, 5, 6, 1, 8, 0, 4, 6, 8, 7, 9, 6};
// int sz = sizeof(arr) / sizeof(arr[0]);
// printf("未排序的数组:> ");
// test(arr,sz); //输出数组中的元素
// quickSort(arr, 0, sz - 1); //快速排序 = 快排
// printf("已经排好序的数组:> ");
// test(arr, sz);
//
// return 0;
//}
///*插入排序思路:
//1. 从第一个元素开始,该元素可以认为已经被排序
//2. 取出下一个元素,在已经排序的元素序列中从后向前扫描
//3. 如果该元素(已排序)大于新元素,将该元素移到下一位置
//4. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
//5. 将新元素插入到该位置后
//6. 重复步骤2~5
//*/
//#include <stdio.h>
//
//void insertSort(int *num, int len)
//{
// int i, j, temp;
// for (i = 0; i < len - 1; i++) {
// j = i + 1;
// temp = num[j]; //temp存储新元素
// while(temp < num[--j] && j >= 0) {//升序排序,降序排序需要num[j] < temp
// num[j + 1] = num[j];
// }
// num[j + 1] = temp;
// }
//}
//
////void insertSort(int *num, int len)
////{
//// int i, j, temp;
//// for (i = 1; i < len; i++) {
//// j = i - 1;
//// temp = num[i];
//// while(num[j] > temp && j >= 0) {//升序排序,降序排序需要num[j] < temp
//// num[j + 1] = num[j];
//// j--;
//// }
//// num[++j] = temp;
//// }
////}
//
//void test(int arr[], int sz)
//{
// for (int i = 0; i < sz; ++i)
// printf("%d ", arr[i]);
// printf("\n");
//}
//int main()
//{
// int arr[] = { 2, 5, 6, 1, 8, 0, 4, 6, 8, 7, 9, 6};
// int sz = sizeof(arr) / sizeof(arr[0]);
// printf("未排序的数组:> ");
// test(arr,sz);//输出数组中的元素
// insertSort(arr, sz);//选择排序
// printf("已经排好序的数组:> ");
// test(arr, sz);
//
// return 0;
//}
//#include <stdio.h>
//#include <stdlib.h>
//
//void selectionSort(int *num, int len) //选择排序升序排列
//{
// int i, j, temp, minIndex;
//
// for (i = 0; i < len - 1; i++) {
// minIndex = i;
// for (j = i + 1; j < len; j++) {
// if (num[j] < num[minIndex]) { //降序>
// minIndex = j;
// }
// }
// if (num[minIndex] < num[i]) { //降序>
// temp = num[minIndex];
// num[minIndex] = num[i];
// num[i] = temp;
// }
// }
//}
//void test(int arr[], int sz)
//{
// for (int i = 0; i < sz; ++i)
// printf("%d ", arr[i]);
// printf("\n");
//}
//int main()
//{
// int arr[] = { 2, 5, 6, 1, 8, 0, 4, 6, 8, 7, 9, 6};
// int sz = sizeof(arr) / sizeof(arr[0]);
// printf("未排序的数组:> ");
// test(arr,sz);//输出数组中的元素
// selectionSort(arr, sz);//选择排序
// printf("已经排好序的数组:> ");
// test(arr, sz);
// system("pause");
// return 0;
//}
//#include <stdio.h>
// /************************************************************************
// *冒泡排序是排序算法中较为简单的一种,英文名称为bubble sort。
// *方法一:从前面开始遍历所有数据,每次对相邻的元素进行两两对比。升序排序:每次遍历把大元素
// * 往后排;降序排序:每次遍历把小元素往后排。
// *方法二:从后面开始遍历所有数据,每次对相邻的元素进行两两对比。升序排序:每次遍历把小元素
// * 往前排;降序排序:每次遍历把大元素往前排。
// *平均时间复杂度:O(n2)
// *空间复杂度:O(1)
// *当数据量大时,冒泡算法的效率并不高。
// **************************************************************************/
//
//void swap(int *t1, int *t2)
//{
// int temp;
// temp = *t1;
// *t1 = *t2;
// *t2 = temp;
//}
///*从前面开始对比排序*/
//void bubble_sort_asc(int arr[], int len)
//{
// int i, j;
//
// for (i = 0; i < len -1; i++) { //大数往后沉 len - 1 次数组就已经排序好了
// for (j = 0; j < len -1 -i; j++) {
// if (arr[j] > arr[j + 1]) { //将大的往后排
// swap(&arr[j], &arr[j + 1]);
// }
// }
// }
//}
//
//void bubble_sort_des(int arr[], int len)
//{
// int i, j;
//
// for (i = 0; i < len -1; i++) {
// for (j = 0; j < len -1 -i; j++) {
// if (arr[j] < arr[j + 1]) { //将小的往后排
// swap(&arr[j], &arr[j + 1]);
// }
// }
// }
//}
///*从后面开始对比排序*/
////void bubble_sort_asc(int arr[], int len)
////{
//// int i, j;
////
//// for (i = 0; i < len - 1; i++) {
//// for (j = len - 1; j > i ; j--) {
//// if (arr[j - 1] > arr[j]) { //将小的往前排
//// swap(&arr[j - 1], &arr[j]);
//// }
//// }
//// }
////}
////void bubble_sort_des(int arr[], int len)
////{
//// int i, j;
////
//// for (i = 0; i < len - 1; i++) {
//// for (j = len - 1; j > i ; j--) {
//// if (arr[j - 1] < arr[j]) { //将小的往前排
//// swap(&arr[j - 1], &arr[j]);
//// }
//// }
//// }
////}
//
//int main()
//{
// int arr1[] = {34, 27, 55, 8, 97, 67, 35, 43, 22, 101, 78, 96, 35, 99};
// int i;
// int len = sizeof(arr1) / sizeof(*arr1);
//
// bubble_sort_asc(arr1, len);
// printf("len = %d \n", len);
// printf("use bubble sort asc the arrary is: ");
//
// for(i = 0; i < len; i++){
// printf("%d ", arr1[i]);
// }
// printf("\n");
// bubble_sort_des(arr1, len);
// printf("use bubble sort des the arrary is: ");
//
// for(i = 0; i < len; i++){
// printf("%d ", arr1[i]);
// }
// printf("\n");
// return 0;
//}
//#include <stdio.h>
//
//int main(void)
//{
// int num[10] = {1,2,3,4,5};
// printf("sizeof(num)/sizeof(int)=%lu\n", sizeof(num)/sizeof(int));
// int i = 0;
// for (; i < 10; i++) {
// printf("num[%d]=%d\n", i, num[i]);
// }
// for (i = 0; i < 10; i++) {
// if (num[i] == 0)
// break;
// }
// printf("数组元素个数为:%d\n", i);
//
// return 0;
//}
//void Divarray(int *pArray, int size)
//{
// for (int i = 0; i < size; i++) {
// pArray[i] /= pArray[0];
// }
//}
//
//int main()
//{
// int num[5] = {2,2,3,4,5};
//
// Divarray(num, 5);
//
// for (int i = 0; i < 5; i++) {
// printf("%d\n", num[i]);
// }
//
// return 0;
//}
|
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cctype>
#include <vector>
#include <string>
#include <utility>
#include <map>
struct comp
{
bool operator()(const std::pair<char, int> &a, const std::pair<char, int> &b) const
{
return (a.second > b.second);
}
};
int main(int argc, char **argv)
{
if (argc != 2) {
return 1;
}
std::ifstream f(argv[1]);
bool last_was_whitespace = true;
while (true) {
std::string line;
std::getline(f, line);
if (f.fail()) {
break;
}
std::map<char, int> m;
std::vector<std::pair<char, int> > v;
for (size_t i = 0; i < line.size(); i++) {
if (std::isalpha(line[i])) {
m[std::tolower(line[i])]++;
}
}
for (std::map<char, int>::iterator it = m.begin(); it != m.end(); it++) {
v.push_back(*it);
}
std::sort(v.begin(), v.end(), comp());
int beauty = 0;
for (size_t i = 0; i < v.size(); i++) {
//std::cout << v[i].first << ',' << v[i].second << '\n';
beauty += (v[i].second * (26 - i));
}
std::cout << beauty << '\n';
}
return 0;
}
|
#ifndef MONITOR_H
#define MONITOR_H
#include <QWidget>
#include <QtSql>
#include<QCompleter>
#include<QMenuBar>
#include<QMenu>
#include<QDate>
#include<QSqlQuery>
#include<QMessageBox>
#include<QByteArray>
#include<QtNetwork/QNetworkInterface>
#include<QBuffer>
#include<QFile>
#include<QIODevice>
#include<QPixmap>
#include<QComboBox>
#include<QFontComboBox>
#include<QTableWidgetItem>
#include<QTimer>
#include<qtrpt.h>
#include<qshortcut.h>
#include<QStandardItemModel>
#include<LimeReport>
namespace Ui {
class monitor;
}
class monitor : public QWidget
{
Q_OBJECT
private slots:
void on_comboBox_currentIndexChanged(int index);
void on_pushButton_2_clicked();
void on_pushButton_clicked();
void slotGetCallbackData(const LimeReport::CallbackInfo &info, QVariant &data);
public slots:
void getTable();
void getstat(int id);
public:
explicit monitor(QWidget *parent = nullptr);
~monitor();
private:
Ui::monitor *ui;
QSqlDatabase db;
QSqlDatabase db2;
QSqlQueryModel *model;
QSqlQueryModel *model1;
double sales_cash=0;
double sales_credit=0;
double sales_return_cash=0;
double sales_return_credit=0;
double purchases_cash=0;
double purchases_credit=0;
double purchases_return_cash=0;
double purchases_return_credit=0;
double supplier_payment_out=0;
double supplier_payment_in=0;
double customer_payment_in=0;
double customer_payment_out=0;
double expenses_cash=0;
double expenses_credit=0;
double sales_total=0;
double purchases_total=0;
double purchases_return_total=0;
double cash_deposit_total=0;
LimeReport::ReportEngine *report;
QString shop_name,shop_phone,trade,tax;
};
#endif // MONITOR_H
|
/***********************************************************************
created: Fri Jan 15 20109
author: Eugene Marcotte
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/RendererModules/Null/GeometryBuffer.h"
#include "CEGUI/RenderEffect.h"
namespace CEGUI
{
//----------------------------------------------------------------------------//
NullGeometryBuffer::NullGeometryBuffer(CEGUI::RefCounted<RenderMaterial> renderMaterial)
: GeometryBuffer(renderMaterial)
{
}
//----------------------------------------------------------------------------//
void NullGeometryBuffer::draw(std::uint32_t drawModeMask) const
{
CEGUI_UNUSED(drawModeMask);
const int pass_count = d_effect ? d_effect->getPassCount() : 1;
for (int pass = 0; pass < pass_count; ++pass)
{
// set up RenderEffect
if (d_effect)
d_effect->performPreRenderFunctions(pass);
}
// clean up RenderEffect
if (d_effect)
d_effect->performPostRenderFunctions();
}
}
|
#include <characters/finalmonster.h>
using namespace lab3;
using namespace lab3::characters;
FinalMonster::FinalMonster(const std::string &name, Place *place)
: Character(name, TYPE_FINAL_MONSTER, place),
defeated_player_(false),
distraction_(0)
{
this->talk_msgs_ = {"You will never get out of that jail dear Princess",
"Soon the entire city will be mine muahaha...",
"Your friends cannot defeat me!"};
}
FinalMonster::~FinalMonster()
{}
ActionResult FinalMonster::action(bool display_info)
{
if(this->isFighting())
{
return fight(*this->fighter_);
}
else
{
return this->talk_to(*this->currentPlace()->getCharacter(NAME_PRINCESS));
}
return EVENT_NULL;
}
ActionResult FinalMonster::fight(Character &character)
{
bool finished = Character::fight(character).success_;
// Throw event when defeating the player for the first time
if(finished && !defeated_player_ && character.name() == NAME_PLAYER)
{
defeated_player_ = true;
return ActionResult(true,EVENT_TRIED_MONSTER);
}
return finished;
}
void FinalMonster::addDistraction(int distraction)
{
this->distraction_ = std::max(std::min(this->distraction_ + distraction, DISTRACTION_MAX), DISTRACTION_MIN);
}
int FinalMonster::getDistraction() const {return this->distraction_; }
bool FinalMonster::isEnemy(const Character &ch) const { return true;} // Everyone is an enemy
bool FinalMonster::getDefeatedPlayer() const {return this->defeated_player_;}
void FinalMonster::setDefeatedPlayer(bool x) {this->defeated_player_ = x;}
|
int pinVerde = 11;
int pinAmarelo = 10;
int pinVermelho = 9;
int pinBotao = 7;
int pinPedestreVerde = 3;
int pinPedestreVermelho = 2;
int atraso = 100;
int faseSemaforo;
int estadoBotao;
int estadoAnteriorBotao;
void setup()
{
// put your setup code here, to run once:
pinMode(pinVerde, OUTPUT);
pinMode(pinAmarelo, OUTPUT);
pinMode(pinVermelho, OUTPUT);
pinMode(pinPedestreVerde, OUTPUT);
pinMode(pinPedestreVermelho, OUTPUT);
pinMode(pinBotao, INPUT);
faseSemaforo = 1;
estadoAnteriorBotao = digitalRead(pinBotao);
}
void loop()
{
// put your main code here, to run repeatedly:
estadoBotao = digitalRead(pinBotao);
if((estadoBotao == HIGH) && (estadoAnteriorBotao == LOW))
{
if(faseSemaforo < 4)
{
faseSemaforo = faseSemaforo + 1;
}
else
{
faseSemaforo = 1;
}
}
estadoAnteriorBotao = estadoBotao;
if(faseSemaforo == 1)
{
digitalWrite(pinVerde, HIGH);
digitalWrite(pinAmarelo, LOW);
digitalWrite(pinVermelho, LOW);
digitalWrite(pinPedestreVerde, LOW);
digitalWrite(pinPedestreVermelho, HIGH);
}
if(faseSemaforo == 2)
{
digitalWrite(pinVerde, LOW);
digitalWrite(pinAmarelo, HIGH);
digitalWrite(pinVermelho, LOW);
digitalWrite(pinPedestreVerde, LOW);
digitalWrite(pinPedestreVermelho, HIGH);
}
if(faseSemaforo == 3)
{
digitalWrite(pinVerde, LOW);
digitalWrite(pinAmarelo, LOW);
digitalWrite(pinVermelho, HIGH);
digitalWrite(pinPedestreVerde, HIGH);
digitalWrite(pinPedestreVermelho, LOW);
}
delay(atraso);
}
|
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <fstream>
#include "cyoa.h"
using namespace std;
int main(int argc, char ** argv){
ifstream file;
Page page;
if(argc < 2){
cerr << "please enter a valid page" << endl;
exit(EXIT_FAILURE);
}
file.open(argv[1]);
string str;
vector<string> vec;
if(file.fail()){
cerr << "fail to open file" << endl;
exit(EXIT_FAILURE);
}
//read the content from the input file
while(getline(file, str)){
vec.push_back(str);
}
file.close();
//blank page is not allowed
if(vec.size() == 0){
cerr << "blank page is not allowed" << endl;
exit(EXIT_FAILURE);
}
//constrcut the page and print it
page.setPageContent(vec);
page.constructPage();
page.printPage();
exit(EXIT_SUCCESS);
}
|
#include<iostream>
using namespace std;
const int MAX_N=100;
int pos[MAX_N];
int main()
{
int p=0;
const int n=8;
int ans=0;
memset(pos,0,sizeof(pos));
while(true)
{
if(p>=n)
{
ans++;
p--;
continue;
}
if(pos[p]<n)
{
if(check(p))
{
p++;
continue;
}
pos[p]++;
}
else
{
if(p>0)
{
pos[p]=0;
p--;
pos[p]++;
}
else
{
break;
}
}
}
cout <<ans<<endl;
}
|
// This file has been generated by Py++.
#include "boost/python.hpp"
#include "generators/include/python_CEGUI.h"
#include "WidgetLookIterator.pypp.hpp"
namespace bp = boost::python;
struct ConstMapIterator_less__std_scope_map_less_CEGUI_scope_String_comma__CEGUI_scope_WidgetLookFeel_comma__CEGUI_scope_StringFastLessCompare_comma__std_scope_allocator_less_std_scope_pair_less_CEGUI_scope_String_const_comma__CEGUI_scope_WidgetLookFeel_greater___greater___greater___greater__wrapper : CEGUI::ConstMapIterator< std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > >, bp::wrapper< CEGUI::ConstMapIterator< std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > > > {
ConstMapIterator_less__std_scope_map_less_CEGUI_scope_String_comma__CEGUI_scope_WidgetLookFeel_comma__CEGUI_scope_StringFastLessCompare_comma__std_scope_allocator_less_std_scope_pair_less_CEGUI_scope_String_const_comma__CEGUI_scope_WidgetLookFeel_greater___greater___greater___greater__wrapper(CEGUI::ConstMapIterator<std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > > const & arg )
: CEGUI::ConstMapIterator<std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > >( arg )
, bp::wrapper< CEGUI::ConstMapIterator< std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > > >(){
// copy constructor
}
ConstMapIterator_less__std_scope_map_less_CEGUI_scope_String_comma__CEGUI_scope_WidgetLookFeel_comma__CEGUI_scope_StringFastLessCompare_comma__std_scope_allocator_less_std_scope_pair_less_CEGUI_scope_String_const_comma__CEGUI_scope_WidgetLookFeel_greater___greater___greater___greater__wrapper( )
: CEGUI::ConstMapIterator<std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > >( )
, bp::wrapper< CEGUI::ConstMapIterator< std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > > >(){
// null constructor
}
virtual ::CEGUI::WidgetLookFeel getCurrentValue( ) const {
if( bp::override func_getCurrentValue = this->get_override( "getCurrentValue" ) )
return func_getCurrentValue( );
else{
return this->CEGUI::ConstMapIterator< std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > >::getCurrentValue( );
}
}
::CEGUI::WidgetLookFeel default_getCurrentValue( ) const {
return CEGUI::ConstMapIterator< std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > >::getCurrentValue( );
}
};
void Iterator_next(::CEGUI::ConstMapIterator<std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > >& t)
{
t++;
}
void Iterator_previous(::CEGUI::ConstMapIterator<std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > >& t)
{
t--;
}
void register_WidgetLookIterator_class(){
{ //::CEGUI::ConstMapIterator< std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > >
typedef bp::class_< ConstMapIterator_less__std_scope_map_less_CEGUI_scope_String_comma__CEGUI_scope_WidgetLookFeel_comma__CEGUI_scope_StringFastLessCompare_comma__std_scope_allocator_less_std_scope_pair_less_CEGUI_scope_String_const_comma__CEGUI_scope_WidgetLookFeel_greater___greater___greater___greater__wrapper, bp::bases< CEGUI::ConstBaseIterator< std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > >, CEGUI::WidgetLookFeel > > > WidgetLookIterator_exposer_t;
WidgetLookIterator_exposer_t WidgetLookIterator_exposer = WidgetLookIterator_exposer_t( "WidgetLookIterator", bp::no_init );
bp::scope WidgetLookIterator_scope( WidgetLookIterator_exposer );
WidgetLookIterator_exposer.def( bp::init< >("*************************************************************************\n\
No default construction available\n\
*************************************************************************\n") );
{ //::CEGUI::ConstMapIterator< std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > >::getCurrentKey
typedef CEGUI::ConstMapIterator< std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > > exported_class_t;
typedef ::CEGUI::String ( exported_class_t::*getCurrentKey_function_type )( ) const;
WidgetLookIterator_exposer.def(
"getCurrentKey"
, getCurrentKey_function_type( &::CEGUI::ConstMapIterator< std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > >::getCurrentKey )
, "*!\n\
\n\
Return the key for the item at the current iterator position.\n\
*\n" );
}
{ //::CEGUI::ConstMapIterator< std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > >::getCurrentValue
typedef CEGUI::ConstMapIterator< std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > > exported_class_t;
typedef ::CEGUI::WidgetLookFeel ( exported_class_t::*getCurrentValue_function_type )( ) const;
typedef ::CEGUI::WidgetLookFeel ( ConstMapIterator_less__std_scope_map_less_CEGUI_scope_String_comma__CEGUI_scope_WidgetLookFeel_comma__CEGUI_scope_StringFastLessCompare_comma__std_scope_allocator_less_std_scope_pair_less_CEGUI_scope_String_const_comma__CEGUI_scope_WidgetLookFeel_greater___greater___greater___greater__wrapper::*default_getCurrentValue_function_type )( ) const;
WidgetLookIterator_exposer.def(
"getCurrentValue"
, getCurrentValue_function_type(&::CEGUI::ConstMapIterator< std::map<CEGUI::String, CEGUI::WidgetLookFeel, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::WidgetLookFeel> > > >::getCurrentValue)
, default_getCurrentValue_function_type(&ConstMapIterator_less__std_scope_map_less_CEGUI_scope_String_comma__CEGUI_scope_WidgetLookFeel_comma__CEGUI_scope_StringFastLessCompare_comma__std_scope_allocator_less_std_scope_pair_less_CEGUI_scope_String_const_comma__CEGUI_scope_WidgetLookFeel_greater___greater___greater___greater__wrapper::default_getCurrentValue) );
}
WidgetLookIterator_exposer.def("next", &::Iterator_next);
WidgetLookIterator_exposer.def("previous", &::Iterator_previous);
}
}
|
char _invoke_command(char *command){
return system(command);
}
|
#ifndef DWIZ_COMMON_CATCH_ALL_APPLICATION_H
#define DWIZ_COMMON_CATCH_ALL_APPLICATION_H
#include <common/dwiz_std.h>
#include <QApplication>
namespace dwiz
{
class CatchAllApplication : public QApplication
{
public:
using QApplication::QApplication;
bool hasException() const;
std::string const& getExceptionMessage() const;
private:
virtual bool notify(QObject* f_obj, QEvent* f_event) override;
std::string m_exceptionMessage;
}; // CatchAllApplication
} // namespace dwiz
#endif
|
#include "Carousel.h"
Carousel::Carousel():ChildrenRide() //default constructor, info from parent
{
//left empty on purpose
}
Carousel::Carousel(string rideName, int maxAge):ChildrenRide(rideName, maxAge)
{
//empty on purpose, constructor inherits from ChildrenRide
}
void Carousel::showInfo() const //print out all info
{
cout << "Carousel Type" << endl;
cout << " Name: " << getRideName() << endl;
cout << " Info: 5 minutes on play horses." << endl;
restrictions();
}
|
#include <iostream>
#include <sstream>
#include <vector>
#include <set>
using namespace std;
namespace Graph {
vector<vector<int>> G;
vector<bool> Visited;
vector<int> Predecessors;
vector<set<int>> Dependency;
void DFS(int node)
{
if( Visited[node] ) {
return;
}
Visited[node] = true;
for( int child : G[node] ) {
DFS(child);
}
cout << node << " ";
}
void Populate()
{
int n;
cin >> n;
cin.ignore();
Predecessors = vector<int>(n, 0);
Visited = vector<bool>(n, false);
Dependency.push_back(set<int>());
G = vector<vector<int>>();
G.reserve(n);
for( int node=0; node<n; node++) {
cout << node << " = ";
G.push_back(vector<int>());
string line;
int child;
getline(cin, line);
istringstream ss(line);
while( ss >> child) {
G[node].push_back(child);
if( Predecessors[node] == 0 ) {
Dependency[0].insert(node);
}
if( Predecessors[child] > 0 ) {
Dependency[Predecessors[child]].erase(child);
}
Predecessors[child]++;
while( Predecessors[child] >= Dependency.size() ) {
Dependency.push_back(set<int>());
}
Dependency[Predecessors[child]].insert(child);
}
}
}
void PrintConnected()
{
for( int i=0; i<G.size(); i++) {
cout << "Connected component: ";
DFS(i);
cout << endl;
}
}
auto Sorted = vector<int>();
bool TopoSort()
{
auto pChild = Dependency[0].begin();
while( pChild != Dependency[0].end() ) {
Sorted.push_back(*pChild);
// Decrease child nodes dependecy with 1
for( auto c : G[*pChild] ) {
auto pC = Dependency[Predecessors[c]].find(c);
Dependency[Predecessors[c]].erase(pC);
if( Predecessors[c] > 0) {
Dependency[--Predecessors[c]].insert(c);
}
}
Dependency[0].erase(pChild);
pChild = Dependency[0].begin();
}
for( int i=0; i< Dependency.size(); i++ ) {
if( Dependency[i].size() > 0 ) {
return false;
}
}
return true;
}
}
int main()
{
Graph::Populate();
Graph::PrintConnected();
if( !Graph::TopoSort()) {
cout << "The graph has cycles" << endl;
}
else {
for( auto c : Graph::Sorted ) {
cout << c << ' ';
}
cout << endl;
}
}
|
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
bool cmp(Interval a,Interval b){
return a.start < b.start;
}
class Solution {
public:
vector<Interval> merge(vector<Interval>& intervals) {
sort(intervals.begin(),intervals.end(),cmp);
vector<Interval> ans;
int len = intervals.size();
Interval tmp;
for(int i = 0;i < len;i++){
tmp.start = intervals[i].start; tmp.end = intervals[i].end;
while(i != (len-1) && intervals[i+1].start <= tmp.end) {tmp.end = max(tmp.end,intervals[i+1].end);i++;}
tmp.end = max(tmp.end,intervals[i].end);
ans.push_back(tmp);
}
return ans;
}
};
|
#include "common.h"
#include "DirectDrawPalette.h"
DirectDrawPalette::DirectDrawPalette(IDirectDrawPalette* original)
{
this->_original = original;
}
DirectDrawPalette::~DirectDrawPalette()
{
}
HRESULT DirectDrawPalette::QueryInterface(
REFIID riid,
LPVOID* obp
)
{
std::ostringstream str;
str << this << " " << __FUNCTION__;
str << " " << tostr_IID(riid);
LogText(str.str());
*obp = nullptr;
HRESULT hr = this->_original->QueryInterface(riid, obp);
if (SUCCEEDED(hr))
{
}
return hr;
}
ULONG DirectDrawPalette::AddRef()
{
std::ostringstream str;
str << this << " " << __FUNCTION__;
LogText(str.str());
return this->_original->AddRef();
}
ULONG DirectDrawPalette::Release()
{
std::ostringstream str;
str << this << " " << __FUNCTION__;
LogText(str.str());
ULONG count = this->_original->Release();
if (count == 0)
{
RemoveWrapper(this->_original);
delete this;
}
return count;
}
HRESULT DirectDrawPalette::GetCaps(
LPDWORD lpdwCaps
)
{
std::ostringstream str;
str << this << " " << __FUNCTION__;
LogText(str.str());
return this->_original->GetCaps(lpdwCaps);
}
HRESULT DirectDrawPalette::GetEntries(
DWORD dwFlags,
DWORD dwBase,
DWORD dwNumEntries,
LPPALETTEENTRY lpEntries
)
{
std::ostringstream str;
str << this << " " << __FUNCTION__;
LogText(str.str());
return this->_original->GetEntries(dwFlags, dwBase, dwNumEntries, lpEntries);
}
HRESULT DirectDrawPalette::Initialize(
LPDIRECTDRAW lpDD,
DWORD dwFlags,
LPPALETTEENTRY lpDDColorTable
)
{
std::ostringstream str;
str << this << " " << __FUNCTION__;
LogText(str.str());
return this->_original->Initialize(lpDD, dwFlags, lpDDColorTable);
}
HRESULT DirectDrawPalette::SetEntries(
DWORD dwFlags,
DWORD dwStartingEntry,
DWORD dwCount,
LPPALETTEENTRY lpEntries
)
{
std::ostringstream str;
str << this << " " << __FUNCTION__;
LogText(str.str());
return this->_original->SetEntries(dwFlags, dwStartingEntry, dwCount, lpEntries);
}
|
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int s1,s2,s3;
printf("enter ur markx");
scanf("%d %d %d",&s1,&s2,&s3);
int total=s1+s2+s3;
float per=total/3.0;
printf("ur total is %d out of 300\npercentage is %.1f",total,per);
if(per>=75)
printf("distinction");
else if(per<75&&per>=60)
printf("A");
else if(per<65&&per>=48)
printf("B");
else
printf("Fail");
getch();
}
|
//! Bismillahi-Rahamanirahim.
/** ========================================**
** @Author: Md. Abu Farhad ( RUET, CSE'15)
** @Category:
/** ========================================**/
#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
#define ll long long
#define scl(n) scanf("%lld", &n)
#define fr(i,n) for (ll i=0;i<n;i++)
#define fr1(i,n) for(ll i=1;i<=n;i++)
#define pfl(x) printf("%lld\n",x)
#define endl "\n"
#define pb push_back
#define asort(a) sort(a,a+n)
#define dsort(a) sort(a,a+n,greater<int>())
#define vasort(v) sort(v.begin(), v.end());
#define vdsort(v) sort(v.begin(), v.end(),greater<int>());
#define pn printf("\n")
#define md 10000007
#define debug printf("I am here\n")
#define ps printf(" ")
#define tcas(i,t) for(ll i=1;i<=t;i++)
#define pcas(i) printf("Case %lld: ",i)
int main()
{
ll m,n,t,b,c,d,i,j,k,x,y,z,l,q,r;
ll cnt=0,ans=0;
string s1="aeiou", s2="eioua", s3="iouae", s4="ouaei", s5="uaeio", s;
scl(n);
if(n>=25)
{
for(ll i=5; i<=n; i++)
{
if(n%i==0 && n/i >=5 )
{
x=i;
y=abs(n/i -5) ;
fr(j,y)s1+='a';
fr(j,y)s2+='e';
fr(j,y)s3+='i';
fr(j,y)s4+='o';
fr(j,y)s5+='u';
s=s1+s2+s3+s4+s5;
//pfl(y);pfl(x);
fr(j,y)s+=s1;
cnt=1;
break;
}
}
if(cnt==0) ans=-1;
}
else ans=-1;
ll p=0;
//cout<<s.size()<<endl;
if(ans ==0)fr(i,n)cout<<s[i];
//cout<<s<<endl;
else
cout<<ans<<endl ;
// fr(i,n)
// {
// if(p==n/x){cout<<endl; p=0; }
// cout<<s[i];
// p++;
// }
return 0;
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdio.h>
using namespace std;
#define N 10
#define L 30
int n,l;
struct Box
{
int dim[N];
int index;
Box *below;
Box *above;
};
Box boxs[L];
Box *table[L];
void initboxs(int l,int n);
bool compare(Box *a,Box b);
int main(void)
{
int i,j,k,count,length;
Box begin,record;
Box *temp;
length=0;
scanf("%d %d",&l,&n);
initboxs(l,n);
for(i=0;i<l;i++)
std::sort(&boxs[i].dim[0],&boxs[i].dim[n]);/* no error*/
for(i=0;i<l;i++)
{
k=i;
for(j=i+1;j<l;j++)
{
if(boxs[j].dim[0]<boxs[k].dim[0])
k=j;
}
record=boxs[i];
boxs[i]=boxs[k];
boxs[k]=record;
} /*no error*/
for(i=0;i<l;i++)
{
temp=table[i];
count=1;
for(j=i+1;j<l;j++)
{
if(compare(temp,boxs[j]))
{
temp->above=table[j];
table[j]->below=temp;
temp=table[j];
count++;
}
}
if(count>length)
{
length=count;
begin=boxs[i];
}
}
printf("%d\n",length);
temp=&begin;
for(i=0;i<length;i++)
{
if((temp->index)==7)
temp->index=5;
printf("%d ",((temp->index)+1));
temp=temp->above;
}
getchar();
printf("\n");
return 0;
}
void initboxs(int l,int n)
{
int i,j,b;
for(i=0;i<l;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b);
boxs[i].dim[j]=b;
}
boxs[i].index=i;
boxs[i].below=(Box *)NULL;
boxs[i].above=(Box *)NULL;
table[i]=&boxs[i];
}
}
bool compare(Box *a,Box b)
{
int i;
for(i=0;i<n;i++)
{
if((a->dim[i]>b.dim[i])||(a->dim[i]==b.dim[i]))
return false;
}
return true;
}
|
#pragma once
#include "FirstHeaders.h"
struct Animation {
};
//########################################
// CObjectBase Start ##
// ##
class CObjectBase{
public:
CObjectBase();
~CObjectBase();
};
// ##
// CObjectBase End ##
//########################################
//########################################
// CObjectBackGround Start ##
// ##
class CObjectBackGround :public CObjectBase {
public:
CObjectBackGround();
~CObjectBackGround();
};
// ##
// CObjectBackGround End ##
//########################################
//########################################
// CObjectTower Start ##
// ##
class CObjectTower :public CObjectBase {
public:
CObjectTower();
~CObjectTower();
};
// ##
// CObjectTower End ##
//########################################
//########################################
// CObjectEnemy Start ##
// ##
class CObjectEnemy :public CObjectBase {
public:
CObjectEnemy();
~CObjectEnemy();
};
// ##
// CObjectEnemy End ##
//########################################
//########################################
// CObjectUI Start ##
// ##
class CObjectUI :public CObjectBase {
public:
CObjectUI();
~CObjectUI();
};
// ##
// CObjectUI End ##
//########################################
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *ptr1 = l1, *ptr2 = l2;
ListNode *ans = new ListNode(0),*tmp;
tmp = ans;
while(ptr1 != NULL and ptr2 != NULL){
ListNode *new_node = new ListNode(0);
if(ptr1->val < ptr2->val){
new_node->val = ptr1->val;
ptr1 = ptr1->next;
}
else{
new_node->val = ptr2->val;
ptr2 = ptr2->next;
}
ans->next = new_node;
ans = ans->next;
}
if(ptr1 != NULL) ans->next = ptr1;
else ans->next = ptr2;
ans = tmp->next;
delete tmp;
return ans;
}
};
|
// 1029. Two City Scheduling
// There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1].
// Return the minimum cost to fly every person to a city such that exactly N people arrive in each city.
// Example 1:
// Input: [[10,20],[30,200],[400,50],[30,20]]
// Output: 110
// Explanation:
// The first person goes to city A for a cost of 10.
// The second person goes to city A for a cost of 30.
// The third person goes to city B for a cost of 50.
// The fourth person goes to city B for a cost of 20.
// The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
// Note:
// 1. 1 <= costs.length <= 100
// 2. It is guaranteed that costs.length is even.
// 3. 1 <= costs[i][0], costs[i][1] <= 1000
// TEST CASES
// [[10,20],[30,200],[400,50],[30,20]]
// [[10,20],[30,200],[400,50],[30,20],[30,50],[20,100]]
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
int twoCitySchedCost(vector<vector<int>>& costs) {
int N = costs.size() / 2;
vector<int> indexA;
vector<int> indexB;
priority_queue<int,vector<int>, greater<int>> diffA;
priority_queue<int,vector<int>, greater<int>> diffB;
int total = 0;
for ( int i = 0; i < costs.size(); i++ ){
if ( costs[i][0] < costs[i][1] ){
indexA.push_back(i);
diffA.push(costs[i][1]-costs[i][0]);
total += costs[i][0];
} else {
indexB.push_back(i);
diffB.push(costs[i][0]-costs[i][1]);
total += costs[i][1];
}
}
while ( diffA.size() > N ){
total += diffA.top();
diffA.pop();
}
while ( diffB.size() > N ){
total += diffB.top();
diffB.pop();
}
return total;
}
};
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
if (root == NULL) return vector<int>();
vector<TreeNode*> *oldv = new vector<TreeNode*>(1, root), *newv = new vector<TreeNode*>(), *tmpv;
vector<int> result;
int i;
while (!oldv->empty())
{
result.push_back((*oldv)[0]->val);
newv->clear();
for (i = 0; i < oldv->size(); i++)
{
if ((*oldv)[i]->right != NULL) newv->push_back((*oldv)[i]->right);
if ((*oldv)[i]->left != NULL) newv->push_back((*oldv)[i]->left);
}
tmpv = oldv;
oldv = newv;
newv = tmpv;
}
return result;
}
};
|
class Solution {
public:
int longestMountain(vector<int>& arr) {
if(arr.size()<3) return 0;
int result=0;
int i=0;
bool peak=false, valley=false;
while(i<arr.size()-1){
if(arr[i]<arr[i+1]){
int start=i;
while(i<arr.size()-1 and arr[i]<arr[i+1] ){
peak=true;
i++;
}
while(i<arr.size()-1 and arr[i]>arr[i+1] ){
valley=true;
i++;
}
if(peak==true and valley==true){
result=max(result,i-start+1);
peak=false;
valley=false;
}
}
else{
i++;
}
}
return result;
}
};
|
#ifndef PRINT_H
#define PRINT_H
#include<thrust/host_vector.h>
#include<thrust/device_vector.h>
#include<iostream>
/*courtesy of https://github.com/thrust/thrust/blob/master/examples/expand.cu */
template <typename Vector>
void printVec(const Vector& v, int d1, int d2)
{
typedef typename Vector::value_type T;
for(int i=0; i<d2; ++i){
thrust::copy(v.begin() + i*d1, v.begin() + (i+1)*d1, std::ostream_iterator<T>(std::cout, " "));
std::cout << std::endl;
}
}
#endif
|
#include <iostream>
#include <vector>
using namespace std;
void swap (vector<long> &a, int i, int j) {
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
void insert(vector<long> &a, int n, long x) {
a[n] = x;
int i = n;
while (i > 0 && a[i] > a[(i - 1) / 2]) {
swap(a, i, (i - 1) / 2);
i = (i - 1) / 2;
}
}
void get_max(vector<long> &a, int n, vector<long> &max, int j) {
max[j] = a[0];
a[0] = a[n - 1];
int i = 0;
while (2 * i + 1 < n) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int j = left;
if (right < n && a[right] > a[left]) {
j = right;
}
if (a[i] >= a[j]) {
break;
}
swap(a, i, j);
i = j;
}
}
int main() {
int n;
cin >> n;
vector<long> a(n);
vector<long> max(n);
int j = 0;
int size = 0;
for (int i = 0; i < n; i++) {
int command;
cin >> command;
if (command == 0) {
long x;
cin >> x;
insert(a, size, x);
size++;
} else {
get_max(a, size, max, j);
j++;
size--;
}
}
int k = 0;
while (max[k] != 0) {
cout << max[k] << endl;
k++;
}
return 0;
}
|
#include "BNO055.h"
uint8_t BNO055::init(POWER_MODE _Power, OPERATION_MODE _Operation_Mode, PLACEMENT _orientation)
{
write(Page0::SYSTEM_TRIGGER, 0x01); //External oscillator
write(Page0::UNIT_SELECTION, 0x90); //Android orientation(pitch+ counter clockwise), fahrenheit temp, euler degrees, rotation DPS, accel m/s�
meas_units = 0x90;
orientation(_orientation);
write(Page0::POWER_MODE_REG, uint8_t(_Power));
write(Page0::OPERATION_MODE_REG, uint8_t(_Operation_Mode));
if (_Operation_Mode != OPERATION_MODE::CONFIG) delay(7); //wait 7ms to come out of config mode
return 0;
}
//Barebones begin, just checks that self test/communication are ok. All setup is external to this
bool BNO055::begin()
{
uint8_t counter = 0;
if (!page0) writePage(0);
while (read(Page0::SELFTEST_RESULT) != 0x0F) {
delay(25);
counter++;
if (counter == 100) return false;
}
meas_units = 0x80;
opmode = 0x00;
return true;
}
uint8_t BNO055::begin(POWER_MODE _Power_Mode, OPERATION_MODE _Operation_Mode, PLACEMENT _orientation, bool _Load, uint8_t _ResetPin, uint8_t _AddressPin, bool _SlaveHigh)
{
if (running) return 0xFF; //if it's already running you can't do this
uint8_t counter, ret;
counter = ret = 0;
resetpin = _ResetPin;
addresspin = _AddressPin;
if (resetpin != 255) {
pinMode(resetpin, OUTPUT);
digitalWrite(resetpin, HIGH);
}
if (addresspin != 255) {
pinMode(addresspin, OUTPUT);
setAddress(_SlaveHigh);
} else SLADD = 0x28;
//If self test hasn't returned all success wait... may still be booting
while (read(Page0::SELFTEST_RESULT) != 0x0F) {
delay(25); //We delay to keep chip from locking up in case of some error
counter++;
if (counter == 100) return 0xFF; //Doesn't seem like its going to happen return FF
}
if (_Load) loadCalib();
//Power or config mode invalid, return with high byte flagged
//if (_Power_Mode > 2 || _Operation_Mode > 12) return 0x80;
ret |= init(_Power_Mode, _Operation_Mode, _orientation);
opmode = uint8_t(_Operation_Mode);
if (_Operation_Mode != OPERATION_MODE::CONFIG) running = true; //BNO055 is ready and available(configmode is NOT selected)
return ret;
}
//returns 0 on error, sadly any value could be ok
uint8_t BNO055::read(Page0 _register)
{
if (!page0) writePage(0);
Wire.beginTransmission(SLADD);
Wire.write(uint8_t(_register));
Wire.endTransmission();
if (Wire.requestFrom(SLADD, uint8_t(1))) return Wire.read();
return 0;
}
//returns 0 on error, sadly any value could be ok
uint8_t BNO055::read(Page1 _register)
{
if (page0) writePage(1);
Wire.beginTransmission(SLADD);
Wire.write(uint8_t(_register));
Wire.endTransmission();
if (Wire.requestFrom(SLADD, uint8_t(1))) return Wire.read();
return 0;
}
/*
uint8_t BNO055::read(uint8_t _register, uint8_t _page)
{
uint8_t ret = 0;
if (_page == page0) {
writePage(_page);
page0 = !page0;
}
Wire.beginTransmission(SLADD);
Wire.write(_register);
Wire.endTransmission();
if (Wire.requestFrom(SLADD, uint8_t(1))) ret = Wire.read();
if (page0 == _page) writePage(!_page);
return ret;
}*/
bool BNO055::read(Page0 _register, uint8_t _NumBytes, uint8_t *_dataread)
{
if (!page0) writePage(0);
if (_NumBytes == 0) return false;
if (_NumBytes < 2) {
_dataread[0] = read(_register);
return true;
}
Wire.beginTransmission(SLADD);
Wire.write(uint8_t(_register));
Wire.endTransmission();
if (Wire.requestFrom(SLADD, _NumBytes) != _NumBytes) return false;
if (Wire.available() >= _NumBytes) {
for (size_t i = 0; i < _NumBytes; ++i) _dataread[i] = Wire.read();
return true;
}
return false;
}
bool BNO055::read(Page1 _register, uint8_t _NumBytes, uint8_t *_dataread)
{
if (page0) writePage(1);
if (_NumBytes == 0) return false;
if (_NumBytes < 2) {
_dataread[0] = read(_register);
return true;
}
Wire.beginTransmission(SLADD);
Wire.write(uint8_t(_register));
Wire.endTransmission();
if (Wire.requestFrom(SLADD, _NumBytes) != _NumBytes) return false;
if (Wire.available() >= _NumBytes) {
for (size_t i = 0; i < _NumBytes; ++i) _dataread[i] = Wire.read();
return true;
}
return false;
}
int16_t BNO055::read16(Page0 _register)
{
if (!page0) writePage(0);
Wire.beginTransmission(SLADD);
Wire.write(uint8_t(_register));
Wire.endTransmission();
Wire.requestFrom(SLADD, uint8_t(2));
uint8_t low, high;
low = Wire.read();
high = Wire.read();
return (high << 8) | low;
}
bool BNO055::write(Page0 _register, uint8_t _data)
{
if (!page0) writePage(0);
if (running && _register != Page0::OPERATION_MODE_REG) return false;
uint8_t ret;
//Record any change to units of measure
if (_register == Page0::UNIT_SELECTION) meas_units = _data;
Wire.beginTransmission(SLADD);
Wire.write(uint8_t(_register));
Wire.write(_data);
ret = Wire.endTransmission();
//Min delay between writes is 2 micros in normal, 450micros in low_power or suspend
//Shouldn't be an issue since writes are for setup
if (opmode == uint8_t(POWER_MODE::NORMAL)) delayMicroseconds(2);
else delayMicroseconds(450);
if (ret == 0) return true;
else return false;
}
bool BNO055::write(Page1 _register, uint8_t _data)
{
if (page0) writePage(1);
if (running && (_register != Page1::INTERRUPT_MASK || _register != Page1::INTERRUPT_ENABLE)) return false;
uint8_t ret;
Wire.beginTransmission(SLADD);
Wire.write(uint8_t(_register));
Wire.write(_data);
ret = Wire.endTransmission();
if (ret == 0) return true;
else return false;
}
bool BNO055::write(Page0 _register, uint8_t _NumBytes, uint8_t *_data)
{
if (!page0) writePage(0);
if (_NumBytes == 0) return false;
if (_NumBytes < 2) return write(_register, _data[0]);
if (running && _register != Page0::OPERATION_MODE_REG) return false;
bool ret;
for (size_t i = 0; i < _NumBytes; ++i)
{
//Record any change to units of measure
if (Page0(_register + i) == Page0::UNIT_SELECTION) meas_units = _data[i];
ret = write(Page0(uint8_t(_register) + i), _data[i]);
//Min delay between write is 2 micros in normal, 450micros in low_power or suspend
//Shouldn't be an issue since writes are for setup
if (opmode == uint8_t(POWER_MODE::NORMAL)) delayMicroseconds(2);
else delayMicroseconds(450);
if (!ret) return false;
}
return true;
}
bool BNO055::write(Page1 _register, uint8_t _NumBytes, uint8_t *_data)
{
if (page0) writePage(1);
if (_NumBytes == 0) return false;
if (_NumBytes < 2) return write(_register, _data[0]);
if (running && (_register != Page1::INTERRUPT_ENABLE || _register != Page1::INTERRUPT_MASK)) return false;
bool ret;
for (size_t i = 0; i < _NumBytes; ++i)
{
ret = write(Page1(uint8_t(_register) + i), _data[i]);
//Min delay between write is 2 micros in normal, 450micros in low_power or suspend
//Shouldn't be an issue since writes are for setup
if (opmode == uint8_t(POWER_MODE::NORMAL)) delayMicroseconds(2);
else delayMicroseconds(450);
if (!ret) return false;
}
return true;
}
/*
bool BNO055::write(uint8_t _register, uint8_t _data, bool _page)
{
//You can only write to 3 registers when not in CONFIG_MODE
//Page0::0x3D(op_mode), Page1::0x10, and Page1::0x0F
if (running) {
if (_page == 0 && _register != 0x3D) return false;
if (_page == 1 && (_register != 0x10 || _register != 0x0F)) return false;
}
//Record any change to units of measure
if (_register == 0x3B) meas_units = _data;
bool ret;
if (page0 != _page) {
writePage(_page);
page0 = !page0;
}
ret = write(_register, _data);
//Min delay between write is 2 micros in normal, 450micros in low_power or suspend
//Shouldn't be an issue since writes are for setup
if (opmode == POWER_MODE::NORMAL) delayMicroseconds(2);
else delayMicroseconds(450);
if (page0 != _page) writePage(page0);
if (ret) return true;
return false;
}
**/
bool BNO055::writePage(uint8_t _page)
{
if (_page > 1) return false;
//bypass issue of register checking while running
Wire.beginTransmission(SLADD);
Wire.write(0x07);
Wire.write(_page);
bool ret = Wire.endTransmission();
//Min delay between write is 2 micros in normal, 450micros in low_power or suspend
//Shouldn't be an issue since writes are for setup
if (opmode == uint8_t(POWER_MODE::NORMAL)) delayMicroseconds(2);
else delayMicroseconds(450);
if (ret && _page == 0) page0 = true;
if (ret && _page == 1) page0 = false;
return ret;
}
//uint8_t BNO055::readPage()
//{
// if (page0) return 0;
// else return 1;
//}
bool BNO055::orientation(PLACEMENT _placement)
{
uint8_t config, sign;
if (running) return false;
switch (_placement) {
case PLACEMENT::P0:
config = 0x21;
sign = 0x04;
break;
case PLACEMENT::P1:
config = 0x24;
sign = 0x00;
break;
case PLACEMENT::P2:
config = 0x24;
sign = 0x06;
break;
case PLACEMENT::P3:
config = 0x21;
sign = 0x02;
break;
case PLACEMENT::P4:
config = 0x24;
sign = 0x03;
break;
case PLACEMENT::P5:
config = 0x21;
sign = 0x01;
break;
case PLACEMENT::P6:
config = 0x21;
sign = 0x07;
break;
case PLACEMENT::P7:
config = 0x24;
sign = 0x05;
break;
default:
config = 0x24;
sign = 0x00;
break;
}
write(Page0::AXIS_SIGN_CONFIG, config);
write(Page0::AXIS_SIGN_REMAPPED, sign);
if (read(Page0::AXIS_SIGN_CONFIG) == config) //two ifs, if config isn't right we just return false
if (read(Page0::AXIS_SIGN_REMAPPED) == sign) return true; //otherwise we check axis signs
return false;
}
bool BNO055::orientation(uint8_t _Axis_Config, uint8_t _Axis_Remap)
{
if (running) return false;
write(Page0::AXIS_SIGN_CONFIG, _Axis_Config);
write(Page0::AXIS_SIGN_REMAPPED, _Axis_Remap);
if (read(Page0::AXIS_SIGN_CONFIG) == _Axis_Config)
if (read(Page0::AXIS_SIGN_REMAPPED) == _Axis_Remap) return true;
return false;
}
bool BNO055::setAddress(bool _High)
{
if (addresspin == 255) return false;
digitalWrite(addresspin, _High);
if (digitalRead(addresspin)) SLADD = 0x29;
else SLADD = 0x28;
return true;
}
bool BNO055::reset()
{
if (resetpin == 255) return false;
digitalWrite(resetpin, LOW);
delayMicroseconds(1); //Needs to be low at least 20ns, should be fine with no delay but ehh......
digitalWrite(resetpin, HIGH);
delay(700); //reset to config time is 650ms, do 700 to be safe
running = false;
page0 = true;
meas_units = 0x80; //default
return true;
}
bool BNO055::setOperationMode(OPERATION_MODE _Operation_Mode)
{
bool temp = running;
if (_Operation_Mode == OPERATION_MODE::CONFIG) running = false;
else running = true;
uint8_t ret = write(Page0::OPERATION_MODE_REG, uint8_t(_Operation_Mode));
if (temp && _Operation_Mode == OPERATION_MODE::CONFIG) delay(19); //switch from any mode to config requires 19ms
if (!temp && _Operation_Mode != OPERATION_MODE::CONFIG) delay(7); //switch from config to any mode requires 7ms
return ret;
}
bool BNO055::setPowerMode(POWER_MODE _Power_Mode)
{
return write(Page0::POWER_MODE_REG, uint8_t(_Power_Mode));
}
bool BNO055::setUnits(uint8_t _UnitSel)
{
if (running) return false;
meas_units = _UnitSel;
return write(Page0::UNIT_SELECTION, _UnitSel);
}
bool BNO055::setUnits(bool _Acceleration, bool _Angular_rate, bool _Euler_angles, bool _Temperature, bool _Fusion_Format)
{
if (running) return false;
uint8_t units = 0;
units |= _Acceleration;
units |= (_Angular_rate << 1);
units |= (_Euler_angles << 2);
units |= (_Temperature << 4);
units |= (_Fusion_Format << 7);
meas_units = units;
return write(Page0::UNIT_SELECTION, units);
}
bool BNO055::setTempSource(bool Gyro)
{
if (running) return false;
return write(Page0::TEMP_SOURCE, Gyro);
}
bool BNO055::getTempSource()
{
return read(Page0::TEMP_SOURCE);
}
int8_t BNO055::getTemp()
{
if ((meas_units & 0x10)) return read(Page0::TEMP) * 2; //F*
return read(Page0::TEMP); //C*
}
bool BNO055::getEuler(float *_data)
{
uint8_t datastor[6]{ 0,0,0,0,0,0 };
if (!read(Page0::EULER_HEADING_LSB, 6, datastor)) return false;
if (meas_units & 0x04) {//Radians
_data[0] = int16_t((datastor[1] << 8) | datastor[0]) / 900.0;
_data[1] = int16_t((datastor[3] << 8) | datastor[2]) / 900.0;
_data[2] = int16_t((datastor[5] << 8) | datastor[4]) / 900.0;
}
else //Degrees
{
_data[0] = int16_t((datastor[1] << 8) | datastor[0]) / 16.0;
_data[1] = int16_t((datastor[3] << 8) | datastor[2]) / 16.0;
_data[2] = int16_t((datastor[5] << 8) | datastor[4]) / 16.0;
}
return true;
}
//Returns calculated pitch in degrees or radians depending on UNIT_SELECTION
float BNO055::getEulerPitch() {
if (meas_units & 0x04) return (read16(Page0::EULER_PITCH_LSB)) / 900.0;
return (read16(Page0::EULER_PITCH_LSB)) / 16.0;
}
//Returns calculated heading in degrees or radians depending on UNIT_SELECTION
float BNO055::getEulerHeading() {
if (meas_units & 0x04) return (read16(Page0::EULER_HEADING_LSB)) / 900.0;
return (read16(Page0::EULER_HEADING_LSB)) / 16.0;
}
//Returns calculated roll in degrees or radians depending on UNIT_SELECTION
float BNO055::getEulerRoll() {
if (meas_units & 0x04) return (read16(Page0::EULER_ROLL_LSB)) / 900.0;
return (read16(Page0::EULER_ROLL_LSB)) / 16.0;
}
bool BNO055::getGravity(float *_data)
{
uint8_t datastor[6]{ 0,0,0,0,0,0 };
if (!read(Page0::GRAV_XDATA_LSB, 6, datastor)) return false;
if (meas_units & 0x01) { // mg
_data[0] = int16_t((datastor[1] << 8) | datastor[0]);
_data[1] = int16_t((datastor[3] << 8) | datastor[2]);
_data[2] = int16_t((datastor[5] << 8) | datastor[4]);
}
else // m/s�
{
_data[0] = int16_t((datastor[1] << 8) | datastor[0]) / 100.0;
_data[1] = int16_t((datastor[3] << 8) | datastor[2]) / 100.0;
_data[2] = int16_t((datastor[5] << 8) | datastor[4]) / 100.0;
}
return true;
}
//Gravity vector Z in mg or m/s� depending on UNIT_SELECTION
float BNO055::getGravityVectorZ()
{
if (meas_units & 0x01) return (read16(Page0::GRAV_ZDATA_LSB)); // mg
return (read16(Page0::GRAV_ZDATA_LSB)) / 100.0; // m/s�
}
//Gravity vector Y in mg or m/s� depending on UNIT_SELECTION
float BNO055::getGravityVectorY()
{
if (meas_units & 0x01) return (read16(Page0::GRAV_YDATA_LSB)); // mg
return (read16(Page0::GRAV_YDATA_LSB)) / 100.0; // m/s�
}
//Gravity vector X in mg or m/s� depending on UNIT_SELECTION
float BNO055::getGravityVectorX()
{
if (meas_units & 0x01) return (read16(Page0::GRAV_XDATA_LSB)); // mg
return (read16(Page0::GRAV_XDATA_LSB)) / 100.0; // m/s�
}
bool BNO055::getLinearAccel(float *_data)
{
uint8_t datastor[6]{ 0,0,0,0,0,0 };
if (!read(Page0::LINEAR_ACCEL_XDATA_LSB, 6, datastor)) return false;
if (meas_units & 0x01) { // mg
_data[0] = int16_t((datastor[1] << 8) | datastor[0]);
_data[1] = int16_t((datastor[3] << 8) | datastor[2]);
_data[2] = int16_t((datastor[5] << 8) | datastor[4]);
}
else // m/s�
{
_data[0] = int16_t((datastor[1] << 8) | datastor[0]) / 100.0;
_data[1] = int16_t((datastor[3] << 8) | datastor[2]) / 100.0;
_data[2] = int16_t((datastor[5] << 8) | datastor[4]) / 100.0;
}
return true;
}
//Returns calculated Linear accel for Z axis, in mg or m/s�(determined by UNIT_SELECTION)
float BNO055::getLinearAccelZ()
{
if (meas_units & 0x01) return (read16(Page0::LINEAR_ACCEL_ZDATA_LSB)); // mg
return (read16(Page0::LINEAR_ACCEL_ZDATA_LSB)) / 100.0; // m/s�
}
//Returns calculated Linear accel for Y axis, in mg or m/s�(determined by UNIT_SELECTION)
float BNO055::getLinearAccelY()
{
if (meas_units & 0x01) return (read16(Page0::LINEAR_ACCEL_YDATA_LSB)); // mg
return (read16(Page0::LINEAR_ACCEL_YDATA_LSB)) / 100.0; // m/�
}
//Returns calculated Linear accel for X axis, in mg or m/s�(determined by UNIT_SELECTION)
float BNO055::getLinearAccelX()
{
if (meas_units & 0x01) return (read16(Page0::LINEAR_ACCEL_XDATA_LSB)); // mg
return (read16(Page0::LINEAR_ACCEL_XDATA_LSB)) / 100.0; // m/s�
}
bool BNO055::getQuaternion(double *_data)
{
uint8_t datastor[8]{ 0,0,0,0,0,0,0,0 };
//Don't overwrite date if read fails
if (!read(Page0::QUAT_WDATA_LSB, 8, datastor)) return false;
_data[0] = int16_t((datastor[1] << 8) | datastor[0]) / 16384.0;
_data[1] = int16_t((datastor[3] << 8) | datastor[2]) / 16384.0;
_data[2] = int16_t((datastor[5] << 8) | datastor[4]) / 16384.0;
_data[3] = int16_t((datastor[7] << 8) | datastor[6]) / 16384.0;
return true;
}
double BNO055::getQuatZ()
{
return (read16(Page0::QUAT_ZDATA_LSB)) / 16384.0;
}
//returns quat Y value
double BNO055::getQuatY()
{
return (read16(Page0::QUAT_YDATA_LSB)) / 16384.0;
}
//returns quat X value
double BNO055::getQuatX()
{
return (read16(Page0::QUAT_XDATA_LSB)) / 16384.0;
}
//returns quat W value
double BNO055::getQuatW()
{
return (read16(Page0::QUAT_WDATA_LSB)) / 16384.0;
}
bool BNO055::getGyro(float *_data)
{
uint8_t datastor[6]{ 0,0,0,0,0,0 };
if (!read(Page0::GRAV_XDATA_LSB, 6, datastor)) return false;
if (meas_units & 0x02) { // RPS
_data[0] = int16_t((datastor[1] << 8) | datastor[0]) / 900.0;
_data[1] = int16_t((datastor[3] << 8) | datastor[2]) / 900.0;
_data[2] = int16_t((datastor[5] << 8) | datastor[4]) / 900.0;
}
else // DPS
{
_data[0] = int16_t((datastor[1] << 8) | datastor[0]) / 16.0;
_data[1] = int16_t((datastor[3] << 8) | datastor[2]) / 16.0;
_data[2] = int16_t((datastor[5] << 8) | datastor[4]) / 16.0;
}
return true;
}
//returns Gyro Z data in DPS or RPS, dependent on UNIT_SELECTION
float BNO055::getGyroZ()
{
if (meas_units & 0x02) return (read16(Page0::GYRO_ZDATA_LSB)) / 900;//RPS
return (read16(Page0::GYRO_ZDATA_LSB)) / 16;//dps
}
//returns Gyro Y data in DPS or RPS, dependent on UNIT_SELECTION
float BNO055::getGyroY()
{
if (meas_units & 0x02) return (read16(Page0::GYRO_YDATA_LSB)) / 900;//RPS
return (read16(Page0::GYRO_YDATA_LSB)) / 16;//dps
}
//returns Gyro X data in DPS or RPS, dependent on UNIT_SELECTION
float BNO055::getGyroX()
{
if (meas_units & 0x02) return (read16(Page0::GYRO_XDATA_LSB)) / 900;//RPS
return (read16(Page0::GYRO_XDATA_LSB)) / 16;//dps
}
bool BNO055::getAccel(float *_data)
{
uint8_t datastor[6]{ 0,0,0,0,0,0 };
if (!read(Page0::ACCEL_XDATA_LSB, 6, datastor)) return false;
if (meas_units & 0x01) { // mg
_data[0] = int16_t((datastor[1] << 8) | datastor[0]);
_data[1] = int16_t((datastor[3] << 8) | datastor[2]);
_data[2] = int16_t((datastor[5] << 8) | datastor[4]);
}
else // m/s�
{
_data[0] = int16_t((datastor[1] << 8) | datastor[0]) / 100.0;
_data[1] = int16_t((datastor[3] << 8) | datastor[2]) / 100.0;
_data[2] = int16_t((datastor[5] << 8) | datastor[4]) / 100.0;
}
return true;
}
//returns accel Z data based on UNIT_SELECTION, mg or m/s�
float BNO055::getAccelZ()
{
if (meas_units & 0x01) return (read16(Page0::ACCEL_ZDATA_LSB));//mg
return (read16(Page0::ACCEL_ZDATA_LSB)) / 100.0;// m/s�
}
//returns accel X data based on UNIT_SELECTION, mg or m/s�
float BNO055::getAccelY()
{
if (meas_units & 0x01) return (read16(Page0::ACCEL_YDATA_LSB));//mg
return (read16(Page0::ACCEL_YDATA_LSB)) / 100.0;// m/s�
}
//returns accel X data based on UNIT_SELECTION, mg or m/s�
float BNO055::getAccelX()
{
if (meas_units & 0x01) return (read16(Page0::ACCEL_XDATA_LSB));//mg
return (read16(Page0::ACCEL_XDATA_LSB)) / 100.0;// m/s�
}
bool BNO055::getMag(float *_data)
{
uint8_t datastor[6]{ 0,0,0,0,0,0 };
if (!read(Page0::MAG_XDATA_LSB, 6, datastor)) return false;
_data[0] = int16_t((datastor[1] << 8) | datastor[0]) / 16.0;
_data[1] = int16_t((datastor[3] << 8) | datastor[2]) / 16.0;
_data[2] = int16_t((datastor[5] << 8) | datastor[4]) / 16.0;
return true;
}
//returns mag Z value in uT
float BNO055::getMagZ()
{
return (read16(Page0::MAG_ZDATA_LSB)) / 16.0;
}
//returns mag Y value in uT
float BNO055::getMagY()
{
return (read16(Page0::MAG_YDATA_LSB)) / 16.0;
}
//returns mag X value in uT
float BNO055::getMagX()
{
return (read16(Page0::MAG_XDATA_LSB)) / 16.0;
}
bool BNO055::saveCalib()
{
#ifdef MyCalibrations
return printCalib();
#else
#ifdef EEPROM_h
return saveEEPROM();
#else
return printCalib();
#endif
#endif
}
bool BNO055::loadCalib()
{
#ifdef MyCalibrations
return loadMyCal();
#else
#ifdef EEPROM_h
return loadEEPROM();
#else
return false;
#endif
#endif
}
#ifdef MyCalibrations
bool BNO055::loadMyCal()
{
uint8_t OPMODE;
OPMODE = read(Page0::OPERATION_MODE_REG);
if (OPMODE != 0x00) setOperationMode(OPERATION_MODE::CONFIG);
if (read(Page0::OPERATION_MODE_REG) != uint8_t(OPERATION_MODE::CONFIG)) return false; //couldn't set config mode
delay(20); //delay to allow to switch to config
for (size_t i = 0; i < 22; ++i)
{
write(Page0(i + 0x55), MyCal[i]);
}
write(Page0::OPERATION_MODE_REG, OPMODE);
delay(8); //wait to come out of config
return true;
}
#else
#ifdef EEPROM_h
bool BNO055::saveEEPROM()
{
int8_t temp = 0;
for (size_t i = 0; i<22; ++i)
{
temp = read(Page0(i + 0x55));
EEPROM.write(i + eepromaddress, temp);
}
return true;
}
bool BNO055::loadEEPROM()
{
uint8_t OPMODE = 0;
uint8_t temp = 0;
OPMODE = read(Page0::OPERATION_MODE_REG);
if (OPMODE != 0x00) write(Page0::OPERATION_MODE_REG, OPERATION_MODE::CONFIG);
delay(20); //delay to allow time to switch to config mode
if (read(Page0::OPERATION_MODE_REG) != OPERATION_MODE::CONFIG) return false; //couldn't set config mode
for (size_t i = 0; i<22; ++i)
{
EEPROM.read(i + eepromaddress, temp);
write(Page0(i + 0x55), temp);
}
write(Page0::OPERATION_MODE_REG, OPMODE);
delay(8); //wait to come out of config
return true;
}
#endif
#endif
#ifndef EEPROM_h
bool BNO055::printCalib()
{
uint8_t temp;
if (!Serial) return false;
Serial.println("Calibration Profile, copy/paste lines to BNODEFS.h:");
Serial.println("#define MyCalibrations");
Serial.print("static const uint8_t MyCal[] = { ");
for (size_t i = 0; i<22; ++i)
{
temp = read(Page0(i + 0x55));
Serial.print(temp, DEC);
if (i != 21) Serial.print(", ");
else Serial.println(" };");
}
return true;
}
#endif
/////////////////////////////////////////////////////////////
//These are Page1 register functions.
//
//
//These are mainly for interrupt settings and manual sensor config
//for non-fusion operating modes
//These all reselect whichever page was selected, doesn't write page if already page 1
/////////////////////////////////////////////////////////////
bool BNO055::setInterruptEnable(uint8_t _IntEnable)
{
return write(Page1::INTERRUPT_ENABLE, _IntEnable); //write data
}
uint8_t BNO055::getInterruptEnable()
{
return read(Page1::INTERRUPT_ENABLE); //write data
}
bool BNO055::setInterruptMask(uint8_t _IntMask)
{
return write(Page1::INTERRUPT_MASK, _IntMask); //write data
}
uint8_t BNO055::getInterruptMask()
{
return read(Page1::INTERRUPT_MASK);
}
bool BNO055::setMagConfig(uint8_t _Mag_Config)
{
if (running) return false; //can't set if not in configmode
return write(Page1::MAG_CONFIG, _Mag_Config);
}
uint8_t BNO055::getMagConfig()
{
return read(Page1::MAG_CONFIG);
}
bool BNO055::setGyroConfig(uint8_t _Config0, uint8_t _Config1)
{
if (running) return false;
uint8_t ret = 0;
ret = write(Page1::GYRO_CONFIG_0, _Config0);
ret |= write(Page1::GYRO_CONFIG_1, _Config1);
return ret;
}
uint8_t BNO055::getGyroConfig0()
{
return read(Page1::GYRO_CONFIG_0);
}
uint8_t BNO055::getGyroConfig1()
{
return read(Page1::GYRO_CONFIG_1);
}
bool BNO055::setGyroSleepConfig(uint8_t _SleepData)
{
if (running) return false;
return write(Page1::GYRO_SLEEP_CONFIG, _SleepData);
}
uint8_t BNO055::getGyroSleepConfig()
{
return read(Page1::GYRO_SLEEP_CONFIG);
}
bool BNO055::setGyroInterruptSettings(uint8_t _GyroIntSettings)
{
if (running) return false;
return write(Page1::GYRO_INTERRUPT_SETUP, _GyroIntSettings);
}
uint8_t BNO055::getGyroInterruptSettings()
{
return read(Page1::GYRO_INTERRUPT_SETUP);
}
bool BNO055::setGyroHR_XThreshold(uint8_t _HighRateX)
{
if (running) return false;
return write(Page1::GYRO_XHIGHRATE_THRESHOLD, _HighRateX);
}
uint8_t BNO055::getGyroHR_XThreshold()
{
return read(Page1::GYRO_XHIGHRATE_THRESHOLD);
}
bool BNO055::setGyroHR_XDuration(uint8_t _HighRateXDur)
{
if (running) return false;
return write(Page1::GYRO_XHIGHRATE_DURATION, _HighRateXDur);
}
uint8_t BNO055::getGyroHR_XDuration()
{
return read(Page1::GYRO_XHIGHRATE_DURATION);
}
bool BNO055::setGyroHR_YThreshold(uint8_t _HighRateY)
{
if (running) return false;
return write(Page1::GYRO_YHIGHRATE_THRESHOLD, _HighRateY);
}
uint8_t BNO055::getGyroHR_YThreshold()
{
return read(Page1::GYRO_YHIGHRATE_THRESHOLD);
}
bool BNO055::setGyroHR_YDuration(uint8_t _HighRateYDur)
{
if (running) return false;
return write(Page1::GYRO_YHIGHRATE_DURATION, _HighRateYDur);
}
uint8_t BNO055::getGyroHR_YDuration()
{
return read(Page1::GYRO_YHIGHRATE_DURATION);
}
bool BNO055::setGyroHR_ZThreshold(uint8_t _HighRateZ)
{
if (running) return false;
return write(Page1::GYRO_ZHIGHRATE_THRESHOLD, _HighRateZ);
}
uint8_t BNO055::getGyroHR_ZThreshold()
{
return read(Page1::GYRO_ZHIGHRATE_THRESHOLD);
}
bool BNO055::setGyroHR_ZDuration(uint8_t _HighRateZDur)
{
if (running) return false;
return write(Page1::GYRO_ZHIGHRATE_DURATION, _HighRateZDur);
}
uint8_t BNO055::getGyroHR_ZDuration()
{
return read(Page1::GYRO_ZHIGHRATE_DURATION);
}
bool BNO055::setGyroAnyMotionThreshold(uint8_t _AMThresh)
{
if (running) return false;
return write(Page1::GYRO_ANYMOTION_THRESHOLD, _AMThresh);
}
uint8_t BNO055::getGyroAnyMotionThreshold()
{
return read(Page1::GYRO_ANYMOTION_THRESHOLD);
}
bool BNO055::setGyroAnyMotionSettings(uint8_t _AMSettings)
{
if (running) return false;
return write(Page1::GYRO_ANYMOTION_SETUP, _AMSettings);
}
uint8_t BNO055::getGyroAnyMotionSettings()
{
return read(Page1::GYRO_ANYMOTION_SETUP);
}
bool BNO055::setAccConfig(uint8_t _ACC_Config)
{
if (running) return false;
return write(Page1::ACCEL_CONFIG, _ACC_Config);
}
bool BNO055::setAccConfig(ACC_RANGE _G_Range, ACC_BANDWIDTH _Bandwidth, ACC_OPMODE _Op_Mode)
{
if (running) return false;
return write(Page1::ACCEL_CONFIG, uint8_t(_G_Range) | uint8_t(_Bandwidth) | uint8_t(_Op_Mode));
}
uint8_t BNO055::getAccConfig()
{
return read(Page1::ACCEL_CONFIG);
}
bool BNO055::setAccSleepConfig(uint8_t _SleepData)
{
if (running) return false;
return write(Page1::ACCEL_SLEEP_CONFIG, _SleepData);
}
uint8_t BNO055::getAccSleepConfig()
{
return read(Page1::ACCEL_SLEEP_CONFIG);
}
bool BNO055::setAccAnyMotionThreshold(uint8_t _AMTheshold)
{
if (running) return false;
return write(Page1::ACCEL_ANYMOTION_THRESHOLD, _AMTheshold);
}
uint8_t BNO055::getAccAnyMotionThreshold()
{
return read(Page1::ACCEL_ANYMOTION_THRESHOLD);
}
bool BNO055::setAccInterruptSettings(uint8_t _IntSettings)
{
if (running) return false;
return write(Page1::ACCEL_INTERRUPT_SETTINGS, _IntSettings);
}
uint8_t BNO055::getAccInterruptSettings()
{
return read(Page1::ACCEL_INTERRUPT_SETTINGS);
}
bool BNO055::setAccHighGDuration(uint8_t _HighGDuration)
{
if (running) return false;
return write(Page1::ACCEL_HIGHG_DURATION, _HighGDuration);
}
uint8_t BNO055::getAccHighGDuration()
{
return read(Page1::ACCEL_HIGHG_DURATION);
}
bool BNO055::setAccHighGThreshold(uint8_t _HighGThreshold)
{
if (running) return false;
return write(Page1::ACCEL_HIGHG_THRESHOLD, _HighGThreshold);
}
uint8_t BNO055::getAccHighGThreshold()
{
return read(Page1::ACCEL_HIGHG_THRESHOLD);
}
bool BNO055::setAccNoMotionThreshold(uint8_t _NoMotionThreshold)
{
if (running) return false;
return write(Page1::ACCEL_NOMOTION_THRESHOLD, _NoMotionThreshold);
}
uint8_t BNO055::getAccNoMotionThreshold()
{
return read(Page1::ACCEL_NOMOTION_THRESHOLD);
}
bool BNO055::setAccNoMotionSetting(uint8_t _SloNoMotionSet)
{
if (running) return false;
return write(Page1::ACCEL_NOMOTION_SETUP, _SloNoMotionSet);
}
uint8_t BNO055::getAccNoMotionSetting()
{
return read(Page1::ACCEL_NOMOTION_SETUP);
}
|
#ifndef MFMESHQUADSURFACE_H
#define MFMESHQUADSURFACE_H
#include "mfMacros.h"
#include "mfSing.h"
#include "mfMesh.h"
#include "mfMeshOper.h"
//#include "mfVertexStarIteratorQuadSurf.h"
namespace mf
{
/**
* @class mfMeshQuadSurface
* @file mfMeshQuadSurface.h
* @short
* Mesh Operator Class
*
* Operation Class for Quadrilaterals in 3D space (with oriented quadrilaterals)
*
* _Traits must have: ids, sVertex, sCell , sSing, sMesh
*
* @author Icaro da Cunha
* @version 1.0
* @date 2008, july
*/
template <class _Traits> class mfMeshQuadSurface : public mfMeshOper<_Traits>
{
public:
typedef typename _Traits::ids ids; /**< Id typename definition */
typedef typename _Traits::sVertex sVertex; /**< Vertex typename definition */
typedef typename _Traits::sCell sCell; /**< Cell typename definition */
typedef mfSing<_Traits> sSing; /**< Singular typename definition */
typedef typename _Traits::sMesh sMesh; /**< /mesh typename definition */
/** Constructor
*
* \param _mesh: the mesh address that this class will manipulate
*/
mfMeshQuadSurface(sMesh *_mesh);
/** Destructor */
~mfMeshQuadSurface();
/** Add cell in mesh
*
* \param idcell: cell id
* \param idvertices: vector with vertices ids of the cell
*/
void addCell(ids idcell, ids *idvertices MF_DMUTEXVD);
/** Delete a cell
*
* \param idcell: cell id
*/
void delCell(ids idcell MF_DMUTEXVD);
private:
#ifdef MF_THREADS
//void lockVertices(int num, sVertex* v);
//void unlockVertices(int num, sVertex* v);
#endif
};
template <class _Traits> mfMeshQuadSurface<_Traits>::mfMeshQuadSurface(sMesh *_mesh)
: mfMeshOper<_Traits>(_mesh)
{
}
template <class _Traits> mfMeshQuadSurface<_Traits>::~mfMeshQuadSurface()
{
}
/* To check the mates calculations */
template <class _Traits> void mfMeshQuadSurface<_Traits>::addCell(ids idcell, ids *idvertices MF_DMUTEXV)
{
// Correct vertex id (i.e. >=0)
MF_ASSERT((idvertices[0] >= 0)&&(idvertices[1] >= 0)&&(idvertices[2] >= 0)&&(idvertices[3] >= 0));
// Any vertex that are alike
MF_ASSERT((idvertices[0] != idvertices[1])&&(idvertices[0] != idvertices[2])&&(idvertices[0] != idvertices[3]));
MF_ASSERT((idvertices[1] != idvertices[2])&&(idvertices[1] != idvertices[3])&&(idvertices[2] != idvertices[3]));
sCell *c = this->mesh->getCell(idcell);
ids idv[4] = {idvertices[0], idvertices[1], idvertices[2], idvertices[3]};
sVertex *v[4] = {this->mesh->getVertex(idv[0]), this->mesh->getVertex(idv[1]), this->mesh->getVertex(idv[2]), this->mesh->getVertex(idv[3])};
sCell *cop;
sSing *s;
ids icop;
ids idEdge;
int i, pos;
c->clearMates();
c->setVertexId(0,idv[0]);
c->setVertexId(1,idv[1]);
c->setVertexId(2,idv[2]);
c->setVertexId(3,idv[3]);
for(i = 0; i < 4 ; i++)
{
// singularity from ant vertex
s = v[i]->getSing(); // [i]
while (s)
{
icop = s->getCell();
cop = this->mesh->getCell(icop);
if(cop->getVertexId((cop->getVertexIndex(idv[i]) + 3)%4) == idv[(i+1)%4])
{
idEdge = this->mesh->addEdge();
c->setEdgeId(i, idEdge);
cop->setEdgeId(cop->getVertexIndex(idv[(i+1)%4]), idEdge);
c->setMateId(i, icop);
cop->setMateId(cop->getVertexIndex(idv[(i+1)%4]), idcell);
s = NULL;
}
else
s = s->getNext();
}
}
for(i = 0; i < 4; i++)
{
if (c->getMateId((i+3)%4) < 0)
{
if(c->getMateId(i) >= 0)
{
pos = v[i]->inSings(c->getMateId(i));
v[i]->setSingCell(pos,idcell);
}
else
v[i]->addSing(idcell);
}
else
{
if(c->getMateId(i) >= 0)
{
icop = c->getMateId(i);
pos = v[i]->inSings(icop);
while((icop >= 0)&&(icop != idcell))
{
cop = this->mesh->getCell(icop);
icop = cop->getMateId(cop->getVertexIndex(idv[i]));
if(icop < 0)
v[i]->delSing(pos);
}
}
}
}
}
/* Not tested */
template <class _Traits> void mfMeshQuadSurface<_Traits>::delCell(ids idcell MF_DMUTEXV)
{
int i,pos;
sCell *cop, *c = this->mesh->getCell(idcell);
sVertex *v[4] = { this->mesh->getVertex(c->getVertexId(0)), this->mesh->getVertex(c->getVertexId(1)), this->mesh->getVertex(c->getVertexId(2)), this->mesh->getVertex(c->getVertexId(3))};
ids icop;
for(i = 0; i < 4; i++)
{
if(c->getMateId((i+3)%4) >= 0)
{
if(c->getMateId(i) >= 0)
{
icop = c->getMateId(i);
while((icop >= 0)&&(icop != idcell))
{
cop = this->mesh->getCell(icop);
icop = cop->getMateId(cop->getVertexIndex(c->getVertexId(i)));
if(icop < 0)
v[i]->addSing(c->getMateId(i));
else if (icop == idcell)
v[i]->getSing()->setCell(c->getMateId(i));
}
}
}
else
{
pos = v[i]->inSings(idcell);
if(c->getMateId(i) >= 0)
v[i]->setSingCell(pos,c->getMateId(i));
else
v[i]->delSing(pos);
}
}
for(i=0; i < 4; i++)
{
icop = c->getMateId(i);
if(icop >= 0)
{
cop = this->mesh->getCell(icop);
cop->setMateId(cop->getMateIndex(idcell),-1);
}
}
c->setMateId(0,-1);
c->setMateId(1,-1);
c->setMateId(2,-1);
c->setMateId(3,-1);
}
}
#endif
|
#pragma once
#include <iostream>
using namespace std;
#define VALID_MAX_AGE 110
#define VALID_MIN_AGE 18
enum DataType {
NUMBER = 0x1,
SYMBOL = 0x2,
LWCASE = 0x4,
UPCASE = 0x8,
SPACE = 0x10,
};
unsigned int stringContains(const string& s);
bool doesStringContainOnlyAndOptional(const string& s, unsigned int DataTypeOnly, unsigned int DataTypeOptional);
bool doesStringContainOnly(const string& s, unsigned int DataType);
bool doesStringContainAnyOf(const string& s, unsigned int DataType);
bool isStringInRange(const string& s, unsigned int DataType);
bool isInputValid(const string& s, const unsigned int targetLength);
bool isAgeValid(int age);
bool stringToCharArray(const string& source, char dest[], const unsigned int targetLength);
|
#include<iostream>
using namespace std;
enum VehicleType {
VT_Twowheeler, VT_ThreeWheeler, VT_FourWheeler
};
class Vehicle {
public:
virtual void printVehicle()=0;
static Vehicle*create(VehicleType type);
};
class Twowheeler:public Vehicle{
void printVehicle() {
cout<<" IM TWO WHEELER !!";
}
};
class Threewheeler:public Vehicle{
void printVehicle() {
cout<<"IM THREE WHEELER @@";
}
};
class Fourwheeler:public Vehicle{
void printVehicle() {
cout<<" IM FOUR WHEELER 44444444";
}
};
Vehicle* Vehicle::create(VehicleType type) {
if(type==VT_Twowheeler)
return new Twowheeler();
else if(type==VT_ThreeWheeler)
return new Threewheeler();
else if (type==VT_FourWheeler)
return new Fourwheeler();
else return NULL;
}
class Client {
public:
Client() {
VehicleType type=VT_ThreeWheeler;
pVehicle=Vehicle ::create(type);
}
~Client(){
if (pVehicle){
delete [] pVehicle;
pVehicle=NULL;
}
}
Vehicle*getVehicle() {
return pVehicle;
}
private:
Vehicle *pVehicle;
};
int main () {
Client*pClient= new Client();
Vehicle *pVehicle=pClient->getVehicle();
pVehicle->printVehicle();
return 0;
}
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// 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 Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
#ifndef POOMA_UTILITIES_ELEMENTPROPERTIES_H
#define POOMA_UTILITIES_ELEMENTPROPERTIES_H
//-----------------------------------------------------------------------------
// Classes:
// ElementProperties<T> and specializations
// TrivialElementProperties<T>
//-----------------------------------------------------------------------------
///////////////////////////////////////////////////////////////////////////////
// namespace POOMA {
/** @file
* @ingroup Utilities
* @brief
* Traits class for determining, and possibly modifying, the
* construction and destruction properties of elements of type T.
*/
//-----------------------------------------------------------------------------
// Include Files
//-----------------------------------------------------------------------------
#include "Utilities/PAssert.h"
#include <new>
/**
* Traits class for determining, and possibly modifying, the
* construction and destruction properties of elements of type T.
*
* In detail, this class serves several purposes:
* - First it allows RefCountedBlockPtr to optimize away the
* constructor and destructor calls for classes with "trivial"
* default constructors and destructors (e.g. the native C data
* types, but see below for details).
* - Second, certain types can be safely copied with memcpy. We
* refer to these as "concrete" types. Such types should set
* the concrete trait to true.
* - Third, it allows specializations to provide special construct,
* clone, and destruct methods that override the default behavior.
* The primary reason for this capability is to allow RefCountedPtr
* and RefCountedBlockPtr to store deep copies of (and potentially
* make further deep copies of) objects that have shallow copy
* semantics. This can be done by specializing ElementProperties to
* provide construct and clone methods that make deep copies of the
* model object.
* - Finally, one might want RefCountedPtr<T> to point to an object
* that inherits from T. In such situations, asking the
* RefCountedPtr to make a deep copy of its pointee would, with the
* default behavior, cause the object to be sliced (as T's copy
* constructor would be used). If T has a "virtual constructor" (a
* virtual clone method), then one can specialize ElementProperties'
* clone() method to call the virtual constructor and make the
* proper copy.
*
* The first capability is provided by defining the two bool fields:
* - enum { hasTrivialDefaultConstructor };
* - enum { hasTrivialDestructor };
*
* hasTrivialDefaultConstructor is true for data types whose default
* constructors have the same semantics as the native C data types;
* i.e. they do nothing: no allocations, no default values, etc.
* Normally RefCountedBlockPtr calls placement operator new to
* initizlize objects in the space that it allocates and manages.
* However, this is unnecessary overhead for types whose default
* constructor does nothing. Thus if hasTrivialDefaultConstructor is
* true, RefCountedBlockPtr will leave memory uninitialized in the
* default case.
*
* Versions of ElementProperties for the most common C data types are
* defined below. Similar specializations might also be useful for
* other statically sized data types, such as TinyArrays. (Note that
* one could optionally define the specializations for native data
* types to initialize memory with some obviously corrupt value in
* order to help track initialization problems during debugging,
* although purify is probably a better tool for such investigations.)
*
* Similarly, hasTrivialDestructor == true causes RefCountedBlockPtr
* to skip the explicit destructor calls that are normally necessary
* when destroying an object created with placement new.
* This will almost always have the same value as
* hasTrivialDefaultConstructor, but the additional flexibility
* carries no additional cost so it was included.
*
* The class must also define the following static functions:
* - inline static void construct(T * addr, const T & model)
* - inline static void T * clone(const T & model);
* - inline static void construct(T * addr)
* - inline static void destruct(T *addr)
*
* If the "trivial" flags are true, then the last two functions will
* never be called, but they must be defined or the compiler will
* complain. In these cases it is best to define the functions to
* throw an exception (see below).
*
* The non-specialized ElementProperties<T> class defines both flags
* to be false. It defines the construct methods to use the default
* and copy constructors with placement new, respectively, under the
* assumption that these will make deep copies. Finally, it defines
* the destruct method to explicitly invoke the destructor on the
* object.
*/
template <class T>
struct ElementProperties
{
//---------------------------------------------------------------------------
// Convenience typedef (not needed here, but useful for
// specializations, which may want to copy parts of this definition)
typedef T This_t;
//---------------------------------------------------------------------------
// By default, we assume that the default constructor and the
// destructor do something.
enum { hasTrivialDefaultConstructor = false };
enum { hasTrivialDestructor = false };
//---------------------------------------------------------------------------
// We specialize this struct for concrete types. These are types that
// have no pointers, etc., so that their data can be copied with routines
// such as std::copy or std::memcpy.
enum { concrete = false };
//---------------------------------------------------------------------------
// Sometimes it is necessary to know if a type is one of the C basic
// types. The following trait answers this question.
enum { basicType = false };
//---------------------------------------------------------------------------
// Since the above are false, the code will use placement new for
// initialization, and thus must explicitly call the destructor. The
// following are the default methods for doing these things.
static void construct(This_t * addr)
{
new (addr) This_t();
}
static void construct(This_t * addr, const This_t & model)
{
new (addr) This_t(model);
}
static This_t * clone(const This_t &model)
{
return new This_t(model);
}
static void destruct(This_t * addr)
{
addr->~This_t();
}
};
/**
* Concrete types that have trivial default construction and destruction
* semantics can just inherit from this:
*/
template <class T>
struct TrivialElementPropertiesBase
{
typedef T This_t;
enum { hasTrivialDefaultConstructor = true };
enum { hasTrivialDestructor = true };
enum { concrete = true };
static void construct(This_t * addr, const This_t & model)
{
new (addr) This_t(model);
}
static This_t * clone(const This_t &model)
{
return new This_t(model);
}
static void construct(This_t *addr)
{
new (addr) This_t();
}
static void destruct(This_t *)
{
PInsist(0,"TrivialElementProperties<T>::destruct(addr) not allowed!");
}
};
template <class T>
struct TrivialElementProperties : public TrivialElementPropertiesBase<T>
{
enum { basicType = false };
};
/**
* Basic types are the C basic types. This is the same as
* TrivialElementProperties, but with basicType == true;
*/
template <class T>
struct BasicTypeProperties : public TrivialElementPropertiesBase<T>
{
enum { basicType = true };
};
/**
* Classes that have shallow copy semantics and "makeOwnCopy" methods
* can specialize ElementProperties<T> by simply inheriting from this.
*/
template <class T>
struct MakeOwnCopyProperties
{
typedef T This_t;
enum { hasTrivialDefaultConstructor = false };
enum { hasTrivialDestructor = false };
enum { concrete = false };
enum { basicType = false };
static void construct(This_t * addr)
{
new (addr) This_t;
addr->makeOwnCopy();
}
static void construct(This_t * addr, const This_t & model)
{
new (addr) This_t(model);
addr->makeOwnCopy();
}
static This_t * clone(const This_t &model)
{
This_t * temp = new This_t(model);
temp->makeOwnCopy();
return temp;
}
static void destruct(This_t * addr)
{
addr->~This_t();
}
};
//-----------------------------------------------------------------------------
// Specializations for standard C++ types, which do not do initialization
// in their "default constructors".
template <>
struct ElementProperties<bool> : public BasicTypeProperties<bool>
{ };
template <>
struct ElementProperties<char> : public BasicTypeProperties<char>
{ };
template <>
struct ElementProperties<unsigned char>
: public BasicTypeProperties<unsigned char>
{ };
template <>
struct ElementProperties<short> : public BasicTypeProperties<short>
{ };
template <>
struct ElementProperties<unsigned short>
: public BasicTypeProperties<unsigned short>
{ };
template <>
struct ElementProperties<int> : public BasicTypeProperties<int>
{ };
template <>
struct ElementProperties<unsigned int>
: public BasicTypeProperties<unsigned int>
{ };
template <>
struct ElementProperties<long> : public BasicTypeProperties<long>
{ };
#if POOMA_HAS_LONG_LONG
template <>
struct ElementProperties<long long> : public BasicTypeProperties<long long>
{ };
#endif
template <>
struct ElementProperties<unsigned long>
: public BasicTypeProperties<unsigned long>
{ };
template <>
struct ElementProperties<float> : public BasicTypeProperties<float>
{ };
template <>
struct ElementProperties<double> : public BasicTypeProperties<double>
{ };
namespace std {
template <class Float> class complex;
}
template <class FloatType>
struct ElementProperties<std::complex<FloatType> >
: public TrivialElementProperties<std::complex<FloatType> >
{ };
// } // namespace POOMA
///////////////////////////////////////////////////////////////////////////////
#endif // POOMA_UTILITIES_ELEMENTPROPERTIES_H
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: ElementProperties.h,v $ $Author: richard $
// $Revision: 1.21 $ $Date: 2004/11/01 18:17:17 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
#include "List.h"
template <typename T>
List<T>::List()
{
arr = new T[1];
maxSize = 1;
currentSize = 0;
}
template <typename T>
List<T>::List(const List& obj)
{
maxSize = obj.maxSize;
currentSize = obj.currentSize;
arr = new int[maxSize];
for (int i = 0; i < currentSize; i++)
{
arr[i] = obj.arr[i];
}
}
template <typename T>
T* List<T>::regrow(T num)
{
T* temp=new T[currentSize];
for (int i = 0; i < currentSize; i++)
{
temp[i] = arr[i];
}
arr = new T[currentSize + 1];
for (int i = 0; i < currentSize; i++)
{
arr[i] = temp[i];
}
arr[currentSize] = num;
currentSize++; maxSize++;
return arr;
}
template <typename T>List<T>::~List()
{
delete[] arr;
arr = nullptr;
}
|
#ifndef TIMERS_H
#define TIMERS_H
#include <sys/time.h>
#include <time.h>
// See http://apps.topcoder.com/forums/?module=Thread&threadID=642239&start=0
int get_time_counter = 0;
double get_time() {
get_time_counter++;
timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + tv.tv_usec * 1e-6;
}
double work = 0.0;
void add_work(double delta_work) {
work += delta_work;
}
double cached_get_time() {
static auto last = get_time();
if (work < 0.01)
return last;
work = 0.0;
auto t = get_time();
if (t - last > 0.05) {
cerr << "cached_get_time " << (t - last) << endl;
}
last = t;
return t;
}
vector<double> deadlines;
void add_subdeadline(double fraction) {
assert(!deadlines.empty());
double now = get_time();
double remaining = deadlines.back() - now;
if (remaining < 0) {
cerr << "# DEADLINE_MISSED = " << remaining << endl;
deadlines.push_back(deadlines.back());
return;
}
deadlines.push_back(now + remaining * fraction);
}
bool check_deadline() {
return !deadlines.empty() and cached_get_time() > deadlines.back();
}
void set_deadline_from_now(double seconds) {
deadlines.push_back(get_time() + seconds);
}
map<string, clock_t> timers;
#ifdef USE_TIME_IT
class TimeIt {
private:
string name;
public:
TimeIt(string name) : name(name) {
timers[name] -= clock();
}
~TimeIt() {
timers[name] += clock();
}
};
#else
class TimeIt {
public:
TimeIt(string name) {}
};
#endif
void print_timers(ostream &out) {
for (auto kv : timers) {
out << "# " << kv.first << "_time = " << 1.0 * kv.second / CLOCKS_PER_SEC << endl;
}
}
// On their machines, I saw about 5K get_time() calls per second.
// There are ~60K clock() calls per _CPU_ second, which turns out to be roughly
// the same.
void benchmark_timers(ostream &out) {
{
auto start_time = get_time();
int cnt = 0;
while (get_time() < start_time + 0.1) cnt++;
cerr << 10*cnt << " get_time() calls per second" << endl;
}
{
auto start_time = clock();
int cnt = 0;
while (clock() < start_time + 0.1*CLOCKS_PER_SEC) cnt++;
cerr << 10*cnt << " clock() calls per second" << endl;
}
}
#endif
|
#include <iostream>
#include <string>
using namespace std;
void lucky(string s) {
int len = s.size() / 2;
int sum1 = 0, sum2 = 0;
for (int i = 0; i < len; i++) {
int n1 = s[i] - '0';
int n2 = s[i + len] - '0';
sum1 += n1;
sum2 += n2;
}
if (sum1 == sum2)
cout << "LUCKY" << endl;
else if(sum1!=sum2)
cout << "READY" << endl;
}
int main() {
string num;
cin >> num;
lucky(num);
}
|
//3->2,5->2,9->4
#include <iostream>
#include<vector>
#include<test_if_sorted.hpp>
#include<random>
using namespace std;
random_device r;
void traverse(vector<int>& a) { for (auto i : a)cout << i << ends; cout << endl; }
void merge(vector<int>&a, vector<int>& aux, int lo, int mid, int hi) {
int k;
for (k = lo; k <= hi; k++) {
aux[k] = a[k];
}cout << "回合内:";
traverse(aux);
traverse(a);
cout << "回合结束" << endl;
int i = lo, j = mid + 1;
for (k = lo; k <= hi; k++) {
cout << endl;
cout << "k: "<<k << ends;
cout << endl;
if (i > mid)
a[k] = aux[j++];
else if(j>hi)
a[k] = aux[i++];
else if (aux[j] < aux[i])
a[k] = aux[j++];
else
a[k] = aux[i++];
}
}
void sort(vector<int>&a) {
const int N = a.size();
vector<int> aux(N, 0);
for (int sz = 1; sz < N; sz+=sz) {
for (int lo = 0; lo < N-sz ; lo += 2*sz ) {
cout << "lo: " << lo << " mid: " << lo + sz - 1 << " end: " << min(lo + 2 * sz - 1, N - 1)<<endl;
merge(a, aux, lo, lo + sz - 1, min(lo + 2*sz - 1, N - 1));
traverse(a);
}
}
}
int main()
{
vector<int> a;
for (auto i = 0; i < 14; ++i) {
//a.emplace_back(r() % 100);
a.emplace_back(14 - i);
};
traverse(a);
sort(a);
traverse(a);
}
|
#include "rfiddll.h"
#include <QDebug>
RfidDLL::RfidDLL()
{
qDebug() << "RfidDLL->DLL created, initialising";
}
void RfidDLL::initialiseSerialPort()
{
serial = new QSerialPort(this);
serial->setPortName("com8"); // set this to what is the real port
serial->setBaudRate(QSerialPort::Baud9600);
serial->setDataBits(QSerialPort::Data8);
serial->setParity(QSerialPort::NoParity);
serial->setStopBits(QSerialPort::OneStop);
serial->setFlowControl(QSerialPort::HardwareControl);
if (serial->open(QIODevice::ReadWrite))
{
qDebug() << "RfidDLL->Port opened: " << serial->portName();
}
else
{
qDebug() << "RfidDLL->Error while opening port" << serial->portName();
}
connect(serial, SIGNAL(readyRead()), this, SLOT(readByteStream()));
}
void RfidDLL::readByteStream()
{
char data[20];
int bytesread;
bytesread = serial->read(data,20);
data[bytesread] = '\0';
if (bytesread>10)
{
cardSerialNumber = data;
cardSerialNumber.remove(0, 3);
cardSerialNumber.chop(3);
qDebug() << "RfidDLL->cardSerialNumber: " << cardSerialNumber;
}
else
{
qDebug() << "RfidDLL->Error reading card";
}
emit userLoginSignal(cardSerialNumber);
}
void RfidDLL::simulateUserLoggedIn() //Huolto.
{
emit userLoginSignal("A123456789");
}
|
#include "FlowWriter.h"
#include "ndpiReader/ndpiReader.h"
#include "MACVendors.h"
#include <sys/stat.h>
#include <iostream>
#include <boost/format.hpp>
#include "tools.h"
FlowWriter::FlowWriter()
{
}
FlowWriter::FlowWriter(ndpi_detection_module_struct* ndpi_struct,
std::string result_dirname)
: ndpi_detect_module(ndpi_struct)
{
if(!result_dirname.empty())
OpenFiles(result_dirname);
}
FlowWriter::~FlowWriter()
{
for(auto thread : threads) {
delete thread;
}
threads.clear();
}
void FlowWriter::WriteAndDeleteFlow(FlowInfo* flow)
{
if(threads.empty()) {
std::lock_guard<std::mutex> lock(cout_mutex);
PrintAndDeleteFlow(flow);
} else {
auto thread = threads[flow->get_app_proto()];
{
std::lock_guard<std::mutex> lock(thread->mutex);
thread->queue.push(flow);
}
thread->cond_var.notify_all(); // starts FlowWriter::backgroundWriter
}
}
void FlowWriter::WriteAndDeleteFlows(std::vector<FlowInfo*>& flows)
{
for(auto flow : flows)
WriteAndDeleteFlow(flow);
flows.clear();
}
void FlowWriter::PrintAndDeleteFlow(FlowInfo* flow)
{
std::string proto_name = flow->get_proto_name(ndpi_detect_module);
std::cout << "\t " << IpProto2Name(flow->get_proto_id());
std::cout << boost::format("%s(MAC_%012X):%d %s %s(MAC_%012X):%d ")
% flow->get_src_name() // s
% MacAsInt(flow->get_src_mac()) // 0X
% flow->get_src_port() // d
% (flow->IsBidirectional() ? "<->" : "->") // s
% flow->get_dst_name() // s
% MacAsInt(flow->get_dst_mac()) // 0X
% flow->get_dst_port(); // d
if(flow->get_vlan_id() > 0)
std::cout << "[VLAN: " << flow->get_vlan_id() << "]";
if(flow->get_master_proto())
std::cout << boost::format("[proto: %1%.%2%/%3%]")
% flow->get_master_proto()
% flow->get_app_proto()
% proto_name;
else
std::cout << boost::format("[proto: %1%/%2%]")
% flow->get_app_proto()
% proto_name;
std::cout << boost::format("[%1% pkts/%2% bytes ")
% flow->get_src2dst_packets()
% flow->get_src2dst_bytes();
std::cout << boost::format("%1% %2% pkts/%3% bytes]")
% (flow->get_dst2src_packets() > 0 ? "<->" : "->")
% flow->get_dst2src_packets()
% flow->get_dst2src_bytes();
if(!flow->get_host_server_name().empty())
std::cout << "[Host: " << flow->get_host_server_name() << "]";
if(!flow->get_info().empty())
std::cout << "[" << flow->get_info() << "]";
if(!flow->get_ssl_client_info().empty())
std::cout << "[client: " << flow->get_ssl_client_info() << "]";
if(!flow->get_ssl_server_info().empty())
std::cout << "[server: " << flow->get_ssl_server_info() << "]";
if(!flow->get_bittorent_hash().empty())
std::cout << "[BT Hash: " << flow->get_bittorent_hash() << "]";
std::cout << std::endl;
delete flow;
}
void FlowWriter::OpenFiles(std::string results_dirname)
{
struct stat st;
st.st_dev = 0;
st.st_ino = 0;
if(stat(results_dirname.c_str(), &st) == -1) {
if(mkdir(results_dirname.c_str(), 0700)) {
std::cerr << "Can't create dir!" << std::endl;
exit(-1);
}
} else {
std::cout << "Directory is exists. Continue? [yn]";
char answ = 0;
std::cin >> answ;
if(answ == 'N' || answ == 'n') {
std::cout << std::endl
<< "Stop the program." << std::endl;
exit(0);
}
}
threads = std::vector<Thread*>(NDPI_MAX_SUPPORTED_PROTOCOLS, nullptr);
for(uint16_t i = 0; i < NDPI_MAX_SUPPORTED_PROTOCOLS; i++) {
char* proto_name = ndpi_get_proto_name(ndpi_detect_module, i);
std::string filename = std::string(results_dirname)
+ "/" + std::string(proto_name) + ".csv";
std::fstream* file = new std::fstream(filename,
std::ios_base::out
| std::ios_base::in
| std::ios_base::app);
if(!file->is_open()) {
std::cerr << "Can't create file: " << filename << std::endl;
exit(-1);
}
if(FileIsEmpty(file)) {
(*file) << csv_header;
file->flush();
}
threads[i] = new Thread(filename, file);
threads[i]->thread = new std::thread(&FlowWriter::BackgroundWriter, this, i);
}
}
void FlowWriter::CloseFile(std::ostream* stream, std::string& path)
{
stream->flush();
if(FileIsEmpty(static_cast<std::fstream*>(stream), true)) {
delete stream;
remove(path.c_str());
} else
delete stream;
}
bool FlowWriter::FileIsEmpty(std::fstream* file, bool with_header) const
{
file->seekg(0, std::ios_base::end);
if(!file->tellg()
|| (with_header && file->tellg() == static_cast<long>(csv_header.size())))
return true;
else
return false;
}
void FlowWriter::WriteFlow(const FlowInfo* flow, std::ostream* stream) const
{
std::string proto_name;
char buf[64];
if(flow->get_master_proto())
proto_name = ndpi_protocol2name(ndpi_detect_module,
flow->get_ndpi_proto(), buf, sizeof(buf));
else
proto_name = ndpi_get_proto_name(ndpi_detect_module, flow->get_app_proto());
(*stream) << IpProto2Name(flow->get_proto_id())
<< "," << uint(flow->get_ip_version())
<< "," << flow->get_src_name()
<< "," << flow->get_src_port()
<< boost::format(",%012X") % MacAsInt(flow->get_src_mac())
<< "," << AppPrefs::mac_vendors[MacAsInt(flow->get_src_mac())]
<< "," << uint(flow->IsBidirectional())
<< "," << flow->get_dst_name()
<< "," << flow->get_dst_port()
<< boost::format(",%012X") % MacAsInt(flow->get_dst_mac())
<< "," << AppPrefs::mac_vendors[MacAsInt(flow->get_dst_mac())]
<< "," << flow->get_vlan_id()
<< "," << proto_name
<< "," << flow->get_src2dst_packets()
<< "," << flow->get_src2dst_bytes()
<< "," << flow->get_dst2src_packets()
<< "," << flow->get_dst2src_bytes()
<< "," << flow->get_host_server_name()
<< "," << flow->get_info()
<< "," << flow->get_ssl_client_info()
<< "," << flow->get_ssl_server_info()
<< "," << flow->get_bittorent_hash()
<< "," << flow->get_last_seen()
<< std::endl;
}
void FlowWriter::BackgroundWriter(uint16_t id)
{
auto thread = threads[id];
while(true) {
FlowInfo* flow;
{
auto lock = std::unique_lock<std::mutex>(thread->mutex);
thread->cond_var.wait(lock, [&] { return thread->queue.size() > 0
|| thread->stop; });
if(thread->stop && thread->queue.empty())
break;
flow = thread->queue.front();
thread->queue.pop();
}
WriteFlow(flow, thread->stream);
delete flow;
}
CloseFile(thread->stream, thread->path);
}
|
#ifndef PowerupType_H
#define PowerupType_H
namespace Dungeon {
enum PowerupType {
Sword,
Heart
};
}
#endif // PowerupType_H
|
#pragma once
#include "Transform.h"
#include "CollisionVolume.h"
#include "PhysicsObject.h"
#include "RenderObject.h"
#include "NetworkObject.h"
#include <vector>
using std::vector;
namespace NCL {
namespace CSC8503 {
class NetworkObject;
class GameObject {
public:
GameObject(string name = "");
~GameObject();
void SetBoundingVolume(CollisionVolume* vol) {
boundingVolume = vol;
}
const CollisionVolume* GetBoundingVolume() const {
return boundingVolume;
}
bool IsActive() const {
return isActive;
}
const Transform& GetConstTransform() const {
return transform;
}
Transform& GetTransform() {
return transform;
}
RenderObject* GetRenderObject() const {
return renderObject;
}
PhysicsObject* GetPhysicsObject() const {
return physicsObject;
}
NetworkObject* GetNetworkObject() const {
return networkObject;
}
void SetRenderObject(RenderObject* newObject) {
renderObject = newObject;
}
void SetPhysicsObject(PhysicsObject* newObject) {
physicsObject = newObject;
}
const string& GetName() const {
return name;
}
void SetName(string s) {
name = s;
}
virtual void OnCollisionBegin(GameObject* otherObject) {
if (name == "goal") {
if (otherObject->name == "") return;
if (winner == nullptr) winner = otherObject;
} else if (name.substr(0, 3) == "bot") {
if (otherObject->name.substr(0, 3) == "bot") {
std::cout << "bot collision with bot" << std::endl;
killBot = true;
}
else if (otherObject->name != "") {
std::cout << "bot collision with player" << std::endl;
if (otherObject->GetPhysicsObject()->GetLinearVelocity().Length() < 300) {
otherObject->GetPhysicsObject()->AddForce(
Vector3(rand(), 0, rand()).Normalised() * 15000
);
} else {
killBot = true;
killerName = otherObject->name;
}
}
}
}
virtual void OnCollisionEnd(GameObject* otherObject) {
//std::cout << "OnCollisionEnd event occured!\n";
}
bool InsideAABB(const Vector3& pos, const Vector3& halfSize);
GameObject* GetWinner() const {
return winner;
}
bool killBot = false;
string killerName = "";
protected:
Transform transform;
CollisionVolume* boundingVolume;
PhysicsObject* physicsObject;
RenderObject* renderObject;
NetworkObject* networkObject;
bool isActive;
string name;
GameObject* winner = nullptr;
};
}
}
|
/*******************************************************************************
* Cristian Alexandrescu *
* 2163013577ba2bc237f22b3f4d006856 *
* 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 *
* bc9a53289baf23d369484f5343ed5d6c *
*******************************************************************************/
/* Problem 12457 - Tennis contest */
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
template <typename T>
T CombSimple(int nN, int nK) {
T tResult(1);
for (int nLoop = nN - nK + 1; nLoop <= nN; nLoop++) {
tResult *= static_cast<T>(nLoop);
tResult /= static_cast<T>(nN - nLoop + 1);
}
return tResult;
}
template <typename T>
T ProbabilityAWinsTitleInTotalMatches(double lfMatchWinProbability, int nTotalMatches, int nN) {
auto lfResult = CombSimple<T>(nTotalMatches - 1, nTotalMatches - nN);
lfResult *= pow(lfMatchWinProbability, nN);
lfResult *= pow(1 - lfMatchWinProbability, nTotalMatches - nN);
return lfResult;
}
int main() {
int nNoTestCases;
for (cin >> nNoTestCases; nNoTestCases--; ) {
int nN;
double lfWinProbability;
while (cin >> nN >> lfWinProbability) {
double lfAnswer(0);
for (int nTotalMatches = 2 * nN - 1; nTotalMatches >= nN; nTotalMatches--)
lfAnswer += ProbabilityAWinsTitleInTotalMatches<double>(lfWinProbability, nTotalMatches, nN);
cout << setprecision(2) << fixed << lfAnswer << endl;
}
}
return 0;
}
|
// @copyright 2017 - 2018 Shaun Ostoic
// Distributed under the MIT License.
// (See accompanying file LICENSE.md or copy at https://opensource.org/licenses/MIT)
#pragma once
namespace distant::utility {
template <class Derived>
class static_polymorphic
{
public:
const Derived& derived() const
{
// Downcast (const) to the derived type.
return *static_cast<const Derived*>(this);
}
Derived& derived()
{
// Downcast to the derived type.
return *static_cast<Derived*>(this);
}
protected:
// Protected keyword allows the dervied destructor to call this one
// Disables destruction of derived type via the base
~static_polymorphic() = default;
};
} // end namespace distant::utility
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::UI::Xaml::Markup {
struct XamlBinaryWriterErrorInformation;
struct XmlnsDefinition;
}
namespace Windows::UI::Xaml::Markup {
using XamlBinaryWriterErrorInformation = ABI::Windows::UI::Xaml::Markup::XamlBinaryWriterErrorInformation;
struct XmlnsDefinition;
}
namespace ABI::Windows::UI::Xaml::Markup {
struct IComponentConnector;
struct IComponentConnector2;
struct IDataTemplateComponent;
struct IXamlBinaryWriter;
struct IXamlBinaryWriterStatics;
struct IXamlBindingHelper;
struct IXamlBindingHelperStatics;
struct IXamlMarkupHelper;
struct IXamlMarkupHelperStatics;
struct IXamlMember;
struct IXamlMetadataProvider;
struct IXamlReader;
struct IXamlReaderStatics;
struct IXamlType;
struct XamlBinaryWriter;
struct XamlBindingHelper;
struct XamlMarkupHelper;
struct XamlReader;
}
namespace Windows::UI::Xaml::Markup {
struct IComponentConnector;
struct IComponentConnector2;
struct IDataTemplateComponent;
struct IXamlBinaryWriter;
struct IXamlBinaryWriterStatics;
struct IXamlBindingHelper;
struct IXamlBindingHelperStatics;
struct IXamlMarkupHelper;
struct IXamlMarkupHelperStatics;
struct IXamlMember;
struct IXamlMetadataProvider;
struct IXamlReader;
struct IXamlReaderStatics;
struct IXamlType;
struct XamlBinaryWriter;
struct XamlBindingHelper;
struct XamlMarkupHelper;
struct XamlReader;
}
namespace Windows::UI::Xaml::Markup {
template <typename T> struct impl_IComponentConnector;
template <typename T> struct impl_IComponentConnector2;
template <typename T> struct impl_IDataTemplateComponent;
template <typename T> struct impl_IXamlBinaryWriter;
template <typename T> struct impl_IXamlBinaryWriterStatics;
template <typename T> struct impl_IXamlBindingHelper;
template <typename T> struct impl_IXamlBindingHelperStatics;
template <typename T> struct impl_IXamlMarkupHelper;
template <typename T> struct impl_IXamlMarkupHelperStatics;
template <typename T> struct impl_IXamlMember;
template <typename T> struct impl_IXamlMetadataProvider;
template <typename T> struct impl_IXamlReader;
template <typename T> struct impl_IXamlReaderStatics;
template <typename T> struct impl_IXamlType;
}
}
|
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cstring>
#include <string>
#include <queue>
#include <deque>
#include <vector>
#include <stack>
#include <map>
#include <set>
#include <regex>
#include <math.h>
#define MAX 11
#define INF 987654321
using namespace std;
typedef pair<int, int> pii;
typedef long long ll;
vector<int> solution(vector<string> gems) {
vector<int> answer;
map<string, int> m;
set<string> se;
for(int i = 0; i < gems.size(); i++)
{
se.insert(gems[i]);
}
int s = 0;
int e = 0;
pii pi = {-987654321,987654321};
//"DIA", "RUBY", "RUBY", "DIA", "DIA", "EMERALD", "SAPPHIRE", "DIA"
while (1)
{
if(e == gems.size()) break;
m[gems[e]]++;
while(se.size() == m.size())
{
if(pi.second-pi.first > e-s)
{
pi = {s,e};
}
m[gems[s]]--;
if(m[gems[s]] == 0)
m.erase(gems[s]);
s++;
}
e++;
}
//["DIA", "RUBY", "RUBY", "DIA", "DIA", "EMERALD", "SAPPHIRE", "DIA"]
answer.push_back(pi.first+1);
answer.push_back(pi.second+1);
return answer;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
solution({"DIA", "RUBY", "RUBY", "DIA", "DIA", "EMERALD", "SAPPHIRE", "DIA"});
return 0;
}
|
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
vector<int> v;
for (int i = 0; i < 100000; i++)
{
v.push_back(i);
}
cout << "capacity:" << v.capacity() << endl;
cout << "size:" << v.size() << endl;
//此时 通过resize改变容器大小
v.resize(10);
cout << "capacity:" << v.capacity() << endl;
cout << "size:" << v.size() << endl;
// 匿名变量只在当前行有效
//容量没有改变
vector<int>(v).swap(v);
cout << "capacity:" << v.capacity() << endl;
cout << "size:" << v.size() << endl;
return 0;
}
|
#include <TESTS/test_assertions.h>
#include <TESTS/testcase.h>
#include <CORE/UTIL/lrparser.h>
#include <CORE/UTIL/tokenizer.h>
using namespace core::util::parser;
struct eTokenNames {
enum type { TOKEN_IDENT, TOKEN_OBRACE, TOKEN_CBRACE, TOKEN_WS, COUNT };
static const char *names[COUNT];
};
const char *eTokenNames::names[] = {
"TOKEN_IDENT",
"TOKEN_OBRACE",
"TOKEN_CBRACE",
"TOKEN_WS",
};
typedef LRParser< eTokenNames > tParser;
typedef Tokenizer< eTokenNames > tTokenizer;
typedef tParser::Rule Rule;
/**
*
*/
static bool HandleField2(
tParser::iNode *&ret,
const tParser::tTokenOrNodeList::const_iterator &begin,
const tParser::tTokenOrNodeList::const_iterator &end) {
TEST(testing::assertEquals(2, std::distance(begin, end)));
return true;
}
/**
*
*/
static bool HandleField3(
tParser::iNode *&ret,
const tParser::tTokenOrNodeList::const_iterator &begin,
const tParser::tTokenOrNodeList::const_iterator &end) {
TEST(testing::assertEquals(3, std::distance(begin, end)));
tParser::tTokenOrNodeList::const_iterator itr = begin;
itr++;
TEST(testing::assertEquals(itr->m_type, tParser::TokenOrNode::RULE_NODE));
return true;
}
static std::vector< std::string > g_errorMsg;
/**
*
*/
static void HandleError(const std::string &msg) {
g_errorMsg.push_back(msg);
}
/**
*
*/
static const tTokenizer &CreateTokenizer() {
tTokenizer::tTokenizerList tokenTypes;
tokenTypes.push_back(
tTokenizer::tTokenizer(eTokenNames::TOKEN_OBRACE, RegExPattern("{")));
tokenTypes.push_back(
tTokenizer::tTokenizer(eTokenNames::TOKEN_CBRACE, RegExPattern("}")));
tokenTypes.push_back(
tTokenizer::tTokenizer(eTokenNames::TOKEN_IDENT, RegExPattern("\\w+")));
tokenTypes.push_back(
tTokenizer::tTokenizer(eTokenNames::TOKEN_WS, RegExPattern("\\s+")));
static tTokenizer tokenizer(tokenTypes);
return tokenizer;
}
/**
*
*/
static tParser CreateParser() {
tParser parser(CreateTokenizer());
Rule &objBody = parser.addRule("objectbody");
Rule &object = parser.addRule("object");
objBody |=
tParser::RuleOrTokenChain(
tParser::RuleOrTokenChain::tProc::from_function< HandleField2 >())
& eTokenNames::TOKEN_OBRACE & eTokenNames::TOKEN_CBRACE;
objBody |=
tParser::RuleOrTokenChain(
tParser::RuleOrTokenChain::tProc::from_function< HandleField3 >())
& eTokenNames::TOKEN_OBRACE & object & eTokenNames::TOKEN_CBRACE;
object |= tParser::RuleOrTokenChain() & eTokenNames::TOKEN_IDENT & objBody;
g_errorMsg.clear();
return parser;
}
REGISTER_TEST_CASE(testSuccessfulLRParse) {
const std::string testFile = "testmessage {\n"
" testmessage2 {\n"
" \n"
" }\n"
"}\n";
tParser parser = CreateParser();
TEST(testing::assertTrue(
parser.parse(eTokenNames::TOKEN_WS, testFile.begin(), testFile.end())));
}
REGISTER_TEST_CASE(testLRParseErrorOnMissingEnd) {
const std::string testFile = "testmessage {\n"
" testmessage2 {\n"
" \n"
" }\n"
"\n";
tParser parser = CreateParser();
TEST(testing::assertFalse(parser.parse(
eTokenNames::TOKEN_WS,
testFile.begin(),
testFile.end(),
tParser::tErrorCB::from_function< HandleError >())));
TEST(testing::assertEquals(g_errorMsg.size(), 2));
TEST(testing::assertEquals(
g_errorMsg[1], "Unexpected <EOF> while parsing objectbody on line 0"));
}
REGISTER_TEST_CASE(testLRParseErrorOnMissingFirstToken) {
const std::string testFile = "testmessage {\n"
" {\n"
" \n"
" }\n"
"}\n";
tParser parser = CreateParser();
TEST(testing::assertFalse(parser.parse(
eTokenNames::TOKEN_WS,
testFile.begin(),
testFile.end(),
tParser::tErrorCB::from_function< HandleError >())));
TEST(testing::assertEquals(g_errorMsg.size(), 4));
TEST(testing::assertEquals(
g_errorMsg[0], "Unexpected TOKEN_OBRACE while parsing object on line 0"));
}
|
// <ctype> 은 없다
// tolower : <ctype.h>
// 문자 하나는 ' '
#include <string>
#include <iostream>
#include <ctype.h>
using namespace std;
bool solution(string s)
{
bool answer = true;
int cntP=0;
int cntY=0;
for(int i=0; i<s.size(); i++){
if (tolower(s[i])=='p') cntP+=1;
else if (tolower(s[i])=='y') cntY+=1;
}
return cntP==cntY ? true : false;
}
|
#include <Arduino.h>
#include <WiFi.h>
const char *ssid = "UniFi";
//const char *ssid = "SRiPhone";
const char *password = "Logitech";
//const IPAddress serverIP(192, 168, 0, 200); //Address to visit
const IPAddress serverIP(85, 191, 171, 18); //Address to visit External IP
uint16_t serverPort = 200; //Server port number
WiFiClient client; //Declare a client object to connect to the server
String readString;
char c;
char sendBuffer[1024];
int i;
int indexSend = 2;
int lengthRctm = 0;
void setup()
{
Serial.begin(115200);
Serial1.begin(115200);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.setSleep(false); //Turn off wifi sleep in STA mode to improve response speed
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("MAC address: ");
Serial.println(WiFi.macAddress());
Serial.print("Gateway address: ");
Serial.println(WiFi.gatewayIP());
Serial.print("Subnet address: ");
Serial.println(WiFi.subnetMask());
Serial.print("SSID Power: ");
Serial.println(WiFi.getTxPower());
Serial.println("");
delay(100);
}
void loop()
{
/*
while(Serial.available())
{
Serial1.print((char)Serial.read());
}
Serial1.flush();
while(Serial1.available())
{
Serial.print((char)Serial1.read());
}
//Serial.println(millis());
//Serial1.println(millis());
//delay(1000);
*/
Serial.println("Try to access the server");
if (client.connect(serverIP, serverPort)) //Try to access the target address
{
Serial.println("Visit successful");
delay(2000);
//client.print("X"); //Send data to the server
while (client.connected() || client.available()) //If it is connected or has received unread data
{
//delay(2000);
//Serial.println("Visit successful");
//Serial.print("Connected: ");
//Serial.println(client.connected());
//Serial.print("Avalible: ");
//Serial.println(client.available());
// Earlierer program
while (client.available()) //If there is data to read
{
sendBuffer[indexSend] = client.read();
if (sendBuffer[indexSend - 1] == 0xd3 && sendBuffer[indexSend] == 0x00 && indexSend != 1) // Find beginning of message
{
sendBuffer[0] = 0xd3;
sendBuffer[1] = 0x00;
indexSend = 1;
}
lengthRctm = (int)sendBuffer[2] + 6; // Get lenght of RCTM message
if (indexSend > 1023 || indexSend < 0) // Overflow send buffer
{
indexSend = 0;
Serial.println("Overflow");
}
if (indexSend == lengthRctm && indexSend > 10 && lengthRctm > 10)
{
// Serial.print("lengthRctm: ");
//Serial.println(lengthRctm);
// if (client.connected() == true)
Serial1.write(sendBuffer, lengthRctm);
Serial.write(sendBuffer, lengthRctm); //DEBUG
/*
for (int i = 0; i <= lengthRctm; i++)
{
if (client.connected() == true)
{
client.write(sendBuffer[i]);
}
//Serial.print(sendBuffer[i]);
}
*/
delay(100);
Serial1.flush();
Serial.flush();
}
// serverBytesSent++;
//lastSentRTCM_ms = millis();
indexSend++;
/*
if (client.peek() == 0xD3)
{
delay(500);
while (client.available()) //If there is data to read
{
char line = client.read();
//Serial.print("Read data:");
readString += line;
if (readString.length()<1023)
{
Serial1.print(readString);
readString = "";
}
}
Serial1.print(readString);
readString = "";
}
else
{
while (client.available()) //If there is data to read
{
client.read();
}
}
//client.write(line.c_str()); //Send the received data back
}
delay(5);
*/
}
//Serial.println("Close the current connection");
//client.write("X");
//delay(900);
//client.stop(); //Close the client
}
}
else
{
Serial.println("Access failed");
client.stop(); //Close the client
}
}
|
#ifndef TUNING_H
#define TUNING_H
#include <map>
#include <string>
#include <list>
#include <AstInterface.h>
#include <LoopTree.h>
#include <LoopTreeTransform.h>
class POETProgram;
class XformVar;
class CodeVar;
class LocalVar;
class POETCode;
class LoopTreeNode;
class LoopBlocking;
class ParallelizeLoop;
class ArrayAbstractionInterface;
class CopyArrayConfig;
/*QY: map loop tree nodes and AST nodes to tracing variables in POET */
class LoopTreeCodeGenInfo;
class HandleMap : public LoopTreeObserver, public AstObserver
{
public: typedef std::map<const void*, LocalVar*> AstMapType;
private:
static XformVar* const modifyHandle;
static LocalVar* const modify_trace;
int loopindex, bodyindex;
std::vector<LocalVar*> topHandles;
std::map<const LoopTreeNode*,LocalVar*> loopMap;
std::map<LocalVar*,LocalVar*> bodyMap;
AstMapType astMap;
LocalVar* NewLoopHandle();
LocalVar* NewBodyHandle();
virtual void UpdateCodeGen(const LoopTreeCodeGenInfo& info);
virtual void UpdateDeleteNode(LoopTreeNode* n);
virtual void ObserveCopyAst(AstInterfaceImpl& fa, const AstNodePtr& orig, const AstNodePtr& n);
public:
~HandleMap();
HandleMap() :loopindex(0),bodyindex(0) {}
/*QY: return the number of loop handles created*/
int NumOfLoops() { return loopindex; }
int NumOfBodies() { return bodyindex; }
/*QY:return a POET trace handle for the given AST or loop tree node*/
LocalVar* GetLoopHandle(AstInterface& fa, const AstNodePtr& loop);
LocalVar* GetLoopHandle(LoopTreeNode* loop);
LocalVar* GetBodyHandle(LoopTreeNode* loop, LocalVar* loopHandle);
/*QY:sort all the loop nest handles with AST root; return the top handles*/
const std::vector<LocalVar*>& GetTopTraceHandles() { return topHandles; }
void GenTraceHandles(POETProgram& poet, AstInterface& fa);
void GenTraceHandles(POETProgram& poet, LoopTreeNode* r);
LocalVar* HasBodyHandle(LocalVar* loopHandle)
{ std::map<LocalVar*,LocalVar*>::const_iterator p =
bodyMap.find(loopHandle);
if (p == bodyMap.end()) return 0;
return (*p).second;
}
/*QY: return trace handle for extra-top and decl of transformations*/
static LocalVar* GetTraceTarget();
static LocalVar* GetTraceTop(const std::string& handleName);
static LocalVar* GetTraceDecl(LocalVar* top);
static LocalVar* GetTracePrivate(LocalVar* top);
static LocalVar* FindTracePrivate(LocalVar* top);
static LocalVar* GetTraceInclude();
static LocalVar* FindTraceInclude();
static LocalVar* GetTraceCleanup(LocalVar* top);
static LocalVar* FindTraceCleanup(LocalVar* top);
static LocalVar* DeclareTraceInclude(POETProgram& poet, int& lineNo);
/*QY: generate commands to start tracing; return the top trace handle */
static LocalVar* GenTraceCommand(POETProgram& poet,
const std::vector<LocalVar*>& handles, LocalVar* target, int& lineNo);
};
/*QY: specification of program transformations to be implemented in POET*/
class OptSpec {
protected:
LocalVar* handle;
std::string handleName;
OptSpec(LocalVar* _handle);
protected:
struct LoopInfo { LocalVar* handle; std::string ivarname;
LoopInfo(LocalVar* _handle=0, const std::string& name="")
: handle(_handle),ivarname(name) {}
};
public:
typedef enum {PARLOOP, BLOCK, UNROLL, COPY_ARRAY, BLOCK_COPY_ARRAY, FINITE_DIFF,OPT_ENUM_SIZE} OptEnum;
typedef enum {OPT_NONE=0,OPT_PAR_LEVEL = 1,OPT_CACHE_LEVEL = 2, OPT_PAR_CACHE_LEVEL=3, OPT_REG_LEVEL = 4, OPT_CACHE_REG_LEVEL=6, OPT_PROC_LEVEL=8, OPT_POST_PAR_LEVEL=16, OPT_CLEANUP_LEVEL=32, OPT_CACHE_CLEANUP_LEVEL=34, OPT_CACHE_REG_CLEANUP_LEVEL=38, OPT_CACHE_PROC_CLEANUP_LEVEL=42, OPT_ALL=63, OPT_LEVEL_MAX=32} OptLevel;
typedef std::vector<OptSpec*>::const_iterator OptIterator;
LocalVar* get_handle() const { return handle; }
std::string get_handleName() const { return handleName; }
/*QY loop-based strength reduction optimization; return the invocation */
POETCode* gen_fdInvoke(POETProgram& poet, LocalVar* top,
const std::string& nvarName, POETCode* exp,
POETCode* expType, const std::vector<POETCode*>& dimVec,
POETCode* permute=0, POETCode* traceMod=0,
bool is_scalar=true);
virtual ~OptSpec() {}
virtual OptEnum get_enum() const = 0;
virtual OptLevel get_opt_level() const = 0;
virtual std::string get_opt_prefix(OptLevel optLevel) = 0;
/*QY: insert parameter decl; modify lineNo with new line number */
virtual void insert_paramDecl(POETProgram& poet, OptLevel optLevel,
int& lineNo) {}
/*QY: return xform declaration; modify lineNo;
append traceMod with variables that need to be kept track of; */
virtual void insert_xformDecl(POETProgram& poet, LocalVar* top, POETCode*& traceMod, int& lineNo) {}
/*QY: return xform evaluation; modify lineNo with new line number */
virtual POETCode* gen_xformEval(POETProgram& poet, LocalVar* top,
POETCode* traceMod, OptLevel optLevel, int& lineNo) = 0;
/*QY: return the permutation configuration for strength reduction */
static POETCode* gen_permute(std::vector<int>& permuteVec);
friend class AutoTuningInterface;
protected:
static CodeVar* const Nest;
static CodeVar* const Loop;
static CodeVar* const LoopBound;
static CodeVar* const IntType;
static POETCode* const Nest_ctrl;
static POETCode* const Nest_body;
static POETCode* const Loop_ivar;
static POETCode* const Loop_step;
static POETCode* const Loop_ub;
static POETCode* const LoopBound_ivar;
static POETCode* const LoopBound_step;
static XformVar* const appendDecl;
static XformVar* const finiteDiff;
static LocalVar* const fd_exp_type;
static LocalVar* const fd_trace;
static LocalVar* const fd_traceVar;
static LocalVar* const fd_traceDecl;
static LocalVar* const fd_is_scalar;
static LocalVar* const fd_mod;
static LocalVar* const fd_permute;
};
/*QY: used for specifying non-perfect loops in loop blocking */
struct FuseLoopInfo
{
typedef std::pair<LoopTreeNode*,int> Entry;
std::vector<Entry> loops; /*QY: the loops being fused*/
LoopTreeNode *pivotLoop; /*QY: the pivot loop*/
FuseLoopInfo(LoopTreeNode* _pivot=0) : pivotLoop(_pivot) {}
static POETCode* toPOET(HandleMap& handleMap, const FuseLoopInfo* info);
};
class BlockSpec;
/*QY: interface for POET-code generation*/
class AutoTuningInterface
{
HandleMap handleMap;
std::vector<OptSpec*> optvec;
std::string inputName;
POETProgram* poet;
int lineNo;
LocalVar* target;
static ArrayAbstractionInterface* arrayInfo;
static POETCode* arrayAccess;
static CodeVar* const Array;
static POETCode* const Array_var;
static POETCode* const Array_sub;
static CodeVar* const FunctionCall;
static POETCode* const FunctionCall_arg;
void BuildPOETProgram();
void Gen_POET_opt();
public:
AutoTuningInterface(const std::string& _fname)
: inputName(_fname), poet(0), lineNo(-1), target(0) {}
~AutoTuningInterface() ;
void set_astInterface(AstInterface& fa);
static void set_arrayInfo( ArrayAbstractionInterface& arrayInfo);
static POETCode* CreateArrayRef(POETProgram& poet, POETCode* arr, POETCode* subscript, int dim);
static POETCode* Access2Subscript(POETProgram& poet, POETCode* ref, int dim);
static POETCode* Access2Array(POETProgram& poet, POETCode* ref, int dim);
LocalVar* get_target() { return target; }
BlockSpec* LoopBlocked(LocalVar* loop); /*QY: whether loop has been blocked*/
void UnrollLoop(AstInterface& fa, const AstNodePtr& loop, int unrollsize);
void BlockLoops(LoopTreeNode* outerLoop, LoopTreeNode* innerLoop, LoopBlocking* config, const FuseLoopInfo* nonperfect = 0);
void ParallelizeLoop(LoopTreeNode* outerLoop, int bsize);
void CopyArray( CopyArrayConfig& config, LoopTreeNode* repl);
bool ApplyOpt(LoopTreeNode* root);
bool ApplyOpt(AstInterface& fa);
void GenOutput();
};
/*QY: loop unrolling optimization*/
class UnrollSpec : public OptSpec
{
/*QY: relevant POET invocation names
(need to be consistent with POET/lib/opt.pi*/
static XformVar* const unroll;
static LocalVar* const unroll_factor;
static LocalVar* const unroll_cleanup;
LocalVar* paramVar;
public:
UnrollSpec(LocalVar* handle, int unrollSize);
virtual OptEnum get_enum() const { return UNROLL; }
virtual OptLevel get_opt_level() const { return OPT_PROC_LEVEL; }
virtual std::string get_opt_prefix(OptLevel optLevel) { return "unroll"; }
/*QY: insert parameter decl; modify lineNo with new line number */
virtual void insert_paramDecl(POETProgram& poet, OptLevel optLevel,
int& lineNo);
virtual POETCode* gen_xformEval(POETProgram& poet, LocalVar* top,
POETCode* traceMod, OptLevel optLevel, int& lineNo);
/*QY: return a unique name that save relevant info. for a loop unroll optimization*/
static LocalVar* get_unrollSizeVar(const std::string& handleName);
};
class ParLoopSpec : public OptSpec
{
static XformVar* const parloop;
static LocalVar* const par_trace;
static LocalVar* const par_thread;
static LocalVar* const par_private;
static LocalVar* const par_include;
POETCode* privateVars;
POETCode* ivarName, *bvarName;
LocalVar* parVar, *parblockVar;
public:
ParLoopSpec(LocalVar* outerHandle, LoopTreeNode* loop, int bsize);
virtual OptEnum get_enum() const { return PARLOOP; }
virtual OptLevel get_opt_level() const { return OPT_PAR_LEVEL; }
virtual std::string get_opt_prefix(OptLevel optLevel) { return "par"; }
/*QY: insert parameter decl; modify lineNo with new line number */
virtual void insert_paramDecl(POETProgram& poet, OptLevel optLevel,
int& lineNo);
virtual void insert_xformDecl(POETProgram& poet, LocalVar* top, POETCode*& traceMod, int& lineNo);
virtual POETCode* gen_xformEval(POETProgram& poet, LocalVar* top,
POETCode* traceMod, OptLevel optLevel, int& lineNo);
};
/*QY: loop blocking optimization*/
class BlockSpec : public OptSpec
{
/*QY: relevant POET invocation names
(need to be consistent with POET/lib/opt.pi*/
static XformVar* const unrollJam;
static LocalVar* const unrollJam_cleanup;
static XformVar* const cleanup;
static LocalVar* const cleanup_trace;
static LocalVar* const unrollJam_factor;
static LocalVar* const unrollJam_trace;
std::vector<LoopInfo> loopVec; /*QY: the loops to block */
POETCode* nonperfect; /*QY: the non-perfect loops*/
LocalVar* blockPar, *ujPar;
HandleMap& handleMap;
unsigned loopnum;
/*QY: compute the blocking dimension configuration */
POETCode* compute_blockDim(LocalVar* paramVar);
public:
BlockSpec(HandleMap& handleMap, LocalVar* outerHandle, LoopTreeNode* innerLoop, LoopBlocking* config, const FuseLoopInfo* nonperfect=0);
virtual OptEnum get_enum() const { return BLOCK; }
virtual OptLevel get_opt_level() const { return OPT_CACHE_REG_CLEANUP_LEVEL; }
virtual std::string get_opt_prefix(OptLevel optLevel)
{
switch (optLevel) {
case OPT_CACHE_LEVEL: return "block";
case OPT_REG_LEVEL: return "unrolljam";
case OPT_CLEANUP_LEVEL: return "cleanup";
default: return "";
}
}
unsigned get_loopnum() const { return loopVec.size(); }
const LoopInfo& get_loop(int i) const { return loopVec[i]; }
void insert_paramDecl(POETProgram& poet, OptLevel optLevel, int& lineNo);
/*QY: return xform declaration; modify lineNo;
append traceMod with variables that need to be kept track of; */
virtual void insert_xformDecl(POETProgram& poet, LocalVar* top, POETCode*& traceMod, int& lineNo);
virtual POETCode* gen_xformEval(POETProgram& poet, LocalVar* top,
POETCode* traceMod, OptLevel optLevel, int& lineNo);
/*QY: return unique names that save relevant info. for a blocking opt*/
static LocalVar* get_blockSizeVar(const std::string& handleName);
static LocalVar* get_unrollJamSizeVar(const std::string& handleName);
static LocalVar* get_blockDimVar(const std::string& handleName);
static LocalVar* get_blockTileVar(const std::string& handleName);
static LocalVar* get_blockSplitVar(const std::string& handleName);
static POETCode* get_blockSize(const std::string& handleName, int level);
};
/*QY: array copy */
class CopyArraySpec : public OptSpec
{
protected:
/*QY: relevant POET invocation names
(need to be consistent with POET/lib/opt.pi*/
static XformVar* const copyarray;
static LocalVar* const bufname;
static LocalVar* const init_loc;
static LocalVar* const save_loc;
static LocalVar* const delete_loc;
static LocalVar* const elem_type;
static LocalVar* const trace_decl;
static LocalVar* const trace_mod;
static LocalVar* const trace_vars;
static LocalVar* const trace;
static LocalVar* const is_scalar;
static LocalVar* const block_spec;
static int index;
SelectArray sel; /*QY: which array elements to copy*/
CopyArrayOpt opt; /*QY: alloc/init/save/free configurations */
std::vector<LoopInfo> loopVec; /*QY: the surrounding loops*/
std::vector<int> placeVec; /* QY: placement of loop dim*/
POETCode* permute; /* permutation of array dimension*/
std::string cur_id;
int get_loopLevel(const SelectArray::ArrayDim& cur);
/* QY: return the subscript pattern for the array references.
beforeCopy: before or after the copy optimization is done */
POETCode* compute_copySubscript(POETProgram& poet, bool afterCopy);
/* QY: return a list of copy dimensions */
POETCode* compute_copyDim(POETProgram& poet, bool scalar);
/* QY: compute internal info for copy; need to be done in constructor*/
void compute_config();
POETCode* gen_copyInvoke(POETProgram& poet, POETCode* cphandle,
LocalVar* top, POETCode* cpblock, bool scalar,
POETCode* traceMod, int& lineNo);
void insert_paramDecl(POETProgram& poet, OptLevel optLevel, int& lineNo);
CopyArraySpec(LocalVar* handle, CopyArrayConfig& config)
: OptSpec(handle), sel(config.get_arr()), opt(config.get_opt()),permute(0)
{}
public:
CopyArraySpec(HandleMap& handleMap,LocalVar* handle,CopyArrayConfig& config, LoopTreeNode* root);
virtual OptEnum get_enum() const { return COPY_ARRAY; }
virtual OptLevel get_opt_level() const { return OPT_REG_LEVEL; }
/*QY: insert xform declaration; append traceMod with variables that need to be kept track of;
return the new line number */
virtual void insert_xformDecl(POETProgram& poet, LocalVar* top,
POETCode*& traceMod, int& lineNo);
virtual POETCode* gen_xformEval(POETProgram& poet, LocalVar* top,
POETCode* traceMod, OptLevel optLevel, int& lineNo);
static bool do_scalarRepl(OptLevel optLevel)
{
switch (optLevel) {
case OPT_CACHE_LEVEL: return false;
case OPT_REG_LEVEL: return true;
default: assert(0);
}
}
std::string get_opt_prefix(OptLevel optLevel)
{
switch (optLevel) {
case OPT_CACHE_LEVEL: return "copy"+cur_id;
case OPT_REG_LEVEL: return "scalar"+cur_id;
default: assert(0);
}
}
/* QY: global variable for tracing array dimension and ref exp */
LocalVar* get_dimVar(POETProgram& poet, const std::string& arrname);
LocalVar* get_arrVar(POETProgram& poet, const std::string& arrname);
/*copy buffer name*/
std::string get_bufName(const std::string& arrname, bool scalar)
{ return (scalar)? arrname+"_"+cur_id+"_scalar" : arrname+"_buf"; }
/* QY: copy induction variable name */
std::string get_cpIvarName(const std::string& arrname, int sel_index)
{
assert( sel_index >= 0);
std::string copyIvar = handleName + "_" + cur_id+"_"+arrname + "_cp";
copyIvar.push_back('0' + sel_index);
return copyIvar;
}
/*QY: declaring copy induction variables*/
POETCode* gen_cpIvarDecl(POETProgram& poet, LocalVar* top,
const std::string& arrname, int dim, bool cpblock);
/*QY: the copy invocation*/
POETCode*
gen_copyInvoke(POETProgram& poet, POETCode* handle,LocalVar* top,
const std::string& arrname, POETCode* arrelemType, CopyArrayOpt opt,
POETCode* cpDim, POETCode* cpblock, bool scalar, POETCode* traceMod);
};
/*QY: array copy associated with blocking */
class BlockCopyArraySpec : public CopyArraySpec
{
/*QY: relevant POET invocation names
(need to be consistent with POET/lib/opt.pi*/
POETCode* AfterCopy_dimSize(POETProgram& poet);
POETCode* compute_copyBlock(POETProgram& poet);
/*QY: return handle for scalar repl*/
LocalVar* scalarRepl_handle(POETProgram& poet);
static std::string get_fdName(const std::string& arrname)
{ return arrname+"_fd"; } /*finite difference var name*/
/*QY:compute strenghth reduction dimension configuration
: return outermost loop level to start reduction */
int compute_fdConfig(POETProgram& poet, POETCode* handle, bool scalar,
std::vector<POETCode*>& expDimVec_cp, /*QY: to go with copying */
std::vector<POETCode*>& expDimVec_nocp);/*QY: to go without copying*/
public:
BlockCopyArraySpec(LocalVar* handle, CopyArrayConfig& config,
BlockSpec& _block);
virtual OptEnum get_enum() const { return BLOCK_COPY_ARRAY; }
virtual OptLevel get_opt_level() const { return OPT_CACHE_REG_LEVEL; }
virtual POETCode* gen_xformEval(POETProgram& poet, LocalVar* top,
POETCode* traceMod, OptLevel optLevel, int& lineNo);
};
#endif
|
#include "Polynomial_Utils.h"
#include <iostream>
Polynomial_Utils::Polynomial_Utils()
{
}
Polynomial_Utils::~Polynomial_Utils()
{
}
void Polynomial_Utils::print_polynomial(const char* name, long long *P, int size)
{
std::cout << name << " = ";
for (int i = 0; i < size - 1; i++)
std::cout << P[i] << "X^" << i << " + ";
std::cout << P[size - 1] << "X^" << size - 1 << std::endl;
}
long long *Polynomial_Utils::get_rand_polynomial(int size)
{
long long *P = new long long[size];
for (int i = 0; i < size; i++)
P[i] = rand() % 10;
return P;
}
long long * Polynomial_Utils::extend_polynomial(long long * P, int size, int size_f)
{
long long *new_P = new long long[size_f];
memcpy(new_P, P, size * sizeof(long long));
long long *value = new_P + size - 1;
memset(new_P + size, 0, (size_f - size) * sizeof(long long));
return new_P;
}
|
#include "game_object_factory.hpp"
using namespace game;
engine::GameObject* GameObjectFactory::fabricate(std::string name, std::pair<int, int> position, std::string object_name=""){
if(name == "little_girl"){
return fabricate_little_girl(position, object_name);
}else if(name == "thorn"){
return fabricate_thorn(position, object_name);
}else if(name == "coin"){
return fabricate_coin(position, object_name);
}else if(name == "platform"){
return fabricate_platform(position, object_name);
}else{
return NULL;
}
}
engine::GameObject* GameObjectFactory::fabricate_platform(std::pair<int, int> position, std::string object_name){
engine::Game& game = engine::Game::get_instance();
engine::Image* platform_image = new engine::Image(game.renderer, "../assets/images/plataforma.png", true, std::make_pair(0,0), 2);
platform_image-> set_values(std::make_pair(507, 256), std::make_pair(507, 256), std::make_pair(0, 0));
engine::GameObject* platform = new engine::Platform(object_name, position, 2);
engine::Hitbox* hitbox = new engine::Hitbox("hitbox", platform->position, std::make_pair(40,70), std::make_pair(400,30), game.renderer);
platform->add_component(platform_image);
platform->add_component(hitbox);
return platform;
}
engine::GameObject* GameObjectFactory::fabricate_thorn(std::pair<int, int> position, std::string object_name){
engine::Game& game = engine::Game::get_instance();
engine::Image* thorn_image = new engine::Image(game.renderer, "../assets/images/thorn.png", true, std::make_pair(0,0), 2);
thorn_image-> set_values(std::make_pair(144, 109), std::make_pair(144, 109), std::make_pair(0,0));
engine::GameObject* thorn = new Thorn(object_name, position, 2);
engine::Hitbox* hitbox= new engine::Hitbox("hitbox", thorn->position, std::make_pair(0, 0), std::make_pair(120, 109), game.renderer);
thorn->add_component(thorn_image);
thorn->add_component(hitbox);
return thorn;
}
engine::GameObject* GameObjectFactory::fabricate_coin(std::pair<int, int> position, std::string object_name){
engine::Game& game = engine::Game::get_instance();
engine::Image* coin_image = new engine::Image(game.renderer, "../assets/images/coin.png", true, std::make_pair(0,0), 2);
coin_image-> set_values(std::make_pair(50, 50), std::make_pair(278, 236), std::make_pair(0,0));
engine::GameObject* coin = new game::Coin(object_name, position, 2);
engine::Hitbox* hitbox= new engine::Hitbox("hitbox", coin->position, std::make_pair(0, 0), std::make_pair(50, 50), game.renderer);
coin->add_component(coin_image);
coin->add_component(hitbox);
return coin;
}
engine::GameObject* GameObjectFactory::fabricate_little_girl(std::pair<int, int>, std::string object_name){
engine::Game& game = engine::Game::get_instance();
std::pair<int, int> place (416, 335);
//Creating running right image
engine::Image* image_running_right = new engine::Image(
game.renderer,
"../assets/images/menina_correndo_direita.png",
true,
std::make_pair(0, 0),
2
);
image_running_right->set_values(
std::make_pair(192, 192),
std::make_pair(192, 192),
std::make_pair(0, 0)
);
//Creating running right image
engine::Image* image_running_left = new engine::Image(
game.renderer,
"../assets/images/menina_correndo_esquerda.png",
false,
std::make_pair(0, 0),
2
);
image_running_left->set_values(
std::make_pair(192, 192),
std::make_pair(192, 192),
std::make_pair(0, 0)
);
engine::GameObject* little_girl = new engine::LittleGirl("little_girl", place, 52);
engine::Hitbox* hitbox= new engine::Hitbox("hitbox", little_girl->position, std::make_pair(60, 180), std::make_pair(50,40), game.renderer);
engine::Hitbox* dorso= new engine::Hitbox("dorso", little_girl->position, std::make_pair(60, 150), std::make_pair(50,40), game.renderer);
little_girl->collidable = true;
little_girl->add_component(image_running_right);
little_girl->add_component(image_running_left);
little_girl->add_component(hitbox);
little_girl->add_component(dorso);
return little_girl;
}
|
#ifndef NETSOCKET_H
#define NETSOCKET_H
#include <stdint.h>
#include <vector>
#include <QThread>
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QTcpSocket>
#include <QtNetwork/QTcpServer>
#include <QByteArray>
#include <QHostInfo>
#include <QNetworkInterface>
using namespace std;
class netsocket : public QThread
{
Q_OBJECT
public:
netsocket( QString target_ip, quint16 port );
netsocket();
~netsocket();
void stop();
private:
QTcpSocket *socket;
QTcpServer *server;
bool* is_enable_sample;
quint64 packet_number;
protected:
void run();
public slots:
void on_new_connect();
void on_dsp_data_recv(std::vector<float>);
void on_get_ready_datas( float *data, int length );
private slots:
void on_read_message();
signals:
void change_sample_para(uint32_t,uint32_t);
void cmd_start_sample();
void cmd_stop_sample();
};
#endif // NETSOCKET_H
|
/*
* SPDX-FileCopyrightText: 2021 Rolf Eike Beer <eike@sf-mail.de>
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
#include <settings.h>
#include <wms.h>
#include <algorithm>
#include <cassert>
#include <osm2go_annotations.h>
#include <osm2go_test.h>
namespace {
class emptySettings : public settings_t {
emptySettings() {}
public:
static std::shared_ptr<settings_t> get()
{
std::shared_ptr<settings_t> ret(new emptySettings());
return ret;
}
static void clearServers(std::vector<wms_server_t *> &srvs)
{
std::for_each(srvs.begin(), srvs.end(), std::default_delete<wms_server_t>());
srvs.clear();
}
void ld()
{
load();
}
void defs()
{
setDefaults();
}
};
void testRef()
{
settings_t::ref s = settings_t::instance();
assert(s.get() == settings_t::instance().get());
}
void testDefaults()
{
settings_t::ref settings = emptySettings::get();
setenv("OSM_USER", "ouser", 1);
setenv("OSM_PASS", "secret123", 1);
static_cast<emptySettings *>(settings.get())->defs();
assert_cmpstr(settings->username, "ouser");
assert_cmpstr(settings->password, "secret123");
assert_cmpstr(settings->style, DEFAULT_STYLE);
std::vector<wms_server_t *> defservers = wms_server_get_default();
assert_cmpnum(defservers.size(), settings->wms_server.size());
for (size_t i = 0; i < defservers.size(); i++) {
assert_cmpstr(defservers.at(i)->name, settings->wms_server.at(i)->name);
assert_cmpstr(defservers.at(i)->server, settings->wms_server.at(i)->server);
}
emptySettings::clearServers(defservers);
emptySettings::clearServers(settings->wms_server);
// now load whatever is on disk so that the save() call in the base destructor
// will hopefully not change anything
static_cast<emptySettings *>(settings.get())->ld();
}
} // namespace
int main(int argc, char **argv)
{
OSM2GO_TEST_INIT(argc, argv);
testRef();
testDefaults();
return 0;
}
#include "dummy_appdata.h"
|
/*
* HUDWindow.h
*
* Created on: Sep 17, 2009
* Author: ibi
* Purpose: provide the 2D overlay window for a Headsup Display
*/
#ifndef HUDWINDOW_H_
#define HUDWINDOW_H_
//
// Info window
//
class CZWBHUDWindow: public CSkinWindow {
public:
CZWBHUDWindow();
virtual ~CZWBHUDWindow();
void AccelUpdate(int x, int y, int z, int roll, int pitch);
protected:
virtual void OnPaint(CSkinGuiResource* pGuiResource, CRect dirtyRect,
CBuffer *pSurface, cairo_t* pCairoContext);
virtual void OnCreate(void);
virtual void OnTimer(uint32_t timerID);
protected:
int mTimerPaint;
int mX;
int mY;
int mZ;
int mRoll;
int mPitch;
};
#endif /* HUDWINDOW_H_ */
|
/*****************************************************************************************************
* 剑指offer第63题
* 给定一棵二叉搜索树,请找出其中的第k小的结点。例(5,3,7,2,4,6,8)中,按结点数值大小顺序第三小结点的值为4。
* Input: 二叉树
* Output: 二叉树第K小的节点数
*
* Note:(二叉树非递归的前、中、后序遍历必须要熟悉)--后序最难
* 本题要用到二叉树的中序遍历,因为中序遍历的二叉树是从小到大进行排列的,因此可以直接利用二叉树的前序遍历的
非递归写法,只是在中间增加计数即可,关键在于对基础的掌握程度
******************本题编程已通过*********************
二叉树非递归很经典的结构前序和中序都用stack结构
while(!s.empty()||node!=NULL)
{
while(node!=NULL)
.....
if(!s.empty())
}
* author: lcxanhui@163.com
* time: 2019.7.8
******************************************************************************************************/
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
//树结构体
struct TreeNode {
int value;
TreeNode * left;
TreeNode * right;
TreeNode(int value) :value(value), left(NULL), right(NULL) {}
};
//构建二叉树
void insertTreeNode(TreeNode *node, int value) {
if (value <= node->value) {
if (!node->left) {
node->left = new TreeNode(value);
}
else {
insertTreeNode(node->left, value);
}
}
else {
if (!node->right) {
node->right = new TreeNode(value);
}
else {
insertTreeNode(node->right, value);
}
}
}
//中序遍历非递归实现,只是在非递归实现中增加了出栈的简单计数
TreeNode* inOrder(TreeNode *root,unsigned int k) {
if (root == NULL || k == 0)
return NULL;
stack<TreeNode*> nstack;
TreeNode *temp = root;
int count = 0;
while (temp !=NULL || !nstack.empty())
{
while(temp!=NULL)
{
nstack.push(temp);
temp = temp->left;
}
if(!nstack.empty())
{
temp = nstack.top();
cout << temp->value<<" ";
nstack.pop();
//出栈的简单计数判断
count++;
if (count == k)
return temp;
//左子树不存在,则下面同样看右子树
else
temp = temp->right;
}
}
return temp;
}
int main()
{
int n,k;
cin >> k;
while (cin >> n) {
n--;
int value;
cin >> value;
TreeNode root(value);
while (n--) {
int newValue;
cin >> newValue;
insertTreeNode(&root, newValue);
}
TreeNode *res = NULL;
cout << "inOrder without recursion is:";
res=inOrder(&root,k);
cout << endl;
cout <<"The Node is:" <<res->value <<endl;
system("pause");
return 0;
}
}
|
#include <chrono>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <math.h>
#include <iostream>
#include <Shader.hpp>
#include <ShaderProgram.hpp>
void framebuffer_size_callback(GLFWwindow *window, int width, int height)
{
glViewport(0, 0, width, height);
}
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
bool hold = false;
bool wireframe = false;
void toggleWireframe(GLFWwindow *window)
{
/* Wireframe Mode */
if (hold && glfwGetKey(window, GLFW_KEY_W) == GLFW_RELEASE)
{
hold = false;
}
if (!hold && glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
{
if (wireframe)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
else
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
wireframe = !wireframe;
hold = true;
}
}
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
GLFWwindow *window = glfwCreateWindow(640, 480, "Test1", NULL, NULL);
if (!window)
{
std::cerr << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cerr << "Failed to initialize GLAD" << std::endl;
return -1;
}
glViewport(0, 0, 640, 480);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
ShaderProgram sprog1;
{
Shader vert1("vertex.vert", GL_VERTEX_SHADER);
Shader frag1("fragment.frag", GL_FRAGMENT_SHADER);
sprog1.attach(vert1);
sprog1.attach(frag1);
sprog1.link();
}
float vertices[] = {
-1.0f, -0.5f, // 1 bottom left
0.3f, -0.0f, // 1 bottom right
-0.5f, 0.5f, // 1 top
0.0f, 0.0, // last
};
int indices[] = {0, 1, 2};
GLuint VAO, VBO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void *)0);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
while (!glfwWindowShouldClose(window))
{
processInput(window);
toggleWireframe(window);
//Get time
auto current_time = std::chrono::high_resolution_clock::now();
float time = glfwGetTime();
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glBindVertexArray(VAO);
sprog1.use();
sprog1.setUniform2f("positionOffset", sin(time),cos(time)/10);
sprog1.setUniform3f("colorChange", (sin(time)+1)/2,(cos(time)+1)/2, (sin(time/2)+1)/2);
glDrawElements(GL_TRIANGLES, 4, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Phone.Devices.Notification.2.h"
WINRT_EXPORT namespace winrt {
namespace Windows::Phone::Devices::Notification {
struct WINRT_EBO VibrationDevice :
Windows::Phone::Devices::Notification::IVibrationDevice
{
VibrationDevice(std::nullptr_t) noexcept {}
static Windows::Phone::Devices::Notification::VibrationDevice GetDefault();
};
}
}
|
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *reverse(ListNode *head);
// or using stack
bool isPalindrome(ListNode *head) {
ListNode *fast = head, *slow = head;
if (!head)
return false;
if (!head->next)
return true;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode *rhs = reverse(slow);
ListNode *lhs = head;
while (rhs) {
if (lhs->val != rhs->val)
return false;
else {
lhs = lhs->next;
rhs = rhs->next;
}
}
return true;
}
ListNode *reverse(ListNode *head){
if (!head || !head->next)
return head;
ListNode *pre = nullptr;
ListNode *cur = head;
while (cur) {
const ListNode *sec = cur->next;
cur->next = pre;
pre = cur;
cur = const_cast<ListNode *>(sec);
}
return pre;
}
|
/*
* Scene.cpp
*
*/
#include "Scene.h"
namespace rt {
/**
* Parses json scene object to generate scene to render
*
* @param scenespecs the json scene specificatioon
*/
void Scene::createScene(Value& scenespecs) {
//----------parse json object to populate scene-----------
}
} // namespace rt
|
/*
ID: khurana2
PROG: gift1
LANG: C++
*/
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <utility>
using namespace std;
typedef pair<long, long>Balance;
int main()
{
ofstream fout("gift1.out");
ifstream fin("gift1.in");
string names[10];
string current_name, friend_name;
map<string, Balance> data;
map<string, Balance> :: iterator it;
long amount, group_size, per;
unsigned short count, i, j;
fin >> count;
for (i = 0; i < count; ++i) {
fin >> names[i];
data.insert(make_pair(names[i], make_pair(0, 0)));
}
for (i = 0; i < count; ++i) {
fin >> current_name;
fin >> amount >> group_size;
it = data.find(current_name);
(*it).second.first = amount;
per = group_size > 0 ? amount / group_size : 0;
for (j = 0; j < group_size; ++j) {
fin >> friend_name;
data[friend_name].second += per;
}
(*it).second.second += (amount - (per*group_size));
}
for (i = 0; i < count; ++i) {
Balance bal = data[names[i]];
fout << names[i] << " " << bal.second - bal.first << endl;
}
return 0;
}
|
/**********************************************************************
** Some utility functions that are coommonly used, are listed here
**********************************************************************/
#include "utilities.h"
#include <iostream>
#include <fstream>
using namespace std;
utilities::utilities()
{
}
utilities::~utilities()
{
}
//Delay function for display update
//Intensity calculation (Amplitude^2)
double utilities::ComplexAbsSquared(std::complex<double> a)
{
return (a.real()*a.real() + a.imag()*a.imag());
}
//Absolute value (amplitude) calculation
double utilities::ComplexAbs(std::complex<double> a)
{
return sqrt(ComplexAbsSquared(a));
}
//Simpson's 1/3 rule
double utilities::SimpsonsWeight (int i, int n)
{
double weight = 1.0;
if ((i!=0) && (i!=n-1))
{
if ((i+1)%2==0)
weight = 4.0;
else
weight = 2.0;
}
return weight /3.0;
}
|
#pragma once
#include "Elf.h"
Elf::Elf(std::string n)
:Class(n)
{
}
std::string Elf::render() {
return "Elf " + name;
}
Elf::~Elf()
{
}
|
#include<bits/stdc++.h>
using namespace std;
// remember after sorting always traverse from the end
// codeforces contest 683 div 2 C by meet IT
//https://codeforces.com/contest/1447/problem/C
bool compare(pair<int,int>& a,pair<int,int>& b)
{
return a.first < b.first;
}
int main()
{
int t;
cin >> t;
while(t--)
{
int n;
long long W;
cin >> n >> W;
vector<pair<int,int>> arr(n);
for(int i=0;i<n;i++)
{
int val;
cin >> val;
arr[i]=make_pair(val,i+1);
}
sort(arr.begin(),arr.end(),compare);
int ff=0;
int index = -1;
for(int i=0;i<n;i++)
{
if(arr[i].first<=W && arr[i].first>=ceil((W)/2.0))
{
ff=1;
index = arr[i].second;
break;
}
}
if(ff)
{
cout << 1 << endl;
cout << index << endl;
continue;
}
ff=0;
long long sum = 0;
vector<int> output;
for(int i=n-1;i>=0;i--)
{
if(sum+arr[i].first <= W)
{
sum+=arr[i].first;
output.push_back(arr[i].second);
}
if(sum >= ceil((W)/2.0))
{
ff=1;
break;
}
}
if(ff==1)
{
sort(output.begin(),output.end());
cout << output.size() << endl;
for(int i=0;i<output.size();i++)
{
cout << output[i] << " ";
}
cout << endl;
continue;
}
cout << -1 << endl;
}
return 0;
}
|
#include "miscFunctions.hpp"
#include <SFML/Graphics.hpp>
#include <cmath>
#include <ctime>
#include <cstdlib>
sf::IntRect getRectForSprite (SpriteType type)
{
if (type == GRASS_1)
{
return getRectForSpriteSheetPos (0, 0, 1);
}
if (type == GRASS_2)
{
return getRectForSpriteSheetPos (0, 1, 1);
}
if (type == GRASS_3)
{
return getRectForSpriteSheetPos (0, 2, 1);
}
if (type == GRASS_4)
{
return getRectForSpriteSheetPos (0, 3, 1);
}
if (type == STONE_1)
{
return getRectForSpriteSheetPos (1, 0, 1);
}
if (type == HUMAN_RIGHT)
{
return getRectForSpriteSheetPos (2, 0, 2);
}
// The backup in case something goes wrong
return sf::IntRect (36, 0, 16, 16);
}
sf::IntRect getRectForSpriteSheetPos (int xPos, int yPos, int size)
{
return sf::IntRect (xPos * (BLOCK_LENGTH_IN_PIXELS + 1), yPos * (BLOCK_LENGTH_IN_PIXELS + 1), size * BLOCK_LENGTH_IN_PIXELS, size * BLOCK_LENGTH_IN_PIXELS);
}
int roundToInt (double a)
{
if (a >= 0)
{
return static_cast<int> (a + 0.5);
}
else
{
return static_cast<int> (a - 0.5);
}
}
int randomInt (int a, int b)
{
return (rand () % (b - a)) + a;
}
double safeAcos (double fraction)
{
if (fraction < -1)
{
fraction = -1;
}
else if (fraction > 1)
{
fraction = 1;
}
return acos (fraction);
}
|
#include "sysconfig.h"
#include "sysdeps.h"
#include "ethernet.h"
#ifdef _WIN32
#include "win32_uaenet.h"
#endif
#include "threaddep/thread.h"
#include "options.h"
#include "traps.h"
#include "sana2.h"
#include "uae/slirp.h"
#include "gui.h"
#include "rommgr.h"
#ifndef HAVE_INET_ATON
static int inet_aton(const char *cp, struct in_addr *ia)
{
uint32_t addr = inet_addr(cp);
if (addr == 0xffffffff)
return 0;
ia->s_addr = addr;
return 1;
}
#endif
struct ethernet_data
{
ethernet_gotfunc *gotfunc;
ethernet_getfunc *getfunc;
void *userdata;
};
#define SLIRP_PORT_OFFSET 0
static const int slirp_ports[] = { 21, 22, 23, 80, 0 };
static struct ethernet_data *slirp_data;
static bool slirp_inited;
uae_sem_t slirp_sem1, slirp_sem2;
static int netmode;
static struct netdriverdata slirpd =
{
UAENET_SLIRP,
_T("slirp"), _T("SLIRP User Mode NAT"),
1500,
{ 0x00, 0x00, 0x00, 50, 51, 52 },
{ 0x00, 0x00, 0x00, 50, 51, 52 },
1
};
static struct netdriverdata slirpd2 =
{
UAENET_SLIRP_INBOUND,
_T("slirp_inbound"), _T("SLIRP + Open ports (21-23,80)"),
1500,
{ 0x00, 0x00, 0x00, 50, 51, 52 },
{ 0x00, 0x00, 0x00, 50, 51, 52 },
1
};
void slirp_output (const uint8_t *pkt, int pkt_len)
{
if (!slirp_data)
return;
gui_flicker_led(LED_NET, 0, gui_data.net | 1);
uae_sem_wait (&slirp_sem1);
slirp_data->gotfunc (slirp_data->userdata, pkt, pkt_len);
uae_sem_post (&slirp_sem1);
}
void ethernet_trigger (struct netdriverdata *ndd, void *vsd)
{
if (!ndd)
return;
gui_flicker_led(LED_NET, 0, gui_data.net | 2);
switch (ndd->type)
{
case UAENET_SLIRP:
case UAENET_SLIRP_INBOUND:
{
struct ethernet_data *ed = (struct ethernet_data*)vsd;
if (slirp_data) {
uae_u8 pkt[4000];
int len = sizeof pkt;
int v;
uae_sem_wait (&slirp_sem1);
v = slirp_data->getfunc(ed->userdata, pkt, &len);
uae_sem_post (&slirp_sem1);
if (v) {
uae_sem_wait (&slirp_sem2);
uae_slirp_input(pkt, len);
uae_sem_post (&slirp_sem2);
}
}
}
return;
#ifdef WITH_UAENET_PCAP
case UAENET_PCAP:
uaenet_trigger (vsd);
return;
#endif
}
}
int ethernet_open (struct netdriverdata *ndd, void *vsd, void *user, ethernet_gotfunc *gotfunc, ethernet_getfunc *getfunc, int promiscuous, const uae_u8 *mac)
{
switch (ndd->type)
{
case UAENET_SLIRP:
case UAENET_SLIRP_INBOUND:
{
struct ethernet_data *ed = (struct ethernet_data*)vsd;
ed->gotfunc = gotfunc;
ed->getfunc = getfunc;
ed->userdata = user;
slirp_data = ed;
uae_sem_init (&slirp_sem1, 0, 1);
uae_sem_init (&slirp_sem2, 0, 1);
uae_slirp_init();
for (int i = 0; i < MAX_SLIRP_REDIRS; i++) {
struct slirp_redir *sr = &currprefs.slirp_redirs[i];
if (sr->proto) {
struct in_addr a;
if (sr->srcport == 0) {
inet_aton("10.0.2.15", &a);
uae_slirp_redir (0, sr->dstport, a, sr->dstport);
} else {
#ifdef HAVE_STRUCT_IN_ADDR_S_UN
a.S_un.S_addr = sr->addr;
#else
a.s_addr = sr->addr;
#endif
uae_slirp_redir (sr->proto == 1 ? 0 : 1, sr->dstport, a, sr->srcport);
}
}
}
if (ndd->type == UAENET_SLIRP_INBOUND) {
struct in_addr a;
inet_aton("10.0.2.15", &a);
for (int i = 0; slirp_ports[i]; i++) {
int port = slirp_ports[i];
int j;
for (j = 0; j < MAX_SLIRP_REDIRS; j++) {
struct slirp_redir *sr = &currprefs.slirp_redirs[j];
if (sr->proto && sr->dstport == port)
break;
}
if (j == MAX_SLIRP_REDIRS)
uae_slirp_redir (0, port + SLIRP_PORT_OFFSET, a, port);
}
}
netmode = ndd->type;
uae_slirp_start ();
}
return 1;
#ifdef WITH_UAENET_PCAP
case UAENET_PCAP:
if (uaenet_open (vsd, ndd, user, gotfunc, getfunc, promiscuous, mac)) {
netmode = ndd->type;
return 1;
}
return 0;
#endif
}
return 0;
}
void ethernet_close (struct netdriverdata *ndd, void *vsd)
{
if (!ndd)
return;
switch (ndd->type)
{
case UAENET_SLIRP:
case UAENET_SLIRP_INBOUND:
if (slirp_data) {
slirp_data = NULL;
uae_slirp_end ();
uae_slirp_cleanup ();
uae_sem_destroy (&slirp_sem1);
uae_sem_destroy (&slirp_sem2);
}
return;
#ifdef WITH_UAENET_PCAP
case UAENET_PCAP:
return uaenet_close (vsd);
#endif
}
}
void ethernet_enumerate_free (void)
{
#ifdef WITH_UAENET_PCAP
uaenet_enumerate_free ();
#endif
}
bool ethernet_enumerate (struct netdriverdata **nddp, int romtype)
{
int j;
struct netdriverdata *nd;
const TCHAR *name = NULL;
if (romtype) {
struct romconfig *rc = get_device_romconfig(&currprefs, romtype, 0);
name = ethernet_getselectionname(rc ? rc->device_settings : 0);
}
gui_flicker_led(LED_NET, 0, 0);
if (name) {
netmode = 0;
*nddp = NULL;
if (!_tcsicmp (slirpd.name, name))
*nddp = &slirpd;
if (!_tcsicmp (slirpd2.name, name))
*nddp = &slirpd2;
#ifdef WITH_UAENET_PCAP
if (*nddp == NULL)
*nddp = uaenet_enumerate (name);
#endif
if (*nddp) {
netmode = (*nddp)->type;
return true;
}
return false;
}
j = 0;
nddp[j++] = &slirpd;
nddp[j++] = &slirpd2;
#ifdef WITH_UAENET_PCAP
nd = uaenet_enumerate (NULL);
if (nd) {
int last = MAX_TOTAL_NET_DEVICES - 1 - j;
for (int i = 0; i < last; i++) {
if (nd[i].active)
nddp[j++] = &nd[i];
}
}
#endif
nddp[j] = NULL;
return true;
}
void ethernet_close_driver (struct netdriverdata *ndd)
{
switch (ndd->type)
{
case UAENET_SLIRP:
case UAENET_SLIRP_INBOUND:
return;
#ifdef WITH_UAENET_PCAP
case UAENET_PCAP:
return uaenet_close_driver (ndd);
#endif
}
netmode = 0;
}
int ethernet_getdatalenght (struct netdriverdata *ndd)
{
switch (ndd->type)
{
case UAENET_SLIRP:
case UAENET_SLIRP_INBOUND:
return sizeof (struct ethernet_data);
#ifdef WITH_UAENET_PCAP
case UAENET_PCAP:
return uaenet_getdatalenght ();
#endif
}
return 0;
}
bool ethernet_getmac(uae_u8 *m, const TCHAR *mac)
{
if (!mac)
return false;
if (_tcslen(mac) != 3 * 5 + 2)
return false;
for (int i = 0; i < 6; i++) {
TCHAR *endptr;
if (mac[0] == 0 || mac[1] == 0)
return false;
if (i < 5 && (mac[2] != '.' && mac[2] != ':'))
return false;
uae_u8 v = (uae_u8)_tcstol(mac, &endptr, 16);
mac += 3;
m[i] = v;
}
return true;
}
|
//
// Created by sunjiaming on 19-5-13.
//
#ifndef EX_7_4_PERSON_H
#define EX_7_4_PERSON_H
class Person {
private:
string name;
string adress;
};
#endif //EX_7_4_PERSON_H
|
//// *** user.cpp ***
void init(int N, int bidArr[], int duration[], int capacity[]) {
}
int add(int tick, int bid, int guestNum, int priority) {
return 0;
}
void search(int tick, int findCnt, int bidArr[], int numResult[]) {
}
|
#include "PizzaService.h"
PizzaService::PizzaService()
{
//ctor
}
PizzaService::~PizzaService()
{
//dtor
}
|
<<<<<<< HEAD
#include <cstdint>
#include <utility>
namespace sum_of_multiples {
uint32_t to(std::pair<uint32_t, uint32_t> input, uint32_t);
}
=======
#ifndef SUM_OF_MULTIPLES_H
#define SUM_OF_MULTIPLES_H
#include <list>
#include <cstdint>
#include <numeric>
namespace sum_of_multiples{
uint32_t to(std::list<uint32_t>, uint32_t num);
}
#endif //!SUM_OF_MULTIPLES_H
>>>>>>> 733f2d20503743b23f6125408e037628a7cef28f
|
#if __has_include(<optional>)
#include <optional>
#define have_optional 1
#elif __has_include(<experimental/optional>)
#include <experimental/optional>
#define have_optional 1
#define experimental_optional 1
#else
#define have_optional 0
#endif
#include <iostream>
int main()
{
if (have_optional)
std::cout << "<optional> is present.\n";
int x = 42;
#if have_optional == 1
std::optional<int> i = x;
#else
int *i = &x;
#endif
std::cout << "i = " << *i << '\n';
}
|
//Copyright 2015-2016 Tomas Mikalauskas. All rights reserved.
#pragma once
#include "IRendererInitializer.h"
#define WINDOW_STYLE (WS_OVERLAPPED|WS_BORDER|WS_CAPTION|WS_VISIBLE | WS_THICKFRAME)
class WindowsGLRendererInitializer final: public IRendererInitializer
{
friend class GLRenderer;
public:
WindowsGLRendererInitializer();
~WindowsGLRendererInitializer();
bool CreateRendererScreen(uint32_t height, uint32_t widht, bool isFullscreen, LRESULT(CALLBACK MainWindowProc)(HWND, UINT, WPARAM, LPARAM));
void DestroyRendererScreen();
HWND GetWind32Handle() { return m_hWnd; }
/*
if interval = 0 then vsync is disabled
if interval = 1 then vsync is enabled
if intervak = -1 then adaptive vsync is enabled
Adaptive vsync enables v-blank synchronisation when the frame rate is higher than the sync rate,
but disables synchronisation when the frame rate drops below the sync rate.
Disabling the synchronisation on low frame rates prevents the common problem where the frame rate
syncs to a integer fraction of the screen's refresh rate in a complex scene.
*/
void RendererSwapBuffers();
protected:
int WGLChoosePixelFormat(const HDC hdc, const uint32_t multisamples, const bool stereo3D);
//Used only to get wglExtension
static LONG WINAPI CreateFakeWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
//Checks if wgl extensions are supported on this hardware
bool CheckWGLExtensions(HDC hDC);
void GetWGLExtensionsWithFakeWindow();
HGLRC CreateOpenGLContextOnDC(const HDC hdc, const bool debugContext);
void CreateWindowClasses(LRESULT(CALLBACK MainWindowProc)(HWND, UINT, WPARAM, LPARAM));
/*
Set the pixelformat for the window before it isshown, and create the rendering context
@param gl_params: user params that are in GLRenderer
*/
bool InitDriver();
/*
Responsible for creating the Win32 window.
If fullscreen, it won't have a border
*/
bool WGLCreateWindow();
protected:
glconfig_st m_glConfigs;
gl_params m_glParams;
HWND m_hWnd; //Window handle
HINSTANCE m_hInstance;
HINSTANCE m_hinstOpenGL; // HINSTANCE for the OpenGL library
PIXELFORMATDESCRIPTOR m_pfd;
HDC m_hDC; // handle to device context
HGLRC m_hGLRC; // handle to GL rendering context
uint32_t m_iPixelFormat;
uint32_t m_iDesktopBitsPixel;
uint32_t m_iDesktopWidth;
uint32_t m_iDesktopHeight;
bool m_bWindowClassRegistered;
};
|
/**********************************************************
* License: The MIT License
* https://www.github.com/doc97/TxtAdv/blob/master/LICENSE
**********************************************************/
#include "catch.hpp"
#include "TxtContentReader.h"
namespace txt
{
TEST_CASE("TxtContentReader - All fields correct", "[TxtContentReader]")
{
std::stringstream ss;
ss << "Ctrl: test.ctrl\n";
ss << "Style: test.style\n";
ss << "\n";
ss << "Story: hello\n";
ss << " text\n";
TxtContentReader reader;
TxtContentInfo info = reader.Read(ss);
REQUIRE(info.ctrl_filename == "test.ctrl");
REQUIRE(info.style_filename == "test.style");
REQUIRE(info.story_points.size() == 1);
REQUIRE(info.story_points[0].GetName() == "hello");
REQUIRE(info.story_points[0].GetTextStr() == "text");
}
TEST_CASE("TxtContentReader - invalid file", "[TxtContentReader]")
{
try
{
TxtContentReader reader;
TxtContentInfo info = reader.Read("DoesNotExist.txt");
FAIL("Trying to read a non-existent file should throw a std::runtime_error");
}
catch (std::runtime_error)
{
}
}
TEST_CASE("TxtContentReader - Ctrl field", "[TxtContentReader]")
{
TxtContentReader reader;
std::stringstream ss;
SECTION("missing completely")
{
ss << "Story: hello\n";
ss << " text\n";
try
{
TxtContentInfo info = reader.Read(ss);
FAIL("Missing Ctrl-field should throw a std::runtime_error");
}
catch (std::runtime_error)
{
}
}
SECTION("wrong order")
{
ss << "Story: hello\n";
ss << " text\n";
ss << "Ctrl: test.ctrl\n";
TxtContentInfo info = reader.Read(ss);
REQUIRE(info.story_points.size() == 0);
}
}
TEST_CASE("TxtContentReader - Style field, before ctrl field", "[TxtContentReader]")
{
std::stringstream ss;
ss << "Style: test.style\n";
ss << "Ctrl: test.ctrl\n";
TxtContentReader reader;
TxtContentInfo info = reader.Read(ss);
REQUIRE(info.style_filename.empty());
}
TEST_CASE("TxtContentReader - story spacing", "[TxtContentReader]")
{
TxtContentReader reader;
std::stringstream ss;
ss << "Ctrl: test.ctrl\n";
SECTION("single story, no spacing")
{
ss << "Story: hello\n";
ss << " text\n";
TxtContentInfo info = reader.Read(ss);
REQUIRE(info.story_points.size() == 0);
}
SECTION("multiple stories no spacing between")
{
ss << "\n";
ss << "Story: hello\n";
ss << " text\n";
ss << "Story: foo\n";
ss << " bar\n";
TxtContentInfo info = reader.Read(ss);
REQUIRE(info.story_points.size() == 2);
REQUIRE(info.story_points[0].GetTextStr() == "text");
REQUIRE(info.story_points[1].GetTextStr() == "bar");
}
}
TEST_CASE("TxtContentReader - story text indentation", "[TxtContentReader]")
{
TxtContentReader reader;
std::stringstream ss;
ss << "Ctrl: test.ctrl\n";
ss << "\n";
ss << "Story: hello\n";
SECTION("no indentation")
{
ss << "text\n";
TxtContentInfo info = reader.Read(ss);
REQUIRE(info.story_points[0].GetTextStr() == "");
}
SECTION("too little indentation")
{
ss << " text\n";
TxtContentInfo info = reader.Read(ss);
REQUIRE(info.story_points[0].GetTextStr() == "");
}
SECTION("correct indendation")
{
ss << " text\n";
TxtContentInfo info = reader.Read(ss);
REQUIRE(info.story_points[0].GetTextStr() == "text");
}
SECTION("too much indentation")
{
ss << " text\n";
TxtContentInfo info = reader.Read(ss);
REQUIRE(info.story_points[0].GetTextStr() == "text");
}
}
TEST_CASE("TxtContentReader - story text spacing", "[TxtContentReader]")
{
TxtContentReader reader;
std::stringstream ss;
ss << "Ctrl: test.ctrl\n";
ss << "\n";
ss << "Story: hello\n";
ss << " First line\n";
ss << " \n";
ss << " new line\n";
TxtContentInfo info = reader.Read(ss);
REQUIRE(info.story_points[0].GetTextStr() == "First line\n\nnew line");
}
} // namespace txt
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <queue>
using namespace std;
/*
题目:
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
因为明确了有序数组一定发生了旋转,所以我们二分的目标就是找到相邻的两个数,而且这两个数是降序的。
要找相邻的两个数,所以二分的终止条件就得是 left+1 < right
下面的解法有误,请见 https://www.nowcoder.com/questionTerminal/9f3231a991af4f55b95579b44b7a01ba?toCommentId=1259695
int minNumberInRotateArray(vector<int> v) {
if(v.empty()) return 0;
int l = 0, r = v.size()-1;
while(l+1 < r){
int mid = (l+r)/2;
if(v[l] > v[mid]){
r = mid;
} else{
l = mid;
}
} return v[r];
}
需要考虑的特殊情况:
① 数组旋转部分的长度 len s.t. (len%v.size()) == 0
② 如果原序列为011111,旋转后序列为101111,这种情况就不能通过了。
所以当v[l]=v[mid]时候情况比较特殊,只能顺序遍历整段数组。
//* 经典测试样例 /
1
2 1
5 6 1
6 1 2
4 5 6 1 2 3
1 2 // is OK?
2, 2, 2, 1, 1, 1
1, 1, 1, 0, 1, 1
1, 0, 1, 1, 1, 1 // 上面的错误代码不能通过该样例
*/
class Solution {
public:
int minNumberInRotateArray(vector<int> v) {
if(v.empty()) return 0; // 给出的所有元素都大于0,若数组大小为0,请返回0。
int l = 0, r = v.size()-1;
if(v[l] < v[r]) return v[l]; // 补丁,旋转过的数组与原来的数组一样
while(l+1 < r){
int mid = (l+r)/2;
if(v[l] == v[mid] && v[mid] == v[r]){
// 顺序遍历找最小值
int res = v[l];
for(int i = l+1; i<=r; ++i)
if(v[i]<res)
res = v[i];
return res;
}
if(v[l] > v[mid]){
r = mid;
} else{ // if(v[l] <= v[mid]){ // 这里的分析很重要。v[l] < v[mid]时,容易分析。当v[l] == v[mid]时,因为v[mid]与v[r]不相等,因此一定满足v[mid]>v[r]
l = mid;
}
} return v[r];
}
};
int main(){
int a[] = {1, 0, 1, 1, 1, 1};
int res = Solution().minNumberInRotateArray(vector<int>(a, a+6));
cout << res << endl;
return 0;
}
|
/* Copyright (C) 2015 Willi Menapace <willi.menapace@gmail.com>, Simone Lorengo - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Willi Menapace <willi.menapace@gmail.com>
*/
#include "DataManager.h"
#include "GlobalDefines.h"
#include <assert.h>
#include "SecureFileReader.h"
#include "SecureFileWriter.h"
#include <assert.h>
const unsigned long DataManager::CONNECTION_RETRY_PERIOD = 120000;
const unsigned long DataManager::STORED_VALUE_SIZE = 17;
const unsigned long DataManager::DUMP_SAVEPOINT_DISTANCE = 255;
const unsigned long DataManager::ALL_VALUES_RECEIVED_CONFIRM_TIMEOUT = 15000;
const unsigned long DataManager::COMMIT_TIMEOUT = 10000;
void DataManager::closeConnection() {
dbConnector.closeConnection();
dbReader = 0;
dbWriter = 0;
}
void DataManager::tryDbConnection() {
dbConnector.tryConnection();
if(dbConnector.isConnected()) {
dbReader = dbConnector.getReader();
dbWriter = dbConnector.getWriter();
}
}
bool DataManager::isConnected() {
return dbReader != 0 && dbWriter != 0 && dbReader->isConnected() && dbWriter->isConnected();
}
void DataManager::store(StreamWriter *writer, long value, unsigned char *deviceAddress, unsigned char sensorId, unsigned long receptionTime) {
writer->writeLong((unsigned long) value);
for(int i = 0; i < ADDRESS_BYTES; ++i) {
writer->writeByte(deviceAddress[i]);
}
writer->writeByte(sensorId);
writer->writeLong(receptionTime);
}
void DataManager::storeInMemory(long value, unsigned char *deviceAddress, unsigned char sensorId, unsigned long receptionTime) {
#ifdef OFFBOARD
assert(false); //Il metodo non funziona se richiamato al di fuori della piattaforma di esecuzione
#endif // OFFBOARD
//Se il non e' aperto a causa di un commit precedente lo apre
if(!memoryWriter.isOpen()) {
memoryWriter.open(STORED_DATA_FILENAME, true);
}
assert(memoryWriter.isOpen());
//Invia il valore sul file
store(&memoryWriter, value, deviceAddress, sensorId, receptionTime);
unsigned long now = 0;
#ifdef ONBOARD
now = millis();
#endif // ONBOARD
//Se e' scaduto il timeout per il commit o se si e' resettato il contatore effettua il commit
if(now - lastCommit > COMMIT_TIMEOUT || now <= lastCommit) {
memoryWriter.close();
lastCommit = now;
}
}
void DataManager::storeInDb(long value, unsigned char *deviceAddress, unsigned char sensorId, unsigned long receptionTime) {
//La connessione deve essere presente alla chiamata del metodo
assert(isConnected());
dbWriter->writeByte(SINGLE_VALUE_PACKET); //Si trasmette al DB un singolo valore
store(dbWriter, value, deviceAddress, sensorId, receptionTime);
dbWriter->flush();
}
void DataManager::dumpMemoryToDb() {
#ifdef OFFBOARD
assert(false); //Il metodo non funziona se richiamato al di fuori della piattaforma di esecuzione
#endif // OFFBOARD
//Alla chiamata la connessione deve essere presente
assert(isConnected());
assert(!dbReader->isAvailable()); //Si assicura che non ci siano residui di comunicazioni precedenti in arrivo
if(memoryWriter.isOpen()) {
memoryWriter.close(); //Si effettua il commit in modo da salvare i valori prima dell'invio
}
unsigned long dumpStartByte = 0; //Byte da cui iniziare ad inviare i dati al DB
SecureFileReader startByteFile;
startByteFile.open(BYTE_TO_DUMP_FILENAME);
//Se non e' presenta il file con l'ultimo byte sincronizzato ne crea uno nuovo
if(!startByteFile.isOpen()) {
SecureFileWriter startByteCreator;
startByteCreator.open(BYTE_TO_DUMP_FILENAME, false);
startByteCreator.writeLong(0);
startByteCreator.close();
//Se e' presente legge il byte da cui cominciare il dump
} else {
dumpStartByte = startByteFile.readLong();
startByteFile.close();
}
SecureFileReader storedData;
storedData.open(STORED_DATA_FILENAME);
assert(storedData.isOpen());
unsigned long dumpFileSize = storedData.getSize();
//Deve essere presente almeno un valore da inviare al DB
assert(dumpFileSize > dumpStartByte);
storedData.seek(dumpStartByte);
//Segnala l'invio di valori multipli
dbWriter->writeByte(MULTI_VALUE_PACKET_START);
unsigned long bytesToSend = dumpFileSize - dumpStartByte;
//Calcola e invia il numero di valori che verranno inviati
assert(bytesToSend % STORED_VALUE_SIZE == 0);
unsigned long valuesToSend = bytesToSend / STORED_VALUE_SIZE;
dbWriter->writeLong(valuesToSend);
unsigned long receivedRecords = 0; //Numero di record di cui e' avvenuta la conferma ricezione
unsigned long lastPointSaved = 0; //Numero di record la cui ricezione e' stata salvata su file
long value;
unsigned char deviceAddress[ADDRESS_BYTES];
unsigned char sensorId;
unsigned long receptionTime;
//Finche' ci sono dati da sincronizzare
while(storedData.isAvailable()) {
//Se si e' persa la connessione
if(!isConnected()) {
closeConnection();
storedData.close(); //Chiude il file con i valori
return;
}
assert(storedData.isAvailable() >= STORED_VALUE_SIZE); //Deve essere disponibile il valore intero
while(dbReader->isAvailable()) {
unsigned char confirmedRecords = dbReader->readByte();
assert(confirmedRecords != ALL_VALUES_RECEIVED); //E' impossibile che tutti i dati siano arrivati in questo momento
receivedRecords += confirmedRecords;
//Se non ci sono altre conferme in arrivo e se sono stati confermati molti record si salva l'avvenuta ricezione su file
if(!dbReader->isAvailable() && receivedRecords - lastPointSaved > DUMP_SAVEPOINT_DISTANCE) {
SecureFileWriter startByteFileWriter;
startByteFileWriter.open(BYTE_TO_DUMP_FILENAME, false);
startByteFileWriter.writeLong((receivedRecords * STORED_VALUE_SIZE) + dumpStartByte);
startByteFileWriter.close();
lastPointSaved = receivedRecords; //Abbiamo appena salvato la corretta ricezione
}
}
value = (long) storedData.readLong();
for(int i = 0; i < ADDRESS_BYTES; ++i) {
deviceAddress[i] = storedData.readByte();
}
sensorId = storedData.readByte();
receptionTime = storedData.readLong();
store(dbWriter, value, deviceAddress, sensorId, receptionTime);
}
//Segnala la fine dell'invio
dbWriter->writeByte(MULTI_VALUE_PACKET_END);
//Si assicura che venga ricevuta la fine
dbWriter->flush();
storedData.close(); //Chiude il file con i valori memorizzati
unsigned long requestTime = 0;
unsigned long currentTime = 0;
#ifdef ONBOARD
requestTime = millis();
#endif
//Attende la conferma di ricezione di tutti i record
while(true) {
//Se si e' persa la connessione e non sono rimaste conferme da leggere
if(!isConnected() && !dbReader->isAvailable()) {
closeConnection();
return;
}
#ifdef ONBOARD
currentTime = millis();
#endif // ONBOARD
//Riceve conferme di ricezione pregresse e quella di ricezione completa
while(dbReader->isAvailable()) {
unsigned char confirmedRecords = dbReader->readByte();
//Il DB conferma l'avvenuta ricezione di tutti i record
if(confirmedRecords == ALL_VALUES_RECEIVED) {
SecureFileWriter startByteFileWriter;
SecureFileWriter storedDataWriter;
//Elimina il vecchio file
storedDataWriter.open(STORED_DATA_FILENAME, false);
startByteFileWriter.open(BYTE_TO_DUMP_FILENAME, false);
startByteFileWriter.writeLong(0);
//Apporta le modifiche a entrambi i file
startByteFileWriter.close();
storedDataWriter.close();
//Tutto e' stato completato
return;
//Si ricevono conferme parziali pregresse
} else {
receivedRecords += confirmedRecords;
//Se non ci sono altre conferme in arrivo e se sono stati confermati molti record si salva l'avvenuta ricezione su file
if(!dbReader->isAvailable() && receivedRecords - lastPointSaved > DUMP_SAVEPOINT_DISTANCE) {
SecureFileWriter startByteFileWriter;
startByteFileWriter.open(BYTE_TO_DUMP_FILENAME, false);
startByteFileWriter.writeLong((receivedRecords * STORED_VALUE_SIZE) + dumpStartByte);
startByteFileWriter.close();
lastPointSaved = receivedRecords; //Abbiamo appena salvato la corretta ricezione
}
}
}
//In caso sia superato il timeout o si sia resettato il contatore intero
//il DB ha incontrato problemi quindi si termina la connessione
if(currentTime - requestTime > ALL_VALUES_RECEIVED_CONFIRM_TIMEOUT || currentTime < requestTime) {
closeConnection();
break;
}
}
}
void DataManager::store(long value, unsigned char *deviceAddress, unsigned char sensorId, DateTime *receptionTime) {
if(isConnected()) {
#ifdef ONBOARD
//Non devono essere presenti byte di comunicazioni precedenti non concluse correttamente
assert(!dbReader->isAvailable());
#endif //ONBOARD
storeInDb(value, deviceAddress, sensorId, receptionTime->getTimeOffset());
} else {
//Il valore va comunque inserito in memoria indipendentemente dall'avvenuta riconnessione
storeInMemory(value, deviceAddress, sensorId, receptionTime->getTimeOffset());
unsigned long currentTime = 0;
#ifdef ONBOARD
currentTime = millis();
#endif // ONBOARD
//E' passato il tempo di guardia o il contatore si e' resettato
if(currentTime - lastConnectionAttempt > CONNECTION_RETRY_PERIOD || currentTime < lastConnectionAttempt) {
//Ritenta la connessione con la base di dati
tryDbConnection();
//Se la connessione ha successo
if(isConnected()) {
#ifdef ONBOARD
//Non devono essere presenti valori di comunicazioni precedenti non concluse correttamente
assert(!dbReader->isAvailable());
#endif //ONBOARD
//Memorizza il valore e spedisce tutto il contenuto della memoria alla base di dati
dumpMemoryToDb();
} else {
#ifdef ONBOARD
//Imposta la data dell'ultimo tentativo di connessione
lastConnectionAttempt = millis();
#endif // ONBOARD
}
}
}
}
DataManager::DataManager(Settings *_settings) : dbConnector(_settings->getDbParameters()) {
assert(_settings != 0);
dbReader = 0;
dbWriter = 0;
lastCommit = 0;
#ifdef ONBOARD
lastCommit = millis(); //Non si effettua il commit immediatamente
#endif // ONBOARD
lastConnectionAttempt = 4294967294; //Forza il tentativo di connessione all'avvio
}
|
//分数f1和f2的加法,数学公式展开即可,最后结果化简
Fraction add(Fraction f1,Fraction f2){
Fraction result;
result.up=f1.up*f2.down +f1.down *f2.up ;//分数和的分子
result.down =f1.down *f2.down ;//分数和的分母
return reduction(result);
}
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "array_list.h"
#include "quicksort3.h"
#include <ctime>
#include <cstdlib>
#include <string>
#include <QMessageBox>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_Generate_clicked();
void on_Input_clicked();
void on_Sort_clicked();
private:
Ui::MainWindow *ui;
array_list list;
void visualize();
};
#endif // MAINWINDOW_H
|
#ifndef __MENU_CREATE_SHAPE_H__
#define __MENU_CREATE_SHAPE_H__
//#include "imgui/imgui.h"
//#include <functional>
//#include "Panel.h"
//#include <vector>
//#include "RenderTexture.h"
//#include "MathGeoLib/include/Math/float3.h"
//
//#define X_COORD 0
//#define Y_COORD 1
//#define Z_COORD 2
//
//typedef unsigned int uint;
//typedef struct par_shapes_mesh_s par_shapes_mesh;
//class MenuCreateShape;
//class ComponentTransform;
//class GameObject;
//class ResourceMesh;
//class ShapeValue
//{
//public:
// ShapeValue(std::string name, ImGuiDataType data_type, void * value_ptr);
//
//public:
// std::string name;
// ImGuiDataType data_type;
// void * value_ptr;
//};
//
////If you want to create a different layout for your shape, create a derived class from PanelCreateShape
//class PanelCreateShape : public Panel
//{
//public:
// PanelCreateShape(std::string name, bool active = false, std::vector<SDL_Scancode> shortcut = {});
// void MenuItem(const float button_height, const float button_space, const ImVec4& button_color, const ImVec2& button_size);
//private:
// void Draw() override;
// void CreateCopiesXYZ(float3 & position);
// void CreateCopiesYZ(float3 & position);
// void CreateCopiesZ(float3 & position);
// void CreateCopyAtPosition(float3 position);
// void CreateMultiple();//Function to create multiple is going to be the same for each one of them
//
// //Function to call(may be the same that the MenuCreateShape::MenuItem() calls)
//public:
// std::function<par_shapes_mesh*()> mesh_function;
// std::vector<ShapeValue> shape_values;
// std::string shape_name;
//
//private:
// //Create multiple
// //How many copies are going to be created in x, y and z?
// int copies[3] = { 0u };
// //How many separation is going to be between the copies?
// float separation[3] = { 0.f };
//
// //TODO: Think does each panel need to have its own copies value?
// //TODO: Should this values be reset to 0 when you close the panel?
//};
//
////A class to handle the create shapes menu which lets you create different geometric shapes
class MenuCreateShape
{
//public:
// MenuCreateShape();
// ~MenuCreateShape();
//
// void MenuBarTab();
// void CreateEmpty();
// GameObject * CreateGameObjectWithParShape(std::string name, ComponentTransform * parent, ResourceMesh * asset_mesh);
// //TODO: Load variables with a function from ModuleGui
//
//public:
// RenderTexture preview_shapes_fbo;
// //A dummy gameobject not connected to any parents
// GameObject* preview_shape_gameobject = nullptr;
// ResourceMesh* preview_shape_mesh = nullptr;
//
//private:
//
// const float button_height = 7.5f;
// const float button_space = 150.f;
// ImVec4 button_color;
// ImVec2 button_size;
//
// //Parametric sphere
// int parametric_sphere_slices = 10;
// int parametric_sphere_stacks = 10;
//
// //Subdivided sphere
// int subdivided_sphere_nsubdivisions = 1;
//
// //Hemisphere
// int hemisphere_slices = 50;
// int hemisphere_stacks = 20;
//
// //Plane
// int plane_slices = 10;
// int plane_stacks = 10;
//
// //Klein bottle
// int klein_bottle_slices = 10;
// int klein_bottle_stacks = 10;
//
// //Cylinder
// int cylinder_slices = 50;
// int cylinder_stacks = 10;
//
// //Cone variables
// int cone_slices = 12;
// int cone_stacks = 12;
//
// //Torus variables
// int torus_slices = 12;
// int torus_stacks = 12;
// float torus_radius = 0.5f;
//
// //Trefoil knot
// int trefoil_knot_slices = 50;
// int trefoil_knot_stacks = 20;
// float trefoil_knot_radius = 2.f;
//
// //Disk
// float * disk_center = nullptr;
// float * disk_normal = nullptr;
// int disk_slices = 12;
// float disk_radius = 12.f;
//
// //INFO: We create a different panel for each because we might want to customize them individually
// std::vector<PanelCreateShape*> panels_create_shape;
};
#endif
|
void loop () {
if (cycletimer < 250 ) cycletimer++;
#if (MIDI_IN_block == 0)
#if defined (__AVR_ATmega32U4__) // USB MIDI in
do {
rx = MidiUSB.read();
if (rx.header != 0) {
incomingByte = rx.byte1; midifeedback();
incomingByte = rx.byte2; midifeedback();
incomingByte = rx.byte3; midifeedback();
}
} while (rx.header != 0);
#if ( stratos == 0)
// DIN MIDI in
if (Serial1.available() > 0) {
incomingByte = Serial1.read();
midifeedback();
}
else
#endif
#endif
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega168P__) || defined(__AVR_ATmega328P__)
if (Serial.available() > 0) {
incomingByte = Serial.read();
midifeedback(); }
else
#endif
if (openeditor != 1)
#endif
{
indexXen++; if (indexXen == 3) indexXen = 0;
#if (capacitivesensor_active == 1)
touch_sensors(0);
#if (stratos == 0)
if (dmxtable[general_mempos] >1) // attiva il secondo touch solo se è attivo il secondo spinner
touch_sensors(1);
#endif
#endif
#if (stratos == 1)
AIN_stratos();
#endif
#if (stratos == 0)
AIN();
#endif
#if (shifter_active == 1 && stratos == 0)
if (qwertyvalue[general_mempos] > 2) buttonledefx();
#endif
#if (autosend == 1)
// autosend_();
#endif
#if (page_active == 1)
if (page_mempos > 0 ) pageswitch();
#endif
//shifter.setAll(LOW);
// if (valuetable[general_mempos] == 0) shifter.write();
#if (shifter_active == 1 && stratos == 0)
if (shifterwrite ==1 && valuetable[general_mempos] == 0) {shifter.write(); shifterwrite=0;
}
#endif
}
}
|
#include "Camera.h"
void Camera::update(Controls* control)
{
position += front * control->forward;
position += up * control->up;
position += (front.cross(up)).normalize() * control->right;
control->forward = 0.0f;
control->right = 0.0f;
control->up = 0.0f;
Maths::mat4 rollRotation = Maths::mat4::rotation(control->roll, front);
up = Maths::vec3(
(rollRotation * Maths::vec4(up, 1.0f)).values[0],
(rollRotation * Maths::vec4(up, 1.0f)).values[1],
(rollRotation * Maths::vec4(up, 1.0f)).values[2]
).normalize();
Maths::mat4 yawRotation = Maths::mat4::rotation(control->yaw, up);
front = Maths::vec3(
(yawRotation * Maths::vec4(front, 1.0f)).values[0],
(yawRotation * Maths::vec4(front, 1.0f)).values[1],
(yawRotation * Maths::vec4(front, 1.0f)).values[2]
).normalize();
Maths::mat4 pitchRotation = Maths::mat4::rotation(control->pitch, front.cross(up));
front = Maths::vec3(
(pitchRotation * Maths::vec4(front, 1.0f)).values[0],
(pitchRotation * Maths::vec4(front, 1.0f)).values[1],
(pitchRotation * Maths::vec4(front, 1.0f)).values[2]
).normalize();
up = Maths::vec3(
(pitchRotation * Maths::vec4(up, 1.0f)).values[0],
(pitchRotation * Maths::vec4(up, 1.0f)).values[1],
(pitchRotation * Maths::vec4(up, 1.0f)).values[2]
).normalize();
control->pitch = 0.0f;
control->yaw = 0.0f;
control->roll = 0.0f;
viewMatrix = Maths::mat4::lookat(position, front, up);
}
|
/*
Multicolor Fade
This example code is in the public domain.
Codice per il fade continuo di tre colori in formato RGB 0-255
.--.
| .-.|
|T ||
[_|__|_]
| |
| |
| |
Make it work : Done
Make it right : Done
Make it fast : Work in progress :D
*/
//numerazione pin (variabile ausilira; non toccare)
int r = 9;
int g = 10;
int b = 11;
//numero di colori da alternare
int c = 7;
//velocità del fade
int rit = 30;
//colore voluto in RGB (modificabile da 0 a 255) [leggere in verticale ;p ]
int rv[7] = {156, 253, 140, 150, 120, 42, 200};
int gv[7] = {200, 82, 152, 255, 140, 150, 200};
int bv[7] = {45, 120, 200, 50, 255, 200, 200};
//campionamento dei colori (possibilmente multipli di 5 :p )
int fade = 100;
//valore incrementale dei led (variabile ausilira; non toccare)
int ri[7];
int gi[7];
int bi[7];
//luminosità di partenza (variabile ausiliaria; non toccare)
int aus1 = 0;
int aus2 = 0;
int count = 0;
//variabili ausiliare dell'uscita (variabile ausiliaria; non toccare)
float ru[7];
float gu[7];
float bu[7];
void setup() {
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
for (count = 1; count < c; count++)
{
ri[count]=rv[count]/fade;
gi[count]=gv[count]/fade;
bi[count]=bv[count]/fade;
}
}
//comincia il fade del primo colore
void loop() {
//scrive sulla seriale il valore del colore
Serial.print("r");
Serial.print(rv[aus2]);
Serial.print(" g");
Serial.print(gv[aus2]);
Serial.print(" b");
Serial.println(bv[aus2]);
do {
aus1++;
analogWrite(r,ru[aus2]);
analogWrite(b,bu[aus2]);
analogWrite(g,gu[aus2]);
ru[aus2]=ru[aus2]+ri[aus2];
gu[aus2]=gu[aus2]+gi[aus2];
bu[aus2]=bu[aus2]+bi[aus2];
delay(rit) ;
}
while (aus1<=fade);
//Adesso comincia il fade inverso e azzeriamo l'ausiliare 1
aus1=0;
do {
aus1++;
analogWrite(r,ru[aus2]);
analogWrite(b,bu[aus2]);
analogWrite(g,gu[aus2]);
ru[aus2]=ru[aus2]-ri[aus2];
gu[aus2]=gu[aus2]-gi[aus2];
bu[aus2]=bu[aus2]-bi[aus2];
delay(rit) ;
}
while (aus1<=fade);
//se aus2 arriva a "c" (il ciclo ha terminato di fadare i colori, il ciclo ricomincia dal primo colore
aus1=0;
if (aus2>=c)
aus2=0;
else
aus2++;
}
|
/*
* File: String.cpp
* Author: gmena
*
* Created on 23 de agosto de 2014, 11:06 AM
*/
#include "String.h"
using namespace std;
Str::Str(void){}
int Str::findPosition(string target,string filter, int limit)
{
int count = 0;
int find = 0;
string replace("");
while((find = target.find_first_of(filter))!= string::npos)
{
this->replaceStr(filter, replace , target);
if(++count == limit)
{
break;
}
}
return find + 3;
}
string Str::replaceStr(string &search, string &replace, string &target)
{
if(target.find(search) != string::npos){
return target.replace(target.find(search), search.size(), replace);
}
}
string Str::replaceAll(string &search, string &replace, string &target)
{
while (target.find(search) != string::npos)
{
this->replaceStr(search, replace, target);
}
}
string Str::subStr(string &target, int to, int from)
{
return target.substr(to, from);
}
|
//============================================================================
// Name : C_showBits.cpp
// Author : Cristian Mosquera
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <stdio.h>
#include <climits>
using namespace std;
void displayBits( unsigned int value ); // prototype
int main( void )
{
unsigned int x; // variable to hold user input
printf( "Enter a nonnegative int: " );
fflush( stdout );
scanf( "%u", &x );
displayBits( x );
return 0;
} // end main
// display bits of an unsigned int value
void displayBits( unsigned int value )
{
unsigned int c; // counter
// define displayMask and left shift 31 bits
unsigned int displayMask = 1 << (CHAR_BIT * sizeof(unsigned int) - 1);
//unsigned int displayMask = 1 << 31;
printf( "%10u = ", value );
// loop through bits
for ( c = 1; c <= CHAR_BIT * sizeof(unsigned int); ++c ) {
putchar( value & displayMask ? '1' : '0' );
value <<= 1; // shift value left by 1
// same as value = value << 1
if ( c % 8 == 0 ) { // output space after 8 bits
putchar( ' ' );
} // end if
} // end for
putchar( '\n' );
} // end function displayBits
|
#include <iostream>
#include <map>
using namespace std;
#define toBraille 'S'
#define toNum 'B'
#define nLayers 3
#define nColumns 2
#define nDigits 10
#define zeroInChar 48
typedef struct {
char matrix[nLayers][nColumns];
char digit;
} brailleScript;
bool operator==(const brailleScript &bs1, const brailleScript &bs2) {
for (int i = 0; i < nLayers; ++i) {
for (int j = 0; j < nColumns; ++j) {
if (bs1.matrix[i][j] != bs2.matrix[i][j]) return false;
}
}
return true;
}
brailleScript zero = {{'.', '*', '*', '*', '.', '.'}, '0'};
brailleScript one = {{'*', '.', '.', '.', '.', '.'}, '1'};
brailleScript two = {{'*', '.', '*', '.', '.', '.'}, '2'};
brailleScript tree = {{'*', '*', '.', '.', '.', '.'}, '3'};
brailleScript four = {{'*', '*', '.', '*', '.', '.'}, '4'};
brailleScript five = {{'*', '.', '.', '*', '.', '.'}, '5'};
brailleScript six = {{'*', '*', '*', '.', '.', '.'}, '6'};
brailleScript seven = {{'*', '*', '*', '*', '.', '.'}, '7'};
brailleScript eight = {{'*', '.', '*', '*', '.', '.'}, '8'};
brailleScript nine = {{'.', '*', '*', '.', '.', '.'}, '9'};
brailleScript brailleScripts[nDigits] = {zero, one, two, tree, four, five, six, seven, eight, nine};
class Braille {
private:
brailleScript brailleScript1;
int lineCounter;
void setNum() {
if (lineCounter == nLayers) {
for (int i = 0; i < nDigits; ++i) {
if (brailleScripts[i] == brailleScript1) brailleScript1.digit = brailleScripts[i].digit;
}
}
}
public:
Braille() {
lineCounter = 0;
brailleScript1.digit = '\0';
}
void setMatrix (string input) {
if (lineCounter < nLayers) {
for (int i = 0; i < nColumns; ++i) {
brailleScript1.matrix[lineCounter][i] = input[i];
}
lineCounter++;
}
}
void printNum() {
if (brailleScript1.digit == '\0') {
setNum();
}
cout << brailleScript1.digit;
}
};
int main() {
int len;
char translation;
string input;
while (true) {
cin >> len;
if (len == 0) break;
cin >> translation;
if (translation == toBraille) {
cin >> input;
for (int l = 0; l < nLayers; ++l) {
for (int d = 0; d < len; ++d) {
for (int c = 0; c < nColumns; ++c) {
cout << brailleScripts[input[d] - zeroInChar].matrix[l][c];
}
if (d == len - 1) cout << endl;
else cout << ' ';
}
}
} else if (translation == toNum) {
Braille brailles[len];
for (int k = 0; k < len; ++k) {
Braille braille;
brailles[k] = braille;
}
for (int i = 0; i < nLayers; ++i) {
for (int j = 0; j < len; ++j) {
cin >> input;
brailles[j].setMatrix(input);
}
}
for (int l = 0; l < len; ++l) {
brailles[l].printNum();
} cout << endl;
}
}
return 0;
}
|
#include "stdafx.h"
#include "UMosesWorld.h"
#include "CBox.h"
#include "CDirectionalLight.h"
#include "CCharacter.h"
IMPLEMENT_CLASS(UMosesWorld);
UMosesWorld::UMosesWorld()
{
Box = new CBox(SideType_Inside);
Box->m_Scale = TVector3(100.0f,100.0f,100.0f);
Box->UpdateTransform();
AddThing(Box);
DirectionalLight = new CDirectionalLight();
DirectionalLight->m_Location = TVector3(0.0f, 100.0f, 0.0f);
DirectionalLight->UpdateTransform();
//AddThing(DirectionalLight);
Character = new CCharacter();
Character->UpdateTransform();
AddThing(Character);
}
UMosesWorld::~UMosesWorld()
{
}
bool UMosesWorld::DestroyWorld()
{
__super::DestroyWorld();
delete Box;
delete DirectionalLight;
delete Character;
return true;
}
bool UMosesWorld::Tick(DWORD dTime)
{
__super::Tick(dTime);
return true;
}
|
// SimulationDocumentManager.h: interface for the SimulationDocumentManager class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SIMULATIONDOCUMENTMANAGER_H__02F90CF5_0D86_4A44_9B66_CC9C9A3D5C36__INCLUDED_)
#define AFX_SIMULATIONDOCUMENTMANAGER_H__02F90CF5_0D86_4A44_9B66_CC9C9A3D5C36__INCLUDED_
#include <jni.h>
class SimulationDocumentManager
{
public:
SimulationDocumentManager();
virtual ~SimulationDocumentManager();
static jint getDocumentWidth(JNIEnv *, jobject);
static jint getDocumentHeight(JNIEnv *, jobject);
};
#endif // !defined(AFX_SIMULATIONDOCUMENTMANAGER_H__02F90CF5_0D86_4A44_9B66_CC9C9A3D5C36__INCLUDED_)
|
#include "Qfloat.h"
unsigned int* Qfloat::getData() const
{
unsigned int* Result = new unsigned int[4];
for (int i = 0; i < 4; i++)
Result[i] = this->data[i];
return Result;
}
void Qfloat::setData(int viTrim, unsigned int Data)
{
this->data[viTrim] = Data;
}
bool* DecToBin15Bit(unsigned long long int Data15Bit, int &size, bool want) //ham chuyen dec to bin max la 15 bit
{
string temp;
if (want == false)
{
unsigned long long int x;
int i = 0;
while (Data15Bit > 0)
{
x = Data15Bit % 2;
temp.push_back(x);
Data15Bit = Data15Bit / 2;
i++;
}
int chay = i;
size = chay;
int *binaryNum = new int[temp.size()];
bool *Res = new bool[temp.size()];
for (int j = 0; j < chay; j++)
{
binaryNum[j] = temp[j];
}
for (int j = 0; j < chay; j++)
{
Res[i - 1] = binaryNum[j];
i--;
}
return Res;
delete[]Res;
}
else
{
bool Res[15];
int binaryNum[15];
// counter for binary array
int i = 0;
while (Data15Bit > 0)
{
// storing remainder in binary array
binaryNum[i] = Data15Bit % 2;
Data15Bit = Data15Bit / 2;
i++;
}
if (i < 15)
{
for (int run = 14; run >= i; run--)
{
binaryNum[run] = 0;
}
}
int temp = 14;
for (int j = 0; j <15; j++)
{
Res[temp] = binaryNum[j];
temp--;
}
return Res;
}
};
unsigned long long int NguyenSangSo(string x)
{
int l1 = x.length();
unsigned long long int num1 = 0;
for (int i = l1 - 1; i >= 0; --i)
{
num1 += (int)(x[i] - '0') * pow(10, l1 - i - 1);
}
return num1;
}
bool* StrDecToBin(string Dec)
{
bool res[128];
string tempDec = Dec;
bool Negative = false;
if (tempDec[0] == '-') //kiem tra so am
{
tempDec.erase(tempDec.begin());
Negative = true;
res[127] = 1;
}
else res[127] = 0;
//tach phan nguyen va frac khoi chuoi
bool resFrac[112];
string tempRes15Bit;
string tempFrac;
int size = 0;
bool ktCoPhanFrac = false;
for (int i = 0; i < Dec.length(); i++)
{
if (Dec[i] == '.')
{
ktCoPhanFrac = true;
break;
}
}
int run = 0;
if (ktCoPhanFrac == false)
{
while (tempDec[run] != '\0')
{
tempRes15Bit.push_back(tempDec[run]);
run++;
}
tempFrac.push_back('.');
tempFrac.push_back('0');
}
else
{
while (tempDec[run] != '.')
{
tempRes15Bit.push_back(tempDec[run]);
run++;
}
while (tempDec[run] != '\0')
{
tempFrac.push_back(tempDec[run]);
run++;
}
}
if (tempFrac[0] == '.') //kiem tra coi co dau cham dau chuoi khong neu co thi xoa
{
tempFrac.erase(tempFrac.begin());
}
//doi phan so nguyen tu string sang so;
unsigned long long int nguyen = NguyenSangSo(tempRes15Bit);
//doi phan Frac tu string sang so
int sizeFrac = tempFrac.size();
long double frac = NguyenSangSo(tempFrac) / pow(10, sizeFrac);
int dichNguyen;
DecToBin15Bit(nguyen, dichNguyen, false); //dich qua bao nhieu bit
bool* res15Bit = new bool[dichNguyen];
//doi phan nguyen sang bin
for (int i = 0; i < dichNguyen; i++)
{
if (DecToBin15Bit(nguyen, dichNguyen, false)[i] == true)
{
res15Bit[i] = true;
}
else res15Bit[i] = false;
}
dichNguyen--;
int soMuE = 16383 + dichNguyen; //so mu E
//chuyen phan da dich (cua nguyen) sang frac
int lapDayFrac = 111 - dichNguyen + 1;
int tempLDF = lapDayFrac;
run = 1;
if (lapDayFrac != 111)
{
for (int i = 111; i >=tempLDF; i--)
{
if (res15Bit[run] == true)
{
resFrac[i] = true;
}
else resFrac[i] = false;
run++;
}
}
//doi frac sang bin
int dem = 0;
while (lapDayFrac!=0)
{
lapDayFrac--;
frac = frac * 2;
int fract_bit = frac;
if (fract_bit == 1)
{
frac = frac - fract_bit;
resFrac[lapDayFrac] = true;
}
else
resFrac[lapDayFrac] = false;
}
//doi so so mu E
for (int i = 0; i < 15; i++)
{
if (DecToBin15Bit(soMuE, dichNguyen, true)[i] == true)
{
res15Bit[i] = true;
}
else res15Bit[i] = false;
}
//dua so mu E vao trong chuoi ket qua
run = 0;
for (int i = 126; i >= 112; i--)
{
if (res15Bit[run] == true)
{
res[i] = true;
}
else res[i] = false;
run++;
}
// dua so frac vao ket qua
run = 0;
for (int i = 0; i < 112; i++)
{
if (resFrac[run] == true)
{
res[i] = true;
}
else res[i] = false;
run++;
}
//doi res lai do code nguoc
bool tempRev[128];
int runRev = 127;
for (int i = 0; i < 128; i++)
{
tempRev[runRev] = res[i];
runRev--;
}
return tempRev;
}
|
#ifndef SARIBBONLINEEDIT_H
#define SARIBBONLINEEDIT_H
#include "SARibbonGlobal.h"
#include <QLineEdit>
class SA_RIBBON_EXPORT SARibbonLineEdit : public QLineEdit
{
Q_OBJECT
public:
SARibbonLineEdit(QWidget *parent = Q_NULLPTR);
};
#endif // SARIBBONLINEEDIT_H
|
#include <iostream>
#include <tclap/CmdLine.h>
#include "SRSRawFile.h"
#include "vmmef.h"
#include "event.h"
#include "Pedestal.h"
#include "HDF5File.h"
int verbose = 0; // global verbosity level
void buildDAQMap(std::string str, std::vector<size_t >& daqMap) {
std::stringstream ss(str); // Turn the string into a stream.
std::string idx;
while(std::getline(ss, idx, ','))
{
size_t i = std::stoi(idx);
daqMap.push_back(i);
}
}
int main(int argc, char** argv)
{
// A few safety measures against DATE's event.h
assert(sizeof(uint32_t) == sizeof(long32));
assert(sizeof(eventHeaderStruct) == EVENT_HEAD_BASE_SIZE);
Histogram* histogram = NULL;
Pedestal* pedestal = NULL;
HDF5File* hdf5File = NULL;
std::vector<size_t > daqMap;
try
{
// Setting up the command line perser
TCLAP::CmdLine cmd("Event formation proto type for the VMM3", ' ', "0.001");
TCLAP::ValueArg<std::string> dataFile_("d","data","Name of raw data file",false,"","filename",cmd);
TCLAP::ValueArg<int> numEvents_("n","nevent","Number of events to read from file",false,-1,"int",cmd);
TCLAP::ValueArg<int> numPedEvents_("N","nped","Number of events to read from pedestal file",false,-1,"int",cmd);
TCLAP::ValueArg<std::string> pedFile_("p","pedestal","Name of file containing pedestal data", false,"","filename",cmd);
TCLAP::ValueArg<std::string> aggFile_("a","aggregate","Aggregate the data in file in the same manner as the pedestal", false,"","filename",cmd);
TCLAP::ValueArg<std::string> hdf5File_("o","hdf5","Write output to HDF5 file <filename>", false,"","filename",cmd);
TCLAP::ValueArg<std::string> x_("x","Xmap","Comma separated list of DAQ indexes mapping to the X projection", false,"1,0","int,int",cmd);
TCLAP::ValueArg<std::string> y_("y","Ymap","Comma separated list of DAQ indexes mapping to the Y projection", false,"3,2","int,int",cmd);
TCLAP::ValueArg<int> verbose_("v","verbose","Level of verbosity [0-1]",false,0,"int",cmd);
// Parsing commandline paramneters
cmd.parse(argc, argv);
std::string dataFileName = dataFile_.getValue();
std::string pedestalFileName = pedFile_.getValue();
std::string aggregateFileName = aggFile_.getValue();
std::string hdf5FileName = hdf5File_.getValue();
int numEvents = numEvents_.getValue();
int numPedEvents = numPedEvents_.getValue();
verbose = verbose_.getValue();
buildDAQMap(x_.getValue(),daqMap);
if (daqMap.size() != DAQ_CHANNELS/2)
{
std::cerr << "Xmap must consist of " << DAQ_CHANNELS/2 << " elements." << std::endl;
return 1;
}
buildDAQMap(y_.getValue(),daqMap);
if (daqMap.size() != DAQ_CHANNELS)
{
std::cerr << "Ymap must consist of " << DAQ_CHANNELS/2 << " elements." << std::endl;
return 1;
}
if (!hdf5FileName.empty())
{
hdf5File = new HDF5File(hdf5FileName);
}
// Start processing
if (!pedestalFileName.empty())
{
SRSRawFile pedFile(pedestalFileName,daqMap);
histogram = new Histogram(pedFile, numPedEvents);
pedestal = new Pedestal(*histogram);
if (hdf5File)
hdf5File->addAggregate(pedestal,histogram, "/pedestal");
}
if (!aggregateFileName.empty())
{
SRSRawFile aggFile(aggregateFileName,daqMap);
histogram = new Histogram(aggFile, numPedEvents);
pedestal = new Pedestal(*histogram);
if (hdf5File)
hdf5File->addAggregate(pedestal,histogram,"/aggregate");
}
if (!dataFileName.empty())
{
SRSRawFile dataFile(dataFileName,daqMap);
if (hdf5File)
hdf5File->addEvents(dataFile,numEvents);
}
}
catch (TCLAP::ArgException &e)
{
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
}
catch (std::exception e)
{
std::cerr << "error: " << e.what() << std::endl;
}
// Clean up
if (pedestal)
delete pedestal;
if (histogram)
delete histogram;
if (hdf5File)
delete hdf5File;
return 0;
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2006-2010 MStar Semiconductor, Inc.
// All rights reserved.
//
// Unless otherwise stipulated in writing, any and all information contained
// herein regardless in any format shall remain the sole proprietary of
// MStar Semiconductor Inc. and be kept in strict confidence
// (''MStar Confidential Information'') by the recipient.
// Any unauthorized act including without limitation unauthorized disclosure,
// copying, use, reproduction, sale, distribution, modification, disassembling,
// reverse engineering and compiling of the contents of MStar Confidential
// Information is unlawful and strictly prohibited. MStar hereby reserves the
// rights to any and all damages, losses, costs and expenses resulting therefrom.
//
////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// This file is automatically generated by SkinTool [Version:0.2.3][Build:Jun 14 2017 09:17:51]
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////
// MAINFRAME styles..
/////////////////////////////////////////////////////
// SUBLANG_BG_PANE styles..
/////////////////////////////////////////////////////
// SUBLANG_BG_C styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Sublang_Bg_C_Normal_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_89 },
{ CP_NOON, 0 },
};
#define _Zui_Sublang_Bg_C_Focus_DrawStyle _Zui_Sublang_Bg_C_Normal_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_BG_L styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Sublang_Bg_L_Normal_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_88 },
{ CP_NOON, 0 },
};
#define _Zui_Sublang_Bg_L_Focus_DrawStyle _Zui_Sublang_Bg_L_Normal_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_BG_R styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Sublang_Bg_R_Normal_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_90 },
{ CP_NOON, 0 },
};
#define _Zui_Sublang_Bg_R_Focus_DrawStyle _Zui_Sublang_Bg_R_Normal_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_TOP_HALF_BANNER_TITLE styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Sublang_Top_Half_Banner_Title_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_886 },
{ CP_NOON, 0 },
};
#define _Zui_Sublang_Top_Half_Banner_Title_Focus_DrawStyle _Zui_Sublang_Top_Half_Banner_Title_Normal_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_BOTTOM_HALF_OK_BTN styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Sublang_Bottom_Half_Ok_Btn_Normal_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_36 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// SUBLANG_LIST_PANE styles..
/////////////////////////////////////////////////////
// SUBLANG_ITEM0 styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Sublang_Item0_Focus_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_126 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// SUBLANG_ITEM0_ICON_TTX styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Sublang_Item0_Icon_Ttx_Normal_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_203 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Sublang_Item0_Icon_Ttx_Focus_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_204 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// SUBLANG_ITEM0_ICON_HOH styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Sublang_Item0_Icon_Hoh_Normal_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_205 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Sublang_Item0_Icon_Hoh_Focus_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_206 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// SUBLANG_ITEM0_TEXT styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Sublang_Item0_Text_Normal_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_601 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Sublang_Item0_Text_Focus_DrawStyle[] =
{
{ CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_887 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// SUBLANG_ITEM0_ICON_HD styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Sublang_Item0_Icon_Hd_Normal_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_207 },
{ CP_NOON, 0 },
};
static DRAWSTYLE _MP_TBLSEG _Zui_Sublang_Item0_Icon_Hd_Focus_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_208 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// SUBLANG_ITEM0_ICON_UPDOWN_ARROW_0 styles..
static DRAWSTYLE _MP_TBLSEG _Zui_Sublang_Item0_Icon_Updown_Arrow_0_Focus_DrawStyle[] =
{
{ CP_BITMAP, CP_ZUI_BITMAP_INDEX_127 },
{ CP_NOON, 0 },
};
/////////////////////////////////////////////////////
// SUBLANG_ITEM1 styles..
#define _Zui_Sublang_Item1_Focus_DrawStyle _Zui_Sublang_Item0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM1_ICON_TTX styles..
#define _Zui_Sublang_Item1_Icon_Ttx_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Normal_DrawStyle
#define _Zui_Sublang_Item1_Icon_Ttx_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM1_ICON_HOH styles..
#define _Zui_Sublang_Item1_Icon_Hoh_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Normal_DrawStyle
#define _Zui_Sublang_Item1_Icon_Hoh_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM1_TEXT styles..
#define _Zui_Sublang_Item1_Text_Normal_DrawStyle _Zui_Sublang_Item0_Text_Normal_DrawStyle
#define _Zui_Sublang_Item1_Text_Focus_DrawStyle _Zui_Sublang_Item0_Text_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM1_ICON_HD styles..
#define _Zui_Sublang_Item1_Icon_Hd_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Normal_DrawStyle
#define _Zui_Sublang_Item1_Icon_Hd_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM0_ICON_UPDOWN_ARROW_1 styles..
#define _Zui_Sublang_Item0_Icon_Updown_Arrow_1_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Updown_Arrow_0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM2 styles..
#define _Zui_Sublang_Item2_Focus_DrawStyle _Zui_Sublang_Item0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM2_ICON_TTX styles..
#define _Zui_Sublang_Item2_Icon_Ttx_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Normal_DrawStyle
#define _Zui_Sublang_Item2_Icon_Ttx_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM2_ICON_HOH styles..
#define _Zui_Sublang_Item2_Icon_Hoh_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Normal_DrawStyle
#define _Zui_Sublang_Item2_Icon_Hoh_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM2_TEXT styles..
#define _Zui_Sublang_Item2_Text_Normal_DrawStyle _Zui_Sublang_Item0_Text_Normal_DrawStyle
#define _Zui_Sublang_Item2_Text_Focus_DrawStyle _Zui_Sublang_Item0_Text_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM2_ICON_HD styles..
#define _Zui_Sublang_Item2_Icon_Hd_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Normal_DrawStyle
#define _Zui_Sublang_Item2_Icon_Hd_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM0_ICON_UPDOWN_ARROW_2 styles..
#define _Zui_Sublang_Item0_Icon_Updown_Arrow_2_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Updown_Arrow_0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM3 styles..
#define _Zui_Sublang_Item3_Focus_DrawStyle _Zui_Sublang_Item0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM3_ICON_TTX styles..
#define _Zui_Sublang_Item3_Icon_Ttx_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Normal_DrawStyle
#define _Zui_Sublang_Item3_Icon_Ttx_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM3_ICON_HOH styles..
#define _Zui_Sublang_Item3_Icon_Hoh_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Normal_DrawStyle
#define _Zui_Sublang_Item3_Icon_Hoh_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM3_TEXT styles..
#define _Zui_Sublang_Item3_Text_Normal_DrawStyle _Zui_Sublang_Item0_Text_Normal_DrawStyle
#define _Zui_Sublang_Item3_Text_Focus_DrawStyle _Zui_Sublang_Item0_Text_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM3_ICON_HD styles..
#define _Zui_Sublang_Item3_Icon_Hd_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Normal_DrawStyle
#define _Zui_Sublang_Item3_Icon_Hd_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM0_ICON_UPDOWN_ARROW_3 styles..
#define _Zui_Sublang_Item0_Icon_Updown_Arrow_3_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Updown_Arrow_0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM4 styles..
#define _Zui_Sublang_Item4_Focus_DrawStyle _Zui_Sublang_Item0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM4_ICON_TTX styles..
#define _Zui_Sublang_Item4_Icon_Ttx_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Normal_DrawStyle
#define _Zui_Sublang_Item4_Icon_Ttx_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM4_ICON_HOH styles..
#define _Zui_Sublang_Item4_Icon_Hoh_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Normal_DrawStyle
#define _Zui_Sublang_Item4_Icon_Hoh_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM4_TEXT styles..
#define _Zui_Sublang_Item4_Text_Normal_DrawStyle _Zui_Sublang_Item0_Text_Normal_DrawStyle
#define _Zui_Sublang_Item4_Text_Focus_DrawStyle _Zui_Sublang_Item0_Text_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM4_ICON_HD styles..
#define _Zui_Sublang_Item4_Icon_Hd_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Normal_DrawStyle
#define _Zui_Sublang_Item4_Icon_Hd_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM0_ICON_UPDOWN_ARROW_4 styles..
#define _Zui_Sublang_Item0_Icon_Updown_Arrow_4_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Updown_Arrow_0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM5 styles..
#define _Zui_Sublang_Item5_Focus_DrawStyle _Zui_Sublang_Item0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM5_ICON_TTX styles..
#define _Zui_Sublang_Item5_Icon_Ttx_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Normal_DrawStyle
#define _Zui_Sublang_Item5_Icon_Ttx_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM5_ICON_HOH styles..
#define _Zui_Sublang_Item5_Icon_Hoh_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Normal_DrawStyle
#define _Zui_Sublang_Item5_Icon_Hoh_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM5_TEXT styles..
#define _Zui_Sublang_Item5_Text_Normal_DrawStyle _Zui_Sublang_Item0_Text_Normal_DrawStyle
#define _Zui_Sublang_Item5_Text_Focus_DrawStyle _Zui_Sublang_Item0_Text_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM5_ICON_HD styles..
#define _Zui_Sublang_Item5_Icon_Hd_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Normal_DrawStyle
#define _Zui_Sublang_Item5_Icon_Hd_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM0_ICON_UPDOWN_ARROW_5 styles..
#define _Zui_Sublang_Item0_Icon_Updown_Arrow_5_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Updown_Arrow_0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM6 styles..
#define _Zui_Sublang_Item6_Focus_DrawStyle _Zui_Sublang_Item0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM6_ICON_TTX styles..
#define _Zui_Sublang_Item6_Icon_Ttx_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Normal_DrawStyle
#define _Zui_Sublang_Item6_Icon_Ttx_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM6_ICON_HOH styles..
#define _Zui_Sublang_Item6_Icon_Hoh_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Normal_DrawStyle
#define _Zui_Sublang_Item6_Icon_Hoh_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM6_TEXT styles..
#define _Zui_Sublang_Item6_Text_Normal_DrawStyle _Zui_Sublang_Item0_Text_Normal_DrawStyle
#define _Zui_Sublang_Item6_Text_Focus_DrawStyle _Zui_Sublang_Item0_Text_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM6_ICON_HD styles..
#define _Zui_Sublang_Item6_Icon_Hd_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Normal_DrawStyle
#define _Zui_Sublang_Item6_Icon_Hd_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM0_ICON_UPDOWN_ARROW_6 styles..
#define _Zui_Sublang_Item0_Icon_Updown_Arrow_6_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Updown_Arrow_0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM7 styles..
#define _Zui_Sublang_Item7_Focus_DrawStyle _Zui_Sublang_Item0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM7_ICON_TTX styles..
#define _Zui_Sublang_Item7_Icon_Ttx_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Normal_DrawStyle
#define _Zui_Sublang_Item7_Icon_Ttx_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM7_ICON_HOH styles..
#define _Zui_Sublang_Item7_Icon_Hoh_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Normal_DrawStyle
#define _Zui_Sublang_Item7_Icon_Hoh_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM7_TEXT styles..
#define _Zui_Sublang_Item7_Text_Normal_DrawStyle _Zui_Sublang_Item0_Text_Normal_DrawStyle
#define _Zui_Sublang_Item7_Text_Focus_DrawStyle _Zui_Sublang_Item0_Text_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM7_ICON_HD styles..
#define _Zui_Sublang_Item7_Icon_Hd_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Normal_DrawStyle
#define _Zui_Sublang_Item7_Icon_Hd_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM0_ICON_UPDOWN_ARROW_7 styles..
#define _Zui_Sublang_Item0_Icon_Updown_Arrow_7_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Updown_Arrow_0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM8 styles..
#define _Zui_Sublang_Item8_Focus_DrawStyle _Zui_Sublang_Item0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM8_ICON_TTX styles..
#define _Zui_Sublang_Item8_Icon_Ttx_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Normal_DrawStyle
#define _Zui_Sublang_Item8_Icon_Ttx_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM8_ICON_HOH styles..
#define _Zui_Sublang_Item8_Icon_Hoh_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Normal_DrawStyle
#define _Zui_Sublang_Item8_Icon_Hoh_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM8_TEXT styles..
#define _Zui_Sublang_Item8_Text_Normal_DrawStyle _Zui_Sublang_Item0_Text_Normal_DrawStyle
#define _Zui_Sublang_Item8_Text_Focus_DrawStyle _Zui_Sublang_Item0_Text_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM8_ICON_HD styles..
#define _Zui_Sublang_Item8_Icon_Hd_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Normal_DrawStyle
#define _Zui_Sublang_Item8_Icon_Hd_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM0_ICON_UPDOWN_ARROW_8 styles..
#define _Zui_Sublang_Item0_Icon_Updown_Arrow_8_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Updown_Arrow_0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM9 styles..
#define _Zui_Sublang_Item9_Focus_DrawStyle _Zui_Sublang_Item0_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM9_ICON_TTX styles..
#define _Zui_Sublang_Item9_Icon_Ttx_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Normal_DrawStyle
#define _Zui_Sublang_Item9_Icon_Ttx_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Ttx_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM9_ICON_HOH styles..
#define _Zui_Sublang_Item9_Icon_Hoh_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Normal_DrawStyle
#define _Zui_Sublang_Item9_Icon_Hoh_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hoh_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM9_TEXT styles..
#define _Zui_Sublang_Item9_Text_Normal_DrawStyle _Zui_Sublang_Item0_Text_Normal_DrawStyle
#define _Zui_Sublang_Item9_Text_Focus_DrawStyle _Zui_Sublang_Item0_Text_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM9_ICON_HD styles..
#define _Zui_Sublang_Item9_Icon_Hd_Normal_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Normal_DrawStyle
#define _Zui_Sublang_Item9_Icon_Hd_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Hd_Focus_DrawStyle
/////////////////////////////////////////////////////
// SUBLANG_ITEM0_ICON_UPDOWN_ARROW_9 styles..
#define _Zui_Sublang_Item0_Icon_Updown_Arrow_9_Focus_DrawStyle _Zui_Sublang_Item0_Icon_Updown_Arrow_0_Focus_DrawStyle
//////////////////////////////////////////////////////
// Window Draw Style List (normal, focused, disable)
WINDOWDRAWSTYLEDATA _MP_TBLSEG _GUI_WindowsDrawStyleList_Zui_Subtitle_Language[] =
{
// HWND_MAINFRAME
{ NULL, NULL, NULL },
// HWND_SUBLANG_BG_PANE
{ NULL, NULL, NULL },
// HWND_SUBLANG_BG_C
{ _Zui_Sublang_Bg_C_Normal_DrawStyle, _Zui_Sublang_Bg_C_Focus_DrawStyle, NULL },
// HWND_SUBLANG_BG_L
{ _Zui_Sublang_Bg_L_Normal_DrawStyle, _Zui_Sublang_Bg_L_Focus_DrawStyle, NULL },
// HWND_SUBLANG_BG_R
{ _Zui_Sublang_Bg_R_Normal_DrawStyle, _Zui_Sublang_Bg_R_Focus_DrawStyle, NULL },
// HWND_SUBLANG_TOP_HALF_BANNER_TITLE
{ _Zui_Sublang_Top_Half_Banner_Title_Normal_DrawStyle, _Zui_Sublang_Top_Half_Banner_Title_Focus_DrawStyle, NULL },
// HWND_SUBLANG_BOTTOM_HALF_OK_BTN
{ _Zui_Sublang_Bottom_Half_Ok_Btn_Normal_DrawStyle, NULL, NULL },
// HWND_SUBLANG_LIST_PANE
{ NULL, NULL, NULL },
// HWND_SUBLANG_ITEM0
{ NULL, _Zui_Sublang_Item0_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM0_ICON_TTX
{ _Zui_Sublang_Item0_Icon_Ttx_Normal_DrawStyle, _Zui_Sublang_Item0_Icon_Ttx_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM0_ICON_HOH
{ _Zui_Sublang_Item0_Icon_Hoh_Normal_DrawStyle, _Zui_Sublang_Item0_Icon_Hoh_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM0_TEXT
{ _Zui_Sublang_Item0_Text_Normal_DrawStyle, _Zui_Sublang_Item0_Text_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM0_ICON_HD
{ _Zui_Sublang_Item0_Icon_Hd_Normal_DrawStyle, _Zui_Sublang_Item0_Icon_Hd_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM0_ICON_UPDOWN_ARROW_0
{ NULL, _Zui_Sublang_Item0_Icon_Updown_Arrow_0_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM1
{ NULL, _Zui_Sublang_Item1_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM1_ICON_TTX
{ _Zui_Sublang_Item1_Icon_Ttx_Normal_DrawStyle, _Zui_Sublang_Item1_Icon_Ttx_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM1_ICON_HOH
{ _Zui_Sublang_Item1_Icon_Hoh_Normal_DrawStyle, _Zui_Sublang_Item1_Icon_Hoh_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM1_TEXT
{ _Zui_Sublang_Item1_Text_Normal_DrawStyle, _Zui_Sublang_Item1_Text_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM1_ICON_HD
{ _Zui_Sublang_Item1_Icon_Hd_Normal_DrawStyle, _Zui_Sublang_Item1_Icon_Hd_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM0_ICON_UPDOWN_ARROW_1
{ NULL, _Zui_Sublang_Item0_Icon_Updown_Arrow_1_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM2
{ NULL, _Zui_Sublang_Item2_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM2_ICON_TTX
{ _Zui_Sublang_Item2_Icon_Ttx_Normal_DrawStyle, _Zui_Sublang_Item2_Icon_Ttx_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM2_ICON_HOH
{ _Zui_Sublang_Item2_Icon_Hoh_Normal_DrawStyle, _Zui_Sublang_Item2_Icon_Hoh_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM2_TEXT
{ _Zui_Sublang_Item2_Text_Normal_DrawStyle, _Zui_Sublang_Item2_Text_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM2_ICON_HD
{ _Zui_Sublang_Item2_Icon_Hd_Normal_DrawStyle, _Zui_Sublang_Item2_Icon_Hd_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM0_ICON_UPDOWN_ARROW_2
{ NULL, _Zui_Sublang_Item0_Icon_Updown_Arrow_2_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM3
{ NULL, _Zui_Sublang_Item3_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM3_ICON_TTX
{ _Zui_Sublang_Item3_Icon_Ttx_Normal_DrawStyle, _Zui_Sublang_Item3_Icon_Ttx_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM3_ICON_HOH
{ _Zui_Sublang_Item3_Icon_Hoh_Normal_DrawStyle, _Zui_Sublang_Item3_Icon_Hoh_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM3_TEXT
{ _Zui_Sublang_Item3_Text_Normal_DrawStyle, _Zui_Sublang_Item3_Text_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM3_ICON_HD
{ _Zui_Sublang_Item3_Icon_Hd_Normal_DrawStyle, _Zui_Sublang_Item3_Icon_Hd_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM0_ICON_UPDOWN_ARROW_3
{ NULL, _Zui_Sublang_Item0_Icon_Updown_Arrow_3_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM4
{ NULL, _Zui_Sublang_Item4_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM4_ICON_TTX
{ _Zui_Sublang_Item4_Icon_Ttx_Normal_DrawStyle, _Zui_Sublang_Item4_Icon_Ttx_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM4_ICON_HOH
{ _Zui_Sublang_Item4_Icon_Hoh_Normal_DrawStyle, _Zui_Sublang_Item4_Icon_Hoh_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM4_TEXT
{ _Zui_Sublang_Item4_Text_Normal_DrawStyle, _Zui_Sublang_Item4_Text_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM4_ICON_HD
{ _Zui_Sublang_Item4_Icon_Hd_Normal_DrawStyle, _Zui_Sublang_Item4_Icon_Hd_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM0_ICON_UPDOWN_ARROW_4
{ NULL, _Zui_Sublang_Item0_Icon_Updown_Arrow_4_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM5
{ NULL, _Zui_Sublang_Item5_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM5_ICON_TTX
{ _Zui_Sublang_Item5_Icon_Ttx_Normal_DrawStyle, _Zui_Sublang_Item5_Icon_Ttx_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM5_ICON_HOH
{ _Zui_Sublang_Item5_Icon_Hoh_Normal_DrawStyle, _Zui_Sublang_Item5_Icon_Hoh_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM5_TEXT
{ _Zui_Sublang_Item5_Text_Normal_DrawStyle, _Zui_Sublang_Item5_Text_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM5_ICON_HD
{ _Zui_Sublang_Item5_Icon_Hd_Normal_DrawStyle, _Zui_Sublang_Item5_Icon_Hd_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM0_ICON_UPDOWN_ARROW_5
{ NULL, _Zui_Sublang_Item0_Icon_Updown_Arrow_5_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM6
{ NULL, _Zui_Sublang_Item6_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM6_ICON_TTX
{ _Zui_Sublang_Item6_Icon_Ttx_Normal_DrawStyle, _Zui_Sublang_Item6_Icon_Ttx_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM6_ICON_HOH
{ _Zui_Sublang_Item6_Icon_Hoh_Normal_DrawStyle, _Zui_Sublang_Item6_Icon_Hoh_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM6_TEXT
{ _Zui_Sublang_Item6_Text_Normal_DrawStyle, _Zui_Sublang_Item6_Text_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM6_ICON_HD
{ _Zui_Sublang_Item6_Icon_Hd_Normal_DrawStyle, _Zui_Sublang_Item6_Icon_Hd_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM0_ICON_UPDOWN_ARROW_6
{ NULL, _Zui_Sublang_Item0_Icon_Updown_Arrow_6_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM7
{ NULL, _Zui_Sublang_Item7_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM7_ICON_TTX
{ _Zui_Sublang_Item7_Icon_Ttx_Normal_DrawStyle, _Zui_Sublang_Item7_Icon_Ttx_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM7_ICON_HOH
{ _Zui_Sublang_Item7_Icon_Hoh_Normal_DrawStyle, _Zui_Sublang_Item7_Icon_Hoh_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM7_TEXT
{ _Zui_Sublang_Item7_Text_Normal_DrawStyle, _Zui_Sublang_Item7_Text_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM7_ICON_HD
{ _Zui_Sublang_Item7_Icon_Hd_Normal_DrawStyle, _Zui_Sublang_Item7_Icon_Hd_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM0_ICON_UPDOWN_ARROW_7
{ NULL, _Zui_Sublang_Item0_Icon_Updown_Arrow_7_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM8
{ NULL, _Zui_Sublang_Item8_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM8_ICON_TTX
{ _Zui_Sublang_Item8_Icon_Ttx_Normal_DrawStyle, _Zui_Sublang_Item8_Icon_Ttx_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM8_ICON_HOH
{ _Zui_Sublang_Item8_Icon_Hoh_Normal_DrawStyle, _Zui_Sublang_Item8_Icon_Hoh_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM8_TEXT
{ _Zui_Sublang_Item8_Text_Normal_DrawStyle, _Zui_Sublang_Item8_Text_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM8_ICON_HD
{ _Zui_Sublang_Item8_Icon_Hd_Normal_DrawStyle, _Zui_Sublang_Item8_Icon_Hd_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM0_ICON_UPDOWN_ARROW_8
{ NULL, _Zui_Sublang_Item0_Icon_Updown_Arrow_8_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM9
{ NULL, _Zui_Sublang_Item9_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM9_ICON_TTX
{ _Zui_Sublang_Item9_Icon_Ttx_Normal_DrawStyle, _Zui_Sublang_Item9_Icon_Ttx_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM9_ICON_HOH
{ _Zui_Sublang_Item9_Icon_Hoh_Normal_DrawStyle, _Zui_Sublang_Item9_Icon_Hoh_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM9_TEXT
{ _Zui_Sublang_Item9_Text_Normal_DrawStyle, _Zui_Sublang_Item9_Text_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM9_ICON_HD
{ _Zui_Sublang_Item9_Icon_Hd_Normal_DrawStyle, _Zui_Sublang_Item9_Icon_Hd_Focus_DrawStyle, NULL },
// HWND_SUBLANG_ITEM0_ICON_UPDOWN_ARROW_9
{ NULL, _Zui_Sublang_Item0_Icon_Updown_Arrow_9_Focus_DrawStyle, NULL },
};
|
#include "Unit.h"
#include "PhysicsUnits.h"
#include <algorithm>
namespace solar
{
SimData::units_t * SimData::operator->()
{
return &units;
}
const SimData::units_t * SimData::operator->() const
{
return &units;
}
SimData::units_t & SimData::operator*()
{
return units;
}
const SimData::units_t & SimData::operator*() const
{
return units;
}
Unit & SimData::operator[](size_t index)
{
return units[index];
}
const Unit & SimData::operator[](size_t index) const
{
return units[index];
}
SimData::units_t & SimData::Get()
{
return units;
}
const SimData::units_t & SimData::Get() const
{
return units;
}
void SimData::SetPhysUnits(PhysUnits::ratio newMass, PhysUnits::ratio newDist, PhysUnits::ratio newTime)
{
physUnits.mass = newMass;
physUnits.dist = newDist;
physUnits.time = newTime;
}
void SimData::SetPhysUnits(const PhysUnits & newPhysUnits)
{
physUnits = newPhysUnits;
}
const PhysUnits & SimData::GetPhysUnits() const
{
return physUnits;
}
void SimData::ConvertTo(PhysUnits::ratio newMass, PhysUnits::ratio newDist, PhysUnits::ratio newTime)
{
ConvertMassTo(newMass);
ConvertDistTo(newDist);
ConvertTimeTo(newTime);
}
void SimData::ConvertMassTo(PhysUnits::ratio newMass)
{
//IMPROVE redo epsilon math
if (abs(newMass - physUnits.mass) > epsilon<PhysUnits::ratio>)
{
PhysUnits::ratio ratio = physUnits.mass / newMass;
for (auto& unit : units)
unit.mass *= ratio;
physUnits.mass = newMass;
}
}
void SimData::ConvertDistTo(PhysUnits::ratio newDist)
{
//IMPROVE redo epsilon math
if (abs(newDist - physUnits.dist) > epsilon<PhysUnits::ratio>)
{
PhysUnits::ratio ratio = physUnits.dist / newDist;
for (auto& unit : units)
{
unit.pos *= ratio;
unit.vel *= ratio;
unit.radius *= ratio;
}
physUnits.dist = newDist;
}
}
void SimData::ConvertTimeTo(PhysUnits::ratio newTime)
{
//IMPROVE redo epsilon math
if (abs(newTime - physUnits.time) > epsilon<PhysUnits::ratio>)
{
PhysUnits::ratio ratio = physUnits.time / newTime;
for (auto& unit : units)
unit.vel /= ratio;//speed is in denominator
physUnits.time = newTime;
}
}
void SimData::Normalize()
{
if (units.size() == 0)
return;
double maxPos, maxMass, maxVel;
maxPos = maxMass = maxVel = std::numeric_limits<double>::min();
for (const auto& unit : units)
{
maxPos = std::max(maxPos, std::abs(unit.pos.x));
maxVel = std::max(maxVel, std::abs(unit.vel.x));
maxPos = std::max(maxPos, std::abs(unit.pos.y));
maxVel = std::max(maxVel, std::abs(unit.vel.y));
maxMass = std::max(maxMass, std::abs(unit.mass));
}
ConvertTo(physUnits.mass*maxMass, physUnits.dist*maxPos, physUnits.time* maxPos / maxVel);
}
PhysUnits::ratio SimData::RatioOfMassTo(PhysUnits::ratio newMass) const
{
return physUnits.mass / newMass;
}
PhysUnits::ratio SimData::RatioOfDistTo(PhysUnits::ratio newDist) const
{
return physUnits.dist / newDist;
}
PhysUnits::ratio SimData::RatioOfTimeTo(PhysUnits::ratio newTime) const
{
return physUnits.time / newTime;
}
}
|
/* SPDX-License-Identifier: LGPL-2.1 */
/*
* Copyright (C) 2020 VMware Inc, Yordan Karadzhov (VMware) <y.karadz@gmail.com>
*/
/**
* @file LatencyPlotDialog.hpp
* @brief Dialog class used by the atencyPlot plugin.
*/
#ifndef _KS_EFP_DIALOG_H
#define _KS_EFP_DIALOG_H
// KernelShark
#include "plugins/latency_plot.h"
#include "KsWidgetsLib.hpp"
class KsMainWindow;
/**
* The LatencyPlotDialog class provides a widget for selecting Trace event field to
* be visualized.
*/
class LatencyPlotDialog : public QDialog
{
Q_OBJECT
public:
explicit LatencyPlotDialog(QWidget *parent = nullptr);
void update();
KsWidgetsLib::KsEventFieldSelectWidget _efsWidgetA, _efsWidgetB;
KsMainWindow *_gui_ptr;
private:
QVBoxLayout _topLayout;
QGridLayout _fieldSelectLayout;
QHBoxLayout _buttonLayout;
QLabel _evtALabel, _evtBLabel;
QPushButton _applyButton, _resetButton, _cancelButton;
void _apply();
void _reset();
};
#endif
|
// https://www.luogu.com.cn/problem/P3372
// 洛谷 线段树
// 学习
#include <bits/stdc++.h>
using namespace std;
#define cin ios::sync_with_stdio(false); cin
const int M = 1 << 17;
int date[2 * M - 1];
int arr[2 * M - 1];
int b[2 * M - 1]; // 标记数组
void build(int s, int t, int p) {
// 对 [s,t] 区间建立线段树,当前根的编号为 p
if (s == t) {
date[s] = arr[s];
return ;
}
int m = (s + t) >> 1;
build(s, m, p << 1), build(m + 1, t, (p << 1) + 1);
// 递归对左右区间建树
date[p] = date[p << 1] + date[(p << 1) + 1];
}
// 区间值查询
int query(int l, int r, int s, int t, int p) {
if (t <= l || r <= s) {
return INT_MIN;
}
// [l,r] 为查询区间,[s,t] 为当前节点包含的区间,p 为当前节点的编号
if (l <= s && t <= r) {
// [l, r]完全包含[s, t] 直接返回当前值
return date[p];
}
int m = (s + t) >> 1;
int sum = 0;
if (l <= m) sum += query(l, r, s, m, p << 1);
if (r > m) sum += query(l, r, m + 1, t, (p << 1) + 1);
return sum;
}
// 区间修改 区间加上某个值
void update_add(int l, int r, int c, int s, int t, int p) {
// [l,r] 为修改区间,c为被修改的元素的变化量,[s,t] 为当前节点包含的区间,p
// 为当前节点的编号
if (l <= s && t <= r) {
date[p] += (t - s + 1) * c, b[p] = c;
return ;
}
// 当前区间为修改区间的子集时直接修改当前节点的值,然后打标记,结束修改
int m = (s + t) >> 1;
if (b[p] && s != t) {
// 如果当前节点的懒惰标记非空,则更新当前节点两个子节点的值和懒标记值
date[p << 1] += b[p] * (m - s + 1), date[p << 1 | 1] += b[p] * (t - m);
b[p << 1] += b[p], b[p << 1 | 1] += b[p];
b[p] = 0;
}
if (l <= m) update_add(l, r, c, s, m, p << 1);
if (r > m) update_add(l, r, c, m + 1, t, p << 1 | 1);
// 区间合并
date[p] = date[p << 1] + date[(p << 1) + 1];
}
// 区间查询(区间求和)
int getsum(int l, int r, int s, int t, int p) {
// [l,r] 为修改区间,c 为被修改的元素的变化量,[s,t] 为当前节点包含的区间,p
// 为当前节点的编号
if (l <= s && r >= t) {
return date[p];
}
int m = (s + t) >> 1;
if (b[p]) {
// // 如果当前节点的懒标记非空,则更新当前节点两个子节点的值和懒标记值
date[p << 1] += b[p] * (m - s + 1), date[(p << 1) + 1] += b[p] * (t - m);
b[p << 1] += b[p], b[p << 1 | 1] += b[p];
b[p] = 0;
}
int sum = 0;
if (l <= m) sum = getsum(l, r, s, m, p << 1);
if (r > m) sum += getsum(r, s, m + 1, t, p << 1 | 1);
return sum;
}
// 实现区间修改为某一个值而不是加上某一个值
void update(int l, int r, int c, int s, int t, int p) {
if (l <= s && r >= t) {
date[p] = (t - s + 1) * c, b[p] = c;
return ;
}
int m = (s + t) << 1;
if (b[p]) {
date[p << 1] = (m - s + 1) * b[p], date[p << 1 | 1] = b[p] * (t - m);
b[p << 1] = b[p << 1 | 1] = b[p];
b[p] = 0;
}
}
int getsum_u(int l, int r, int s, int t, int p) {
if (l <= s && t <= r) return date[p];
int m = (s + t) << 1;
if (b[p]) {
date[p << 1] = (m - s + 1) * b[p], date[(p << 1) + 1] = b[p] * (t - m);
b[p << 1] = b[p << 1 | 1] = b[p];
b[p] = 0;
}
int sum = 0;
if (l <= m) sum = getsum_u(l, r, s, m, p << 1);
if (r > m) sum += getsum_u(l, r, m + 1, t, p << 1 | 1);
return sum;
}
int main() {
return 0;
}
|
template <class Type>
Type trans(Type x){
return Type(2)/(Type(1) + exp(-Type(2) * x)) - Type(1);
}
template <class Type>
Type jacobiUVtrans( array<Type> logF){
// int nr=logF.rows(); //Cange to .rows eller .cols
// int nc=logF.cols();
int nr=logF.cols(); //Cange to .rows eller .cols
int nc=logF.rows();
matrix<Type> A(nc,nc);
for(int i=0; i<nc; ++i){
for(int j=0; j<nc; ++j){
A(i,j) = -1;
}
}
for(int i=0; i<nc; ++i){
A(0,i)=1;
}
for(int i=1; i<nc; ++i){
A(i,i-1)=nc-1;
}
A/=nc;
return nr*log(CppAD::abs(A.determinant()));
}
template<class Type>
matrix<Type> get_fvar(dataSet<Type> &dat, confSet &conf, paraSet<Type> &par, array<Type> &logF){
using CppAD::abs;
int stateDimF=logF.dim[0];
int timeSteps=logF.dim[1];
int stateDimN=conf.keyLogFsta.dim[1];
vector<Type> sdLogFsta=exp(par.logSdLogFsta);
array<Type> resF(stateDimF,timeSteps-1);
matrix<Type> fvar(stateDimF,stateDimF);
matrix<Type> fcor(stateDimF,stateDimF);
vector<Type> fsd(stateDimF);
if(conf.corFlag==0){
fcor.setZero();
}
for(int i=0; i<stateDimF; ++i){
fcor(i,i)=1.0;
}
if(conf.corFlag==1){
for(int i=0; i<stateDimF; ++i){
for(int j=0; j<i; ++j){
fcor(i,j)=trans(par.itrans_rho(0));
fcor(j,i)=fcor(i,j);
}
}
}
if(conf.corFlag==2){
for(int i=0; i<stateDimF; ++i){
for(int j=0; j<i; ++j){
fcor(i,j)=pow(trans(par.itrans_rho(0)),abs(Type(i-j)));
fcor(j,i)=fcor(i,j);
}
}
}
int i,j;
for(i=0; i<stateDimF; ++i){
for(j=0; j<stateDimN; ++j){
if(conf.keyLogFsta(0,j)==i)break;
}
fsd(i)=sdLogFsta(conf.keyVarF(0,j));
}
for(i=0; i<stateDimF; ++i){
for(j=0; j<stateDimF; ++j){
fvar(i,j)=fsd(i)*fsd(j)*fcor(i,j);
}
}
return fvar;
};
template <class Type>
Type nllF(dataSet<Type> &dat, confSet &conf, paraSet<Type> &par, array<Type> &logF, data_indicator<vector<Type>,Type> &keep, objective_function<Type> *of){
Type nll=0;
int stateDimF=logF.dim[0];
int timeSteps=logF.dim[1];
int stateDimN=conf.keyLogFsta.dim[1];
vector<Type> sdLogFsta=exp(par.logSdLogFsta);
array<Type> resF(stateDimF,timeSteps-1);
if(conf.corFlag==3){
return(nllFseparable(dat, conf, par, logF, keep ,of));
}
//density::MVNORM_t<Type> neg_log_densityF(fvar);
matrix<Type> fvar = get_fvar(dat, conf, par, logF);
MVMIX_t<Type> neg_log_densityF(fvar,Type(conf.fracMixF));
Eigen::LLT< Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> > lltCovF(fvar);
matrix<Type> LF = lltCovF.matrixL();
matrix<Type> LinvF = LF.inverse();
for(int i=1;i<timeSteps;i++){
resF.col(i-1) = LinvF*(vector<Type>(logF.col(i)-logF.col(i-1)));
if(dat.forecast.nYears > 0 && dat.forecast.forecastYear(i) > 0){
// Forecast
int forecastIndex = CppAD::Integer(dat.forecast.forecastYear(i))-1;
Type timeScale = dat.forecast.forecastCalculatedLogSdCorrection(forecastIndex);
nll += neg_log_densityF((logF.col(i) - (vector<Type>)dat.forecast.forecastCalculatedMedian.col(forecastIndex)) / timeScale) + log(timeScale) * Type(stateDimF);
SIMULATE_F(of){
if(dat.forecast.simFlag(0) == 0){
logF.col(i) = (vector<Type>)dat.forecast.forecastCalculatedMedian.col(forecastIndex) + neg_log_densityF.simulate() * timeScale;
}
}
}else{
nll+=neg_log_densityF(logF.col(i)-logF.col(i-1)); // F-Process likelihood
SIMULATE_F(of){
if(conf.simFlag(0)==0){
logF.col(i)=logF.col(i-1)+neg_log_densityF.simulate();
}
}
}
}
if(CppAD::Variable(keep.sum())){ // add wide prior for first state, but _only_ when computing ooa residuals
Type huge = 10;
for (int i = 0; i < stateDimF; i++) nll -= dnorm(logF(i, 0), Type(0), huge, true);
}
if(conf.resFlag==1){
ADREPORT_F(resF,of);
}
return nll;
}
template <class Type>
Type nllFseparable(dataSet<Type> &dat, confSet &conf, paraSet<Type> &par, array<Type> &logF, data_indicator<vector<Type>,Type> &keep, objective_function<Type> *of){
int stateDimF=logF.dim[0];
int timeSteps=logF.dim[1];
matrix<Type> SigmaU(stateDimF-1,stateDimF-1);
SigmaU.setZero();
vector<Type> sdU(stateDimF-1);
vector<Type> sdV(1);
for(int i=0; i<sdU.size(); ++i){
sdU(i) = exp(par.sepFlogSd(0));
}
sdV(0) = exp(par.sepFlogSd(1));
Type rhoU = trans(par.sepFlogitRho(0));
Type rhoV = trans(par.sepFlogitRho(1));
Type nll=0;
matrix<Type> logU(timeSteps,stateDimF-1);
logU.setZero();
vector<Type> logV(timeSteps);
logV.setZero();
for(int i=0; i<timeSteps; ++i){
if(dat.forecast.nYears > 0 && dat.forecast.forecastYear(i) > 0){
Rf_warning("Forecast with separable F is experimental");
int forecastIndex = CppAD::Integer(dat.forecast.forecastYear(i))-1;
vector<Type> logFtmp = (vector<Type>)dat.forecast.forecastCalculatedMedian.col(forecastIndex);
logV(i)=(logFtmp).mean();
for(int j=0; j<stateDimF-1; ++j){
logU(i,j)=logFtmp(j)-logV(i);
}
}else{
logV(i)=(logF).col(i).mean();
// }
// for(int i=0; i<timeSteps; ++i){
for(int j=0; j<stateDimF-1; ++j){
logU(i,j)=logF(j,i)-logV(i);
}
logV(i)=(logF).col(i).mean();
}
}
SigmaU.diagonal() = sdU*sdU;
density::MVNORM_t<Type> nldens(SigmaU);
for(int y=1; y<timeSteps; ++y){
vector<Type> diff=vector<Type>(logU.row(y))-rhoU*vector<Type>(logU.row(y-1))- par.sepFalpha.segment(0,par.sepFalpha.size()-1);
nll += nldens(diff);
SIMULATE_F(of){
if(conf.simFlag(0)==0){
vector<Type> uu = nldens.simulate();
Type sumUZero = 0;
for(int j=0; j<stateDimF-1; ++j){
logU(y,j)=rhoU*logU(y-1,j) +uu(j)+ par.sepFalpha(j);
logF(j,y) = logU(y,j);
sumUZero += logU(y,j);
}
logF(stateDimF-1,y) = -sumUZero;
}
}
}
for(int y=1; y<timeSteps; ++y){
nll += -dnorm(logV(y),rhoV* logV(y-1) - par.sepFalpha(par.sepFalpha.size()-1) ,sdV(0),true);
SIMULATE_F(of){
if(conf.simFlag(0)==0){
logV(y)=rhoV*logV(y-1)+ rnorm( Type(0) , sdV(0))+ par.sepFalpha(par.sepFalpha.size()-1);
for(int j=0; j<stateDimF; ++j){
logF(j,y) = logF(j,y)+ logV(y) ;
}
}
}
}
nll += -jacobiUVtrans(logF);
return nll;
}
|
///////////////////////////////////////////////////////////////////////
//ConfigEngine.cpp
///////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include "../common/common.hpp"
#include "ConfigEngine.hpp"
///////////////////////////////////////////////////////////////////////
mr::ConfigEngine::ConfigEngine() :
ConfigEngine("")
{
}
///////////////////////////////////////////////////////////////////////
mr::ConfigEngine::ConfigEngine(std::string thePath) :
mPathConfig(thePath),
mPathFont(""),
mTextObjectsMax(0),
mLevelDebugMode(0),
mLogicRate(100)
{
}
///////////////////////////////////////////////////////////////////////
mr::ConfigEngine::~ConfigEngine()
{
}
///////////////////////////////////////////////////////////////////////
bool mr::ConfigEngine::load(std::string thePath)
{
if(thePath == "" && mPathConfig == "") return false; else
if(thePath != "" && mPathConfig == "") mPathConfig = thePath; else
if(thePath == "" && mPathConfig != "") thePath = mPathConfig;
std::vector<std::string> tVars;
if(!mr::getValuesFromArgs(thePath, "[Engine]", tVars)) return false;
mPathFont = tVars[0];
mTextObjectsMax = atoi(tVars[1].c_str());
mLevelDebugMode = atoi(tVars[2].c_str());
mLogicRate = atoi(tVars[3].c_str());
return true;
}
///////////////////////////////////////////////////////////////////////
|
#include "stdafx.h"
#include "StagesWindow.h"
#include "NagDlg.h"
#include "utilites/Localizator.h"
#include "utilites/serl/Archive.h"
#include "utilites/serl/serl_registry.h"
#include "utilites/document.h"
#include "data/nodeFactory.h"
#include "StagesDlg.h"
#include "toolbarbtns.h"
#include "resource.h"
#include <atlwin.h>
CStagesWnd::CStagesWnd()
{
}
void CStagesWnd::serialization(serl::archiver &arc)
{
arc.serial("docking", serial_dock_pos_.bDocking);
arc.serial("side", serial_dock_pos_.dockPos.dwDockSide);
arc.serial("left", serial_dock_pos_.rect.left);
arc.serial("right", serial_dock_pos_.rect.right);
arc.serial("top", serial_dock_pos_.rect.top);
arc.serial("bottom",serial_dock_pos_.rect.bottom);
arc.serial("nBar", serial_dock_pos_.dockPos.nBar);
arc.serial("fPctPos", serial_dock_pos_.dockPos.fPctPos);
arc.serial("nWidth", serial_dock_pos_.dockPos.nWidth);
arc.serial("nHeight", serial_dock_pos_.dockPos.nHeight);
}
HWND CStagesWnd::Create(HWND hparent)
{
CWindow parent(hparent);
CRect prc; parent.GetWindowRect(prc);
parent.ClientToScreen(prc);
return baseClass::Create(
parent, CRect(prc.TopLeft(), CSize(200, 200)), "",
WS_VISIBLE|WS_CAPTION|WS_POPUP|WS_OVERLAPPED|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|WS_SYSMENU
|WS_SYSMENU|WS_THICKFRAME);
}
LRESULT CStagesWnd::OnCreate(LPCREATESTRUCT)
{
listctrl_.Create(m_hWnd, rcDefault, "",
WS_VISIBLE|WS_CHILD|WS_BORDER
|LVS_REPORT|LVS_SINGLESEL|LVS_NOCOLUMNHEADER);
listctrl_.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT);
listctrl_.InsertColumn(0, "Stage", 0, 200, 0);
// toolbar_.Create(m_hWnd, rcDefault, "",
// WS_CHILD|WS_VISIBLE|TBSTYLE_FLAT,//|CCS_NORESIZE|CCS_NOPARENTALIGN,
// TBSTYLE_EX_DRAWDDARROWS
// );
// toolbar_.SetButtonStructSize();
//
// CToolbarButtons main=IDR_STAGE_WND;
// main.Append(ID_STAGE_PROPERTY, 0);
// main.Apply(toolbar_);
BuildList();
OnChangeLanguage();
stages::instance()->connect( (int)this, bind(&CStagesWnd::UpdateList, this));
return 0;
}
void CStagesWnd::OnChangeLanguage()
{
SetWindowText(_lcs("Stages"));
}
LRESULT CStagesWnd::OnDestroy()
{
stages::instance()->disconnect((int)this);
return 0;
}
void CStagesWnd::UpdateList()
{
listctrl_.DeleteAllItems();
BuildList();
}
void CStagesWnd::BuildList()
{
listctrl_.InsertItem(0, _lcs("Entire test"));
bool selected=false;
stage cstage=nodes::factory().get_sel_stage();
unsigned count=stages::instance()->size();
for (unsigned index=0; index<count; ++index)
{
shared_ptr<stage> stg=stages::instance()->at(index);
listctrl_.InsertItem(index+1, stg->name.c_str());
if (*stg==cstage)
{
selected=true;
listctrl_.SelectItem(index+1);
}
}
if (!selected) listctrl_.SelectItem(0);
}
LRESULT CStagesWnd::OnEraseBackground(HDC hdc)
{
CDCHandle dc=hdc;
CRect rc; GetClientRect(rc);
dc.FillRect(rc, GetSysColorBrush(COLOR_3DFACE));
return 0;
}
void CStagesWnd::SavePositionToRegistry()
{
if (registry_loaded_)
{
GetDockingWindowPlacement(&serial_dock_pos_);
serl::save_archiver(
new serl::registry(HKEY_CURRENT_USER, "Software\\AETestingTools\\Layouts"))
.serial("StagesBar", *this);
}
}
void CStagesWnd::LoadPositionFromRegistry()
{
GetDockingWindowPlacement(&serial_dock_pos_);
serl::load_archiver(
new serl::registry(HKEY_CURRENT_USER, "Software\\AETestingTools\\Layouts"))
.serial("StagesBar", *this);
SetDockingWindowPlacement(&serial_dock_pos_);
GetDockingWindowPlacement(&serial_dock_pos_);
registry_loaded_=true;
}
LRESULT CStagesWnd::OnSizeChanged(UINT uMsg, WPARAM, LPARAM)
{
CRect rc; GetClientRect(rc);
rc.DeflateRect(5, 5);
if (toolbar_)
{
CRect tb;
toolbar_.GetWindowRect(tb);
ScreenToClient(tb);
rc.top=tb.bottom+5;
}
listctrl_.MoveWindow(rc);
CRect lrc; listctrl_.GetClientRect(lrc);
listctrl_.SetColumnWidth(0, lrc.Width()-3);
return 0;
}
LRESULT CStagesWnd::OnItemChanged(LPNMHDR hdr)
{
LPNMLISTVIEW nm=(LPNMLISTVIEW)hdr;
if (nm->uNewState & LVIS_SELECTED)
{
int index=nm->iItem;
stage stg=index==0
? stage()
: *stages::instance()->at(index-1);
nodes::factory().set_sel_stage(stg);
}
return 0;
}
LRESULT CStagesWnd::OnItemDblClick(LPNMHDR)
{
OnStageProperty(0, 0, 0);
return 0;
}
LRESULT CStagesWnd::OnStageProperty(UINT, int, HWND)
{
Document().Nag();
CStagesDlg dlg;
dlg.DoModal();
return 0;
}
|
#include "Textures.h"
Textures::Textures()
{
background_texture.loadFromFile("resources/images/background.png");
overlay_texture.loadFromFile("resources/images/overlay.png");
bird_texture.loadFromFile("resources/images/bird.png");
column_top_texture.loadFromFile("resources/images/column_top.png");
column_bottom_texture.loadFromFile("resources/images/column_bottom.png");
gameover_screen_texture.loadFromFile("resources/images/gameover_screen.png");
gameinactive_screen_texture.loadFromFile("resources/images/gameinactive_screen.png");
}
Textures::~Textures()
{
}
|
/*Given an array of integers, sort the array into a wave like array and return it,
In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5.....*/
#include<bits/stdc++.h>
using namespace std;
void print_vector(vector <int> a)
{
for(auto i=a.begin();i!=a.end();++i)
{
cout<<*i<<" ";
}
}
vector <int> wave(vector <int> a)
{
sort(a.begin(),a.end());
for(auto i=a.begin();i!=a.end()&&i+1!=a.end();i=i+2)
{
iter_swap(i,i+1);
}
return a;
}
int main()
{
int n;
cin>>n;
vector <int> a;
int temp;
while(n--)
{
cin>>temp;
a.push_back(temp);
}
print_vector(wave(a));
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.