text
stringlengths 8
6.88M
|
|---|
#pragma once
#include <vector>
#include <complex>
#include "given.h"
//typedef std::complex<double> cmpx;
typedef std::vector<std::vector<cmpx>> Matrix;
cmpx KernelK(cmpx kappa, cmpx ConstA0, cmpx ConstA1, double ConstEps, int K, int J, int N);
void Enter_Data ( cmpx kappa, double ConstEps, Matrix& M);
cmpx Fun_Gn(cmpx kappa, int Nu);
cmpx KernelK(cmpx kappa, cmpx ConstA0, cmpx ConstA1, double ConstEps, int K, int J, int N);
double Pol_Cheb_I(int K, int TempN, int N);
double Sum_Base_Elem (int K, int J, int N);
//Fun_T_0 is mth::uchebNodes<double>
|
#pragma once
#include "../../Graphics/Mesh/3D/PlaneMesh.h"
#include "../../UI/Dependencies/IncludeImGui.h"
namespace ae
{
namespace priv
{
namespace ui
{
inline void PlaneMeshToEditor( ae::PlaneMesh& _PlaneStatic )
{
ImGui::Text( "Plane Mesh" );
float Size = _PlaneStatic.GetSize();
if( ImGui::DragFloat( "Size", &Size, 1.0f, Math::Epsilon(), std::numeric_limits<float>::max() ) )
{
_PlaneStatic.SetSize( Size );
_PlaneStatic.ApplyChanges();
}
int SubdivisionWidth = Cast( int, _PlaneStatic.GetSubdivisionWidth() );
if( ImGui::DragInt( "Subdivision Width", &SubdivisionWidth, 1.0f, 1, Math::Max<int>() ) )
_PlaneStatic.SetSubdivisionWidth( Cast( Uint32, SubdivisionWidth ) );
int SubdivisionHeight = Cast( int, _PlaneStatic.GetSubdivisionHeight() );
if( ImGui::DragInt( "Subdivision Height", &SubdivisionHeight, 1.0f, 1, Math::Max<int>() ) )
_PlaneStatic.SetSubdivisionHeight( Cast( Uint32, SubdivisionHeight ) );
ImGui::Separator();
}
}
} // priv
} // ae
|
#include <ParticlesSystem.h>
#include <EntityComponentSystem.h>
#include <ParticlesComponent.h>
using namespace breakout;
void ParticlesRenderSystem::Init()
{
}
void ParticlesRenderSystem::Update(float dtMilliseconds)
{
auto& particlesComponents = EntityComponentSystem::Get().GetAllComponentsByType<ParticlesComponent>();
for (auto& particles : particlesComponents)
{
particles->GetContainer().Update(dtMilliseconds);
particles->GetContainer().Draw();
}
}
|
#include <cstdlib>
#include <cstring>
#include <getopt.h>
#include <iostream>
#include <string>
#include "gmock/gmock.h"
#include "dbg.h"
#define USAGE "USAGE: TEST [OPTIONS]\n" \
" -h display this message\n" \
" -o TESTCASE only run the testcase TESTCASE\n" \
" -v increase verbosity, can be passed multiple times\n"
int main(int argc, char** argv) {
int verbosity = 0;
option const longopts[] {
{"help", no_argument, nullptr, 'h'},
{"only", required_argument, nullptr, 'o'}
};
int opt, index;
while ((opt = getopt_long(argc, argv, "ho:v", longopts, &index)) != -1) {
switch(opt) {
case 'h':
std::cout << USAGE;
exit(EXIT_SUCCESS);
case 'o':
testing::GTEST_FLAG(filter) = std::string("*") + optarg + "*";
break;
case 'v':
++verbosity;
break;
case '?':
std::cerr << USAGE;
exit(EXIT_FAILURE);
}
}
switch(verbosity) {
case 0:
DBG_SET_LOGLEVEL(WARN);
break;
case 1:
DBG_SET_LOGLEVEL(INFO);
break;
case 2:
DBG_SET_LOGLEVEL(DEBUG);
break;
default:
DBG_SET_LOGLEVEL(TRACE);
break;
}
testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
|
//
// Created by 钟奇龙 on 2019-04-15.
//
#include <iostream>
#include <stack>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int x):data(x),next(NULL){
}
};
bool isPalindrome(Node *head){
stack<Node*> s;
Node *cur = head;
while(cur){
s.push(cur);
cur = cur->next;
}
while(head){
if(head->data != s.top()->data){
return false;
}
head = head->next;
s.pop();
}
return true;
}
|
/*
File: VLMath.h
Function: Various math definitions for VL
Author(s): Andrew Willmott
Copyright: Copyright (c) 1995-1996, Andrew Willmott
*/
#ifndef __VL_MATH__
#define __VL_MATH__
// --- Inlines ----------------------------------------------------------------
#ifdef __SGI__
#include <ieeefp.h>
#define vl_finite(X) finite(X)
#elif __GCC__
#define vl_finite(X) finite(X)
#else
#define vl_finite(X) (1)
#endif
#ifdef VL_HAS_ABSF
inline Float abs(Float x)
{ return (fabsf(x)); }
inline Float len(Float x)
{ return (fabsf(x)); }
#endif
namespace SubMath{
inline Double abs(Double x)
{
return (fabs(x));
}
}
inline Double len(Double x)
{ return (fabs(x)); }
inline Float sqrlen(Float r)
{ return(sqr(r)); }
inline Double sqrlen(Double r)
{ return(sqr(r)); }
inline Float mix(Float a, Float b, Float s)
{ return((1.0f - s) * a + s * b); }
inline Float mix(Double a, Double b, Double s)
{ return((float)( (1.0 - s) * a + s * b )); }
inline Void SetReal(Float &a, Double b)
{ a = (float) b; }
inline Void SetReal(Double &a, Double b)
{ a = b; }
template <class S, class T> Void ConvertVec(const S &u, T &v)
{
for (Int i = 0; i < u.Elts(); i++)
v[i] = u[i];
}
#endif
|
// 0920_5.cpp : 定义控制台应用程序的入口点。
//给定一个日期,输出这个日期是该年的第几天。
#include <iostream>
using namespace std;
int LeapYear(int year)
{
int x = year % 4;
int y = year % 100;
int z = year % 400;
if (x == 0 && y != 0)
return 1;
else if (z == 0)
return 1;
else
return 0;
}
int main()
{
int year, month, day;
char x;
while (cin >> year >> x >> month >> x >> day)
{
int i,sum = 0;
int mon[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
if ((month > 2) && (LeapYear(year)))
sum++;
for (i = 0; i < month-1; i++)
{
sum = sum + mon[i];
}
sum =sum+day;
cout << sum << endl;
}
return 0;
}
|
/*
* This file contains the the line follower
* The line follower doenst follow lines
* The line follower avoids driving through black lines
*
*
* Creation date: 2019 07 29
* Author: Taha Tekdemir
*/
#include "steering.h"
#include "lineTracking.h"
#include "LineFollower.h"
extern SteeringInterface steering;
extern lineTrackInterface lineSensorFrontLeft;
extern lineTrackInterface lineSensorFrontRight;
extern lineTrackInterface lineSensorBackLeft;
extern lineTrackInterface lineSensorBackRight;
void LineFollower::checkMod() {
// Modus1, falls RDM rechts vorne auf schwarzen Streifen kommt, nach links fahren für 0,5 Sekunden
if(mod == 1) {
steering.setVal(0,0x010);
steering.setVal(1,255);
if((millis() - startMod1 > 500) && (lineSensorFrontRight.getColorCode() != 0)) {
mod = 0;
steering.straightForewards(0xA0);
}
}
// Modus2, falls RDM links vorne auf schwarzen Streifen kommt, nach rechts fahren dür 0,5 Sekunden
if(mod == 2) {
steering.setVal(0,0x010);
steering.setVal(1,0);
if((millis() - startMod2 > 500) && (lineSensorFrontLeft.getColorCode() != 0)){
mod = 0;
steering.straightForewards(0xA0);
}
}
}
void LineFollower::followLine(){
// all line sensors are read in
int rawValueFL = lineSensorFrontLeft.getColorCode();
int rawValueFR = lineSensorFrontRight.getColorCode();
int rawValueBL = lineSensorBackLeft.getColorCode();
int rawValueBR = lineSensorBackRight.getColorCode();
// rechst vorne erkennt schwarzen Streifen
if(rawValueFR == 0 &&
rawValueFL != 0 &&
rawValueBL != 0 &&
rawValueBR != 0 &&
mod == 0) {
mod = 1;
startMod1 = millis();
}
// links vorne erkennt schwarzen Streifen
if(rawValueFL == 0 &&
rawValueFR != 0 &&
rawValueBL != 0 &&
rawValueBR != 0 &&
mod == 0) {
mod = 2;
startMod2 = millis();
}
// normaler Modus --> geradeaus Fahren
if(mod == 0) {
steering.straightForewards(0xA0);
}
checkMod();
/*
// if the front sensors are in the black stripe, the car drive back and turn
if (rawValueFL == 0 && rawValueFR == 0){
steering.setVal(1,128);
steering.setVal(1,80);
steering.setVal(0,0x0000);
return;
}
// if no sensor is in the black stripe, the car drive straightforward
if (rawValueBL != 0 && rawValueFL != 0 && rawValueBR != 0 && rawValueFR != 0) {
steering.setVal(1,128);
steering.setVal(0,0x0175);
return;
}
// if the left front sensor is in the stripe,
// turn the car in the position that both left sensors are in stripe
if(rawValueFL == 0 && rawValueBL != 0){
steering.setVal(1,255);
return;
}
// if both left sensors are in the stripe, stop the car
if(rawValueFL == 0 && rawValueBL == 0) {
steering.setVal(1,128);
return;
}
if(rawValueFL != 0 && rawValueBL == 0 && cntleft == 0) {
directionleft = 1;
cntleft = millis();
steering.setVal(1,255);
return;
}
else if(millis() - cntleft > 100 && directionleft == 1) {
directionleft = 2;
cntleft = millis();
steering.setVal(1,0);
return;
}
else if(millis() - cntleft > 200 && directionleft == 2) {
directionleft = 3;
cntleft = millis();
steering.setVal(0,0);
return;
}
// if the right front sensor is in the stripe,
//turn the car in the position that both right sensors are in stripe
if(rawValueFR == 0 && rawValueBR != 0) {
steering.setVal(1,0);
return;
}
// if both right sensors are in the stripe, stop the car
if(rawValueFR == 0 && rawValueBR == 0) {
steering.setVal(1,128);
return;
}
if(rawValueFR != 0 && rawValueBR == 0 && cntright == 0) {
directionright = 1;
cntright = millis();
steering.setVal(1,0);
return;
}
else if(millis() - cntright > 100 && directionright == 1) {
directionright = 2;
cntright = millis();
steering.setVal(1,255);
return;
}
else if(millis() - cntright > 200 && directionright == 2) {
directionright = 3;
cntright = millis();
steering.setVal(0,0);
return;
}
*/
}
|
#include <string.h>
#include <bits/stdc++.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#define n5 3
using namespace std;
int lis(int arr[], int n){
int lis[n];
lis[0] = 1; //base case
for(int i = 1; i < n; i++){ //to calculate values that entered user
lis[i] = 1;
for(int j = 0; j < 1; j++){
if(arr[i] > arr[j] && lis[i] < lis[j] + 1){
lis[i] = lis[j] + 1;
}
}
}
return *max_element(lis, lis+n); //to back maximum value
}
int findMin(int arr[], int n){
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
// Create an array to store results of subproblems
bool dp[n+1][sum+1];
// Initialize first column as true. 0 sum is possible
// with all elements.
for (int i = 0; i <= n; i++)
dp[i][0] = true;
// Initialize top row, except dp[0][0], as false. With
// 0 elements, no other sum except 0 is possible
for (int i = 1; i <= sum; i++)
dp[0][i] = false;
for (int i=1; i<=n; i++) //loop post to fill the partition chart.
{
for (int j=1; j<=sum; j++)
{
dp[i][j] = dp[i-1][j]; //This part if the i element is not included.
if (arr[i-1] <= j) //this part if the i element is included.
dp[i][j] |= dp[i-1][j-arr[i-1]];
}
}
int diff = INT_MAX; //to determine difference of two sums.
// Find the largest j such that dp[n][j]
// is true where j loops from sum/2 t0 0
for (int j=sum/2; j>=0; j--)
{
// Find the
if (dp[n][j] == true)
{
diff = sum-2*j;
break;
}
}
return diff;
}
int printCountRec(int dist){
int count[dist+1]; //to determine base values.
count[0]=1;
if(dist>=1){ //this part if dist is equal 1
count[1]=1;
}
if(dist>=2){ //this part if dist is equal 2
count[2]=2;
}
for(int i=3; i<=dist; i++){ //to complete array in bottom up manner.
count[i]=count[i-1]+count[i-2]+count[i-3];
}
return count[dist]; //to back the count[dist]
}
int findLongestFromACell(int i, int j, int mat[n5][n5], int dp[n5][n5]) {
if (i < 0 || i >= n5 || j < 0 || j >= n5)
return 0;
if (dp[i][j] != -1)
return dp[i][j];
int x = INT_MIN, y = INT_MIN, z = INT_MIN, w = INT_MIN;
if (j < n5 - 1 && ((mat[i][j] + 1) == mat[i][j + 1]))
x = 1 + findLongestFromACell(i, j + 1, mat, dp);
if (j > 0 && (mat[i][j] + 1 == mat[i][j - 1]))
y = 1 + findLongestFromACell(i, j - 1, mat, dp);
if (i > 0 && (mat[i][j] + 1 == mat[i - 1][j]))
z = 1 + findLongestFromACell(i - 1, j, mat, dp);
if (i < n5 - 1 && (mat[i][j] + 1 == mat[i + 1][j]))
w = 1 + findLongestFromACell(i + 1, j, mat, dp);
return dp[i][j] = max(x, max(y, max(z, max(w, 1))));
}
int finLongestOverAll(int mat[n5][n5]) {
int result = 1;
int dp[n5][n5];
memset(dp, -1, sizeof dp);
for (int i = 0; i < n5; i++) {
for (int j = 0; j < n5; j++) {
if (dp[i][j] == -1)
findLongestFromACell(i, j, mat, dp);
result = max(result, dp[i][j]);
}
}
return result;
}
int Eggmax(int a, int b){
return (a>b)? a : b;
}
int eggDrop(int n, int k){ //k is number of floors and n is number of Eggs
int eggFloor[n + 1][k + 1];
int res;
int i, j, x;
for (i = 1; i <= n; i++) { // it is a trying for eggs ,so trying number and floor number is equal
eggFloor[i][1] = 1;
eggFloor[i][0] = 0;
}
for (j = 1; j <= k; j++) //every time need to try one egg and j floors.
eggFloor[1][j] = j;
for (i = 2; i <= n; i++) { //start from second egg and second floor to n eggs and n floors
for (j = 2; j <= k; j++) {
eggFloor[i][j] = INT_MAX; //to assign max value
for (x = 1; x <= j; x++) {
res = 1 + Eggmax(eggFloor[i - 1][x - 1], eggFloor[i][j - x]);
if (res < eggFloor[i][j]) //this part if result is smaller than eggfloor
eggFloor[i][j] = res;
}
}
}
return eggFloor[n][k]; // eggFloor[n][k] holds the result
}
int Optmax(int x, int y){
if(x > y){
return x;
}else{
return y;
}
}
int Optmin(int x, int y){
if(x < y){
return x;
}else{
return y;
}
}
int optimalStrategyOfGame(int* arr, int n) {
int table[n][n]; //to create table
for (int gap = 0; gap < n; ++gap) {
for (int i = 0, j = gap; j < n; ++i, ++j) {
int x = ((i + 2) <= j) ? table[i + 2][j] : 0;
int y = ((i + 1) <= (j - 1)) ? table[i + 1][j - 1] : 0;
int z = (i <= (j - 2)) ? table[i][j - 2] : 0;
table[i][j] = Optmax(arr[i] + Optmin(x, y), arr[j] + Optmin(y, z));
}
}
return table[0][n - 1];
}
int Kmax(int a, int b){ //to return maximum of two integers
return (a > b) ? a : b;
}
int knapSack(int W, int wt[], int val[], int n){
int i, w; //to determine row anc column.
int K[n + 1][W + 1];
for(i = 0; i <= n; i++){ //to create table of K[][] in bottam up manner
for(w = 0; w <= W; w++){ //it start first column and row zero.
if(i == 0 || w == 0){ //if i and w is equal zero k
K[i][w] = 0;
}else if(wt[i - 1] <= w){ //if w is smaller than wt, K is equal kmax value.
K[i][w] = Kmax(val[i - 1] + K[i-1][w-wt[i-1]] , K[i - 1][w]);
}else{
K[i][w] = K[i - 1][w];
}
}
}
return K[n][W];
}
int smax(int a, int b) { //maximum of 2 integers
return (a > b) ? a : b;
}
int slcs(char* X, char* Y, int m, int n); //to returns lCS
int shortestSS(char* X, char* Y){
int m = strlen(X), n = strlen (Y);
int l = slcs(X, Y, m, n); //to find lcs
return (m + n - l); //Result is sum of input string lengths - length of lcs
}
int slcs(char* X, char* Y, int m, int n){
int dp[m + 1][n + 1];
int i, j;
// Fill table in bottom up manner
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if(i == 0 || j == 0){
dp[i][j] = 0;
}else if(X[i - 1] == Y[j - 1]){
dp[i][j] = dp[i - 1][j - 1] + 1;
}else{
dp[i][j] = smax(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
bool findPartiion(int arr[], int n){
int sum = 0;
int i, j;
for (i = 0; i < n; i++) // Calculate sum of all elements
sum += arr[i];
if (sum % 2 != 0)
return false;
bool part[sum / 2 + 1][n + 1];
for (i = 0; i <= n; i++) // initialize top row as true
part[0][i] = true;
for (i = 1; i <= sum / 2; i++) //except i rows and zero columns, start zero.
part[i][0] = false;
for (i = 1; i <= sum / 2; i++) { //
for (j = 1; j <= n; j++) {
part[i][j] = part[i][j - 1];
if (i >= arr[j - 1])
part[i][j] = part[i][j]
|| part[i - arr[j - 1]][j - 1];
}
}
return part[sum / 2][n];
}
int Cutmax(int a, int b){ // A utility function to get the maximum of two integers
return(a > b)? a : b;
}
int CutRod(int price[], int n){
int val[n + 1];
val[0] = 0;
int i, j;
for(i = 1; i <= n; i++){ //to create table and later start from the last.
int max_val = INT_MIN; //to determine min and max values.
for(j = 0; j < i; j++){ //to take different parts and compare them in different configurations.
max_val = Cutmax(max_val, price[j] + val[i - j - 1]);
}
val[i] = max_val;
}
return val[n];
}
int Pmax(int a, int b) { //maximum of 2 integers
return (a > b)? a : b;
}
int Pmax(int a, int b, int c) { //maximum of 2 integers
return Pmax(a, Pmax(b, c));
}
int maxProd(int n){ //n is length of rope.
int val[n + 1];
val[0] = val[1] = 0;
for(int i = 1; i <= n; i++){
int max_val = 0; //to get the maximum value from the cuts made.
for(int j = 1; j <= i/2; j++){
max_val = Pmax(max_val, (i - j) * j, j * val[i - j]);
}
val[i] = max_val; //to equalize val and maximum value
}
return val[n]; //to back maximum value
}
int findWays(int m, int n, int x) {
int table[n + 1][x + 1];
memset(table, 0, sizeof(table)); // Initialize all entries as 0
// Table entries for only one dice
for (int j = 1; j <= m && j <= x; j++)
table[1][j] = 1;
// Fill rest of the entries in table using recursive relation
// i: number of dice, j: sum
for (int i = 2; i <= n; i++)
for (int j = 1; j <= x; j++)
for (int k = 1; k <= m && k < j; k++)
table[i][j] += table[i-1][j-k];
return table[n][x];
}
int Coincount( int S[], int m, int n ) {
int i, j, x, y;
int table[n+1][m];
for (i=0; i<m; i++) //to enter values for zero value
table[0][i] = 1; //n is equal zero.
for (i = 1; i < n+1; i++)
{
for (j = 0; j < m; j++)
{
x = (i-S[j] >= 0)? table[i - S[j]][j]: 0; //x is the number of includings[j]
y = (j >= 1)? table[i][j-1]: 0; //y is sum of solutions including s[j]
table[i][j] = x + y; //it's total number.
}
}
return table[n][m-1];
}
bool isSubsetSum(int set[], int n, int sum){ //bool is used true-false question.
bool subset[n + 1][sum + 1]; //
for (int i = 0; i <= n; i++) //if result is zero, answer is true in this part.
subset[i][0] = true;
for (int i = 1; i <= sum; i++) //if result is zero, answer is false in this part.
subset[0][i] = false;
for (int i = 1; i <= n; i++) { // to create subsetsum table.
for (int j = 1; j <= sum; j++) {
if (j < set[i - 1]) //if j is smaller than set
subset[i][j] = subset[i - 1][j];
if (j >= set[i - 1]) //if j is bigger than set[i-1], use this part.
subset[i][j] = subset[i - 1][j]
|| subset[i - 1][j - set[i - 1]];
}
}
return subset[n][sum];
}
int main(){
int chart, option;
int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; //for First case, it is a specific arrays
int arr2[] = {3, 1, 4, 2, 2, 1};
int arro[] = { 20, 30, 2, 2, 2, 10 };
int n = sizeof(arr)/sizeof(arr[0]);
int n1 = sizeof(arr)/sizeof(arr[0]);
int no = sizeof(arro) / sizeof(arro[0]);
int dist = 4;
int set[] = { 3, 34, 4, 12, 5, 2 };
int sum = 9;
int n6 = sizeof(set) / sizeof(set[0]);
int val[] = { 60, 100, 120 };
int wt[] = { 10, 20, 30 };
int W = 50;
int n8 = sizeof(val) / sizeof(val[0]);
char X[] = "AGGTAB";
char Y[] = "GXTXAYB";
char X1[6];
char Y1[7];
int arr11[] = { 3, 1, 1, 2, 2, 1 };
int n11 = sizeof(arr11) / sizeof(arr11[0]);
int arr12[] = {1, 5, 8, 9, 10, 17, 17, 20};
int size12 = sizeof(arr12)/sizeof(arr12[0]);
int arr13[] = {1, 2, 3};
int m13 = sizeof(arr13)/sizeof(arr13[0]);
int n13 = 4;
printf("DP-1: Longest Increasing Subsequence\nDP-2: Edit Distance\n");
printf("DP-3: Partition a set into two subsets such that the difference of subset sums is minimum\nDP-4: Count number of ways to cover a distance\nDP-5: Find the longest path in a matrix with given constraints");
printf("DP-6: Subset Sum Problem\nDP-7: Optimal Strategy for a Game\nDP-8: 0-1 Knapsack Problem\nDP-9: Boolean Parenthesization Problem\nDP-10: Shortest Common Supersequence\nDP-11: Partition Problem\nDP-12: Cutting a Rod");
printf("DP-13: Coin Change\nDP-14: Word Break Problem\nDP-15: Maximum Product Cutting\nDP-16: Dice Throw\nDP-17: Box Stacking Problem\nDP-18: Egg Dropping Puzzle");
printf("\nPlease enter the number to choose example algorithms!!\n");
scanf("%d",&chart);
switch(chart){ //to create application menu.
case 1:
printf("Which option do you want to look at the algorithm?\n1-)Set pre-defined inputs for easy testing\n2-)Enter input for manuel testing.\n");
scanf("%d", &option); //to take the entered number and process it.
switch(option){ //to create 2 option manuel testing and easy testing.
case 1:
printf("\nLength of lis is %dn\n", lis( arr, n )); //to show LIS results
break;
case 2:
int x = 0; //to determine numbers will entered.
printf("How many numbers do you want to be calculated ?");
scanf("%d", &x);
int arr1[x]; //to save and process the entered numbers as an array
for(int i = 0; i < x; i++){ //loop through which numbers to be entered are printed.
printf("Enter the %d number to calculate:", i + 1);
scanf("%d", &arr1[i]);
}
int size = sizeof(arr1)/sizeof(arr1[0]);
printf("\nLength of lis is %d\n", lis(arr1, size)); //to show LIS results
break;
}
break;
case 3:
printf("Which option do you want to look at the algorithm?\n1-)Set pre-defined inputs for easy testing\n2-)Enter input for manuel testing.\n");
scanf("%d", &option); //to take the entered number and process it
switch(option){ //to create 2 option manuel testing and easy testing.
case 1:
printf("The minimum difference between 2 sets is %d\n", findMin(arr2,n1)); //to show findMin results
break;
case 2:
int x = 0; //to save and process the entered numbers as an array
printf("How many numbers do you want to be calculated ?");
scanf("%d", &x);
int arr21[x]; //to save and process the entered numbers as an array
for(int i = 0; i < x; i++){ //loop through which numbers to be entered are printed.
printf("Enter the %d number to calculate:", i + 1);
scanf("%d", &arr21[i]);
}
int n12 = sizeof(arr21)/sizeof(arr21[0]);
printf("\nThe minimum difference between 2 sets is %d\n", findMin(arr21, n12)); //to show findMin results
break;
}
break;
case 4:
printf("Which option do you want to look at the algorithm?\n1-)Set pre-defined inputs for easy testing\n2-)Enter input for manuel testing.\n");
scanf("%d", &option); //to take the entered number and process it
switch(option){ //to create 2 option manuel testing and easy testing.
case 1:
printf("%d", printCountRec(dist)); //to show printCountRec results
return 0;
break;
case 2:
int dist1; //to specify integer for function
printf("Please enter number for manuel calculation:");
scanf("%d",&dist1);
printf("Result is %d", printCountRec(dist1)); //to show printCountRec results
return 0;
break;
}
break;
case 6:
printf("Which option do you want to look at the algorithm?\n1-)Set pre-defined inputs for easy testing\n2-)Enter input for manuel testing.\n");
scanf("%d", &option); //to take the entered number and process it
switch(option){ //to create 2 option manuel testing and easy testing.
case 1:
if (isSubsetSum(set, n6, sum) == true)
printf("Found a subset with given sum");
else
printf("No subset with given sum");
return 0;
break;
case 2:
int x = 0; //to save and process the entered numbers as an array
printf("How many set numbers do you want to be calculated ?");
scanf("%d", &x);
int set[x]; //to save and process the entered numbers as an array
for(int i = 0; i < x; i++){ //loop through which numbers to be entered are printed.
printf("Enter the %d number to calculate:", i + 1);
scanf("%d", &set[i]);
}
int sum;
printf("Please enter number of sum:");
scanf("%d", &sum);
int n = sizeof(set)/sizeof(set[0]);
if (isSubsetSum(set, n, sum) == true){
printf("Found a subset with given sum");
}
else
printf("No subset with given sum");
return 0;
break;
}
break;
case 7:
printf("Which option do you want to look at the algorithm?\n1-)Set pre-defined inputs for easy testing\n2-)Enter input for manuel testing.\n");
scanf("%d", &option); //to take the entered number and process it
switch(option){ //to create 2 option manuel testing and easy testing.
case 1:
printf("%d\n", optimalStrategyOfGame(arro, no)); //to show optimalStrategyOfGame results
return 0;
break;
case 2:
int x = 0; //to save and process the entered numbers as an array
printf("How many numbers do you want to be calculated ?");
scanf("%d", &x);
int arr21[x]; //to save and process the entered numbers as an array
for(int i = 0; i < x; i++){ //loop through which numbers to be entered are printed.
printf("Enter the %d number to calculate:", i + 1);
scanf("%d", &arr21[i]);
}
int n12 = sizeof(arr21)/sizeof(arr21[0]);
printf("\nThe result of numbers entered is %d\n", optimalStrategyOfGame(arr21, n12)); //to show optimalStrategyOfGame results
break;
}
break;
case 8:
printf("Which option do you want to look at the algorithm?\n1-)Set pre-defined inputs for easy testing\n2-)Enter input for manuel testing.\n");
scanf("%d", &option); //to take the entered number and process it
switch(option){ //to create 2 option manuel testing and easy testing.
case 1:
printf("%d", knapSack(W, wt, val, n8)); //to show knapSack results
return 0;
break;
case 2:
int x =0;
printf("\nPlease enter how many value items do you want:\n");
scanf("%d",&x);
int val1[x]; //to save and process the entered numbers as an array
for(int i = 0; i < x; i++){ //loop through which numbers to be entered are printed.
printf("Please the %d value:", i + 1);
scanf("%d", &val1[x]);
}
printf("\nPlease enter how many weight items do you want:\n");
scanf("%d", &x);
int wt1[x];
for(int i = 0; i < x; i++){
printf("Please the %d weight:", i + 1);
scanf("%d", &wt1[x]);
}
int W1;
printf("\nPlease enter W number:\n");
scanf("%d", &W1);
int n = sizeof(val1) / sizeof(val1[0]);
printf("\n%d", knapSack(W1, wt1, val1, n)); //to show knapSack results
return 0;
break;
}
break;
case 10:
printf("Which option do you want to look at the algorithm?\n1-)Set pre-defined inputs for easy testing\n2-)Enter input for manuel testing.\n");
scanf("%d", &option); //to take the entered number and process it
switch(option){ //to create 2 option manuel testing and easy testing.
case 1:
printf("Length of the shortest supersequence is %d", shortestSS(X, Y)); //to show shortestSS results
return 0;
break;
case 2:
printf("Please enter 6 X letters:");
scanf("%s", &X1);
printf("Please enter 7 Y letters:");
scanf("%s", &Y1);
printf("Length of the shortest supersequence is %d", shortestSS(X1, Y1)); //to show shortestSS results
break;
}
break;
case 11:
printf("Which option do you want to look at the algorithm?\n1-)Set pre-defined inputs for easy testing\n2-)Enter input for manuel testing.\n");
scanf("%d", &option); //to take the entered number and process it
switch(option){ //to create 2 option manuel testing and easy testing.
case 1:
if (findPartiion(arr11, n11) == true){
printf("Can be divided into two subsets of equal sum");
}else{
printf("Can not be divided into two subsets of ""equal sum");
}
getchar();
return 0;
break;
case 2:
int x = 6;
printf("Please enter 6 numbers:\n");
int arr[x]; //to save and process the entered numbers as an array
for(int i = 0; i < x; i++){ //loop through which numbers to be entered are printed.
printf("Enter the %d number to calculate:", i + 1);
scanf("%d", &arr[i]);
}
int n = sizeof(arr)/sizeof(arr[0]);
if (findPartiion(arr, n) == true){
printf("Can be divided into two subsets of equal sum");
}else{
printf("Can not be divided into two subsets of ""equal sum");
}
getchar();
return 0;
break;
}
break;
case 12:
printf("Which option do you want to look at the algorithm?\n1-)Set pre-defined inputs for easy testing\n2-)Enter input for manuel testing.\n");
scanf("%d", &option); //to take the entered number and process it
switch(option){ //to create 2 option manuel testing and easy testing.
case 1:
printf("Maximum Obtainable Value is %dn", CutRod(arr12, size12)); //to show CutRod results
getchar();
return 0;
break;
case 2:
int x = 0;
printf("How many numbers do you want to be calculated ?");
scanf("%d", &x);
int arr[x]; //to save and process the entered numbers as an array
for(int i = 0; i < x; i++){ //loop through which numbers to be entered are printed.
printf("Enter the %d number to calculate:", i + 1);
scanf("%d", &arr[i]);
}
int n = sizeof(arr)/sizeof(arr[0]);
printf("\nMaximum Obtainable Value is %dn\n", CutRod(arr, n)); //to show CutRod results
break;
}
break;
case 13:
printf("Which option do you want to look at the algorithm?\n1-)Set pre-defined inputs for easy testing\n2-)Enter input for manuel testing.\n");
scanf("%d", &option); //to take the entered number and process it
switch(option){ //to create 2 option manuel testing and easy testing.
case 1:
printf(" %d ", Coincount(arr13, m13, n13)); //to show Coincount results
return 0;
break;
case 2:
int x = 3;
printf("Please enter 3 numbers\n");
int arr[x]; //to save and process the entered numbers as an array
for(int i = 0; i < x; i++){ //loop through which numbers to be entered are printed.
printf("Enter the %d number to calculate:", i + 1);
scanf("%d", &arr[i]);
}
int n;
printf("Please enter one number:\n");
scanf("%d", &n);
int m = sizeof(arr)/sizeof(arr[0]);
printf("\nThe result is %d\n", Coincount(arr, m, n)); //to show Coincount results
break;
}
break;
case 15:
printf("Which option do you want to look at the algorithm?\n1-)Set pre-defined inputs for easy testing\n2-)Enter input for manuel testing.\n");
scanf("%d", &option); //to take the entered number and process it
switch(option){ //to create 2 option manuel testing and easy testing.
case 1:
printf("Maximum product is %d", maxProd(10)); //to show maxProd results
return 0;
break;
case 2:
int n; //to save and process the entered numbers as an array
printf("Please enter number to calculate maximum product:");
scanf("%d", &n);
printf("Maximum product is %d", maxProd(n)); //to show maxProd results
return 0;
break;
}
break;
case 16:
printf("Which option do you want to look at the algorithm?\n1-)Set pre-defined inputs for easy testing\n2-)Enter input for manuel testing.\n");
scanf("%d", &option); //to take the entered number and process it
switch(option){ //to create 2 option manuel testing and easy testing.
case 1:
printf("%d", findWays(4, 2, 1)); //to show findWays results
return 0;
break;
case 2:
int m16, n16, x16; //to save and process the entered numbers as an array
printf("Enter Three numbers\n");
printf("First:"); //to enter m value
scanf("%d", &m16);
printf("Second:"); //to enter n value
scanf("%d", &n16);
printf("Third:"); //to enter x value
scanf("%d", &x16);
printf("The result is %d", findWays(m16, n16, x16)); //to show findWays results
return 0;
break;
}
break;
case 18:
printf("Which option do you want to look at the algorithm?\n1-)Set pre-defined inputs for easy testing\n2-)Enter input for manuel testing.\n");
scanf("%d", &option); //to take the entered number and process it
int n = 2, k = 36; //to determine integers in eggDrop
int n1, k1;
switch(option){ //to create 2 option manuel testing and easy testing.
case 1:
printf("\nMinimum number of trials in worst case with %d eggs and %d floors is %d \n", n, k, eggDrop(n, k)); //to show eggDrop results
return 0;
break;
case 2:
printf("Please enter two number for calculation\nFirst number:\n");
scanf("%d", &n1); //to enter n1 value
printf("Second number:\n");
scanf("%d", &k1); //to enter k1 value
printf("Minimum number of trials in worts case with %d eggs and %d floors is %d \n", n1, k1, eggDrop(n,k)); //to show eggDrop results
break;
}
break;
}
return 0;
}
|
#ifndef FACTUREFORNISSEUR_H
#define FACTUREFORNISSEUR_H
#include <QDialog>
namespace Ui {
class facturefornisseur;
}
class facturefornisseur : public QDialog
{
Q_OBJECT
public:
explicit facturefornisseur(QWidget *parent = 0);
~facturefornisseur();
private slots:
void on_AjoutePB_clicked();
private:
Ui::facturefornisseur *ui;
};
#endif // FACTUREFORNISSEUR_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "adjunct/desktop_util/adt/finalizer.h"
#include "adjunct/desktop_util/transactions/OpUndoableOperation.h"
#include "adjunct/desktop_util/transactions/OpTransaction.h"
OpTransaction::OpTransaction()
: m_state(IN_PROGRESS)
{
}
OpTransaction::~OpTransaction()
{
if (COMMITTED != m_state)
{
RollBack();
}
}
OP_STATUS OpTransaction::Continue(OpAutoPtr<OpUndoableOperation> operation)
{
BOOL operation_executed = FALSE;
if (IN_PROGRESS == m_state)
{
Finalizer on_return(BindableFunction(
&AbortUnless, &operation_executed, this));
RETURN_OOM_IF_NULL(operation.get());
RETURN_IF_ERROR(operation->Do());
operation.release()->Into(&m_operations);
operation_executed = TRUE;
}
return operation_executed ? OpStatus::OK : OpStatus::ERR;
}
OP_STATUS OpTransaction::Commit()
{
BOOL committed = COMMITTED == m_state;
if (IN_PROGRESS == m_state)
{
m_state = COMMITTED;
committed = TRUE;
}
return committed ? OpStatus::OK : OpStatus::ERR;
}
void OpTransaction::RollBack()
{
OP_ASSERT(COMMITTED != m_state
|| !"Trying to roll back a committed transaction");
for (OpUndoableOperation* operation = m_operations.Last();
NULL != operation; operation = operation->Pred())
{
operation->Undo();
}
}
void OpTransaction::AbortUnless(BOOL* condition, OpTransaction* tx)
{
OP_ASSERT(NULL != condition && NULL != tx);
if (!*condition)
{
tx->m_state = ABORTED;
}
}
|
#include "Status.h"
#include <iostream>
#include <string>
using namespace std;
Status::Status(){}
string Status::getStatus(){
return status;
}
void Status::setStatus(string status){
this->status = status;
}
string Status::getObject(){
return object;
}
void Status::setObject(string object){
this->object = object;
}
|
#include <iostream>
#include <iomanip>
#include "boost/math/distributions/students_t.hpp"
void two_samples_t_test_equal_sd(
double Sm1, // Sm1 = Sample Mean 1.
double Sd1, // Sd1 = Sample Standard Deviation 1.
unsigned Sn1, // Sn1 = Sample Size 1.
double Sm2, // Sm2 = Sample Mean 2.
double Sd2, // Sd2 = Sample Standard Deviation 2.
unsigned Sn2, // Sn2 = Sample Size 2.
double alpha) // alpha = Significance Level.
{
// A Students t test applied to two sets of data.
// We are testing the null hypothesis that the two
// samples have the same mean and that any difference
// if due to chance.
// See http://www.itl.nist.gov/div898/handbook/eda/section3/eda353.htm
//
// Print header:
std::cout <<
"_______________________________________________\n"
"Student t test for two samples (equal variances)\n"
"_______________________________________________\n\n";
std::cout << std::setprecision(5);
std::cout << std::setw(55) << std::left << "Number of Observations (Sample 1)" << "= " << Sn1 << "\n";
std::cout << std::setw(55) << std::left << "Sample 1 Mean" << "= " << Sm1 << "\n";
std::cout << std::setw(55) << std::left << "Sample 1 Standard Deviation" << "= " << Sd1 << "\n";
std::cout << std::setw(55) << std::left << "Number of Observations (Sample 2)" << "= " << Sn2 << "\n";
std::cout << std::setw(55) << std::left << "Sample 2 Mean" << "= " << Sm2 << "\n";
std::cout << std::setw(55) << std::left << "Sample 2 Standard Deviation" << "= " << Sd2 << "\n";
//
// Now we can calculate and output some stats:
//
// Degrees of freedom:
double v = Sn1 + Sn2 - 2;
std::cout << std::setw(55) << std::left << "Degrees of Freedom" << "= " << v << "\n";
// Pooled variance and hence standard deviation:
double sp = sqrt(((Sn1 - 1) * Sd1 * Sd1 + (Sn2 - 1) * Sd2 * Sd2) / v);
std::cout << std::setw(55) << std::left << "Pooled Standard Deviation" << "= " << sp << "\n";
// t-statistic:
double t_stat = (Sm1 - Sm2) / (sp * sqrt(1.0 / Sn1 + 1.0 / Sn2));
std::cout << std::setw(55) << std::left << "T Statistic" << "= " << t_stat << "\n";
//
// Define our distribution, and get the probability:
//
boost::math::students_t dist(v);
double q = cdf(complement(dist, fabs(t_stat)));
std::cout << std::setw(55) << std::left << "Probability that difference is due to chance" << "= "
<< std::setprecision(3) << std::scientific << 2 * q << "\n\n";
//
// Finally print out results of alternative hypothesis:
//
std::cout << std::setw(55) << std::left <<
"Results for Alternative Hypothesis and alpha" << "= "
<< std::setprecision(4) << std::fixed << alpha << "\n\n";
std::cout << "Alternative Hypothesis Conclusion\n";
std::cout << "Sample 1 Mean != Sample 2 Mean ";
if (q < alpha / 2)
std::cout << "NOT REJECTED\n";
else
std::cout << "REJECTED\n";
std::cout << "Sample 1 Mean < Sample 2 Mean ";
if (cdf(dist, t_stat) < alpha)
std::cout << "NOT REJECTED\n";
else
std::cout << "REJECTED\n";
std::cout << "Sample 1 Mean > Sample 2 Mean ";
if (cdf(complement(dist, t_stat)) < alpha)
std::cout << "NOT REJECTED\n";
else
std::cout << "REJECTED\n";
std::cout << std::endl << std::endl;
}
void two_samples_t_test_unequal_sd(
double Sm1, // Sm1 = Sample Mean 1.
double Sd1, // Sd1 = Sample Standard Deviation 1.
unsigned Sn1, // Sn1 = Sample Size 1.
double Sm2, // Sm2 = Sample Mean 2.
double Sd2, // Sd2 = Sample Standard Deviation 2.
unsigned Sn2, // Sn2 = Sample Size 2.
double alpha) // alpha = Significance Level.
{
// A Students t test applied to two sets of data.
// We are testing the null hypothesis that the two
// samples have the same mean and
// that any difference is due to chance.
// See http://www.itl.nist.gov/div898/handbook/eda/section3/eda353.htm
//
using namespace std;
// Print header:
std::cout <<
"_________________________________________________\n"
"Student t test for two samples (unequal variances)\n"
"_________________________________________________\n\n";
std::cout << std::setprecision(5);
std::cout << std::setw(55) << std::left << "Number of Observations (Sample 1)" << "= " << Sn1 << "\n";
std::cout << std::setw(55) << std::left << "Sample 1 Mean" << "= " << Sm1 << "\n";
std::cout << std::setw(55) << std::left << "Sample 1 Standard Deviation" << "= " << Sd1 << "\n";
std::cout << std::setw(55) << std::left << "Number of Observations (Sample 2)" << "= " << Sn2 << "\n";
std::cout << std::setw(55) << std::left << "Sample 2 Mean" << "= " << Sm2 << "\n";
std::cout << std::setw(55) << std::left << "Sample 2 Standard Deviation" << "= " << Sd2 << "\n";
//
// Now we can calculate and output some stats:
//
// Degrees of freedom:
double v = Sd1 * Sd1 / Sn1 + Sd2 * Sd2 / Sn2;
v *= v;
double t1 = Sd1 * Sd1 / Sn1;
t1 *= t1;
t1 /= (Sn1 - 1);
double t2 = Sd2 * Sd2 / Sn2;
t2 *= t2;
t2 /= (Sn2 - 1);
v /= (t1 + t2);
std::cout << std::setw(55) << std::left << "Degrees of Freedom" << "= " << v << "\n";
// t-statistic:
double t_stat = (Sm1 - Sm2) / sqrt(Sd1 * Sd1 / Sn1 + Sd2 * Sd2 / Sn2);
std::cout << std::setw(55) << std::left << "T Statistic" << "= " << t_stat << "\n";
//
// Define our distribution, and get the probability:
//
boost::math::students_t dist(v);
double q = cdf(complement(dist, fabs(t_stat)));
std::cout << std::setw(55) << std::left << "Probability that difference is due to chance" << "= " << std::setprecision(3) << std::scientific << 2 * q << "\n\n";
// Calculates what T value such that the integral from [-inf,T] == 2.5%
// This means we have 2.5% of the probability of reaching a number outside [-inf,T]
// Because the distribution is symmetrycal, also 5% probability of a number outside [-T,T]
double t = quantile(dist, 0.025); // -1.977e+00
std::cout << std::setw(55) << std::left << "T value that would be enough for a 5% probability that it is due to chance (quantile) " << "= " << std::setprecision(3) << std::scientific << t << "\n\n";
//
// Finally print out results of alternative hypothesis:
//
std::cout << std::setw(55) << std::left <<
"Results for Alternative Hypothesis and alpha" << "= "
<< std::setprecision(4) << std::fixed << alpha << "\n\n";
std::cout << "Alternative Hypothesis Conclusion\n";
std::cout << "Sample 1 Mean != Sample 2 Mean ";
if (q < alpha / 2)
std::cout << "NOT REJECTED\n";
else
std::cout << "REJECTED\n";
std::cout << "Sample 1 Mean < Sample 2 Mean ";
if (cdf(dist, t_stat) < alpha)
std::cout << "NOT REJECTED\n";
else
std::cout << "REJECTED\n";
std::cout << "Sample 1 Mean > Sample 2 Mean ";
if (cdf(complement(dist, t_stat)) < alpha)
std::cout << "NOT REJECTED\n";
else
std::cout << "REJECTED\n";
std::cout << std::endl << std::endl;
}
int main() {
//
// Run tests for Car Mileage sample data
// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3531.htm
// from the NIST website http://www.itl.nist.gov. The data compares
// miles per gallon of US cars with miles per gallon of Japanese cars.
//
two_samples_t_test_equal_sd(20.14458, 6.414700, 249, 30.48101, 6.107710, 79, 0.05);
two_samples_t_test_unequal_sd(20.14458, 6.414700, 249, 30.48101, 6.107710, 79, 0.05);
return 0;
}
/*
Output is:
_______________________________________________
Student t test for two samples (equal variances)
_______________________________________________
Number of Observations (Sample 1) = 249
Sample 1 Mean = 20.145
Sample 1 Standard Deviation = 6.4147
Number of Observations (Sample 2) = 79
Sample 2 Mean = 30.481
Sample 2 Standard Deviation = 6.1077
Degrees of Freedom = 326
Pooled Standard Deviation = 6.3426
T Statistic = -12.621
Probability that difference is due to chance = 5.273e-030
Results for Alternative Hypothesis and alpha = 0.0500
Alternative Hypothesis Conclusion
Sample 1 Mean != Sample 2 Mean NOT REJECTED
Sample 1 Mean < Sample 2 Mean NOT REJECTED
Sample 1 Mean > Sample 2 Mean REJECTED
_________________________________________________
Student t test for two samples (unequal variances)
_________________________________________________
Number of Observations (Sample 1) = 249
Sample 1 Mean = 20.14458
Sample 1 Standard Deviation = 6.41470
Number of Observations (Sample 2) = 79
Sample 2 Mean = 30.48101
Sample 2 Standard Deviation = 6.10771
Degrees of Freedom = 136.87499
T Statistic = -12.94627
Probability that difference is due to chance = 1.571e-025
Results for Alternative Hypothesis and alpha = 0.0500
Alternative Hypothesis Conclusion
Sample 1 Mean != Sample 2 Mean NOT REJECTED
Sample 1 Mean < Sample 2 Mean NOT REJECTED
Sample 1 Mean > Sample 2 Mean REJECTED
*/
|
#include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i=0;i<(n);i++)
#define for1(i,n) for(int i=1;i<=n;i++)
#define FOR(i,a,b) for(int i=(a);i<=(b);i++)
#define FORD(i,a,b) for(int i=(a);i>=(b);i--)
const int INF = 1<<29;
const int MOD=1073741824;
#define pp pair<ll,ll>
typedef long long int ll;
bool isPowerOfTwo (ll x)
{
return x && (!(x&(x-1)));
}
void fastio()
{
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
}
long long binpow(long long a, long long b) {
long long res = 1;
while (b > 0) {
if (b & 1)
res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
const int dx[] = {1,0,-1,0,1,1,-1,-1};
const int dy[] = {0,-1,0,1,1,-1,-1,1};
////////////////////////////////////////////////////////////////////
const int maxn=55;
ll a[maxn];
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
memset(a,0,sizeof(a));
bool flag=false;
ll i=1;
while(1){
if(flag==true)break;
flag=true;
for1(j,n){
if(!a[j]){
a[j]=i;
i++;
flag=false;
break;
}
ll u=a[j]+i;
u=sqrt(u);
if(u*u == (a[j]+i)){
a[j]=i;
i++;
flag=false;
break;
}
}
//cout<<i<<"\n";
}
if(i>1e5)cout<<"-1\n";
else cout<<i-1<<"\n";
}
return 0;
}
|
// 以下の ifdef ブロックは DLL から簡単にエクスポートさせるマクロを作成する標準的な方法です。
// この DLL 内のすべてのファイルはコマンドラインで定義された BKGNUPG_EXPORTS シンボル
// でコンパイルされます。このシンボルはこの DLL が使用するどのプロジェクト上でも未定義でなけ
// ればなりません。この方法ではソースファイルにこのファイルを含むすべてのプロジェクトが DLL
// からインポートされたものとして BKGNUPG_API 関数を参照し、そのためこの DLL はこのマク
// ロで定義されたシンボルをエクスポートされたものとして参照します。
#ifdef BKGNUPG_EXPORTS
#define BKGNUPG_API __declspec(dllexport)
#else
#define BKGNUPG_API __declspec(dllimport)
#endif
// このクラスは BkGnuPG.dll からエクスポートされます
class BKGNUPG_API CBkGnuPG {
public:
CBkGnuPG(void);
// TODO: この位置にメソッドを追加してください。
};
extern BKGNUPG_API int nBkGnuPG;
BKGNUPG_API int fnBkGnuPG(void);
|
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void Mirror1(TreeNode *pRoot) {
if(!pRoot){
return;
}
queue<TreeNode*> Q;
Q.push(pRoot);
while(!Q.empty()){
TreeNode *cur = Q.front();
Q.pop();
TreeNode *temp = cur->left;
cur->left = cur->right;
cur->right = temp;
if(cur->left){
Q.push(cur->left);
}
if(cur->right){
Q.push(cur->right);
}
}
}
void Mirror2(TreeNode *pRoot) {
if(!pRoot || (!pRoot->left && !pRoot->right)){
return;
}
TreeNode *temp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = temp;
Mirror2(pRoot->left);
Mirror2(pRoot->right);
}
};
|
//
// Created by tonell_m on 22/01/17.
//
#include <Constants.hh>
#include <PhysicsEngine.hh>
#include "Character.hh"
Character::Character(int x, int y, PhysicsEngine* engine) : _pos(sf::Vector2f(PLAYER_START_X, PLAYER_START_Y))
{
//TODO: init sprites and colliders
this->body = engine->createRectangle(x, y, CHARACTER_WIDTH, CHARACTER_HEIGHT, 0);
}
Character::~Character()
{
}
const sf::Vector2f &Character::getPos() const
{
return _pos;
}
void Character::setPos(const sf::Vector2f &_pos)
{
this->_pos = _pos;
}
sf::Sprite *Character::animate(SpriteType anim, bool update)
{
if (update)
{
_sprites.at(anim).next();
}
return _sprites.at(anim).getSprite();
}
void Character::move(Direction way) const
{
if (way == LEFT)
{
b2Vec2 pos = this->body->GetPosition();
pos.x -= CHAR_SPEED;
this->body->SetTransform(pos, this->body->GetAngle());
this->body->ApplyLinearImpulse(b2Vec2(-0.05, -0.1), this->body->GetPosition(), true);
}
else if (way == RIGHT)
{
b2Vec2 pos = this->body->GetPosition();
pos.x += CHAR_SPEED;
this->body->SetTransform(pos, this->body->GetAngle());
this->body->ApplyLinearImpulse(b2Vec2(-0.05, -0.1), this->body->GetPosition(), true);
}
else
{
b2Vec2 pos = this->body->GetPosition();
pos.y -= CHAR_SPEED;
this->body->SetTransform(pos, this->body->GetAngle());
this->body->ApplyLinearImpulse(b2Vec2(-0.05, -0.1), this->body->GetPosition(), true);
}
}
|
#ifndef _GAPP_H
#define _GAPP_H
#include <iostream>
#include <string>
#include <SDL/SDL.h>
#include <SDL/SDL_Image.h>
#include "Surface.h"
#include "Event.h"
#include "TicTacToe.h"
#define INIT_SURFACE(surf, img) if ((surf = Surface::load(#img)) == NULL) { \
std::cerr << "Could not load surface: " << #surf << " (" << #img << ")" << std::endl; \
return false; \
}
#define INIT_SURFACE_ALPHA(surf, img) if ((surf = Surface::loadAlpha(#img)) == NULL) { \
std::cerr << "Could not load surface: " << #surf << " (" << #img << ")" << std::endl; \
return false; \
}
#define DISPLAY_WIDTH 600
#define DISPLAY_HEIGHT 600
class GApp : public Event
{
public:
GApp();
~GApp();
int onExecute(void);
bool onInit(void);
void onEvent(SDL_Event *event);
void onLoop(void);
void onRender(void);
void onCleanup(void);
//events
void onQuit(void);
void onMouseDown(Uint8 button, int mouseX, int mouseY);
//misc functions
void displayWinner(TicTacToe::GridType winner);
void setPVM();
private:
bool isRunning;
SDL_Surface *display;
SDL_Surface *surfGrid;
SDL_Surface *surfX;
SDL_Surface *surfO;
SDL_Surface *surfXWins;
SDL_Surface *surfOWins;
TicTacToe gameBoard;
};
#endif
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *temp = new ListNode(0),*head;
int k = lists.size(), t, n = 0;
head = temp;
// Calculate total number of nodes in final list
for(int i=0;i<k;i++) {
ListNode *list = lists[i];
while(list != NULL) {
n += 1;
list = list->next;
}
}
// Insert the initial k values in heap
for(int i=0;i<k;i++) {
if(lists[i] != NULL) {
pq.push(make_pair(lists[i]->val,i));
}
}
// Main solution
for(int i=0;i<n;i++) {
t = pq.top().second;
temp->next = lists[t];
temp = temp->next;
lists[t] = lists[t]->next;
pq.pop();
if(lists[t] != NULL)
pq.push(make_pair(lists[t]->val,t));
}
return head->next;
}
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef HTML5ATTRCOPY_H
#define HTML5ATTRCOPY_H
#include "modules/logdoc/markup.h"
#include "modules/logdoc/src/html5/html5tokenbuffer.h"
class HTML5Attr;
/**
* HTML5AttrCopy is used to hold a copy of the attributes found at tokenization
* when storing the tokens for elements that may have to be regenerated from the
* original token data, for instance during adoption.
* In standalone mode it is also used for storing attributes in the nodes in
* the logical tree.
*/
class HTML5AttrCopy
{
public:
#ifdef HTML5_STANDALONE
friend class H5Element;
#endif // HTML5_STANDALONE
HTML5AttrCopy() : m_name(0), m_value(NULL), m_ns(Markup::HTML) {}
~HTML5AttrCopy();
void CopyL(HTML5Attr *src);
void CopyL(HTML5AttrCopy *src);
HTML5TokenBuffer*
GetName() { return &m_name; }
uni_char* GetValue() const { return m_value; }
void SetNameL(const uni_char* name, unsigned length);
void SetNameL(HTML5TokenBuffer *name);
void SetValueL(const uni_char* value, unsigned length);
Markup::Ns GetNs() const { return m_ns; }
void SetNs(Markup::Ns ns) { m_ns = ns; }
BOOL IsEqual(HTML5Attr *attr);
private:
HTML5TokenBuffer m_name;
uni_char* m_value;
Markup::Ns m_ns;
};
#endif // HTML5ATTRCOPY_H
|
#ifndef BINARY_SEARCH_TREE_H
#define BINARY_SEARCH_TREE_H
#include "dsexceptions.h"
#include <iostream> // For NULL
#include <iomanip> // To set the width for the line numbers for words
using namespace std;
// AVLTree class
//
// CONSTRUCTION: with ITEM_NOT_FOUND object used to signal failed finds
//
// ******************PUBLIC OPERATIONS*********************
// void insert( x ) --> Insert x
// void remove( x ) --> Remove x
// bool contains( x ) --> Return true if x is present
// Comparable findMin( ) --> Return smallest item
// Comparable findMax( ) --> Return largest item
// boolean isEmpty( ) --> Return true if empty; else false
// void makeEmpty( ) --> Remove all items
// void printTree( ) --> Print tree in sorted order
// ******************ERRORS********************************
// Throws UnderflowException as warranted
template <typename Comparable>
class AVLTree
{
public:
AVLTree() : root(NULL)
{
}
AVLTree(const AVLTree &rhs) : root(NULL)
{
*this = rhs;
}
/**
* Destructor for the tree
*/
~AVLTree()
{
makeEmpty();
}
/**
* Find the smallest item in the tree.
* Throw UnderflowException if empty.
*/
const Comparable &findMin() const
{
if (isEmpty())
throw UnderflowException();
return findMin(root)->element;
}
/**
* Find the largest item in the tree.
* Throw UnderflowException if empty.
*/
const Comparable &findMax() const
{
if (isEmpty())
throw UnderflowException();
return findMax(root)->element;
}
/**
* Returns true if x is found in the tree.
*/
bool contains(const Comparable &x)
{
comparisonsForSearch = 0;
return contains(x, root);
}
/**
* Test if the tree is logically empty.
* Return true if empty, false otherwise.
*/
bool isEmpty() const
{
return root == NULL;
}
/**
* Print the tree contents in sorted order.
*/
void printTree(ostream &out = cout) const
{
if (isEmpty())
out << "Empty tree" << endl;
else
printTree(root, out);
}
/**
* Make the tree logically empty.
*/
void makeEmpty()
{
makeEmpty(root);
}
/**
* Insert x into the tree; duplicates are ignored.
*/
void insert(const Comparable &x, int y)
{
insert(x, root, y);
}
void search(const Comparable &x, ostream &out = cout)
{
search(x, root, out);
}
void findHeight(ostream &out = cout)
{
findHeight(root, out);
}
void findSize(ostream &out = cout)
{
findSize(root, out);
}
void getComparisons(ostream &out = cout)
{
getComparisons(root, out);
}
void getComparisonsInsert(ostream &out = cout)
{
getComparisonsInsert(root, out);
}
void getComparisonsContains(ostream &out = cout)
{
getComparisonsContains(root, out);
}
/**
* Remove x from the tree. Nothing is done if x is not found.
*/
void remove(const Comparable &x)
{
remove(x, root);
}
/**
* Deep copy.
*/
const AVLTree &operator=(const AVLTree &rhs)
{
if (this != &rhs)
{
makeEmpty();
root = clone(rhs.root);
}
return *this;
}
private:
struct AvlNode
{
Comparable element;
AvlNode *left;
AvlNode *right;
int height;
int insertions;
int containsInsertions;
// Added this for the vector
vector<int> lineNumberList;
AvlNode(const Comparable &theElement, AvlNode *lt, AvlNode *rt, vector<int> lnl, int h = 0, int ins = 0, int cins = 0)
: element(theElement), left(lt), right(rt), lineNumberList(lnl), height(h), insertions(ins), containsInsertions(cins) {}
};
AvlNode *root;
int comparisonsForInsertions = 0;
int comparisonsForSearch = 0;
/**
* Internal method to insert into a subtree.
* x is the item to insert.
* t is the node that roots the subtree.
* Set the new root of the subtree.
*/
void insert(const Comparable &x, AvlNode *&t, int l)
{
//comparisonsForInsertions += 1;
if (t == NULL)
{
t = new AvlNode(x, NULL, NULL, vector<int>(), 0);
//comparisonsForInsertions += 1;
t->lineNumberList.push_back(l);
}
else if (x < t->element)
{
comparisonsForInsertions += 1;
insert(x, t->left, l);
}
else if (t->element < x)
{
comparisonsForInsertions += 2;
insert(x, t->right, l);
}
else
{
comparisonsForInsertions += 2;
t->lineNumberList.push_back(l); // Duplicate; do nothing
}
balance(t);
}
static const int ALLOWED_IMBALANCE = 1;
void balance(AvlNode *&t)
{
if (t == NULL)
return;
if (height(t->left) - height(t->right) > ALLOWED_IMBALANCE)
if (height(t->left->left) >= height(t->left->right))
rotateWithLeftChild(t);
else
doubleWithLeftChild(t);
else if (height(t->right) - height(t->left) > ALLOWED_IMBALANCE)
if (height(t->right->right) >= height(t->right->left))
rotateWithRightChild(t);
else
doubleWithRightChild(t);
t->height = max(height(t->left), height(t->right)) + 1;
}
void rotateWithLeftChild(AvlNode *&k2)
{
AvlNode *k1 = k2->left;
k2->left = k1->right;
k1->right = k2;
k2->height = max(height(k2->left), height(k2->right)) + 1;
k1->height = max(height(k1->left), k2->height) + 1;
k2 = k1;
}
void rotateWithRightChild(AvlNode *&k2)
{
AvlNode *k1 = k2->right;
k2->right = k1->left;
k1->left = k2;
k2->height = max(height(k2->left), height(k2->right)) + 1;
k1->height = max(height(k1->left), k2->height) + 1;
k2 = k1;
}
void doubleWithLeftChild(AvlNode *&k3)
{
rotateWithRightChild(k3->left);
rotateWithLeftChild(k3);
}
void doubleWithRightChild(AvlNode *&k3)
{
rotateWithLeftChild(k3->right);
rotateWithRightChild(k3);
}
/**
* Internal method to remove from a subtree.
* x is the item to remove.
* t is the node that roots the subtree.
* Set the new root of the subtree.
*/
void remove(const Comparable &x, AvlNode *&t)
{
if (t == NULL)
return; // Item not found; do nothing
if (x < t->element)
remove(x, t->left);
else if (t->element < x)
remove(x, t->right);
else if (t->left != NULL && t->right != NULL) // Two children
{
t->element = findMin(t->right)->element;
remove(t->element, t->right);
}
else
{
AvlNode *oldNode = t;
t = (t->left != NULL) ? t->left : t->right;
delete oldNode;
}
balance(t);
}
/**
* Internal method to find the smallest item in a subtree t.
* Return node containing the smallest item.
*/
AvlNode *findMin(AvlNode *t) const
{
if (t == NULL)
return NULL;
if (t->left == NULL)
return t;
return findMin(t->left);
}
/**
* Internal method to find the largest item in a subtree t.
* Return node containing the largest item.
*/
AvlNode *findMax(AvlNode *t) const
{
if (t != NULL)
while (t->right != NULL)
t = t->right;
return t;
}
/**
* Internal method to test if an item is in a subtree.
* x is item to search for.
* t is the node that roots the subtree.
*/
bool contains(const Comparable &x, AvlNode *t)
{
if (t == NULL)
{
// t->containsInsertions += 1;
return false;
}
else if (x < t->element)
{
comparisonsForSearch += 1;
return contains(x, t->left);
}
else if (t->element < x)
{
comparisonsForSearch += 2;
return contains(x, t->right);
}
else{
comparisonsForSearch += 2;
return true; // Match
}
}
/****** NONRECURSIVE VERSION*************************
bool contains( const Comparable & x, AvlNode *t ) const
{
while( t != NULL )
if( x < t->element )
t = t->left;
else if( t->element < x )
t = t->right;
else
return true; // Match
return false; // No match
}
*****************************************************/
/**
* Internal method to make subtree empty.
*/
void makeEmpty(AvlNode *&t)
{
if (t != NULL)
{
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
t = NULL;
}
/**
* Internal method to print a subtree rooted at t in sorted order.
*/
void printTree(AvlNode *t, ostream &out) const
{
if (t != NULL)
{
printTree(t->left, out);
out << t->element << " ";
//print out the vector
out << right << setw(20 - t->element.size());
for (auto i = t->lineNumberList.begin(); i != t->lineNumberList.end() - 1; i++)
out << *i << ", ";
out << t->lineNumberList.back() << endl;
printTree(t->right, out);
}
}
void search(const Comparable &x, AvlNode *t, ostream &out = cout)
{
if (t != NULL)
{
if (t->element == x)
{
for (auto i = t->lineNumberList.begin(); i != t->lineNumberList.end() - 1; i++)
out << *i << ", ";
out << t->lineNumberList.back() << endl;
}
search(x, t->left, out);
search(x, t->right, out);
}
}
void findHeight(AvlNode *t, ostream &out = cout)
{
out << height(t);
}
void findSize(AvlNode *t, ostream &out = cout)
{
out << size(t);
}
void getComparisonsInsert(AvlNode *t, ostream &out = cout)
{
out << comparisonsForInsertions;
}
void getComparisonsContains(AvlNode *t, ostream &out = cout)
{
out << comparisonsForSearch;
}
int heights(AvlNode *t) const
{
return t == NULL ? -1 : t->height;
}
/**
* Internal method to clone subtree.
*/
AvlNode *clone(AvlNode *t) const
{
if (t == NULL)
return NULL;
else
return new AvlNode(t->element, clone(t->left), clone(t->right), t->lineNumberList);
}
public:
static int height(AvlNode *t)
{
// returns the height of the tree t
if (t == NULL)
return 0;
else
{
int p = height(t->left);
int q = height(t->right);
if (p < q)
return 1 + q;
else
return 1 + p;
}
}
static int size(AvlNode *t)
{
if (t == NULL)
return 0;
else
return 1 + size(t->left) + size(t->right);
}
AvlNode *getRoot()
{
return root;
}
};
#endif
|
//
// main.cpp
// Author: Michael Bao
// Date: 9/9/2015
//
#include "shared/algorithms/cluster/kmeans/dlib/DlibKmeansInterface.h"
#include "shared/algorithms/features/surf/dlib/DlibSURFInterface.h"
#include "shared/algorithms/ml/svm/dlib/DlibMulticlassSVMInterface.h"
#include "shared/utility/parse/simple/ImageLabelParser.h"
#include "shared/utility/type/STLVectorUtility.h"
#include <iostream>
constexpr int totalDictionaryWords = 100;
using PixelType = unsigned char;
template<typename T>
using KernelType = dlib::radial_basis_kernel<T>;
using Clusterer = DlibKmeansInterface<PixelType, KernelType, totalDictionaryWords, 64, 1>;
using FeatureExtractor = DlibSURFInterface<PixelType, Clusterer, totalDictionaryWords>;
using Classifier = DlibMulticlassSVMInterface<PixelType, FeatureExtractor, std::string>;
int main(int argc, char** argv)
{
if (argc < 2) {
REKOG_ERROR("Pass in training file.");
return 1;
}
std::string trainingFile(argv[1]);
// Training File contains pairs of images to labels.
std::vector<cv::Mat> images;
std::vector<std::string> labels;
ImageLabelParser::Parse(trainingFile, images, labels);
std::vector<std::pair<cv::Mat, std::string>> classificationData;
STLVectorUtility::ZipVectors(images, labels, classificationData);
std::unique_ptr<Classifier> classifier = std::make_unique<Classifier>();
classifier->InitializeInterface();
return 0;
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
using namespace std;
int f[110][110],a[110],s[110];
int main() {
int t;
scanf("%d",&t);
for (int ca = 1;ca <= t;ca++) {
int n;
scanf("%d",&n);
for (int i = 1;i <= n; i++) {
scanf("%d",&a[i]);
s[i] = s[i-1] + a[i];
}
for (int len = 1;len < n; len++)
for (int i = 1;i + len <= n; i++) {
int j = i + len;
f[i][j] = a[j]*len + f[i][j-1];
for (int k = i;k <= j; k++)
f[i][j] = min(f[i][j],f[i+1][k]+f[k+1][j]+(s[j]-s[k])*(k-i+1)+a[i]*(k-i));
//printf("%d %d %d\n",i,j,f[i][j]);
}
printf("Case #%d: %d\n",ca,f[1][n]);
}
return 0;
}
|
#include "hypothetical.hpp"
#include <algorithm>
#include <boost/format.hpp>
#include <worker/visitor/properties.hpp>
#include <worker/visitor/grid.hpp>
namespace svg {
namespace _hypo {
boost::format circle(visitor::Position const & p,
char const * const color) {
return boost::format(R"(<circle cx="%s" cy="%s" r="0.1" style="color:%s"/>)")
% p.breadth % p.depth % color;
}
boost::format arrow(visitor::Position const & s,
visitor::Position const & t,
char const * const color) {
return boost::format(R"(<line x1="%s" y1="%s" x2="%s" y2="%s" style="color:%s"/>)")
% s.breadth % s.depth % t.breadth % t.depth % color;
}
}
/*
* Show hypothetical positions in addition to consistent positions. Edges
* behind vertices, for asthetic reasons ;)
*/
void hypothetical(Graph const & g,
typename Graph::vertex_descriptor root,
std::stringstream & ss) {
visitor::Slots * pSlots = new visitor::Slots[boost::num_vertices(g)];
visitor::Color * pColoring = new visitor::Color[boost::num_vertices(g)];
visitor::computeHypothetical(g, root, pSlots, pColoring);
delete[] pColoring;
for (auto e : range_pair(boost::edges(g))) {
auto source = pSlots[boost::source(e, g)];
auto target = pSlots[boost::target(e, g)];
bool first = true;
std::for_each(source.begin(), source.end(), [&] (visitor::Slot const & s) {
std::for_each(target.begin(), target.end(), [&] (visitor::Slot const & t) {
ss << (first ? _hypo::arrow(s, t, "black") : _hypo::arrow(s, t, "red"));
first = false;
});
});
}
for (auto v : range_pair(boost::vertices(g))) {
auto slot = pSlots[v];
bool first = true;
std::for_each(slot.begin(), slot.end(), [&] (visitor::Slot const & s) {
ss << (first ? _hypo::circle(s, "black") : _hypo::circle(s, "red"));
first = false;
});
}
delete[] pSlots;
}
}
|
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
int main(){
int t;
cin >> t; //testcases
for(int i = 0; i < t; i++){
int n,x; // n = price of dress x = no. of dresses
cin >> n >> x;
vector<int>dress;
for(int i = 0; i < n; i++){
int c;
cin >> c;
dress.push_back(c);
}
if(dress.size() < x){
cout << "Bad husband"<<"\n";
}
if(dress.size() == x){
cout << "Perfect husband"<<"\n";
}
if(dress.size() > x){
cout << "Lame husband"<<"\n";
}
}
return 0;
}
|
#include <windows.h>
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);
ATOM InitApp(HINSTANCE);
BOOL InitInstance(HINSTANCE,int);
char szClassName[]="base";
int WINAPI WinMain(HINSTANCE hCurInst,HINSTANCE hPrevInst,LPSTR lpsCmdLine,int nCmdShow){
MSG msg;
BOOL bRet;
if(!InitApp(hCurInst))
return FALSE;
if(!InitInstance(hCurInst,nCmdShow))
return FALSE;
while((bRet=GetMessage(&msg,NULL,0,0))!=0){
if(bRet==-1){
break;
}else{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int)msg.wParam;
}
ATOM InitApp(HINSTANCE hInst){
WNDCLASSEX wc;
wc.cbSize=sizeof(WNDCLASSEX);
wc.style=CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc=WndProc;
wc.cbClsExtra=0;
wc.cbWndExtra=0;
wc.hInstance=hInst;
wc.hIcon = (HICON)LoadImage(NULL,
MAKEINTRESOURCE(IDI_APPLICATION),
IMAGE_ICON,
0,
0,
LR_DEFAULTSIZE | LR_SHARED);
wc.hCursor = (HCURSOR)LoadImage(NULL,
MAKEINTRESOURCE(IDC_ARROW),
IMAGE_CURSOR,
0,
0,
LR_DEFAULTSIZE | LR_SHARED);
wc.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName=NULL;
wc.lpszClassName=(LPCSTR)szClassName;
wc.hIconSm=(HICON)LoadImage(NULL,
MAKEINTRESOURCE(IDI_APPLICATION),IMAGE_ICON,
0,
0,
LR_DEFAULTSIZE | LR_SHARED);
return (RegisterClassEx(&wc));
}
BOOL InitInstance(HINSTANCE hInst,int nCmdShow){
HWND hWnd;
hWnd=CreateWindow(szClassName,
"寫了好幾次才成功= =\"",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
hInst,
NULL);
if(!hWnd)
return FALSE;
ShowWindow(hWnd,nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
LRESULT CALLBACK WndProc(HWND hWnd,UINT msg,WPARAM wp,LPARAM lp){
switch(msg){
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return (DefWindowProc(hWnd,msg,wp,lp));
}
return 0;
}
|
/*#include <iostream>
using namespace std;
// Recursive function to print from N to 1
int main()
{
int N, num;
cout << "enter any number" << endl;
cin >> num;
for (int i = num; i >= 0; i--)
cout << i << " ";
for (int i = 1; i <= num; i++)
{
cout << i << " ";
}
return 0;
}*/
|
#ifndef RAY_HPP
#define RAY_HPP
#include "../include/vector.hpp"
#include "../include/point.hpp"
#include "../include/color.hpp"
#include <list>
#include "shape.hpp"
#include "light_source.hpp"
class ray {
public:
ray();
ray(math3d::point const&, math3d::point const&);
ray(const ray& orig);
virtual ~ray();
color intersection(std::list<shape*> const&,std::list<light_source> const&);
color calcclr(ray_info const& ,shape* const&,std::list<shape*> const&,std::list<light_source> const&);
private:
math3d::vector direction_;
math3d::point source_;
color color_;
};
#endif /* RAY_HPP */
|
#include <iostream>
#include <queue>
#include <tuple>
#include <vector>
using namespace std;
using ll = long long;
bool visited[300010];
ll w[300010];
vector<pair<int, ll>> path[300010];
ll ans = 0;
ll dfs(int v) {
visited[v] = true;
priority_queue<ll> cost;
for (int i = 0; i < 2; ++i) {
cost.push(0);
}
for (auto p : path[v]) {
int sv;
ll c;
tie(sv, c) = p;
if (visited[sv]) continue;
cost.push(dfs(sv) - c);
}
ll c[2];
for (int i = 0; i < 2; ++i) {
c[i] = cost.top();
cost.pop();
}
ans = max(ans, c[0] + c[1] + w[v]);
return c[0] + w[v];
}
int main() {
int N;
cin >> N;
for (int v = 0; v < N; ++v) {
cin >> w[v];
}
for (int i = 0; i < N - 1; ++i) {
int u, v;
ll c;
cin >> u >> v >> c;
--u, --v;
path[u].push_back(make_pair(v, c));
path[v].push_back(make_pair(u, c));
}
dfs(0);
cout << ans << endl;
return 0;
}
|
#include "glut.h"
#include <stdio.h>
#include <string.h> //文字列関数のインクルード
#include "CModelX.h"
void CModelX::Load(char *file) {
//
//ファイルサイズを取得する
//
FILE *fp; //ファイルポインタ変数の作成
fp = fopen(file, "rb"); //ファイルをオープンする
if (fp == NULL) { //エラーチェック
printf("fopen error:%s\n", file);
return;
}
//ファイルの最後へ移動
fseek(fp, 0L, SEEK_END);
//ファイルサイズの取得
int size = ftell(fp);
//ファイルサイズ+1バイト分の領域を確保
char *buf = mpPointer = new char[size + 1];
//
//ファイルから3Dモデルのデータを読み込む
//
//ファイルの先頭へ移動
fseek(fp, 0L, SEEK_SET);
//確保した領域にファイルサイズ分データを読み込む
fread(buf, size, 1, fp);
//最後に\0を設定する(文字列の終端)
buf[size] = '\0';
fclose(fp); //ファイルをクローズする
//文字列の最後まで繰り返し
while (*mpPointer != '\0') {
GetToken(); //単語の取得
//単語がFrameの場合
if (strcmp(mToken, "Frame") == 0) {
printf("%s ", mToken); //Frame出力
GetToken(); //Frame名を取得
printf("%s\n", mToken); //Frame名を出力
}
else if (strcmp(mToken, "AnimationSet") == 0) {
printf("%s ", mToken); //AnimationSet出力
GetToken(); //AnimationSet名を取得
printf("%s\n", mToken); //AnimationSet名を出力
}
}
SAFE_DELETE_ARRAY(buf); //確保した領域を開放する
}
/*
GetToken
文字列データから、単語を1つ取得する
*/
void CModelX::GetToken() {
char* p = mpPointer;
char* q = mToken;
//空白( )タブ(\t)改行(\r)(\n),;”以外の文字になるまで読み飛ばす
/*
strchr(文字列, 文字)
文字列に文字が含まれていれば、見つかった文字へのポインタを返す
見つからなかったらNULLを返す
*/
while (*p != '\0' && strchr(" \t\r\n,;\"", *p)) p++;
if (*p == '{' || *p == '}') {
//{または}ならmTokenに代入し次の文字へ
*q++ = *p++;
}
else {
//空白( )タブ(\t)改行(\r)(\n),;”}の文字になるまでmTokenに代入する
while (*p != '\0' && !strchr(" \t\r\n,;\"}", *p))
*q++ = *p++;
}
*q = '\0'; //mTokenの最後に\0を代入
mpPointer = p; //次の読み込むポイントを更新する
//もしmTokenが//の場合は、コメントなので改行まで読み飛ばす
/*
strcmp(文字列1, 文字列2)
文字列1と文字列2が等しい場合、0を返します。
文字列1と文字列2が等しい場合、0以外を返します。
*/
if (!strcmp("//", mToken)) {
//改行まで読み飛ばす
while (*p != '\0' && !strchr("\r\n", *p)) p++;
//読み込み位置の更新
mpPointer = p;
//単語を取得する(再帰呼び出し)
GetToken();
}
}
|
#pragma once
////////////////////////////////////////////////////////////////////////////////
#include <Eigen/Dense>
////////////////////////////////////////////////////////////////////////////////
namespace cellogram {
bool read_tif_image(const std::string &path, Eigen::MatrixXd &img);
bool read_png_image(const std::string &path, Eigen::MatrixXd &img);
bool read_image(const std::string &path, Eigen::MatrixXd &img);
} // namespace cellogram
|
#pragma once
#include <string.h>
#include "net_base.h"
namespace sj
{
class udp_client;
class udp_client_handle
{
public:
virtual void OnRecv(udp_client * client, char * buf, size_t len) = 0;
virtual void OnSent(udp_client * client, char * buf, size_t len) = 0;
};
struct udp_client_config
{
std::string _server_ip; // 连接的服务器IP地址
int _server_port; // 连接的服务器端口
int _port; // 本机发送和接收端口
std::string _name; // 客户端名称
};
#define CHECK_ERR_CODE \
if (err_code != 0) \
{ \
_err_info = GetErrorInfo(err_code); \
return err_code; \
}
class udp_client
{
private:
struct uv_udp_t_with_client : public uv_udp_t
{
udp_client * _client;
};
struct recv_buf
{
char _buf[UDP_BUF_MAX_SIZE];
};
struct send_buf
{
udp_client * _client;
size_t _len;
char _buf[UDP_BUF_MAX_SIZE];
};
struct send_param : public uv_udp_send_t
{
send_buf * _send_buf;
};
public:
udp_client()
{
_client._client = this;
_handle = NULL;
uv_loop_init(&_loop);
}
~udp_client()
{
uv_loop_close(&_loop);
}
public:
bool Init(udp_client_config& cfg)
{
_config._server_ip = cfg._server_ip;
_config._server_port = cfg._server_port;
_config._port = cfg._port;
_config._name = cfg._name;
return true;
}
void SetHandle(udp_client_handle* uch)
{
_handle = uch;
}
int StartUp()
{
if (_handle == NULL)
{
_err_info = "no hanle";
return -1;
}
int err_code = uv_async_init(&_loop, &_async_send, udp_client::AsyncSend);
CHECK_ERR_CODE
err_code = uv_async_init(&_loop, &_async_close, udp_client::AsyncClose);
CHECK_ERR_CODE
err_code = uv_ip4_addr(_config._server_ip.c_str(), _config._server_port, &_server_addr);
CHECK_ERR_CODE
err_code = uv_ip4_addr(_config._server_ip.c_str(), _config._port, &_self_addr);
CHECK_ERR_CODE
err_code = uv_udp_init(&_loop, &_client);
CHECK_ERR_CODE
err_code = uv_udp_bind(&_client, (const sockaddr *)&_self_addr, 0);
CHECK_ERR_CODE
err_code = uv_udp_recv_start(&_client, udp_client::AllocCb, udp_client::RecvCb);
CHECK_ERR_CODE
err_code = uv_thread_create(&_thread, udp_client::Run, (void *)this);
CHECK_ERR_CODE
return 0;
}
int Send(const char * buf, size_t len)
{
if (len > UDP_BUF_MAX_SIZE)
{
_err_info = "send buf is too long";
return -1;
}
send_buf * data = _send_buf_stack.GetData();
data->_client = this;
data->_len = len;
memcpy((void *)data->_buf, (const void *)buf, len);
_async_send.data = (void *)data;
int err_code = uv_async_send(&_async_send);
CHECK_ERR_CODE
return 0;
}
int Close()
{
_async_close.data = (void *)this;
int err_code = uv_async_send(&_async_close);
CHECK_ERR_CODE
return 0;
}
private:
void SendInl(send_buf * data)
{
send_param * req = _send_param_stack.GetData();
req->_send_buf = data;
uv_buf_t msg = uv_buf_init((char*)data->_buf, data->_len);
int err_code = uv_udp_send(req,
&_client,
&msg,
1,
(const sockaddr*) &_server_addr,
udp_client::SendCb);
if (err_code != 0)
{
_err_info = GetErrorInfo(err_code);
}
}
private:
static void AsyncSend(uv_async_t * handle)
{
send_buf * data = (send_buf *)handle->data;
data->_client->SendInl(data);
}
static void AsyncClose(uv_async_t * handle)
{
udp_client * client = (udp_client *)handle->data;
int err_code = uv_udp_recv_stop(&(client->_client));
if (err_code != 0)
{
client->_err_info = GetErrorInfo(err_code);
}
uv_close((uv_handle_t *)(&(client->_client)), udp_client::CloseCb);
}
static void AllocCb(uv_handle_t * handle,
size_t suggested_size,
uv_buf_t * buf)
{
uv_udp_t_with_client * uwc = (uv_udp_t_with_client *)handle;
recv_buf * data = uwc->_client->_recv_buf_stack.GetData();
memset((void *)data->_buf, 0, UDP_BUF_MAX_SIZE);
buf->base = data->_buf;
buf->len = UDP_BUF_MAX_SIZE;
}
static void RecvCb(uv_udp_t * handle,
ssize_t nread,
const uv_buf_t * rcvbuf,
const sockaddr * addr,
unsigned flags)
{
uv_udp_t_with_client * uwc = (uv_udp_t_with_client *)handle;
do
{
if (nread <= 0)
{
break;
}
uwc->_client->_handle->OnRecv(uwc->_client, rcvbuf->base, nread);
} while(false);
uwc->_client->_recv_buf_stack.PutData((recv_buf *)rcvbuf->base);
}
static void SendCb(uv_udp_send_t* req, int status)
{
send_param * param = (send_param *)req;
param->_send_buf->_client->_handle->OnSent(param->_send_buf->_client,
param->_send_buf->_buf, param->_send_buf->_len);
param->_send_buf->_client->_send_buf_stack.PutData(param->_send_buf);
param->_send_buf->_client->_send_param_stack.PutData(param);
}
static void CloseCb(uv_handle_t * handle)
{
uv_is_closing(handle);
}
static void Run(void * data)
{
udp_client * client = (udp_client *)data;
int err_code = uv_run(&(client->_loop), UV_RUN_DEFAULT);
if (err_code != 0)
{
client->_err_info = GetErrorInfo(err_code);
}
}
private:
uv_loop_t _loop;
uv_async_t _async_send;
uv_async_t _async_close;
uv_thread_t _thread;
sockaddr_in _server_addr;
sockaddr_in _self_addr;
uv_udp_t_with_client _client;
udp_client_config _config;
udp_client_handle * _handle;
std::string _err_info;
data_stack<send_buf, 4> _send_buf_stack;
data_stack<send_param, 4> _send_param_stack;
data_stack<recv_buf, 4> _recv_buf_stack;
};
#undef CHECK_ERR_CODE
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
#include <cctype>
#include <cstdlib>
using namespace std;
void uppercaseify(string &str) {//Modify string to all uppercase
for(char &ch : str) ch = toupper(ch);
}
void die() {
cout << "Invalid Input!" << endl;
exit(EXIT_FAILURE); //Same as exit(1) except sexier
}
class Table {//Tables will hold VINS and designated by a name
string name = "";
vector<string> data = {};
public:
Table() {//default will not be used but here anyways
name = "BILL";
data = {};
}
Table(string new_name) {
name = new_name;
uppercaseify(new_name); //uppercaseify input
if(name != new_name) die(); //check to see if oringinal input was uppercase Bob != BOB
}
string get_name() {//becuase privates
return name;
}
bool contains(string key) {//See if a VIN is inside a table
for(string i : data) {
if(i == key) return true;
}
return false;
}
void add_table(const Table &rhs) { //Used for inserting entire tables into another...giggity
for(auto i : rhs.data) { //Iterating through table being passed in
this->insert(i); //This is the table that is invoking this function ex: this.add_table(rhs)
}
}
void insert(string new_car_or_vin) { //Insert individual values into a table
string temp = new_car_or_vin;
uppercaseify(temp);
if(temp != new_car_or_vin) die(); //Die if not uppercase
for(char c : new_car_or_vin){//Damn thing better not have special characters
if(!isdigit(c) && !isalpha(c)){
die();
}
}
if(contains(temp)) return; //No duplicates, we dont't take kindly to their kind
data.push_back(temp);//otherwise push on back
return;
}
void print_table() {//Syntax for printing out a table with its name and values
cout << name << ": ";
if(data_size() == 0){
cout << endl;
return;
}
unsigned int index = 0;
for(auto i : data) {
if(index == data_size()-1) cout << i << endl;
if(index != data_size()-1) cout << i << ", ";
index++;
}
}
void print_UI() {//For when we unionize or intersect and want to print out results
unsigned int index = 0;
for(auto i : data) {
if(index == data_size()-1) cout << i << endl;
if(index != data_size()-1) cout << i << ", ";
index++;
}
}
//Union means to add the tables together without duplicates because I forgot this twice in one afternoon!
Table union_fun(Table second){//Cause its fun
for(auto i : second.data){//Going through the second
auto it = find(data.begin(),data.end(),i);//Searching with values from the first
if(it == data.end()){//If it wasnt in there put it in the first
data.push_back(i);
}
}
return *this;//We want to return a table which must be dereferenced
}
void intersex(Table second){//That intersection action only pushing back values found in both
Table temp("INTER");
for(string i : data){
auto it = find(second.data.begin(),second.data.end(),i);
if(it != second.data.end()){
temp.data.push_back(i);
}
}
temp.print_UI();//And print in proper format
}
bool subset(Table second){//If we find a value that isnt in the second its no good
for(string i : data){
auto it = find(second.data.begin(),second.data.end(),i);
if(it == second.data.end()){
return false;
}
}
return true;
}
int data_size() {//Just cause
return data.size();
}
};
class MasterSet {//Class to hold all tables
private:
vector <Table> superset = {};
public:
MasterSet() {
superset = {};
}
bool search(string name) {///One function to find them
for(Table t : superset) {
if(t.get_name() == name) {
return true;
}
}
return false;
}
Table &search_id(string name) {//One funtion to return them
for(Table &t : superset) {
if(t.get_name() == name) {
return t;
}
}
die();
}
void insert(Table new_table) {//And in the darkness combine them!
superset.push_back(new_table);
}
int unique() {//Just need the number of unique values
int total;
Table t("UNIQUE");
for(Table x : superset) {//For every table we need to add them together minus duplicates...
t.union_fun(x); //Union prints out shit, but it got fixed, like a stray dog
}
total = t.data_size();//...and grab its size
return total;//Tada
}
void poset(){//Proper subset is a subset smaller than the parent set
for(Table y : superset){//
//Table temp_1 = y;
for(Table z : superset){
if(y.data_size() < z.data_size()){//Same deal as subset but we only evaluate if its smaller than the one we are running through
if(y.subset(z)){
cout << y.get_name() << " " << z.get_name() << endl;
}
}
}
}
return;
}
void print_masterset() {//Print that whole damn thing
for(Table t : superset) {
t.print_table();//With another fancy print function
}
}
};
MasterSet haystack;//Its the global haystack
int main() {
string user_input = "";
while(true) {
string command = "";//Going to be reading in a bunch of different strings
string table_id = "" , table_id_2 = "";
string values = "";
string name = "";
getline(cin, user_input); //Grab the entire line of user input
istringstream input(user_input);//Set up our own input stream with one line of user input
input >> command; //Read in the first word from the user input
if(command == "EXIT" || command == "") exit(1);//Just for me
else if(command == "CREATE"){
input >> command;
if(command == "TABLE") {
input >> name; //Now we have a table name coming in
if(name == "") die();
if(!haystack.search(name)) { //No duplicate tables
Table temp(name); //Create a table with our captured name
haystack.insert(temp); //insert our table into the haystack
} else die();//Die after every...single...if statement
} else die();
}
else if(command == "INSERT"){
input >> command;
if(command == "INTO") {
input >> table_id; //INSERT INTO <ID>
if(haystack.search(table_id)) {
//We've found the table we wish to insert values into
Table &temp = haystack.search_id(table_id);//Inserting into a table so we grab that table by reference to modify it
input >> command;
if(command == "VALUES") {
string needle;
//ws(input); //Strip white spacea might not need this one
getline(input,needle);//Set up a new input stream
istringstream csv(needle);
string values;
while( getline(csv,values,',') ) { //thanks stack overflow
//Strip the whitespace if any from values
values.erase(remove(values.begin(),values.end(),' '),values.end());
if(haystack.search(values)) {
//The value we're inserting is a table
Table unionT = haystack.search_id(values);
temp.add_table(unionT);
}
else {
temp.insert(values);
}
}
} else die();
}
if(!haystack.search(table_id)) {//Cause we cant insert into a table we dont have
die();
}
}
else die();
}
else if(command == "SELECT"){
input >> command;
if(command == "FROM"){
input >> table_id;
if(haystack.search(table_id)){//Make sure we have the table
input >> command;
if(command == "UNION"){
input >> table_id_2;
if(haystack.search(table_id_2)){//Make sure we have the other one
Table temp_1 = haystack.search_id(table_id);//Now grab the actual tables
Table temp_2 = haystack.search_id(table_id_2);
Table c = temp_1.union_fun(temp_2);//And smush them together
c.print_UI();//Vomit to screen
}
else die();
}
else die();
}
else die();
}
else if(command == "*"){
input >> command;
if(command == "FROM"){
input >> command;
if(command == "*"){
haystack.print_masterset();//Print out everything
cout << haystack.unique() << endl;//Print out number of uniques
}
else if(haystack.search(command)){
table_id = command;
input >> command;
if(command == "INNER"){
input >> command;
if(command == "JOIN"){
input >> command;
if(haystack.search(command)){
table_id_2 = command;
Table c = haystack.search_id(table_id);//Grab the tables again
Table d = haystack.search_id(table_id_2);
c.intersex(d);//Cause its funnier than intersection
}
else die();//Die mother trucker die
}
else die();
}
else die();
}
else die();
}
else die();
}
else die();
}
else if(command == "PRINT"){
input >> command;
if(command == "TABLE") {
input >> name;
if(haystack.search(name)) {
Table temp = haystack.search_id(name);
temp.print_table();
}
}
else if(command == "MASTER") {
haystack.print_masterset();
}
else die();
}
else if(command == "IS"){
input >> table_id;
if(haystack.search(table_id)){
input >> command;
if(command == "SUBSET"){
input >> table_id_2;
if(haystack.search(table_id_2)){
Table temp_1 = haystack.search_id(table_id);
Table temp_2 = haystack.search_id(table_id_2);
if(temp_1.subset(temp_2)){
cout << "TRUE" << endl;
}
else cout << "FALSE" << endl;
}
else die();
}
else die();
}
else die();
}
else if(command == "POSET"){
haystack.poset();
}
else die();
//WE LIVE WE DIE, WE LIVE AGAIN!!!!
int x = 42; //For luck
}
return 0;
}
|
#pragma once
#include "Vector2D.h"
#include "ColorRGB.h"
#include "ETSIDI.h"
using ETSIDI::SpriteSequence;
class coche
{
public:
void dibuja();
void setPos(float x, float y);
void setRad(float r);
void setOrientacion(int o);
void setTamaņo(int t);
Vector2D pos;
float limites[4]; // izquierda, derecha, arriba, abajo
float radio;
float t = 0,t1 = 0;
int flag = 0;
int p = 0;
int orientacion;
int tamaņo = 2;
int principal = 0;
int cas = 0;
float x = pos.x, y = pos.y;
void setColor(int r, int v, int a);
ColorRGB color;
};
|
/*********************************************************\
* Copyright (c) 2012-2018 The Unrimp 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 OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\*********************************************************/
//[-------------------------------------------------------]
//[ Header guard ]
//[-------------------------------------------------------]
#pragma once
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "Renderer/RenderTarget/IRenderTarget.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace Renderer
{
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
/**
* @brief
* Abstract render window interface which is used to implement some platform specific functionality regarding render window needed by the swap chain implementation
*
* @remarks
* This interface can be used to implement the needed platform specific functionality for a platform which isn't known by the renderer backend
* e.g. the user uses a windowing library (e.g. SDL2) which abstracts the window handling on different windowing platforms (e.g. Win32 or Linux/Wayland)
* and the application should run on a windowing platform which isn't supported by the swap chain implementation itself.
*/
class IRenderWindow
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Destructor
*/
inline virtual ~IRenderWindow();
//[-------------------------------------------------------]
//[ Public virtual IRendererWindow methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Return the width and height of the render window
*
* @param[out] width
* Width of the render window
* @param[out] height
* Height of the render window
*/
virtual void getWidthAndHeight(uint32_t& width, uint32_t& height) const = 0;
/**
* @brief
* Present the content of the current back buffer
*
* @note
* - Swap of front and back buffer
*/
virtual void present() = 0;
//[-------------------------------------------------------]
//[ Protected methods ]
//[-------------------------------------------------------]
protected:
inline IRenderWindow();
explicit IRenderWindow(const IRenderWindow& source) = delete;
IRenderWindow& operator =(const IRenderWindow& source) = delete;
};
/**
* @brief
* Abstract swap chain interface
*/
class ISwapChain : public IRenderTarget
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Destructor
*/
inline virtual ~ISwapChain() override;
//[-------------------------------------------------------]
//[ Public virtual ISwapChain methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Return the native window handle
*
* @return
* Native window handle the swap chain is using as output window, can be a null handle
*/
virtual handle getNativeWindowHandle() const = 0;
/**
* @brief
* Set vertical synchronization interval
*
* @param[in] synchronizationInterval
* Synchronization interval, >0 if vertical synchronization should be used, else zero
*/
virtual void setVerticalSynchronizationInterval(uint32_t synchronizationInterval) = 0;
/**
* @brief
* Present the content of the current back buffer
*
* @note
* - Swap of front and back buffer
*/
virtual void present() = 0;
/**
* @brief
* Call this method whenever the size of the native window was changed
*/
virtual void resizeBuffers() = 0;
/**
* @brief
* Return the current fullscreen state
*
* @return
* "true" if fullscreen, else "false"
*/
virtual bool getFullscreenState() const = 0;
/**
* @brief
* Set the current fullscreen state
*
* @param[in] fullscreen
* "true" if fullscreen, else "false"
*/
virtual void setFullscreenState(bool fullscreen) = 0;
/**
* @brief
* Set an render window instance
*
* @param[in] renderWindow
* The render window interface instance, can be a null pointer, if valid the instance must stay valid as long as it's connected to the swap chain instance
*
* @remarks
* This method can be used to override the platform specific handling for retrieving window size and doing an buffer swap on the render window (aka present).
* An instance can be set when the user don't want that the swap chain itself tempers with the given window handle (the handle might be invalid but non zero)
* e.g. the user uses a windowing library (e.g. SDL2) which abstracts the window handling on different windowing platforms (e.g. Win32 or Linux/Wayland) and
* the application should run on a windowing platform which isn't supported by the swap chain implementation itself.
*/
virtual void setRenderWindow(IRenderWindow* renderWindow) = 0;
//[-------------------------------------------------------]
//[ Protected methods ]
//[-------------------------------------------------------]
protected:
/**
* @brief
* Constructor
*
* @param[in] renderPass
* Render pass to use, the swap chain keeps a reference to the render pass
*/
inline explicit ISwapChain(IRenderPass& renderPass);
explicit ISwapChain(const ISwapChain& source) = delete;
ISwapChain& operator =(const ISwapChain& source) = delete;
};
//[-------------------------------------------------------]
//[ Type definitions ]
//[-------------------------------------------------------]
typedef SmartRefCount<ISwapChain> ISwapChainPtr;
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // Renderer
//[-------------------------------------------------------]
//[ Implementation ]
//[-------------------------------------------------------]
#include "Renderer/RenderTarget/ISwapChain.inl"
|
#include "hoist_request_subscriber.h"
CHoistRequestSubscriber::CHoistRequestSubscriber() :
m_pOnDataAvailable(nullptr)
{
}
CHoistRequestSubscriber::~CHoistRequestSubscriber()
{
}
bool CHoistRequestSubscriber::ValidData()
{
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
DataTypes::Uuid CHoistRequestSubscriber::GetId()
{
return m_data.id;
}
DataTypes::Priority CHoistRequestSubscriber::GetPriority()
{
return m_data.priority;
}
DataTypes::Time CHoistRequestSubscriber::GetTimeNeeded()
{
return m_data.timeNeeded;
}
DataTypes::Time CHoistRequestSubscriber::GetDuration()
{
return m_data.estimatedDuration;
}
meters_per_second_t CHoistRequestSubscriber::GetTargetVelocity()
{
return (meters_per_second_t)m_data.targetVelocity;
}
meter_t CHoistRequestSubscriber::GetTargetPosition()
{
return (meter_t)m_data.targetPosition;
}
bool CHoistRequestSubscriber::Create(int32_t domain)
{
return TSubscriber::Create(domain,
nec::process::HOIST_REQUEST,
"EdgeBaseLibrary",
"EdgeBaseProfile");
}
void CHoistRequestSubscriber::OnDataAvailable(OnDataAvailableEvent event)
{
m_pOnDataAvailable = event;
}
void CHoistRequestSubscriber::OnDataDisposed(OnDataDisposedEvent event)
{
m_pOnDataDisposed = event;
}
void CHoistRequestSubscriber::OnLivelinessChanged(OnLivelinessChangedEvent event)
{
m_pOnLivelinessChanged = event;
}
void CHoistRequestSubscriber::DataAvailable(const nec::process::HoistRequest &data,
const DDS::SampleInfo &sampleInfo)
{
m_sampleInfo = sampleInfo;
if (sampleInfo.valid_data == DDS_BOOLEAN_TRUE)
{
m_data = data;
if (m_pOnDataAvailable != nullptr)
{
m_pOnDataAvailable();
}
}
}
void CHoistRequestSubscriber::DataDisposed(const DDS::SampleInfo &sampleInfo)
{
LOG_INFO("Sample disposed");
m_sampleInfo = sampleInfo;
if (m_pOnDataDisposed != nullptr)
{
m_pOnDataDisposed(sampleInfo);
}
}
void CHoistRequestSubscriber::LivelinessChanged(const DDS::LivelinessChangedStatus &status)
{
if (m_pOnLivelinessChanged != nullptr)
{
m_pOnLivelinessChanged(status);
}
}
|
#include "GamePch.h"
#include "AI_HasHP.h"
#include "HealthModule.h"
extern bool g_bDebugAIBehaviors;
bool AI_HasHP::Check( Hourglass::Entity * entity )
{
if (!m_Health)
{
m_Health = entity->GetComponent<Health>();
}
if (m_Health)
{
if (g_bDebugAIBehaviors)
{
char buf[1024];
sprintf_s(buf, "\n\nHP: %f", m_Health->GetValue());
hg::DevTextRenderer::DrawText_WorldSpace(buf, entity->GetPosition());
}
return m_Health->GetValue() > 0;
}
if (g_bDebugAIBehaviors)
{
hg::DevTextRenderer::DrawText_WorldSpace("\n\nAI has no HP", entity->GetPosition());
}
return false;
}
hg::IBehavior* AI_HasHP::MakeCopy() const
{
AI_HasHP* copy = (AI_HasHP*)IBehavior::Create( SID( AI_HasHP ) );
copy->m_Health = nullptr;
return copy;
}
|
//
// Created by jeremyelkayam on 9/29/20.
//
#pragma once
#include "screen.hpp"
#include "menu/main_menu_screen.hpp"
class TitleScreen : public Screen {
private:
sf::Sprite title_background;
sf::Sound title_theme;
bool screen_over;
public:
TitleScreen(TextLoader &text_loader, ResourceManager &resource_manager,
InputManager &an_input_manager);
void draw(sf::RenderWindow &window, ColorGrid &color_grid) override;
bool go_to_next() override;
void handle_event(sf::Event &evt) override;
unique_ptr<Screen> next_screen() override;
};
|
#include "Qt_Battery_View.h"
using namespace cv;
using namespace std;
Qt_Battery_View::Qt_Battery_View(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
}
void Qt_Battery_View::on_OpenFig_clicked()
{
QString filename;
filename = QFileDialog::getOpenFileName(this,
tr("choose img"),
"",
tr("Images (*.png *.bmp *.jpg *.tif *.GIF )"));
if (filename.isEmpty())
{
return;
}
else
{
//QImage* img = new QImage;
//if (!(img->load(filename))) //加载图像
//{
// QMessageBox::information(this,
// tr("打开图像失败"),
// tr("打开图像失败!"));
// delete img;
// return;
//}
string str = filename.toStdString(); // 将filename转变为string类型;
image = imread(str);
//image=imread(fileName.toLatin1().data);
cvtColor(image, image, CV_BGR2RGB);
cv::resize(image, image, Size(300, 200));
QImage img = QImage((const unsigned char*)(image.data), image.cols, image.rows, QImage::Format_RGB888);
label = new QLabel();
label->setPixmap(QPixmap::fromImage(img));
label->resize(QSize(img.width(), img.height()));
ui.scrollArea->setWidget(label);
}
}
void Qt_Battery_View::on_Progress_clicked()
{
//读取图像
dst_image = imread("C:\\Users\\Administrator\\Desktop\\2.jpg",1);
//BGR转RGB
cvtColor(dst_image, dst_image, CV_BGR2RGB);
//修改图像大小
cv::resize(dst_image, dst_image,Size(400,400));
//创建一个QImage类存放图像
QImage img1 = QImage((const unsigned char*)(dst_image.data), dst_image.cols, dst_image.rows, QImage::Format_RGB888);
//创建一个QLabel类来显示图像
label_2 = new QLabel();
//将QImage的内容填入QLabel
label_2->setPixmap(QPixmap::fromImage(img1));
// label_2->resize(QSize(img1.width(), img1.height()));
//设置ScrollArea显示的大小以及显示链接的label
ui.scrollArea_2->setWidget(label_2);
//scrollArea最大显示的长宽
ui.scrollArea_2->setMaximumHeight(768);
ui.scrollArea_2->setMaximumWidth(1024);
ui.scrollArea_2->resize(QSize(img1.width()+5, img1.height()+5));
//多余背景全黑
ui.scrollArea_2->setBackgroundRole(QPalette::Dark);
//显示图片
ui.scrollArea_2->show();
}
|
#include <iostream>
#include <stdlib.h>
#include <cmath>
#include "Network.h"
/**
NOTES
OPTIMIZATION
-While there are General GPU functions (like GPUCopy) code reuse is not used if there is a specific CUDA function for a function to reduce stack jumps
Im not sure which configurations we will want to save, perhaps the seeds? Will need to figure this out for A E S T H E T I C S and also the best performance
The recurrency pipeline could use some significant optimization
*/
//The inputs are always from the input gates independent of the forward or backward pass functions. Output is what the forward pass calculated
void softmax (double* inputs, int length, double* outputTo){
}
void softplus (double* inputs, int length, double* outputTo){
for (int i=0;i<length;i++){
outputTo[i] = log (1+exp(inputs[i]));
}
}
void linrec (double* inputs, int length, double* outputTo){
}
void softmaxder (double* inputs, double* outputs, int length, double* outputTo){
}
void softplusder (double* inputs, double* outputs, int length, double* outputTo){
//sigmoid(inputs, length, outputTo);
}
void linrecder (double* inputs, double* outputs, int length, double* outputTo){
}
GateType::GateType (string type, int minInputs, int maxInputs, bool canChangeInandOutLengthWithoutConstraint){
this->type = type;
this->minInputs = minInputs;
this->maxInputs = maxInputs;
this->canChangeInandOutLengthWithoutConstraint = canChangeInandOutLengthWithoutConstraint;
}
const int TYPEINPUT = 0;
const int TYPEOUTPUT = 1;
const int TYPEWEIGHT = 2;
const int TYPEACTIVATION = 3;
const int TYPEMERGE = 4;
const int TYPEOUTPUTRECURRENT = 5;
const int TYPECONCATENATE = 6;
const GateType GATETYPEINPUT ("INPUT", 0, 0, false);
const GateType GATETYPEOUTPUT ("OUTPUT", 1, 1, false);
const GateType GATETYPEWEIGHT ("WEIGHT", 1, 1, true);
const GateType GATETYPEACTIVATION ("ACTIVATION", 1, 1, false);
const GateType GATETYPEMERGE ("MERGE", 2, 2, false);
const GateType GATETYPEOUTPUTRECURRENT ("OUTPUTRECURRENT", 1, 1, false);
const GateType GATETYPECONCATENATE ("CONCATENATE", 2, 2, false);
//The index on this array is what is set in the constructors of the gates
const GateType GateTypeParams [6] = {GATETYPEINPUT, GATETYPEOUTPUT, GATETYPEWEIGHT, GATETYPEACTIVATION, GATETYPEMERGE, GATETYPEOUTPUTRECURRENT};
Gate::Gate (int outputsLength, bool staticInputs, bool staticOutputs, bool staticTraining) {
this->outputsLength = outputsLength;
this->staticInputs = staticInputs;
this->staticOutputs = staticOutputs;
this->staticTraining = staticTraining;
index = -1;
derivativesInCurrent = 0;
derivativesInDev = 0;
GPUMalloc ((void**)&derivativesTotalDev, outputsLength*sizeof(double));
}
void Gate::resetDerivativeArrays (){
GPUFree (derivativesInDev);
GPUMalloc ((void**)&derivativesInDev, outputsLength*outputGates.size()*sizeof(double));
derivativesInCurrent = 0;
}
GateInput::GateInput (int outputsLength, bool staticInputs, bool staticOutputs, bool staticTraining) : Gate (outputsLength, staticInputs, staticOutputs, staticTraining) {
type = TYPEINPUT;
linkedTo = -1;
indexinput = -1;
}
void GateInput::forwardPass (int pass){}
void GateInput::backwardPass (int pass){
GateInputbackwardPass(derivativesTotalDev, derivativesInDev, outputsLength, derivativesInCurrent);
}
void GateInput::prePass (int forwardpassLength){
outputsDev = new double*[forwardpassLength];
for (int i=0;i<forwardpassLength;i++){
GPUMalloc ((void**)&(outputsDev[i]), outputsLength*sizeof(double));
}
}
void GateInput::postPass (int oldforwardpassLength){
for (int i=0;i<oldforwardpassLength;i++){
GPUFree (outputsDev[i]);
}
delete [] outputsDev;
}
void GateInput::setOutputs (double** setoutputs, int forwardPassLength){
for (int i=0;i<forwardPassLength;i++){
GPUMemcpyHTD (outputsDev[i], setoutputs[i], outputsLength*sizeof(double));
}
}
void GateInput::setOutputsGPU (double* setoutputsDev, int pass){
GPUCopy (setoutputsDev, outputsDev[pass], outputsLength);
}
GateOutput::GateOutput (int outputsLength, bool staticInputs, bool staticOutputs, bool staticTraining, void (*errorFunction)(double*, double*, double*, int), void (*errorFunctionDer)(double*, double*, double*, double*, int, int)) : Gate (outputsLength, staticInputs, staticOutputs, staticTraining) {
type = TYPEOUTPUT;
this->errorFunction = errorFunction;
this->errorFunctionDer = errorFunctionDer;
GPUMalloc ((void**)&errorsDev, outputsLength*sizeof(double));
}
void GateOutput::forwardPass (int pass){
errorFunction (inputGates[0]->outputsDev[pass], actualDev[pass], outputsDev[pass], outputsLength);
}
void GateOutput::backwardPass (int pass){
errorFunctionDer(inputGates[0]->outputsDev[pass], actualDev[pass], outputsDev[pass], inputGates[0]->derivativesInDev, inputGates[0]->derivativesInCurrent, outputsLength);
inputGates[0]->derivativesInCurrent++;
}
void GateOutput::prePass (int forwardpassLength){
outputsDev = new double*[forwardpassLength];
actualDev = new double*[forwardpassLength];
for (int i=0;i<forwardpassLength;i++){
GPUMalloc ((void**)&(outputsDev[i]), outputsLength*sizeof(double));
GPUMalloc ((void**)&(actualDev[i]), outputsLength*sizeof(double));
}
}
void GateOutput::postPass (int oldforwardpassLength){
for (int i=0;i<oldforwardpassLength;i++){
GPUFree (outputsDev[i]);
GPUFree (actualDev[i]);
}
delete [] outputsDev;
delete [] actualDev;
}
void GateOutput::setActual(double** actualset, int forwardPassLength){
for (int i=0;i<forwardPassLength;i++){
GPUMemcpyHTD (actualDev[i], actualset[i], outputsLength*sizeof(double));
}
}
GateOutputRecurrent::GateOutputRecurrent (int outputsLength, bool staticInputs, bool staticOutputs, bool staticTraining) : Gate (outputsLength, staticInputs, staticOutputs, staticTraining) {
type = TYPEOUTPUTRECURRENT;
linkedTo = -1;
}
void GateOutputRecurrent::forwardPass (int pass){
GateOutputRecurrentforwardPass(inputGates[0]->outputsDev[pass], outputsDev[pass], outputsLength);
}
void GateOutputRecurrent::backwardPass (int pass){
GateOutputRecurrentbackwardPass(derivativesTotalDev, inputGates[0]->derivativesInDev, inputGates[0]->derivativesInCurrent, outputsLength);
inputGates[0]->derivativesInCurrent++;
}
void GateOutputRecurrent::prePass (int forwardpassLength){
outputsDev = new double*[forwardpassLength];
for (int i=0;i<forwardpassLength;i++){
GPUMalloc ((void**)&(outputsDev[i]), outputsLength*sizeof(double));
}
GPUSetToZero (derivativesTotalDev, outputsLength);
}
void GateOutputRecurrent::postPass (int oldforwardpassLength){
for (int i=0;i<oldforwardpassLength;i++){
GPUFree (outputsDev[i]);
}
delete [] outputsDev;
}
void GateOutputRecurrent::setDerivatives (double* setDerivatives){
GPUCopy(setDerivatives, derivativesTotalDev, outputsLength);
}
GateWeight::GateWeight (int outputsLength, bool staticInputs, bool staticOutputs, bool staticTraining, double learningRate, int inputsLength, double weightInitial) : Gate (outputsLength, staticInputs, staticOutputs, staticTraining) {
type = TYPEWEIGHT;
if (staticTraining){
this->learningRate = 0;
} else {
this->learningRate = learningRate;
}
this->inputsLength = inputsLength;
GPUMalloc ((void**)&weightsDev, outputsLength*(inputsLength+1)*sizeof(double));
double* temp = new double [(inputsLength+1)*outputsLength];
srand(2);
for (int i=0;i<outputsLength*(inputsLength+1);i++){
temp[i] = ((double) rand() / (RAND_MAX))*weightInitial;
}
GPUMemcpyHTD(weightsDev, temp, outputsLength*(inputsLength+1)*sizeof(double));
delete [] temp;
}
void GateWeight::forwardPass (int pass){
GateWeightforwardPass(weightsDev, inputGates[0]->outputsDev[pass], outputsDev[pass], outputsLength, inputsLength);
}
void GateWeight::backwardPass (int pass){
GateWeightbackwardPass(weightsDev, derivativesTotalDev, derivativesInDev, inputGates[0]->outputsDev[pass], inputGates[0]->derivativesInDev, inputGates[0]->derivativesInCurrent, outputsLength, inputsLength, derivativesInCurrent, learningRate);
inputGates[0]->derivativesInCurrent++;
}
void GateWeight::prePass (int forwardpassLength){
outputsDev = new double*[forwardpassLength];
for (int i=0;i<forwardpassLength;i++){
GPUMalloc ((void**)&(outputsDev[i]), outputsLength*sizeof(double));
}
}
void GateWeight::postPass (int oldforwardpassLength){
for (int i=0;i<oldforwardpassLength;i++){
GPUFree (outputsDev[i]);
}
delete [] outputsDev;
}
GateActivation::GateActivation (int outputsLength, bool staticInputs, bool staticOutputs, bool staticTraining, void (*activationFunction)(double*, double*, int), void (*activationFunctionDerivative)(double*, double*, double*, double*, double*, int, int, int)) : Gate (outputsLength, staticInputs, staticOutputs, staticTraining) {
type = TYPEACTIVATION;
this->activationFunction = activationFunction;
this->activationFunctionDerivative = activationFunctionDerivative;
}
void GateActivation::forwardPass (int pass){
activationFunction(inputGates[0]->outputsDev[pass], outputsDev[pass], outputsLength);
}
void GateActivation::backwardPass (int pass){
activationFunctionDerivative(inputGates[0]->outputsDev[pass], outputsDev[pass], derivativesTotalDev, derivativesInDev, inputGates[0]->derivativesInDev, inputGates[0]->derivativesInCurrent, derivativesInCurrent, outputsLength);
inputGates[0]->derivativesInCurrent++;
}
void GateActivation::prePass (int forwardpassLength){
outputsDev = new double*[forwardpassLength];
for (int i=0;i<forwardpassLength;i++){
GPUMalloc ((void**)&(outputsDev[i]), outputsLength*sizeof(double));
}
}
void GateActivation::postPass (int oldforwardpassLength){
for (int i=0;i<oldforwardpassLength;i++){
GPUFree (outputsDev[i]);
}
delete [] outputsDev;
}
GateMerge::GateMerge (int outputsLength, bool staticInputs, bool staticOutputs, bool staticTraining, void (*mergeFunction)(double*, double*, double*, int), void (*mergeFunctionDerivative)(double*, double*, double*, double*, double*, double*, double*, int, int, int, int)) : Gate (outputsLength, staticInputs, staticOutputs, staticTraining) {
type = TYPEMERGE;
this->mergeFunction = mergeFunction;
this->mergeFunctionDerivative = mergeFunctionDerivative;
}
void GateMerge::forwardPass (int pass){
mergeFunction(inputGates[0]->outputsDev[pass], inputGates[1]->outputsDev[pass], outputsDev[pass], outputsLength);
}
void GateMerge::backwardPass (int pass){
mergeFunctionDerivative(inputGates[0]->outputsDev[pass], inputGates[1]->outputsDev[pass], outputsDev[pass], derivativesTotalDev, derivativesInDev, inputGates[0]->derivativesInDev, inputGates[1]->derivativesInDev, inputGates[0]->derivativesInCurrent, inputGates[1]->derivativesInCurrent, derivativesInCurrent, outputsLength);
inputGates[0]->derivativesInCurrent++;
inputGates[1]->derivativesInCurrent++;
}
void GateMerge::prePass (int forwardpassLength){
outputsDev = new double*[forwardpassLength];
for (int i=0;i<forwardpassLength;i++){
GPUMalloc ((void**)&(outputsDev[i]), outputsLength*sizeof(double));
}
}
void GateMerge::postPass (int oldforwardpassLength){
for (int i=0;i<oldforwardpassLength;i++){
GPUFree (outputsDev[i]);
}
delete [] outputsDev;
}
GateConcatenate::GateConcatenate (int outputsLength, bool staticInputs, bool staticOutputs, bool staticTraining) : Gate (outputsLength, staticInputs, staticOutputs, staticTraining){
type = TYPECONCATENATE;
}
void GateConcatenate::forwardPass (int pass){
GateConcatenateforwardPass(inputGates[0]->outputsDev[pass], inputGates[1]->outputsDev[pass], outputsDev[pass], inputGates[0]->outputsLength, inputGates[1]->outputsLength);
}
void GateConcatenate::backwardPass (int pass){
GateConcatenatebackwardPass(derivativesTotalDev, derivativesInDev, inputGates[0]->derivativesInDev, inputGates[1]->derivativesInDev, inputGates[0]->derivativesInCurrent, inputGates[1]->derivativesInCurrent, derivativesInCurrent, outputsLength, inputGates[0]->outputsLength, inputGates[1]->outputsLength);
inputGates[0]->derivativesInCurrent++;
inputGates[1]->derivativesInCurrent++;
}
void GateConcatenate::prePass (int forwardpassLength){
outputsDev = new double*[forwardpassLength];
for (int i=0;i<forwardpassLength;i++){
GPUMalloc ((void**)&(outputsDev[i]), outputsLength*sizeof(double));
}
}
void GateConcatenate::postPass (int oldforwardpassLength){
for (int i=0;i<oldforwardpassLength;i++){
GPUFree (outputsDev[i]);
}
delete [] outputsDev;
}
Network::Network (){}
int Network::AddGate (Gate* gate){
gate->index = AllGates.size();
AllGates.push_back(gate);
if (gate->type == TYPEINPUT){
GateInput* temp = dynamic_cast<GateInput*>(gate);
temp->indexinput = InputGates.size();
InputGates.push_back(temp);
}
return gate->index; //INDEX OF GATE
}
void Network::RemoveGate (int gateIndex){
}
void Network::AddConnection (int senderIndex, int receiverIndex){
Connection* temp = new Connection;
temp->senderIndex = senderIndex;
temp->receiverIndex = receiverIndex;
GateConnectionsCurrent.push_back(temp);
}
void Network::SetInputOutputLinked (int index, int linkedTo){
GateInput* temp = dynamic_cast<GateInput*>(AllGates[index]);
temp->linkedTo = linkedTo;
if (linkedTo > LINKEDTONOTHING){
GateOutputRecurrent* temp2 = dynamic_cast<GateOutputRecurrent*>(AllGates[linkedTo]);
temp2->linkedTo = index;
}
}
void Network::ForwardPass (int* inputsIndicies, double*** inputValues, int inputLength, int* outputIndicies, double*** actualValues, int outputLength, int forwardPassLength){
for (int i=0;i<ComputeOrder.size();i++){
ComputeOrder[i]->prePass(forwardPassLength);
}
for (int i=0;i<inputLength;i++){
GateInput* temp = dynamic_cast<GateInput*>(AllGates[inputsIndicies[i]]);
temp->setOutputs(inputValues[i], forwardPassLength);
}
for (int i=0;i<outputLength;i++){
GateOutput* temp = dynamic_cast<GateOutput*>(AllGates[outputIndicies[i]]);
temp->setActual(actualValues[i], forwardPassLength);
}
for (int i=0;i<forwardPassLength-1;i++){
for (int j=0;j<ComputeOrder.size();j++){
ComputeOrder[j]->forwardPass(i);
}
LinkRecurrentForward(i);
}
for (int i=0;i<ComputeOrder.size();i++){
ComputeOrder[i]->forwardPass(forwardPassLength-1);
}
}
void Network::ForwardPassTestFirst (int* inputsIndicies, double*** inputValues, int inputLength, int forwardPassLength){
for (int i=0;i<ComputeOrder.size();i++){
ComputeOrder[i]->prePass(forwardPassLength);
}
for (int i=0;i<inputLength;i++){
GateInput* temp = dynamic_cast<GateInput*>(AllGates[inputsIndicies[i]]);
temp->setOutputs(inputValues[i], forwardPassLength);
}
for (int i=0;i<forwardPassLength-1;i++){
for (int j=0;j<ComputeOrder.size();j++){
ComputeOrder[j]->forwardPass(i);
}
LinkRecurrentForward(i);
}
for (int i=0;i<ComputeOrder.size();i++){
ComputeOrder[i]->forwardPass(forwardPassLength-1);
}
}
void Network::ForwardPassTestLast (int forwardPassLength){
for (int j=0;j<ComputeOrder.size();j++){
ComputeOrder[j]->postPass(forwardPassLength);
}
}
void Network::BackwardPass (int forwardPassLength){
for (int i=forwardPassLength-1;i>=1;i--){
for (int j=ComputeOrder.size()-1;j>=0;j--){
ComputeOrder[j]->backwardPass(i);
}
LinkRecurrentBackward();
for (int j=0;j<ComputeOrder.size();j++){
ComputeOrder[j]->derivativesInCurrent = 0;
}
}
for (int i=ComputeOrder.size()-1;i>=0;i--){
ComputeOrder[i]->backwardPass(0);
}
for (int j=0;j<ComputeOrder.size();j++){
ComputeOrder[j]->derivativesInCurrent = 0;
}
for (int j=0;j<ComputeOrder.size();j++){
ComputeOrder[j]->postPass(forwardPassLength);
}
}
void Network::ReconfigureGates (){
for (int i=0;i<AllGates.size();i++){
if (AllGates[i]->staticInputs==false){
AllGates[i]->inputGates.clear();
}
if (AllGates[i]->staticOutputs==false){
AllGates[i]->outputGates.clear();
}
}
for (int i=0;i<GateConnectionsCurrent.size();i++){
if (AllGates[GateConnectionsCurrent[i]->senderIndex]->staticOutputs==false){
AllGates[GateConnectionsCurrent[i]->senderIndex]->outputGates.push_back(AllGates[GateConnectionsCurrent[i]->receiverIndex]);
}
if (AllGates[GateConnectionsCurrent[i]->receiverIndex]->staticInputs==false){
AllGates[GateConnectionsCurrent[i]->receiverIndex]->inputGates.push_back(AllGates[GateConnectionsCurrent[i]->senderIndex]);
}
}
}
void Network::FindComputerOrder (){
vector<int> computeLevels = {0};
vector<Gate*> tempOrder;
int currentLevel = 0;
for (int i=0;i<InputGates.size();i++){
tempOrder.push_back(InputGates[i]);
}
computeLevels.push_back(tempOrder.size());
currentLevel++;
bool done = false;
bool alreadyAdded[AllGates.size()];
for (int i=0;i<AllGates.size();i++){
alreadyAdded[i] = false;
}
while (!done){
done = true;
for (int i=computeLevels[currentLevel-1];i<computeLevels[currentLevel];i++){
if (tempOrder[i]->type!=TYPEMERGE||tempOrder[i]->type!=TYPECONCATENATE){
for (int j=0;j<tempOrder[i]->outputGates.size();j++){
if (!alreadyAdded[tempOrder[i]->outputGates[j]->index]){
tempOrder.push_back(tempOrder[i]->outputGates[j]);
alreadyAdded[tempOrder[i]->outputGates[j]->index] = true;
done = false;
}
}
}
}
computeLevels.push_back(tempOrder.size());
//Having a variable in the gates to easily check compute level would be better but I refuse to do that for a specific outside function
for (int i=computeLevels[currentLevel];i<tempOrder.size();i++){
if (tempOrder[i]->type==TYPEMERGE||tempOrder[i]->type==TYPECONCATENATE){
bool parent1 = false;
bool parent2 = false;
for (int j=0;j<computeLevels[currentLevel];j++){
if (tempOrder[i]->inputGates[0]->index==tempOrder[j]->index){
parent1 = true;
} else if (tempOrder[i]->inputGates[1]->index==tempOrder[j]->index){
parent2 = true;
}
}
if (!parent1||!parent2){
Gate* tempGate = tempOrder[i];
tempOrder.erase(tempOrder.begin() + i);
tempOrder.push_back(tempGate);
computeLevels[currentLevel+1]--;
done = false;
} else {
for (int j=0;j<tempOrder[i]->outputGates.size();j++){
if (!alreadyAdded[tempOrder[i]->outputGates[j]->index]){
tempOrder.push_back(tempOrder[i]->outputGates[j]);
alreadyAdded[tempOrder[i]->outputGates[j]->index] = true;
computeLevels[currentLevel+1]++;
done = false;
}
}
}
}
}
currentLevel++;
}
ComputeOrder = tempOrder;
//test
cout<<"Compute Order:"<<endl;
for (int i=0;i<tempOrder.size();i++){
cout<<tempOrder[i]->index<<endl;
}
cout<<endl;
//test
}
void Network::PostConfiguration (){
for (int i=0;i<ComputeOrder.size();i++){
ComputeOrder[i]->resetDerivativeArrays();
}
}
void Network::LinkRecurrentForward (int pass){
for (int i=0;i<InputGates.size();i++){
if (InputGates[i]->linkedTo>-1){
InputGates[i]->setOutputsGPU(AllGates[InputGates[i]->linkedTo]->outputsDev[pass], pass+1);
}
}
}
void Network::LinkRecurrentBackward (){
for (int i=0;i<InputGates.size();i++){
if (InputGates[i]->linkedTo>-1){
GateOutputRecurrent* temp = dynamic_cast<GateOutputRecurrent*>(AllGates[InputGates[i]->linkedTo]);
temp->setDerivatives(InputGates[i]->derivativesTotalDev);
}
}
}
void Network::TrainWithTestStop (InputData* trainingData, int iterations, int printErrorStride){
double sum = 0;
double** tempOutputs = new double*[trainingData->outputLength];
for (int i=0;i<trainingData->outputLength;i++){
tempOutputs[i] = new double[AllGates[trainingData->outputIndicies[i]]->outputsLength];
}
for (int h=0;h<iterations;h++){
for (int k=0;k<trainingData->totalPasses;k++){
ForwardPass(trainingData->inputsIndicies, trainingData->inputPasses[k].inputValues, trainingData->inputLength, trainingData->outputIndicies, trainingData->inputPasses[k].actualValues, trainingData->outputLength, trainingData->inputPasses[k].forwardPassLength);
if (h%printErrorStride==0){
cout<<"Pass: "<<h<<" "<<"Set: "<<k<<endl;
for (int l=0;l<trainingData->outputLength;l++){
sum = 0;
cout<<" Out: "<<l<<" ";
for (int j=0;j<trainingData->inputPasses[k].forwardPassLength;j++){
GPUMemcpyDTH (tempOutputs[l], AllGates[trainingData->outputIndicies[l]]->outputsDev[j], AllGates[trainingData->outputIndicies[l]]->outputsLength*sizeof(double));
for (int i=0;i<AllGates[trainingData->outputIndicies[l]]->outputsLength;i++){
sum += tempOutputs[l][i];
}
}
cout<<sum<<" "<<endl;
}
}
BackwardPass(trainingData->inputPasses[k].forwardPassLength);
}
}
for (int i=0;i<trainingData->outputLength;i++){
delete [] tempOutputs[i];
}
delete [] tempOutputs;
}
void Network::RunTestData (InputDataTest* testData){
double sum = 0;
double** tempOutputs = new double*[testData->outputLength];
for (int i=0;i<testData->outputLength;i++){
tempOutputs[i] = new double[AllGates[testData->outputIndicies[i]]->outputsLength];
}
for (int k=0;k<testData->totalPasses;k++){
ForwardPassTestFirst(testData->inputsIndicies, testData->inputTestPasses[k].inputValues, testData->inputLength, testData->inputTestPasses[k].forwardPassLength);
cout<<"Set: "<<k<<endl;
for (int l=0;l<testData->outputLength;l++){
sum = 0;
cout<<" Out: "<<l<<" ";
for (int j=0;j<testData->inputTestPasses[k].forwardPassLength;j++){
GPUMemcpyDTH (tempOutputs[l], AllGates[testData->outputIndicies[l]]->outputsDev[j], AllGates[testData->outputIndicies[l]]->outputsLength*sizeof(double));
for (int i=0;i<AllGates[testData->outputIndicies[l]]->outputsLength;i++){
sum += tempOutputs[l][i];
}
}
cout<<sum<<" "<<endl;
}
ForwardPassTestLast(testData->inputTestPasses[k].forwardPassLength);
}
for (int i=0;i<testData->outputLength;i++){
delete [] tempOutputs[i];
}
delete [] tempOutputs;
}
void Network::CreateNextGeneration (){
}
int Network::RunGeneration (){
return 0;
}
|
#ifndef CAFFE_MPI_BASE_LAYER_HPP_
#define CAFFE_MPI_BASE_LAYER_HPP_
#include <string>
#include <utility>
#include <vector>
#include <mpi.h>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
template <typename Dtype>
class MPIBaseLayer : public Layer<Dtype> {
public:
explicit MPIBaseLayer(const LayerParameter& param)
: Layer<Dtype>(param) {
//Set up MPI variables
this->comm_ = (MPI_Comm)param.mpi_param().comm_id();
this->group_ = (MPI_Group)param.mpi_param().group_id();
MPI_Comm_rank(MPI_COMM_WORLD, &this->world_rank_);
MPI_Comm_size(MPI_COMM_WORLD, &this->world_size_);
MPI_Comm_rank(this->comm_, &this->comm_rank_);
MPI_Comm_size(this->comm_, &this->comm_size_);
//Verify root is in local communicator
MPI_Group world_group;
MPI_Comm_group(MPI_COMM_WORLD, &world_group);
int old_src = param.mpi_param().root();
MPI_Group_translate_ranks(world_group, 1, &old_src, this->group_, &this->comm_root_);
CHECK(MPI_UNDEFINED != this->comm_root_) << "MPI Root not listed included in layer group.";
}
protected:
MPI_Comm comm_;
MPI_Group group_;
int comm_rank_;
int comm_size_;
int world_size_;
int world_rank_;
int comm_root_;
};
} // namespace caffe
#endif
|
// SPDX-FileCopyrightText: 2021 Samuel Cabrero <samuel@orica.es>
//
// SPDX-License-Identifier: MIT
#include <LoRa.h>
#include <mbedtls/aes.h>
#include "Comm.h"
TComm Comm;
TComm::TComm() : m_heartbeat_period(10000), m_magic(0xDEADBEEF) {
}
bool TComm::begin(int ss, int reset, int dio0) {
LoRa.setPins(ss, reset, dio0);
/* Set timeout for read ops */
LoRa.setTimeout(1000);
if (!LoRa.begin(433E6)) {
Serial.println("Starting SX1278 failed!");
return false;
}
return true;
}
void TComm::setMagic(uint32_t magic) {
m_magic = magic;
}
void TComm::setEncryptionKey(const unsigned char *key) {
memcpy(m_key, key, 16);
}
void TComm::setHeartbeatPeriod(unsigned long period) {
m_heartbeat_period = period;
}
void TComm::sendPacket(const TComm::Packet *pkt) {
mbedtls_aes_context aes;
const unsigned char *p;
int nchunks, chunk;
if (sizeof(Packet) % 16 != 0) {
Serial.println("Packet size must be a multiple of 16!");
return;
}
mbedtls_aes_init(&aes);
mbedtls_aes_setkey_enc(&aes, m_key, 128);
LoRa.beginPacket();
nchunks = sizeof(Packet) / 16;
for (chunk = 0, p = (const unsigned char *)pkt;
chunk < nchunks;
chunk++, p += 16) {
unsigned char encbuff[16];
mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_ENCRYPT, p, encbuff);
LoRa.write(encbuff, sizeof(encbuff));
}
LoRa.endPacket();
mbedtls_aes_free(&aes);
}
bool TComm::readPacket(TComm::Packet *pkt) {
mbedtls_aes_context aes;
unsigned char *p;
int nchunks, chunk;
int packetSize;
packetSize = LoRa.parsePacket();
if (packetSize <= 0) {
return false;
}
if (packetSize % 16 != 0 || sizeof(Packet) % 16 != 0) {
Serial.println("Packet size must be a multiple of 16!");
return false;
}
mbedtls_aes_init(&aes);
mbedtls_aes_setkey_enc(&aes, m_key, 128);
nchunks = sizeof(Packet) / 16;
for (chunk = 0, p = (unsigned char *)pkt;
chunk < nchunks;
chunk++, p += 16) {
unsigned char encbuff[16];
size_t n;
n = LoRa.available();
if (n <= 0) {
mbedtls_aes_free(&aes);
return false;
}
n = LoRa.readBytes(encbuff, 16);
if (n < 16) {
mbedtls_aes_free(&aes);
return false;
}
mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_DECRYPT, encbuff, p);
}
mbedtls_aes_free(&aes);
if (pkt->magic != m_magic) {
return false;
}
return true;
}
bool TComm::heartbeat(const char *state) {
static unsigned long time_beacon = 0;
if (millis() - time_beacon > m_heartbeat_period) {
static uint64_t counter = 0;
Packet pkt;
memset(&pkt, 0, sizeof(pkt));
pkt.magic = m_magic;
pkt.type = HEARTBEAT;
pkt.heartbeat.counter = counter++;
snprintf(pkt.heartbeat.state, 16, "%s", state);
sendPacket(&pkt);
time_beacon = millis();
return true;
}
return false;
}
void TComm::auth(uint32_t uid, bool authorized) {
Packet pkt;
memset(&pkt, 0, sizeof(pkt));
pkt.magic = m_magic;
pkt.type = AUTH;
pkt.auth.uid = uid;
pkt.auth.authorized = authorized;
sendPacket(&pkt);
}
void TComm::door(bool open) {
Packet pkt;
memset(&pkt, 0, sizeof(pkt));
pkt.magic = m_magic;
pkt.type = DOOR;
pkt.door.open = open;
sendPacket(&pkt);
}
void TComm::alarm() {
Packet pkt;
memset(&pkt, 0, sizeof(pkt));
pkt.magic = m_magic;
pkt.type = ALARM;
sendPacket(&pkt);
}
|
/*********************************************************************
This file is part of QtUrban.
QtUrban is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
QtUrban is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QtUrban. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************/
#include "UrbanGeometry.h"
#include <limits>
#include <iostream>
#include <QFile>
#include "common.h"
#include "global.h"
#include "RendererHelper.h"
#include "GraphUtil.h"
#include "MainWindow.h"
#include "Util.h"
UrbanGeometry::UrbanGeometry(MainWindow* mainWin) {
this->mainWin = mainWin;
//&mainWin->glWidget->vboRenderManager = NULL;
//waterRenderer = new mylib::WaterRenderer(3000, 3000, -2.0f);
//loadTerrain("../data/default.trn");
//selectedAreaIndex = -1;
}
UrbanGeometry::~UrbanGeometry() {
}
void UrbanGeometry::clear() {
clearGeometry();
}
void UrbanGeometry::clearGeometry() {
//if (&mainWin->glWidget->vboRenderManager != NULL) delete &mainWin->glWidget->vboRenderManager;
roads.clear();
}
void UrbanGeometry::render(VBORenderManager& vboRenderManager) {
// draw the road graph
roads.generateMesh(vboRenderManager, "roads_lines", "roads_points");
vboRenderManager.renderStaticGeometry("roads_lines");
vboRenderManager.renderStaticGeometry("roads_points");
}
/**
* Adapt all geometry objects to &mainWin->glWidget->vboRenderManager.
*/
void UrbanGeometry::adaptToTerrain() {
roads.adaptToTerrain(&mainWin->glWidget->vboRenderManager);
}
void UrbanGeometry::newTerrain(int width, int depth, int cellLength) {
clear();
//&mainWin->glWidget->vboRenderManager = new Terrain(width, depth, cellLength);
/*
if (waterRenderer != NULL) {
waterRenderer->setWidth(width);
waterRenderer->setDepth(depth);
}
*/
}
void UrbanGeometry::loadTerrain(const QString &filename) {
printf("NOT IMPLEMENTED YET\n");
/*QFile file(filename);
if (!file.open(QIODevice::ReadOnly)) {
std::cerr << "MyUrbanGeometry::loadInfoLayers... The file is not accessible: " << filename.toUtf8().constData() << endl;
throw "The file is not accessible: " + filename;
}
clear();
QTextStream in(&file);
QString line = in.readLine();
this->width = line.split(" ")[0].toInt();
this->depth = line.split(" ")[1].toInt();
int cellLength = line.split(" ")[2].toInt();
&mainWin->glWidget->vboRenderManager = new Terrain(width, depth, cellLength);
for (int i = 0; i < &mainWin->glWidget->vboRenderManager->getNumRows() * &mainWin->glWidget->vboRenderManager->getNumCols(); ++i) {
line = in.readLine();
int idxX = line.split(" ").at(1).toInt();
int idxY = line.split(" ").at(2).toInt();
line = in.readLine();
float x = line.split(" ").at(0).toFloat();
float y = line.split(" ").at(1).toFloat();
line = in.readLine();
&mainWin->glWidget->vboRenderManager->setValue(x, y, line.toFloat());
}
*/
}
void UrbanGeometry::saveTerrain(const QString &filename) {
printf("NOT IMPLEMENTED YET\n");
/*QFile file(filename);
if (!file.open(QIODevice::WriteOnly)) {
std::cerr << "MyUrbanGeometry::saveInfoLayers... The file is not writable: " << filename.toUtf8().constData() << endl;
throw "The file is not writable: " + filename;
}
QTextStream out(&file);
out << &mainWin->glWidget->vboRenderManager->width << " " << &mainWin->glWidget->vboRenderManager->depth << " " << &mainWin->glWidget->vboRenderManager->getCellLength() << endl;
int count = 0;
for (int i = 0; i < &mainWin->glWidget->vboRenderManager->getNumCols(); ++i) {
for (int j = 0; j < &mainWin->glWidget->vboRenderManager->getNumRows(); ++j) {
out << count++ << " " << i << " " << j << endl;
float x = &mainWin->glWidget->vboRenderManager->getCell(i, j).getX();
float y = &mainWin->glWidget->vboRenderManager->getCell(i, j).getY();
out << x << " " << y << endl;
out << &mainWin->glWidget->vboRenderManager->getTerrainHeight(x, y) << endl;
}
}*/
}
void UrbanGeometry::loadRoads(const QString &filename) {
QFile file(filename);
if (!file.open(QIODevice::ReadOnly)) {
std::cerr << "The file is not accessible: " << filename.toUtf8().constData() << endl;
throw "The file is not accessible: " + filename;
}
roads.clear();
GraphUtil::loadRoads(roads, filename);
roads.adaptToTerrain(&mainWin->glWidget->vboRenderManager);
}
void UrbanGeometry::addRoads(const QString &filename) {
QFile file(filename);
if (!file.open(QIODevice::ReadOnly)) {
std::cerr << "The file is not accessible: " << filename.toUtf8().constData() << endl;
throw "The file is not accessible: " + filename;
}
RoadGraph addRoads;
GraphUtil::loadRoads(addRoads, filename);
GraphUtil::mergeRoads(roads, addRoads);
roads.adaptToTerrain(&mainWin->glWidget->vboRenderManager);
}
void UrbanGeometry::saveRoads(const QString &filename) {
QFile file(filename);
if (!file.open(QIODevice::WriteOnly)) {
std::cerr << "The file is not accessible: " << filename.toUtf8().constData() << endl;
throw "The file is not accessible: " + filename;
}
GraphUtil::saveRoads(roads, filename);
}
void UrbanGeometry::clearRoads() {
roads.clear();
}
|
// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <autoresetevent.h>
#include <condition_variable>
#include <mutex>
#include <thread>
// Moodycamel's concurrent queue
#ifdef _WIN32
#pragma warning(push, 0)
#endif
#include <concurrentqueue.h>
#ifdef _WIN32
#pragma warning(pop)
// HEA-L's oqpi
#include <processthreadsapi.h>
#define OQPI_USE_DEFAULT
#include "oqpi.hpp"
using oqpi_tk = oqpi::default_helpers;
#include <Windows.h>
#endif
#include "CoreUtils.h"
// Typedefs
typedef std::recursive_mutex Mutex;
typedef std::lock_guard<std::recursive_mutex> ScopeLock;
typedef std::unique_lock<std::recursive_mutex> UniqueLock;
typedef std::condition_variable ConditionVariable;
template <typename T>
using LockFreeQueue = moodycamel::ConcurrentQueue<T>;
#ifdef _WIN32
const DWORD MS_VC_EXCEPTION = 0x406D1388;
#pragma pack(push, 8)
typedef struct tagTHREADNAME_INFO {
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
inline void SetThreadNameFallback(HANDLE thread, const std::string& threadName) {
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = threadName.c_str();
info.dwThreadID = GetThreadId(thread);
info.dwFlags = 0;
#pragma warning(push)
#pragma warning(disable : 6320 6322)
__try {
RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);
} __except (EXCEPTION_EXECUTE_HANDLER) {
}
#pragma warning(pop)
}
inline void SetThreadName(HANDLE thread, const wchar_t* threadName) {
using SetThreadDescriptionPtr = HRESULT(WINAPI*)(HANDLE, PCWSTR);
static auto const setThreadDescriptionPtr = []() -> SetThreadDescriptionPtr {
HMODULE kernel32 = LoadLibraryA("kernel32.dll");
SetThreadDescriptionPtr ptr = nullptr;
if (kernel32 != NULL) {
return reinterpret_cast<SetThreadDescriptionPtr>(
GetProcAddress(kernel32, "SetThreadDescription"));
} else {
return nullptr;
}
}();
if (setThreadDescriptionPtr != nullptr) {
(*setThreadDescriptionPtr)(thread, threadName);
} else {
SetThreadNameFallback(thread, ws2s(threadName));
}
}
inline void SetCurrentThreadName(const wchar_t* threadName) {
SetThreadName(GetCurrentThread(), threadName);
}
inline std::string GetThreadName(HANDLE thread) {
std::string name;
using GetThreadDescriptionPtr = HRESULT(WINAPI*)(HANDLE, PWSTR*);
static auto const getThreadDescriptionPtr = []() -> GetThreadDescriptionPtr {
HMODULE kernel32 = LoadLibraryA("kernel32.dll");
GetThreadDescriptionPtr ptr = nullptr;
if (kernel32 != NULL) {
return reinterpret_cast<GetThreadDescriptionPtr>(
GetProcAddress(kernel32, "GetThreadDescription"));
} else {
return nullptr;
}
}();
if (getThreadDescriptionPtr != nullptr) {
PWSTR data = nullptr;
HRESULT hr = (*getThreadDescriptionPtr)(thread, &data);
if (SUCCEEDED(hr)) {
name = ws2s(data);
LocalFree(data);
}
}
return name;
}
inline std::string GetCurrentThreadName() { return GetThreadName(GetCurrentThread()); }
#endif
|
// Copyright 2016 <https://github.com/spelcaster>
//
#ifndef __DCW_OUT_OF_BOUNDS_EXCEPTION_H__
#define __DCW_OUT_OF_BOUNDS_EXCEPTION_H__
#include <iostream>
#include <exception>
//! OutOfBoundsException
/*!
* This exception should be thrown when an invalid index is used
*/
class OutOfBoundsException: public std::exception {
private:
/*!
* The exception message
*/
std::string message_;
public:
//! OutOfBoundsException constructor
explicit OutOfBoundsException(
const std::string& message = "The character index was not found"
);
//! OutOfBoundsException destructor
virtual ~OutOfBoundsException() throw();
/*!
* @see std::exception::what
*/
virtual const char* what() const throw() {
return message_.c_str();
}
};
//! OutOfBoundsException constructor
OutOfBoundsException::OutOfBoundsException(const std::string& message) :
message_(message)
{
}
//! OutOfBoundsException destructor
OutOfBoundsException::~OutOfBoundsException() throw()
{
}
#endif // __DCW_OUT_OF_BOUNDS_EXCEPTION_H__
|
/*
* ¹é²¢ÅÅÐò
*/
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
void merge_sort(vector<int> &nums){
if(nums.empty() || nums.size() < 2 ){
return;
}
_mergeSort(nums,0,nums.size()-1);
}
private:
void _mergeSort(vector<int> &nums,int left,int right){
if(left >= right){
return;
}
int mid = left + (right-left)/2;
_mergeSort(nums,left,mid);
_mergeSort(nums,mid+1,right);
_merge(nums,left,mid,right);
}
void _merge(vector<int> &nums,int left,int mid,int right){
vector<int> support;
int index1 = left;
int index2 = mid+1;
while(index1 <= mid && index2 <= right){
if(nums[index1] < nums[index2]){
support.push_back(nums[index1++]);
}else{
support.push_back(nums[index2++]);
}
}
while(index1 <= mid){
support.push_back(nums[index1++]);
}
while(index2 <= right){
support.push_back(nums[index2++]);
}
for(int i=0; i<support.size(); ++i){
nums[left+i] = support[i];
}
}
};
int main(){
int arr[8] = {3,5,2,1,8,7,4,10};
vector<int> nums(arr,arr+8);
Solution s;
s.merge_sort(nums);
for(int i=0; i<nums.size(); ++i){
printf("%d ",nums[i]);
}
return 0;
}
|
#ifndef PLATFORMER_PLAYER_H
#define PLATFORMER_PLAYER_H
#include "Vector2i.h"
namespace platformer {
/**
* Represents a player, used in the play game state.
*/
class Player {
private:
// Velocity to add when player jumps.
static const int JUMP_HEIGHT = 3;
// The players current location and velocity. Coordinates in this game
// have an origin (0,0) of the bottom left LED to make more sense when
// working on game logic. Increasing Y should make the player move up.
Vector2i *location = new Vector2i();
Vector2i *velocity = new Vector2i();
public:
/**
* Destructs the player, deleting their location and velocity.
*/
virtual ~Player();
/**
* Increases the players Y velocity by JUMP_HEIGHT. Causing them to
* appear to be jumping in game.
*/
void jump();
/**
* Gets the players location.
*
* @return the location.
*/
Vector2i &getLocation() const;
/**
* Gets the players velocity.
*
* @return the velocity.
*/
Vector2i &getVelocity() const;
};
}
#endif // PLATFORMER_PLAYER_H
|
//airlineTicket.cpp
#include<iostream>
#include"airlineTicket.h"
using namespace std;
airlineTicket::airlineTicket()
{
//Initialize data members
fHasEliteSuperRewardsStatus=false;
mPassengerName="Unkown Passenger";
mNumberOfMiles=0;
}
airlineTicket::~airlineTicket()
{
//Nothing need do
}
int airlineTicket::calculatePrinceInDollars()
{
if(getHasEliteSuperRewardsStatus())
{
//Elite Super Rewards customers fly for free.
return 0;
}
return static_cast<int>((getNumberOfMiles()*0.1));
}
string airlineTicket::getPassengerName()
{
return mPassengerName;
}
void airlineTicket::setPassengerName(string inName)
{
mPassengerName=inName;
}
int airlineTicket::getNumberOfMiles()
{
return mNumberOfMiles;
}
void airlineTicket::setNumberOfMiles(int inMiles)
{
mNumberOfMiles=inMiles;
}
bool airlineTicket::getHasEliteSuperRewardsStatus()
{
return (fHasEliteSuperRewardsStatus);
}
void airlineTicket::setHasEliteSuperRewardsStatus(bool inStatus)
{
fHasEliteSuperRewardsStatus=inStatus;
}
|
#include "menu2.h"
#include "jeu.h"
void menu2(SDL_Surface *ecran)
{
///On cree l'ensemble des surfaces nécessaires--------------------------------------------------
SDL_Surface* menu ;
SDL_Surface* buttonHelp ;
SDL_Surface* buttonClose ;
SDL_Surface* easy;
SDL_Surface* medium;
SDL_Surface* hard;
menu = IMG_Load("Images/menu2.jpg") ;
buttonHelp = IMG_Load("Images/Options/help.png");
buttonClose = IMG_Load("Images/Options/close.png");
easy = IMG_Load("Images/Menu/easy.png");
medium = IMG_Load("Images/Menu/medium.png");
hard = IMG_Load("Images/Menu/hard.png");
///On positionne les surfaces---------------------------------------------------
SDL_Rect positionMenu;
SDL_Rect positionHelp;
SDL_Rect positionClose;
SDL_Rect positionEasy;
SDL_Rect positionMedium;
SDL_Rect positionHard;
positionMenu.x = 0 ;
positionMenu.y = 0 ;
positionHelp.x = 0.5 * CELLULE ;
positionHelp.y = 0.5 * CELLULE ;
positionClose.x = 5.5 * CELLULE;
positionClose.y = 0.5 * CELLULE;
positionEasy.x = 2 * CELLULE ;
positionEasy.y = 2 * CELLULE ;
positionMedium.x = 2 * CELLULE ;
positionMedium.y = 4 * CELLULE ;
positionHard.x = 2 * CELLULE ;
positionHard.y = 6 * CELLULE ;
///On colle les surfaces dans l'ecran----------------------------------------------------------
SDL_BlitSurface(menu, NULL, ecran, &positionMenu) ;
SDL_BlitSurface(buttonHelp, NULL, ecran, &positionHelp) ;
SDL_BlitSurface(buttonClose, NULL, ecran, &positionClose) ;
SDL_BlitSurface(easy, NULL, ecran, &positionEasy);
SDL_BlitSurface(medium, NULL, ecran, &positionMedium);
SDL_BlitSurface(hard, NULL, ecran, &positionHard);
///On met à jour l'ecran-----------------------------------------------------------
SDL_Flip(ecran);
///On passe aux évènements------------------------------------------------------------
int continuer = 0;
float n, m;
while (!continuer)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
{
continuer = 1;
break;
}
case SDL_KEYDOWN:
{
if (event.key.keysym.sym == SDLK_ESCAPE)
continuer = 1;
break;
}
case SDL_MOUSEMOTION :
{
m = event.motion.x / CELLULE;
n = event.motion.y / CELLULE;
if ((m >= 2) && (m <= 5) && (n == 2))
{
easy = IMG_Load("Images/Menu/easyHover.png") ;
}
else if ((m >= 2) && (m <= 5) && (n == 4))
{
medium = IMG_Load("Images/Menu/mediumHover.png") ;
}
else if ((m >= 2) && (m <= 5) && (n == 6))
{
hard = IMG_Load("Images/Menu/hardHover.png") ;
}
else if ((m >= 0.5) && (m <= 1.5) && (n >= 0.5) && (n <= 1.5))
{
buttonHelp = IMG_Load("Images/Options/helpHover.png");
}
else if ((m >= 5.5) && (m <= 6.5) && (n >= 0.5) && (n <= 1.5))
{
buttonClose = IMG_Load("Images/Options/closeHover.png");
}
else
{
buttonHelp = IMG_Load("Images/Options/help.png");
buttonClose = IMG_Load("Images/Options/close.png");
easy = IMG_Load("Images/Menu/easy.png");
medium = IMG_Load("Images/Menu/medium.png");
hard = IMG_Load("Images/Menu/hard.png");
}
SDL_BlitSurface(buttonHelp, NULL, ecran, &positionHelp) ;
SDL_BlitSurface(buttonClose, NULL, ecran, &positionClose) ;
SDL_BlitSurface(easy, NULL, ecran, &positionEasy);
SDL_BlitSurface(medium, NULL, ecran, &positionMedium);
SDL_BlitSurface(hard, NULL, ecran, &positionHard);
}
break ;
case SDL_MOUSEBUTTONUP :
{
if (event.button.button == SDL_BUTTON_LEFT)
{
m = event.button.x / CELLULE;
n = event.button.y / CELLULE;
if ((m >= 2) && (m <= 5) && (n == 2))
{
jouer(ecran, 'f') ;
continuer = 1;
}
else if ((m >= 2) && (m <= 5) && (n == 4))
{
jouer(ecran, 'm');
continuer = 1;
}
else if ((m >= 2) && (m <= 5) && (n == 6))
{
jouer(ecran, 'h');
continuer = 1;
}
else if ((m >= 5.5) && (m <= 6.5) && (n >= 0.5) && (n <= 1.5))
{
continuer = 1;
}
}
}
break;
}
}
SDL_Flip(ecran);
}
SDL_FreeSurface(menu);
SDL_FreeSurface(buttonClose);
SDL_FreeSurface(buttonHelp);
SDL_FreeSurface(easy);
SDL_FreeSurface(medium);
SDL_FreeSurface(hard);
}
|
#ifndef OGREUTILS_HPP_GUARD
#define OGREUTILS_HPP_GUARD
#include <gmtl/Matrix.h>
#include <vrj/Display/Frustum.h>
#include <OGRE/OgreMatrix4.h>
#include <vector>
namespace MatrixUtils
{
Ogre::Matrix4 fromGMTL(gmtl::Matrix44f const& m);
gmtl::Matrix44f fromOGRE(Ogre::Matrix4 const& m);
Ogre::Matrix4 makeFrustumMatrix(vrj::Frustum const& frustum);
} // namespace MatrixUtils
#endif // OGREUTILS_HPP_GUARD
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
# include "modules/logdoc/logdoc_module.h"
# include "modules/logdoc/src/html5/html5base.h"
#include "modules/logdoc/html5parser.h"
#include "modules/logdoc/src/html5/html5token.h"
#include "modules/logdoc/src/html5/html5tokenizer.h"
#include "modules/logdoc/html5namemapper.h"
#ifndef HTML5_STANDALONE
# include "modules/doc/frm_doc.h"
# include "modules/console/opconsoleengine.h"
# include "modules/url/url2.h"
# include "modules/layout/traverse/traverse.h"
#endif // HTML5_STANDALONE
HTML5Parser::~HTML5Parser()
{
ClearFinishedTokenizer();
#ifdef HTML5_STANDALONE
OP_DELETE(m_token);
#endif // HTML5_STANDALONE
}
void HTML5Parser::ParseL(HTML5ELEMENT *root, HTML5ELEMENT *context)
{
OP_PROBE7_L(OP_PROBE_HTML5PARSER_PARSEL);
OP_ASSERT(m_tokenizer);
if (!m_is_parsing)
{
m_builder.InitL(this, root);
m_is_parsing = TRUE;
m_is_pausing = FALSE;
m_is_blocking = FALSE;
if (m_is_plaintext)
m_tokenizer->InsertPlaintextPreambleL();
if (g_pcparsing->GetIntegerPref(PrefsCollectionParsing::ShowHTMLParsingErrors))
m_report_errors = TRUE;
#ifdef HTML5_STANDALONE
if (m_output_tokenizer_results)
{
m_token = OP_NEW_L(HTML5Token, ());
m_token->InitializeL();
}
#endif // HTML5_STANDALONE
}
#ifdef HTML5_STANDALONE
if (m_output_tokenizer_results)
{
do
{
m_tokenizer->GetNextTokenL(*m_token);
} while (m_token->GetType() != HTML5Token::ENDOFFILE);
}
else
#endif // HTML5_STANDALONE
if (context) // parsing fragment
m_builder.BuildTreeFragmentL(context);
else
m_builder.BuildTreeL();
ClearFinishedTokenizer();
FlushErrorsToConsoleL();
m_is_parsing = FALSE;
}
void HTML5Parser::ContinueParsingL()
{
#ifdef HTML5_STANDALONE
if (m_output_tokenizer_results)
{
do
{
m_tokenizer->GetNextTokenL(*m_token);
} while (m_token->GetType() != HTML5Token::ENDOFFILE);
return;
}
#endif // HTML5_STANDALONE
if (IsBlocked())
LEAVE(HTML5ParserStatus::EXECUTE_SCRIPT);
m_builder.BuildTreeL();
ClearFinishedTokenizer();
FlushErrorsToConsoleL();
m_is_parsing = FALSE;
}
void HTML5Parser::StopParsingL(BOOL abort)
{
// just finish of the tokenization to put the parser and tree in correct state
OP_PARSER_STATUS pstat = OpStatus::OK;
if (m_is_parsing)
{
do
{
SignalNoMoreDataL(TRUE);
TRAP(pstat, m_builder.StopBuildingL(abort));
}
while (!IsFinished() && !OpStatus::IsMemoryError(pstat));
}
FlushErrorsToConsoleL();
ResetParser();
}
void HTML5Parser::AppendDataL(const uni_char *buffer, unsigned length, BOOL end_of_data, BOOL is_fragment)
{
OP_PROBE7_L(OP_PROBE_HTML5PARSER_APPENDDATA);
if (!m_tokenizer)
CreateTokenizerL();
m_tokenizer->AddDataL(buffer, length, end_of_data, FALSE, is_fragment);
}
void HTML5Parser::InsertDataL(const uni_char *buffer, unsigned length, BOOL add_newline)
{
if (!m_tokenizer)
{
// add a fake terminating buffer for cases where the entire
// document is written using doc.write, just to make the
// algorithm orthogonal.
CreateTokenizerL();
m_tokenizer->AddDataL(UNI_L(""), 0, TRUE, TRUE, FALSE);
}
m_builder.SetState(HTML5TreeState::ILLEGAL_STATE); // to make the builder set the right state
m_tokenizer->InsertDataL(buffer, length, add_newline);
}
void HTML5Parser::ResetParser()
{
m_err_idx = 0;
m_is_parsing = FALSE;
m_is_pausing = FALSE;
m_is_blocking = FALSE;
m_is_plaintext = FALSE;
m_report_errors = FALSE;
if (m_tokenizer)
ClearFinishedTokenizer();
}
/*static*/ HTML5TreeBuilder::InsertionMode HTML5Parser::GetInsertionModeFromElementType(HTML_ElementType elm_type, BOOL is_fragment)
{
switch (elm_type)
{
case Markup::HTE_SELECT:
OP_ASSERT(is_fragment);
return HTML5TreeBuilder::IN_SELECT;
case Markup::HTE_TD:
case Markup::HTE_TH:
if (is_fragment)
return HTML5TreeBuilder::IN_BODY;
else
return HTML5TreeBuilder::IN_CELL;
case Markup::HTE_TR:
return HTML5TreeBuilder::IN_ROW;
case Markup::HTE_TBODY:
case Markup::HTE_TFOOT:
case Markup::HTE_THEAD:
return HTML5TreeBuilder::IN_TABLE_BODY;
case Markup::HTE_CAPTION:
return HTML5TreeBuilder::IN_CAPTION;
case Markup::HTE_COLGROUP:
OP_ASSERT(is_fragment);
return HTML5TreeBuilder::IN_COLUMN_GROUP;
case Markup::HTE_TABLE:
return HTML5TreeBuilder::IN_TABLE;
case Markup::HTE_HEAD:
OP_ASSERT(is_fragment);
return HTML5TreeBuilder::IN_BODY;
case Markup::HTE_BODY:
return HTML5TreeBuilder::IN_BODY;
case Markup::HTE_FRAMESET:
OP_ASSERT(is_fragment);
return HTML5TreeBuilder::IN_FRAMESET;
case Markup::HTE_HTML:
OP_ASSERT(is_fragment);
return HTML5TreeBuilder::BEFORE_HEAD;
default:
if (is_fragment)
return HTML5TreeBuilder::IN_BODY;
break;
}
return HTML5TreeBuilder::INITIAL;
}
#ifdef SPECULATIVE_PARSER
unsigned HTML5Parser::GetStreamPosition()
{
return m_tokenizer->GetLastBufferStartOffset() + m_tokenizer->GetLastBufferPosition();
}
#endif // SPECULATIVE_PARSER
#if defined DELAYED_SCRIPT_EXECUTION || defined SPECULATIVE_PARSER
unsigned HTML5Parser::GetLastBufferStartOffset()
{
return m_tokenizer ? m_tokenizer->GetLastBufferStartOffset() : 0;
}
OP_STATUS HTML5Parser::StoreParserState(HTML5ParserState* state)
{
OP_ASSERT(!GetLogicalDocument()->GetHLDocProfile()->ESIsExecutingDelayedScript()); // With DSE we should have stored state before we started the script
RETURN_IF_ERROR(m_tokenizer->StoreTokenizerState(state));
#ifdef DELAYED_SCRIPT_EXECUTION
RETURN_IF_ERROR(m_builder.StoreParserState(state));
#endif // DELAYED_SCRIPT_EXECUTION
return OpStatus::OK;
}
OP_STATUS HTML5Parser::RestoreParserState(HTML5ParserState* state, HTML5ELEMENT* script_element, unsigned buffer_stream_position, BOOL script_has_completed)
{
// The tokenizer has probably been deleted, so restore it
if (!m_tokenizer)
RETURN_IF_LEAVE(CreateTokenizerL());
else
{
m_tokenizer->Reset();
m_builder.ResetToken();
}
// It will ask for more data later by leaving. But for now we need
// something in the buffer for the doc.write to work (and we're almost certainly getting
// a doc.write, otherwise we wouldn't need to restore in the first place).
RETURN_IF_LEAVE(m_tokenizer->AddDataL(UNI_L(""), 0, FALSE, TRUE, TRUE));
RETURN_IF_ERROR(m_tokenizer->RestoreTokenizerState(state, buffer_stream_position));
#ifdef DELAYED_SCRIPT_EXECUTION
RETURN_IF_ERROR(m_builder.RestoreParserState(state, script_element, script_has_completed));
#endif // DELAYED_SCRIPT_EXECUTION
return OpStatus::OK;
}
#endif // defined DELAYED_SCRIPT_EXECUTION || defined SPECULATIVE_PARSER
#ifdef DELAYED_SCRIPT_EXECUTION
OP_STATUS HTML5Parser::Recover()
{
// The tokenizer has probably been deleted, so restore it
if (!m_tokenizer)
RETURN_IF_LEAVE(CreateTokenizerL());
return OpStatus::OK;
}
BOOL HTML5Parser::HasParserStateChanged(HTML5ParserState* state)
{
if (m_tokenizer->HasTokenizerStateChanged(state))
return TRUE;
return m_builder.HasParserStateChanged(state);
}
BOOL HTML5Parser::HasUnfinishedWriteData()
{
if (m_tokenizer)
return m_tokenizer->HasUnfinishedWriteData();
return FALSE;
}
#endif // DELAYED_SCRIPT_EXECUTION
static BOOL ShouldSerializeChildren(Markup::Type type)
{
switch (type)
{
case Markup::HTE_AREA:
case Markup::HTE_BASE:
case Markup::HTE_BASEFONT:
case Markup::HTE_BGSOUND:
case Markup::HTE_BR:
case Markup::HTE_COL:
case Markup::HTE_EMBED:
case Markup::HTE_FRAME:
case Markup::HTE_HR:
case Markup::HTE_IMG:
case Markup::HTE_INPUT:
case Markup::HTE_KEYGEN:
case Markup::HTE_LINK:
case Markup::HTE_META:
case Markup::HTE_PARAM:
case Markup::HTE_WBR:
return FALSE;
}
return TRUE;
}
static BOOL AttributeNeedToEscapeQuote(Markup::Type type, const uni_char* name, const uni_char* value, uni_char& quote_to_use)
{
BOOL check_value = FALSE;
quote_to_use = '"';
// only for some URI attributes for specific elements should we not escape
// list based on what Webkit does, see CT-371
switch (type)
{
case Markup::HTE_IMG:
if (uni_str_eq(name, "longdesc"))
check_value = TRUE;
else if (uni_str_eq(name, "usemap"))
check_value = TRUE;
else
// fall through
case Markup::HTE_SCRIPT:
case Markup::HTE_INPUT:
case Markup::HTE_FRAME:
case Markup::HTE_IFRAME:
check_value = uni_str_eq(name, "src");
break;
case Markup::HTE_A:
case Markup::HTE_AREA:
case Markup::HTE_LINK:
case Markup::HTE_BASE:
check_value = uni_str_eq(name, "href");
break;
case Markup::HTE_OBJECT:
check_value = uni_str_eq(name, "usemap");
break;
case Markup::HTE_FORM:
check_value = uni_str_eq(name, "action");
break;
case Markup::HTE_BLOCKQUOTE:
case Markup::HTE_Q:
case Markup::HTE_DEL:
case Markup::HTE_INS:
check_value = uni_str_eq(name, "cite");
break;
}
if (check_value)
{
BOOL contains_quot = FALSE, contains_apos = FALSE;
// skip leading whitespace
while (HTML5Parser::IsHTML5WhiteSpace(*value))
value++;
if (!uni_strni_eq(value, "javascript:", 11))
return TRUE;
// javascript URLs shouldn't be quoted unless they have to
value += 11; // skip "javascript:"
for (; *value; value++)
{
if (*value == '"')
if (contains_apos)
return TRUE;
else
contains_quot = TRUE;
else if (*value == '\'')
if (contains_quot)
return TRUE;
else
contains_apos = TRUE;
}
if (contains_quot)
quote_to_use = '\'';
return FALSE;
}
return TRUE;
}
static void QuoteInnerHTMLValuesL(const uni_char *value, TempBuffer *buf, BOOL in_attr, BOOL escape_quote, BOOL escape_nbsp)
{
for (const uni_char *c = value; *c; c++)
{
switch (*c)
{
case '&':
buf->AppendL("&");
break;
case 0xa0:
if (escape_nbsp)
buf->AppendL(" ");
else
buf->AppendL(*c);
break;
case '"':
if (in_attr && escape_quote)
buf->AppendL(""");
else
buf->AppendL(*c);
break;
case '<':
if (!in_attr)
buf->AppendL("<");
else
buf->AppendL(*c);
break;
case '>':
if (!in_attr)
buf->AppendL(">");
else
buf->AppendL(*c);
break;
default:
buf->AppendL(*c);
}
}
}
static BOOL IsTextWithFirstCharacter(HTML_Element *elm, uni_char character)
{
if (elm->Type() == Markup::HTE_TEXT && elm->Content())
return elm->Content()[0] == character;
else if (elm->Type() == Markup::HTE_TEXTGROUP && elm->FirstChild() && elm->FirstChild()->Content())
return elm->FirstChild()->Content()[0] == character;
return FALSE;
}
static const uni_char *GetTagNameFromElement(HTML5ELEMENT *elm)
{
#ifdef HTML5_STANDALONE
return elm->GetName();
#else // HTML5_STANDALONE
Markup::Type type = elm->Type();
if (type == Markup::HTE_UNKNOWN)
return elm->GetTagName();
else
{
Markup::Ns ns = elm->GetNs();
return g_html5_name_mapper->GetNameFromType(type, ns, FALSE);
}
#endif // HTML5_STANDALONE
}
/**
* A helper method for serializing a tree.
*
* @param[in] root - The root node of the tree to be serialized.
* @param[out] buffer - The buffer the serialized tree should be written to.
* @param[in] options - The serialization options.
* @param[in] real_parent - Used when serializing text groups. See SerializeTextgroupL() for datails.
*
* @see HTML5Parser::SerializeTreeOptions.
* @see SerializeTextgroupL()
*/
static void SerializeTreeInternalL(HTML5NODE *root, TempBuffer* buffer, const HTML5Parser::SerializeTreeOptions &options, HTML5NODE* real_parent = NULL);
/**
* A helper method for serializing a text group.
*
* @param[in] textgroup - The textgroup element to be serialized.
* @param[out] buffer - The buffer the serialized text group should be written to.
* @param[in] options - The serialization options.
* @param[in] real_parent - The real parent of the text element being under the text group now.
* It's needed becase the serialization algorithm must sometimes do special things depending on it
* e.g. when serializing a text element being a child of <xmp>. Note that HTML_Element::Parent()
* is no help here since the text group is the parent of the text element now i.e. because we serialize
* <textgroup> the tree must have been changed from:
*
* <the real parent>
* |
* <a text element with more than 32k characters>
*
* to:
*
* <the real parent>
* |
* <text group> ------------------------------------------+
* | |
* <a text element 32k characters long at most> <a text element 32k characters long at most> ...
*
* @see HTML5Parser::SerializeTreeOptions.
* @see SerializeTreeInternalL()
*/
static void SerializeTextgroupL(HTML5NODE *textgroup, TempBuffer* buffer, const HTML5Parser::SerializeTreeOptions &options, HTML5NODE* real_parent = NULL)
{
HTML5NODE *child_node = textgroup->NextActual();
HTML5NODE *stop_node = textgroup->NextSiblingActual();
while (child_node != stop_node)
{
#ifdef PHONE2LINK_SUPPORT
/* Normally we insert HTE_TEXT elements only as children of an HTE_TEXTGROUP.
However with the PHONE2LINK feature an HTE_A may end up under an HTE_TEXTGROUP
and we don't want such to be visible in .innerHTML.
*/
if (child_node->Type() == Markup::HTE_TEXT)
#endif // PHONE2LINK_SUPPORT
SerializeTreeInternalL(child_node, buffer, options, real_parent ? real_parent : textgroup->Parent());
child_node = child_node->NextActual();
}
}
/*static*/ void SerializeTreeInternalL(HTML5NODE *root, TempBuffer* buffer, const HTML5Parser::SerializeTreeOptions &options, HTML5NODE* real_parent)
{
#ifndef HTML5_STANDALONE
if (root->GetInserted() > HE_INSERTED_BYPASSING_PARSER)
return;
#endif // HTML5_STANDALONE
Markup::Type type = root->Type();
switch (type)
{
case Markup::HTE_TEXTGROUP:
SerializeTextgroupL(root, buffer, options, real_parent);
break;
case Markup::HTE_TEXT:
case Markup::HTE_CDATA:
{
const uni_char *content = static_cast<HTML5TEXT*>(root)->Content();
HTML5ELEMENT *parent = real_parent ? real_parent : root->Parent();
if (parent)
{
if (options.m_text_only
|| parent->GetNs() == Markup::HTML
&& (parent->Type() == Markup::HTE_STYLE
|| parent->Type() == Markup::HTE_SCRIPT
|| parent->Type() == Markup::HTE_XMP
|| parent->Type() == Markup::HTE_IFRAME
|| parent->Type() == Markup::HTE_NOEMBED
|| parent->Type() == Markup::HTE_NOFRAMES
|| parent->Type() == Markup::HTE_PLAINTEXT
|| parent->Type() == Markup::HTE_NOSCRIPT))
{
buffer->AppendL(content);
}
else
QuoteInnerHTMLValuesL(content, buffer, FALSE, FALSE, !options.m_is_xml);
}
else
buffer->AppendL(content);
}
break;
case Markup::HTE_COMMENT:
if (!options.m_text_only)
{
buffer->AppendL(UNI_L("<!--"));
#ifdef HTML5_STANDALONE
buffer->AppendL(static_cast<HTML5COMMENT*>(root)->GetData());
#else // HTML5_STANDALONE
buffer->AppendL(root->GetStringAttr(Markup::HA_CONTENT));
#endif // HTML5_STANDALONE
buffer->AppendL(UNI_L("-->"));
}
break;
#ifndef HTML5_STANDALONE
case Markup::HTE_PROCINST:
if (!options.m_text_only)
{
buffer->AppendL(UNI_L("<?"));
buffer->AppendL(root->GetStringAttr(Markup::HA_TARGET));
buffer->AppendL(' ');
buffer->AppendL(root->GetStringAttr(Markup::HA_CONTENT));
buffer->AppendL('>');
}
break;
#endif // HTML5_STANDALONE
case Markup::HTE_DOCTYPE:
if (!options.m_text_only)
{
buffer->AppendL(UNI_L("<!DOCTYPE "));
const uni_char *name = static_cast<HTML5DOCTYPE*>(root)->GetName();
buffer->AppendL(name ? name : UNI_L("html"));
buffer->AppendL(UNI_L(">"));
}
break;
case Markup::HTE_DOC_ROOT:
{
HTML5ELEMENT *elm = static_cast<HTML5ELEMENT*>(root);
HTML5NODE *child_node = elm->FirstChildActual();
while (child_node)
{
SerializeTreeInternalL(child_node, buffer, options);
child_node = child_node->SucActual();
}
}
break;
case Markup::HTE_ENTITY:
case Markup::HTE_ENTITYREF:
case Markup::HTE_UNKNOWNDECL:
// ignore
break;
case Markup::HTE_BR:
if (options.m_text_only)
{
// See SerializeTree() comment why this is done.
buffer->AppendL('\n');
break;
}
default:
{
HTML5ELEMENT *elm = static_cast<HTML5ELEMENT*>(root);
const uni_char *elm_name = NULL;
if (!options.m_text_only)
{
buffer->AppendL('<');
elm_name = GetTagNameFromElement(elm);
buffer->AppendL(elm_name);
#define APPEND_ATTRIBUTE(name, value) do {\
uni_char quote; \
BOOL escape_quote = AttributeNeedToEscapeQuote(type, name, value, quote); \
buffer->AppendL(' '); \
buffer->AppendL(name); \
buffer->AppendL(UNI_L("=")); \
buffer->AppendL(quote); \
QuoteInnerHTMLValuesL(value, buffer, TRUE, escape_quote, options.m_is_xml); \
buffer->AppendL(quote); } while (FALSE)
if (!options.m_skip_attributes)
{
#ifdef HTML5_STANDALONE
unsigned attr_count = elm->GetAttributeCount();
for (unsigned i = 0; i < attr_count; i++)
{
HTML5AttrCopy *attr = elm->GetAttributeByIndex(i);
APPEND_ATTRIBUTE(attr->GetName()->GetBuffer(), attr->GetValue());
}
#else // HTML5_STANDALONE
const uni_char *attr_name, *attr_value;
HTML_AttrIterator iter(elm);
while (iter.GetNext(attr_name, attr_value))
{
APPEND_ATTRIBUTE(attr_name, attr_value);
}
#endif // HTML5_STANDALONE
}
buffer->AppendL('>');
if (type == Markup::HTE_PRE || type == Markup::HTE_TEXTAREA || type == Markup::HTE_LISTING)
{
HTML5NODE *child_node = root->FirstChildActual();
if (child_node && IsTextWithFirstCharacter(child_node, 0x0a))
buffer->AppendL(0x0a);
}
}
if (ShouldSerializeChildren(type))
{
HTML5NODE *child_node = elm->FirstChildActual();
while (child_node)
{
SerializeTreeInternalL(child_node, buffer, options);
child_node = child_node->SucActual();
}
if (!options.m_text_only)
{
buffer->AppendL("</");
buffer->AppendL(elm_name);
buffer->AppendL(">");
}
}
}
break;
}
}
/*static*/ void HTML5Parser::SerializeTreeL(HTML5NODE *root, TempBuffer* buffer, const SerializeTreeOptions &options)
{
#ifndef HTML5_STANDALONE
if (root->GetInserted() > HE_INSERTED_BYPASSING_PARSER)
return;
#endif // HTML5_STANDALONE
if (options.m_include_this)
SerializeTreeInternalL(root, buffer, options);
else
{
Markup::Type type = root->Type();
switch (type)
{
case Markup::HTE_TEXT:
case Markup::HTE_CDATA:
case Markup::HTE_COMMENT:
#ifndef HTML5_STANDALONE
case Markup::HTE_PROCINST:
#endif // HTML5_STANDALONE
case Markup::HTE_DOCTYPE:
case Markup::HTE_ENTITY:
case Markup::HTE_ENTITYREF:
case Markup::HTE_UNKNOWNDECL:
// ignore
break;
case Markup::HTE_TEXTGROUP:
SerializeTextgroupL(root, buffer, options);
break;
case Markup::HTE_BR:
if (options.m_text_only)
{
// HTMLElement.innerText pecularity. <br> and '\n' convert to each other. This is
// not fully supported by any specification but it is what old Operas did and what
// WebKit does. See CORE-46682.
buffer->AppendL('\n');
}
break;
default:
if (ShouldSerializeChildren(type))
{
HTML5ELEMENT *elm = static_cast<HTML5ELEMENT*>(root);
HTML5NODE *child_node = elm->FirstChildActual();
while (child_node)
{
SerializeTreeInternalL(child_node, buffer, options);
child_node = child_node->SucActual();
}
}
break;
}
}
}
#ifndef HTML5_STANDALONE
class SerializeSelectionState
{
public:
SerializeSelectionState(TempBuffer *buffer, const HTML5Parser::SerializeTreeOptions &options)
: m_start_elm(NULL)
, m_end_elm(NULL)
, m_start_unit(NULL)
, m_end_unit(NULL)
, m_common_ancestor(NULL)
, m_buffer(buffer)
, m_options(options) {}
OP_STATUS Init(const TextSelection &selection)
{
// make an empty buffer, so if there is no content in the range we
// return an empty string instead of NULL.
RETURN_IF_MEMORY_ERROR(m_buffer->Expand(64));
m_start_elm = selection.GetStartElement();
m_end_elm = selection.GetEndElement();
// TODO later: refactor out common ancestor code from DOM_Range
if (m_start_elm == m_end_elm)
m_common_ancestor = m_start_elm;
else
{
unsigned start_height = 0;
unsigned end_height = 0;
HTML5NODE *start_iter = m_start_elm;
HTML5NODE *end_iter = m_end_elm;
OP_ASSERT(start_iter && end_iter);
HTML5NODE *parent = start_iter;
while (parent)
{
++start_height;
parent = parent->ParentActual();
}
parent = end_iter;
while (parent)
{
++end_height;
parent = parent->ParentActual();
}
while (end_height < start_height - 1)
{
--start_height;
start_iter = start_iter->ParentActual();
}
while (start_height < end_height - 1)
{
--end_height;
end_iter = end_iter->ParentActual();
}
while (start_iter != end_iter)
{
if (start_height >= end_height)
start_iter = start_iter->ParentActual();
if (end_height >= start_height)
end_iter = end_iter->ParentActual();
start_height = end_height = 0;
}
m_common_ancestor = start_iter;
}
m_start_offset = selection.GetStartSelectionPoint().GetElementCharacterOffset();
if ((m_start_unit = m_start_elm->FirstChild()) != NULL)
{
unsigned index = 0;
while (m_start_unit && index < m_start_offset)
{
m_start_unit = m_start_unit->SucActual();
index++;
}
m_start_offset = 0;
}
m_end_offset = selection.GetEndSelectionPoint().GetElementCharacterOffset();
if ((m_end_unit = m_end_elm->FirstChild()) != NULL)
{
unsigned index = 0;
while (m_end_unit && index < m_end_offset)
{
m_end_unit = m_end_unit->SucActual();
index++;
}
m_end_offset = UINT_MAX;
}
return OpStatus::OK;
}
void AppendL(const uni_char *s, size_t n = static_cast<size_t>(-1))
{
m_buffer->AppendL(s, n);
}
void AppendCharacterL(const uni_char c)
{
m_buffer->AppendL(c);
}
HTML5NODE* m_start_elm;
HTML5NODE* m_end_elm;
HTML5NODE* m_start_unit;
HTML5NODE* m_end_unit;
HTML5NODE* m_common_ancestor;
TempBuffer* m_buffer;
const HTML5Parser::SerializeTreeOptions&
m_options;
unsigned m_start_offset;
unsigned m_end_offset;
};
static void SerializeParentChainL(SerializeSelectionState &state, HTML5NODE *elm, BOOL is_end_branch)
{
if (elm != state.m_common_ancestor)
{
if (!is_end_branch)
SerializeParentChainL(state, elm->ParentActual(), FALSE);
const uni_char *elm_name = GetTagNameFromElement(elm);
if (elm_name && (!is_end_branch || ShouldSerializeChildren(elm->Type())))
{
state.AppendCharacterL('<');
if (is_end_branch)
state.AppendCharacterL('/');
state.AppendL(elm_name);
state.AppendCharacterL('>');
}
if (is_end_branch)
SerializeParentChainL(state, elm->ParentActual(), TRUE);
}
}
static void SerializeTextL(SerializeSelectionState &state, HTML5NODE *elm, unsigned start_offset, unsigned end_offset)
{
HTML5NODE *stop_at = elm->NextSibling();
while (elm != stop_at)
{
const uni_char *content = elm->Content();
unsigned content_len = elm->ContentLength();
if (content_len > start_offset)
{
if (content_len > end_offset)
{
state.AppendL(content + start_offset, end_offset - start_offset);
break;
}
else
{
state.AppendL(content + start_offset);
end_offset -= content_len;
}
start_offset = 0;
}
else
{
start_offset -= content_len;
end_offset -= content_len;
}
elm = elm->Next();
}
}
static void SerializeStartBranchL(SerializeSelectionState &state, HTML5NODE *elm, HTML5NODE *child)
{
if (elm != state.m_common_ancestor)
{
if (elm == state.m_start_elm)
SerializeParentChainL(state, elm, FALSE);
if (elm->IsText())
SerializeTextL(state, elm, state.m_start_offset, UINT_MAX);
else
{
if (child != state.m_start_unit)
child = child->SucActual();
while (child)
{
if (child->IsText())
SerializeTextL(state, child, 0, UINT_MAX);
else
SerializeTreeInternalL(child, state.m_buffer, state.m_options);
child = child->SucActual();
}
const uni_char *elm_name = GetTagNameFromElement(elm);
if (ShouldSerializeChildren(elm->Type()) && elm_name)
{
state.AppendCharacterL('<');
state.AppendCharacterL('/');
state.AppendL(elm_name);
state.AppendCharacterL('>');
}
}
SerializeStartBranchL(state, elm->ParentActual(), elm);
}
}
static void SerializeEndBranchL(SerializeSelectionState &state, HTML5NODE *elm, HTML5NODE *child)
{
if (elm != state.m_common_ancestor)
{
SerializeEndBranchL(state, elm->ParentActual(), elm);
if (elm->IsText())
SerializeTextL(state, elm, 0, state.m_end_offset);
else
{
const uni_char *elm_name = GetTagNameFromElement(elm);
if (elm_name)
{
state.AppendCharacterL('<');
state.AppendL(elm_name);
state.AppendCharacterL('>');
}
HTML5NODE *iter = elm->FirstChildActual();
while (iter != child)
{
if (iter->IsText())
SerializeTextL(state, iter, 0, UINT_MAX);
else
SerializeTreeInternalL(iter, state.m_buffer, state.m_options);
iter = iter->SucActual();
}
}
if (elm == state.m_end_elm)
SerializeParentChainL(state, elm, TRUE);
}
}
/*static*/ void HTML5Parser::SerializeSelectionL(const TextSelection &selection, TempBuffer* buffer, const SerializeTreeOptions &options)
{
OP_ASSERT(options.m_include_this || !"All contents of the selection must be serialized.");
SerializeSelectionState state(buffer, options);
LEAVE_IF_ERROR(state.Init(selection));
if (state.m_start_elm == state.m_end_elm)
{
if (state.m_start_elm->IsText())
SerializeTextL(state, state.m_start_elm, state.m_start_offset, state.m_end_offset);
else
SerializeTreeInternalL(state.m_start_elm, state.m_buffer, state.m_options);
}
else
{
SerializeStartBranchL(state, state.m_start_elm, state.m_start_unit);
HTML5NODE *iter = state.m_start_unit;
HTML5NODE *stop = state.m_end_unit;
HTML5NODE *container = state.m_start_elm;
while (container != state.m_common_ancestor)
{
iter = container;
container = container->ParentActual();
}
container = state.m_end_elm;
while (container != state.m_common_ancestor)
{
stop = container;
container = container->ParentActual();
}
if (iter != state.m_start_unit)
// Leave the tree extracted by SerializeStartBranchL().
iter = iter->SucActual();
#ifdef _DEBUG
if (stop && iter && iter != stop)
OP_ASSERT(iter->Precedes(stop));
#endif // _DEBUG
while (iter != stop)
{
SerializeTreeInternalL(iter, state.m_buffer, state.m_options);
iter = iter->SucActual();
}
SerializeEndBranchL(state, state.m_end_elm, state.m_end_unit);
}
}
#endif // !HTML5_STANDALONE
void HTML5Parser::SignalNoMoreDataL(BOOL stopping)
{
if (m_tokenizer)
m_tokenizer->CloseLastBuffer();
else if (!stopping)
AppendDataL(UNI_L(""), 0, TRUE, FALSE);
}
void HTML5Parser::SignalErrorL(ErrorCode code, unsigned line, unsigned pos)
{
if (m_report_errors)
{
if (m_err_idx == kErrorArraySize)
FlushErrorsToConsoleL();
m_errors[m_err_idx].m_code = code;
m_errors[m_err_idx].m_line = line;
m_errors[m_err_idx++].m_pos = pos;
}
}
HTML5Parser::ErrorCode HTML5Parser::GetError(unsigned i, unsigned &line, unsigned &pos) const
{
line = m_errors[i].m_line;
pos = m_errors[i].m_pos;
return m_errors[i].m_code;
}
#include "modules/logdoc/src/html5/errordescs.h"
/*static*/ const char* HTML5Parser::GetErrorString(ErrorCode code)
{
return g_html5_error_descs[code];
}
void HTML5Parser::FlushErrorsToConsoleL()
{
#if !defined HTML5_STANDALONE && defined OPERA_CONSOLE
if (m_err_idx > 0)
{
if (FramesDocument *doc = m_logdoc->GetFramesDocument())
{
OpConsoleEngine::Message cmessage(OpConsoleEngine::HTML, OpConsoleEngine::Error);
ANCHOR(OpConsoleEngine::Message, cmessage);
cmessage.window = doc->GetWindow()->Id();
doc->GetURL().GetAttribute(URL::KUniName, cmessage.url);
cmessage.context.SetL(UNI_L("During HTML parsing..."));
for (unsigned i = 0; i < m_err_idx; i++)
{
cmessage.message.SetL(GetErrorString(m_errors[i].m_code));
LEAVE_IF_ERROR(cmessage.message.AppendFormat(UNI_L("\n\nLine %d, position %d:\n "), m_errors[i].m_line, m_errors[i].m_pos));
g_console->PostMessageL(&cmessage);
}
}
}
#endif // !HTML5_STANDALONE && OPERA_CONSOLE
m_err_idx = 0;
}
void HTML5Parser::CreateTokenizerL()
{
OP_ASSERT(!m_tokenizer);
m_tokenizer = OP_NEW_L(HTML5Tokenizer, (this));
m_builder.SetCurrentTokenizer(m_tokenizer);
m_builder.ResetToken();
}
void HTML5Parser::ClearFinishedTokenizer()
{
m_builder.SetCurrentTokenizer(NULL);
OP_DELETE(m_tokenizer);
m_tokenizer = NULL;
}
|
#include "main.h"
#include <sodium/sodium.h>
namespace tul{
namespace crypto{
bool init(){
//MAGIC spec says otherwise sodium is not safe to use
return sodium_init() >= 0;
}
}
}
|
#include "Item.hpp"
#include "Map.hpp"
#include "main.hpp"
using namespace std;
Item::Item(const string& name, const string& desc, const string& status,bool enable):
Object(name,desc,status),turnon(enable)
{
// Trigger for drop
Trigger drop = Trigger("drop",name+" is dropped",true);
drop.addCondition([this](){
return getowner()==ZorkMap->getInventory();
});
drop.addAction([this](const string& s){
ZorkMap->getInventory().Remove(*this);
ZorkMap->getCurrentRoom().Add(*this);
});
addTrigger(drop);
// Trigger for put
Trigger put = Trigger("put",name+" is put",true);
put.addCondition([this](){
return getowner()==ZorkMap->getInventory();
});
put.addAction([this](const string& s){
vector<string>s2 = WordParser(s);
if(s2.size()<4){
cout<<"Not enough arguments"<<endl;
return;
}
ZorkMap->getInventory().Remove(*this);
if(string("Container")!=typeid(ZorkMap->get(s2[3])).name()){
cout<<"Not a container"<<endl;
return;
}
ZorkMap->get(s2[3]).Add(*this);
});
addTrigger(put);
defaultEvents = tri.begin();
}
void Item::addTurnon(const string& prt,
list<Action>::iterator s1,
list<Action>::iterator e1)
{
if(!turnon){ // cannot turnon
Trigger trig = Trigger("turn on "+name,"Not applicable for this item",true);
addTrigger(trig);
}else{
Trigger trig = Trigger("turn on "+name,prt,false);
list<Action>::iterator i;
for(i=s1;i!=e1;++i){
trig.addAction(*i);
}
addTrigger(trig);
}
defaultEvents = tri.begin();
}
|
#include <iostream>
using namespace std;
class Node
{
public:
int value;
Node *next;
};
void push(Node **head_ref, int data)
{
Node *new_node = new Node();
new_node -> value = data;
// new node pointing to first node
new_node -> next = *head_ref;
Node *itr = *head_ref;
if(*head_ref != NULL)
{
while(itr -> next != *head_ref)
{
itr = itr -> next;
}
// itr at last node
// attach new node to last node
itr -> next = new_node;
}
else
{
new_node -> next = new_node;
// pointing to itself i.e
// first node
*head_ref = new_node;
}
}
void cprintlist(Node **head_ref)
{
Node *itr = *head_ref;
if(*head_ref == NULL)
cout << "list is empty";
else
{
while(itr -> next != *head_ref)
{
cout << itr -> value << " ";
itr = itr -> next;
}
cout << itr -> value;
}
}
void deleteNode(Node **head_ref,int key)
{
// conditions to check
// if list is empty
if(*head_ref == NULL)
return;
// if node is first node
if((*head_ref)->value == key && (*head_ref)->next == *head_ref)
{
free(*head_ref);
*head_ref = NULL;
return;
}
// we want to delete the head but there are subsequent elements in it
if((*head_ref) -> value == key)
{
Node *last = *head_ref;
while(last -> next != *head_ref)
{
last = last -> next;
}
// linking last to second element
last -> next = (*head_ref) -> next;
free(*head_ref);
// updating head ie linking it to second
(*head_ref) = last -> next;
free(last);
return;
}
Node *itr = *head_ref;
// regular node to be deleted
// check if node is present and find out its position
while(itr -> next != *head_ref && itr->next->value != key)
{
itr = itr -> next;
}
// either itr is at last of node if key is not found
// or is at one node previous to where key is found
// that node hast to be deleted
// if key is found
if(itr->next->value == key)
{
Node *temp_ref = itr -> next;
itr -> next = temp_ref -> next;
free(temp_ref);
return;
}
// if key is not found
else
{
cout << "key is not found";
return;
}
}
int countnodes(Node **head_ref)
{
if(*head_ref == NULL)
return 0;
else
{
int count = 0;
Node *itr = *head_ref;
while(itr -> next != *head_ref)
{
count++;
itr = itr -> next;
}
return count;
}
}
Node *tocircular(Node **head_ref)
{
Node *itr = *head_ref;
while(itr->next != NULL)
{
itr = itr -> next;
}
itr -> next = *head_ref;
return *head_ref;
}
int main()
{
Node *head = NULL;
push(&head,6);
push(&head,7);
push(&head,8);
cprintlist(&head);
}
|
#pragma once
////////////////////////////////////////////////////////////////////////////////
#include <cellogram/common.h>
#include <vector>
#include <Eigen/Dense>
////////////////////////////////////////////////////////////////////////////////
namespace cellogram {
///
/// @brief { Adds or removes vertices from dataset}
///
/// @param[in] V { #V x dims input point positions }
/// @param[out] V { #V x dims output point positions }
///
void add_vertex(const Eigen::MatrixXd &V);
void delete_vertex(const Eigen::MatrixXd &V);
} // namespace cellogram
|
//==================================================================================================
// Name : InputParserUtil.cpp
// Author : Ken Cheng
// Copyright : This work is licensed under the Creative Commons
// Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this
// license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/.
// Description :
//==================================================================================================
#include "InputParserUtil.h"
#include <cstdlib>
#include <algorithm>
#include "StringUtil.h"
using namespace std;
namespace LabRetriever {
string GetAlleleFrequencyTableFileName(const string& alleleFrequencyTablePath, const string locus) {
const string path = (alleleFrequencyTablePath.size() > 0 &&
(alleleFrequencyTablePath[alleleFrequencyTablePath.size() - 1] != '/' ||
alleleFrequencyTablePath[alleleFrequencyTablePath.size() - 1] != '\\'))
? alleleFrequencyTablePath + "/"
: alleleFrequencyTablePath;
return path + locus + "_B.count.csv";
}
vector<Race> GetRaces(const Race& race, const string& alleleFrequencyTablePath,
const set<string>& lociToRun) {
vector<Race> races;
// Determine the races to run.
if (race == ALL_RACE) {
set<Race> allRaces;
for (set<string>::const_iterator iter = lociToRun.begin(); iter != lociToRun.end();
iter++) {
string locus = *iter;
map<Race, map<string, unsigned int> > raceToAlleleCounts = getAlleleCountsFromFile(
GetAlleleFrequencyTableFileName(alleleFrequencyTablePath, locus));
for (map<Race, map<string, unsigned int> >::const_iterator race_iter =
raceToAlleleCounts.begin();
race_iter != raceToAlleleCounts.end(); race_iter++) {
allRaces.insert(race_iter->first);
}
}
for (set<Race>::const_iterator iter = allRaces.begin(); iter != allRaces.end(); iter++) {
races.push_back(*iter);
}
} else {
races.push_back(race);
}
return races;
}
void RetrieveDataFromCSV(const string& inputFileName, double* alpha, double* dropinRate,
double* dropoutRate, double* fst, Race* race,
IdenticalByDescentProbability* identicalByDescentProbability,
map<string, vector<string> >* locusToSuspectAlleles,
map<string, vector<set<string> > >* locusToAssumedAlleles,
map<string, vector<set<string> > >* locusToUnattributedAlleles,
map<string, double>* locusSpecificDropout,
map<string, double>* locusSpecificDropin, set<string>* lociToRun) {
vector<vector<string> > inputData = readRawCsv(inputFileName);
unsigned int csvIndex = 0;
for (; csvIndex < inputData.size(); csvIndex++) {
const vector<string>& row = inputData[csvIndex];
if (row.size() == 0) continue;
const string& header = row[0];
if (header == "alpha") {
if (row.size() <= 1) continue;
double value;
if (!ToDouble(row[1], &value)) continue;
*alpha = value;
} else if (header == "Drop-in rate") {
if (row.size() <= 1) continue;
double value;
if (!ToDouble(row[1], &value)) continue;
*dropinRate = value;
} else if (header == "Drop-out rate") {
if (row.size() <= 1) continue;
double value;
if (!ToDouble(row[1], &value)) continue;
*dropoutRate = value;
} else if (header == "fst") {
if (row.size() <= 1) continue;
double value;
if (!ToDouble(row[1], &value)) continue;
*fst = value;
} else if (header == "Race") {
if (row.size() <= 1) continue;
// Currently only expect one race or ALL. Change this to vector if multiple races
// are needed but not all.
*race = row[1];
} else if (header == "IBD Probs") {
if (row.size() <= 3 || row[1].size() == 0 || row[2].size() == 0 || row[3].size() == 0)
continue;
double zeroAllelesInCommonProb, oneAlleleInCommonProb, twoAllelesInCommonProb;
if (!ToDouble(row[1], &zeroAllelesInCommonProb) ||
!ToDouble(row[2], &oneAlleleInCommonProb) ||
!ToDouble(row[3], &twoAllelesInCommonProb)) {
continue;
}
identicalByDescentProbability->zeroAllelesInCommonProb = zeroAllelesInCommonProb;
identicalByDescentProbability->oneAlleleInCommonProb = oneAlleleInCommonProb;
identicalByDescentProbability->bothAllelesInCommonProb = twoAllelesInCommonProb;
} else {
size_t index = header.find("-");
if (index == string::npos) continue;
string locus = header.substr(0, index);
string locusType = header.substr(index + 1, header.size());
if (locusType == "Drop-in" || locusType == "Drop-out") {
double value;
if (!ToDouble(row[1], &value)) continue;
if (locusType == "Drop-in") {
(*locusSpecificDropin)[locus] = value;
} else if (locusType == "Drop-out") {
(*locusSpecificDropout)[locus] = value;
}
continue;
}
set<string> alleleSet;
vector<string> alleles;
for (unsigned int i = 1; i < row.size(); i++) {
string data = row[i];
if (data.length() != 0) {
alleles.push_back(data);
alleleSet.insert(data);
}
}
if (locusType == "Assumed") {
(*locusToAssumedAlleles)[locus].push_back(alleleSet);
} else if (locusType == "Unattributed") {
(*locusToUnattributedAlleles)[locus].push_back(alleleSet);
} else if (locusType == "Suspected") {
// If there are no suspected alleles, then there's no point of calculating this.
if (alleles.size() == 0) continue;
(*locusToSuspectAlleles)[locus] = alleles;
}
}
}
// Check for loci where there is a suspect allele, and the assumed and unattributed
// rows are present (but possibly empty).
for (map<string, vector<string> >::const_iterator iter = locusToSuspectAlleles->begin();
iter != locusToSuspectAlleles->end(); iter++) {
const string& locus = iter->first;
if (locusToAssumedAlleles->find(locus) != locusToAssumedAlleles->end() &&
locusToUnattributedAlleles->find(locus) != locusToUnattributedAlleles->end()) {
lociToRun->insert(locus);
}
}
// If the number of Assumed and Unattributed cases don't match, extend one of them to match the
// other.
for (set<string>::const_iterator iter = lociToRun->begin(); iter != lociToRun->end(); iter++) {
string allele = *iter;
vector<set<string> >& assumedAlleles = (*locusToAssumedAlleles)[allele];
vector<set<string> >& unattributedAlleles = (*locusToUnattributedAlleles)[allele];
int len = std::max(assumedAlleles.size(), unattributedAlleles.size());
assumedAlleles.resize(len);
unattributedAlleles.resize(len);
}
}
namespace {
set<string> AllAlleles(const vector<string>& suspectAlleles,
const vector<set<string> >& assumedAlleles,
const vector<set<string> >& unattributedAlleles) {
set<string> allAlleles;
allAlleles.insert(suspectAlleles.begin(), suspectAlleles.end());
for (unsigned int i = 0; i < unattributedAlleles.size(); i++) {
allAlleles.insert(unattributedAlleles[i].begin(), unattributedAlleles[i].end());
}
for (unsigned int i = 0; i < assumedAlleles.size(); i++) {
allAlleles.insert(assumedAlleles[i].begin(), assumedAlleles[i].end());
}
return allAlleles;
}
/*
* Returns a mapping from alleles to the proportion that the allele appears in people, after
* sampling adjustment and the Balding-Nichols FST correction.
*
* alleleCounts - a mapping from alleles to a count of how many times that allele appeared in
* the sample.
* suspectProfile - the current suspect's profile.
* samplingAdjustment -
* fst - See Balding-Nichols FST correction. Balding recommends that fst should be at least
* 0.01. It can be as high as 0.05, depending on how representative the sample population
* is of the whole target population.
*/
map<string, double> getAlleleProportionsFromCounts(const map<string, unsigned int>& alleleCounts,
const AlleleProfile& suspectProfile, double fst,
unsigned int samplingAdjustment = 2) {
const map<string, unsigned int>& suspectAlleleCounts = suspectProfile.getAlleleCounts();
double totalCounts = 0, fstCorrection = (1 - fst) / (1 + fst);
for (map<string, unsigned int>::const_iterator iter = alleleCounts.begin();
iter != alleleCounts.end(); iter++) {
totalCounts += iter->second;
}
double totalSuspectAlleleCounts = 0;
for (map<string, unsigned int>::const_iterator iter = suspectAlleleCounts.begin();
iter != suspectAlleleCounts.end(); iter++) {
totalSuspectAlleleCounts += iter->second;
}
// // Find the total counts in the alleleCounts, plus extra per suspect allele.
// totalCounts += totalSuspectAlleleCounts * samplingAdjustment;
double multiplierCorrection = fstCorrection / totalCounts;
map<string, double> alleleProportions;
for (map<string, unsigned int>::const_iterator iter = alleleCounts.begin();
iter != alleleCounts.end(); iter++) {
const string& allele = iter->first;
alleleProportions[allele] = iter->second * multiplierCorrection;
}
// For each suspect allele, add in the proportions that the adjustments would have added.
for (map<string, unsigned int>::const_iterator iter = suspectAlleleCounts.begin();
iter != suspectAlleleCounts.end(); iter++) {
const string& allele = iter->first;
unsigned int count = iter->second;
alleleProportions[allele] += count * (fst / (1 + fst));
}
return alleleProportions;
}
} // namespace
map<Race, map<string, double> > GetRaceToAlleleProportions(
const string& alleleFrequencyTableFileName, const vector<string>& suspectAlleles,
const vector<set<string> >& assumedAlleles, const vector<set<string> >& unattributedAlleles,
double fst) {
const set<string> allAlleles = AllAlleles(suspectAlleles, assumedAlleles, unattributedAlleles);
map<Race, map<string, unsigned int> > raceToAlleleCounts =
getAlleleCountsFromFile(alleleFrequencyTableFileName);
map<Race, map<string, double> > raceToAlleleProp;
for (map<Race, map<string, unsigned int> >::iterator iter = raceToAlleleCounts.begin();
iter != raceToAlleleCounts.end(); ++iter) {
const Race& race = iter->first;
map<string, unsigned int>& alleleCounts = iter->second;
// Edit the allele counts so that every allele is given at least 5 counts, even if the
// allele does not appear in the table.
for (set<string>::const_iterator allele_iter = allAlleles.begin();
allele_iter != allAlleles.end(); allele_iter++) {
const string& allele = *allele_iter;
if (alleleCounts.count(allele) == 0 || alleleCounts[allele] < 5) {
alleleCounts[allele] = 5;
}
}
raceToAlleleProp[race] =
getAlleleProportionsFromCounts(alleleCounts, AlleleProfile(suspectAlleles), fst);
}
return raceToAlleleProp;
}
} // namespace LabRetriever
|
#include "stdafx.h"
#include "IniData.h"
IniData::IniData()
{
}
IniData::~IniData()
{
}
void IniData::AddData(const char * section, const char * key, const char * value)
{
tagIniData iniData;
//iniData.section = section;
//iniData.key = key;
//iniData.value = value;
strcpy_s(iniData.section, sizeof(iniData.section), section);
strcpy_s(iniData.key, sizeof(iniData.key), key);
strcpy_s(iniData.value, sizeof(iniData.value), value);
this->_vIniData.push_back(iniData);
}
void IniData::SaveData(const char * fileName)
{
char str[256];
char dir[256];
ZeroMemory(str, sizeof(str));
ZeroMemory(dir, sizeof(dir));
// C에서 내 프로젝트까지의 경로 가져오는 함수
// 파일이 D에있음 d부터
GetCurrentDirectory(256, str);
// save 폴더는 만들어줘야함
sprintf_s(dir, "/save/%s.ini", fileName);
strcat_s(str, dir);
for (int i = 0; i < _vIniData.size(); i++) {
WritePrivateProfileString(
_vIniData[i].section,
_vIniData[i].key,
_vIniData[i].value,
str);
}
_vIniData.clear();
}
char * IniData::LoadDataString(const char * fileName, const char * section, const char * key)
{
char str[256];
char dir[256];
ZeroMemory(str, sizeof(str));
ZeroMemory(dir, sizeof(dir));
// C에서 내 프로젝트까지의 경로 가져오는 함수
// 파일이 D에있음 d부터
GetCurrentDirectory(256, str);
// save 폴더는 만들어줘야함
sprintf_s(dir, "/save/%s.ini", fileName);
strcat_s(str, dir);
char data[64] = { 0 };
GetPrivateProfileString(
section,
key,
"", // value 값 없을때 어떤 문자로 처리할지
data, // 어디다 저장 할지
64, // 크기
str // 경로
);
return data;
}
int IniData::LoadDataInteger(const char * fileName, const char * section, const char * key)
{
char str[256];
char dir[256];
ZeroMemory(str, sizeof(str));
ZeroMemory(dir, sizeof(dir));
// C에서 내 프로젝트까지의 경로 가져오는 함수
// 파일이 D에있음 d부터
GetCurrentDirectory(256, str);
// save 폴더는 만들어줘야함
sprintf_s(dir, "/save/%s.ini", fileName);
strcat_s(str, dir);
// 실수형은 스트링으로 읽어와서 변경을 해야함
return GetPrivateProfileInt(section, key, 0, str);
}
|
#include "localProcess.h"
#include <algorithm>
#include <numeric>
#include <random>
#include <pcl/common/centroid.h>
#include <pcl/filters/extract_indices.h>
//#include <pcl/features/normal_3d.h>
//#include <pcl/features/normal_3d_omp.h>
#include <pcl/common/transforms.h>
void CentralizePtr(pcl::PointCloud<pcl::PointXYZ>::Ptr ptrTheCld)
{
Eigen::Vector4f v4fCentroid = Eigen::Vector4f::Zero();
pcl::compute3DCentroid(*ptrTheCld, v4fCentroid);
size_t sMax = ptrTheCld->points.size();
for (size_t si = 0; si < sMax; si++)
{
pcl::PointXYZ& ptThePt = ptrTheCld->points.at(si);
ptThePt.x = ptThePt.x - v4fCentroid[0];
ptThePt.y = ptThePt.y - v4fCentroid[1];
ptThePt.z = ptThePt.z - v4fCentroid[2];
}
return;
}
void GetNormals(pcl::PointCloud<pcl::PointXYZ>::Ptr ptrTheCld,
pcl::PointCloud<pcl::Normal>::Ptr ptrTheNormal)
{
/** this function requires the fix in pcl source code first
// Create the normal estimation class, and pass the input dataset to it
pcl::NormalEstimationOMP<pcl::PointXYZ, pcl::Normal> ne;
ne.setInputCloud(ptrTheCld);
// Create an empty kdtree representation, and pass it to the normal estimation object.
// Its content will be filled inside the object, based on the given input dataset (as no other search surface is given).
pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>);
ne.setSearchMethod(tree);
// Output datasets
//pcl::PointCloud<pcl::Normal>::Ptr cloud_normals(new pcl::PointCloud<pcl::Normal>);
// Use all neighbors in a sphere of radius 3cm
//ne.setRadiusSearch(0.03);
ne.setKSearch(16);
// Compute the features
ne.compute(*ptrTheNormal);
*/
return;
}
void Combine2Larger(std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr>& vptrInput,
std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr>& vptrOutput)
{
// combine the adjacent point clouds to make it larger
return;
}
void GenrateRandomSubset(pcl::PointCloud<pcl::PointXYZ>::Ptr ptrRaw,
std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr>& vptrRandSubset,
size_t sHowMany, const size_t sSize)
{
std::cout << "Generate " << sHowMany << " subsets from " << ptrRaw->points.size() << "points. \n";
// generate raw index
std::vector<int>viIndexRaw(ptrRaw->points.size());
std::iota(std::begin(viIndexRaw), std::end(viIndexRaw), 0);
std::random_device rd;
std::mt19937 g(rd());
pcl::ExtractIndices<pcl::PointXYZ> extract;
pcl::PointIndices::Ptr inliers(new pcl::PointIndices());
std::vector<int> viLoopIndex;
Eigen::Matrix4f m4fRotate = Eigen::Matrix4f::Identity();
Eigen::Affine3f a3fRotate;
for (size_t si = 0; si < sHowMany; si++)
{
viLoopIndex = viIndexRaw;
std::shuffle(viIndexRaw.begin(), viIndexRaw.end(), g);
viLoopIndex.resize(sSize);
inliers->indices = viLoopIndex;
pcl::PointCloud<pcl::PointXYZ>::Ptr ptrNew(new pcl::PointCloud<pcl::PointXYZ>);
extract.setInputCloud(ptrRaw);
extract.setIndices(inliers);
extract.setNegative(false);
extract.filter(*ptrNew);
// rotate a random angle
pcl::getTransformation(0.0f, 0.0f, 0.0f,
(float)rand() / (float)RAND_MAX * M_PI * 2,
(float)rand() / (float)RAND_MAX * M_PI * 2,
(float)rand() / (float)RAND_MAX * M_PI * 2,
a3fRotate);
m4fRotate = a3fRotate.matrix();
pcl::transformPointCloud(*ptrNew, *ptrNew, m4fRotate);
vptrRandSubset.push_back(ptrNew);
}
}
void GenerateRandomIndices(const size_t sHowMany, std::vector<size_t>& vsIndices)
{
vsIndices = std::vector<size_t>(sHowMany);
std::iota(std::begin(vsIndices), std::end(vsIndices), 0);
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(vsIndices.begin(), vsIndices.end(), g);
}
|
//
// GStartInterfaceLayer.h
// Core
//
// Created by Max Yoon on 11. 7. 25..
// Copyright 2011년 __MyCompanyName__. All rights reserved.
//
#ifndef Core_GStartInterfaceLayer_h
#define Core_GStartInterfaceLayer_h
#include "GInterfaceLayer.h"
class GnITabCtrl;
class GStartInterfaceLayer : public GInterfaceLayer
{
private:
GnITabCtrl* mpTabCtrl;
public:
GStartInterfaceLayer();
virtual ~GStartInterfaceLayer();
virtual GnInterfaceGroup* CreateInterface(gtuint uiIndex
, GnBaseSlot2<GnInterface*, GnIInputEvent*>* pReceiveSlot);
protected:
GnInterfaceGroup* CreateMenu();
};
#endif
|
/** @file valknut/core/internal/msvc.hpp
*
* @brief This header detects compiler-specific features for Microsoft
* Visual Studios
*
* @note This is an internal header file, included by other library headers.
* Do not attempt to use it directly.
*/
/*
* Change Log:
*
* September 04, 2015:
* - Added detection for type trait intrinsics
*/
#ifndef VALKNUT_CORE_INTERNAL_COMPILER_MSVC_HPP_
#define VALKNUT_CORE_INTERNAL_COMPILER_MSVC_HPP_
//-----------------------------------------------------------------------------
// Compiler Detection
//-----------------------------------------------------------------------------
#define VALKNUT_COMPILER_MSVC 1
#define VALKNUT_COMPILER_VERSION _MSC_FULL_VER
#define VALKNUT_COMPILER_NAME "Microsoft Visual C++"
#define VALKNUT_COMPILER_STRING VALKNUT_COMPILER_NAME " " VALKNUT_STRINGIZE(_MSC_VER)
//-----------------------------------------------------------------------------
// C++ Standards Detection
//-----------------------------------------------------------------------------
#if (_MSC_VER >= 1600)
# define VALKNUT_PLATFORM_HAS_STDINT_H 1
#endif
#if(_MSC_VER > 1200)
# define VALKNUT_COMPILER_HAS_INCLASS_MEMBER_INITIALIZATION 1
#endif
//-----------------------------------------------------------------------------
#if defined(__cplusplus) && (__cplusplus >= 201103L)
# if(_MSC_VER >= 1600) // MSVC++ 10.00 (Visual Studio 2010)
# define VALKNUT_COMPILER_HAS_CPP11_RVALUE 1
# define VALKNUT_COMPILER_HAS_CPP11_STATIC_ASSERT 1
# define VALKNUT_COMPILER_HAS_CPP11_NULLPTR 1
# define VALKNUT_COMPILER_HAS_CPP11_DECLTYPE 1
# endif
# if(_MSC_VER >= 1700) // MSVC++ 11.00 (Visual Studio 2012)
# define VALKNUT_COMPILER_HAS_CPP11_ALIGNOF 1
# define VALKNUT_COMPILER_HAS_CPP11_OVERRIDE 1
# define VALKNUT_COMPILER_HAS_CPP11_FINAL 1
# endif
# if(_MSC_VER >= 1800) // MSVC++ 12.0 (Visual Studio 2013)
# define VALKNUT_COMPILER_HAS_CPP11_VA_TEMPLATE 1
# endif
# if(_MSC_VER >= 1900) // MSVC++ 14.0 (Visual Studio 2015)
# define VALKNUT_COMPILER_HAS_CPP11_CHAR16_T 1
# define VALKNUT_COMPILER_HAS_CPP11_CHAR32_T 1
# define VALKNUT_COMPILER_HAS_CPP11_CONSTEXPR 1
# define VALKNUT_COMPILER_HAS_CPP11_NOEXCEPT 1
# define VALKNUT_COMPILER_HAS_CPP11_UNICODE_LITERALS 1
# define VALKNUT_COMPILER_HAS_CPP11_ALIGNAS 1
# define VALKNUT_COMPILER_HAS_CPP11_USER_DEFINED_LITERALS 1
# endif
#endif
//-----------------------------------------------------------------------------
// C++14 checks
//-----------------------------------------------------------------------------
// C++17 checks
//-----------------------------------------------------------------------------
// C++ Type Traits Intrinsics Detection
//-----------------------------------------------------------------------------
#if (defined(_MSC_FULL_VER) && (_MSC_FULL_VER >=140050215))
# define VALKNUT_IS_UNION(T) __is_union(T)
# define VALKNUT_IS_POD(T) (__is_pod(T) && __has_trivial_constructor(T))
# define VALKNUT_IS_EMPTY(T) __is_empty(T)
# define VALKNUT_HAS_TRIVIAL_CONSTRUCTOR(T) __has_trivial_constructor(T)
# define VALKNUT_HAS_TRIVIAL_COPY(T) __has_trivial_copy(T)
# define VALKNUT_HAS_TRIVIAL_ASSIGN(T) __has_trivial_assign(T)
# define VALKNUT_HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
# define VALKNUT_HAS_NOTHROW_CONSTRUCTOR(T) __has_nothrow_constructor(T)
# define VALKNUT_HAS_NOTHROW_COPY(T) __has_nothrow_copy(T)
# define VALKNUT_HAS_NOTHROW_ASSIGN(T) __has_nothrow_assign(T)
# define VALKNUT_HAS_VIRTUAL_DESTRUCTOR(T) __has_virtual_destructor(T)
# define VALKNUT_IS_ABSTRACT(T) __is_abstract(T)
# define VALKNUT_IS_BASE_OF(T,U) __is_base_of(T,U) && !is_same<T,U>::value)
# define VALKNUT_IS_CLASS(T) __is_class(T)
# define VALKNUT_IS_CONVERTIBLE(T,U) ((__is_convertible_to(T,U) || (valknut::is_same<T,U>::value && !valknut::is_function<U>::value)) && !__is_abstract(U))
# define VALKNUT_IS_ENUM(T) __is_enum(T)
# if defined(_MSC_VER) && (_MSC_VER >= 1700)
# define VALKNUT_HAS_TRIVIAL_MOVE_CONSTRUCTOR(T) ((__has_trivial_move_constructor(T) || __is_pod(T)) )
# define VALKNUT_HAS_TRIVIAL_MOVE_ASSIGN(T) ((__has_trivial_move_assign(T) || __is_pod(T)))
# endif
# if _MSC_FULL_VER >= 180020827
# define VALKNUT_IS_NOTHROW_MOVE_ASSIGN(T) (__is_nothrow_assignable(T&, T&&))
# define VALKNUT_IS_NOTHROW_MOVE_CONSTRUCT(T) (__is_nothrow_constructible(T, T&&))
# endif
# define VALKNUT_COMPILER_HAS_TYPE_TRAITS_INTRINSICS 1
#endif
//-----------------------------------------------------------------------------
// C++ Extensions Detections
//-----------------------------------------------------------------------------
#define VALKNUT_COMPILER_ASM_STYLE_INTEL 1
#if defined(__AVX__)
# define VALKNUT_PLATFORM_HAS_AVX 1
#endif
#if defined(__AVX2__)
# define VALKNUT_PLATFORM_HAS_AVX2 1
#endif
#if !defined(__NOSSE__) && defined(_M_IX86_FP)
# if (_M_IX86_FP >= 1)
# define VALKNUT_PLATFORM_SSE 1
# endif
# if (_M_IX86_FP >= 2)
# define VALKNUT_PLATFORM_SSE2 1
# endif
# if (_M_IX86_FP >= 3)
# define VALKNUT_PLATFORM_SSE3 1
# endif
#endif
#define VALKNUT_LIKELY(x) (x)
#define VALKNUT_UNLIKELY(x) (x)
#define VALKNUT_PRAGMA(x) __pragma(x)
#if (_MSC_VER >= 1300)
# define VALKNUT_WEAK __declspec(selectany)
# define VALKNUT_COMPILER_HAS_WEAK_ALIAS 1
#else
# define VALKNUT_WEAK
# define VALKNUT_COMPILER_HAS_WEAK_ALIAS 0
#endif
#if defined(_CPPUNWIND)
# define VALKNUT_COMPILER_EXCEPTIONS_ENABLED 1
#endif
#if defined(_NATIVE_WCHAR_T_DEFINED)
# define VALKNUT_COMPILER_HAS_WCHAR_T
#endif
#if defined(_MSC_EXTENSIONS) || (_MSC_VER >= 1400)
# define VALKNUT_COMPILER_HAS_LONG_LONG 1
#endif
// MSVC never has int128 defined, as of yet
//----------------------------------------------------------------------------
// Symbol Import/Export (DLL/shared library)
//----------------------------------------------------------------------------
// MSVC always uses declspec
#define VALKNUT_COMPILER_HAS_DECLSPEC 1
#define VALKNUT_COMPILER_SYMBOL_EXPORT __declspec((dllexport))
#define VALKNUT_COMPILER_SYMBOL_IMPORT __declspec((dllimport))
#define VALKNUT_COMPILER_SYMBOL_VISIBLE
#define VALKNUT_COMPILER_SYMBOL_LOCAL
#endif /* VALKNUT_CORE_INTERNAL_COMPILER_MSVC_HPP_ */
|
#pragma once
class Vector2D
{
public:
Vector2D();
virtual ~Vector2D();
float x;
float y;
void SetVector(float xi, float yi);
float GetVectorX();
float GetVectorY();
Vector2D operator+(Vector2D v);
Vector2D operator*(float t);
};
Vector2D operator*(float t, Vector2D v);
|
/*
Copyright (c) 2016, Los Alamos National Security, LLC
All rights reserved.
Copyright 2016. Los Alamos National Security, LLC. This software was produced under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National Laboratory (LANL), which is operated by Los Alamos National Security, LLC for the U.S. Department of Energy. The U.S. Government has rights to use, reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified to produce derivative works, such modified software should be clearly marked, so as not to confuse it with the version available from LANL.
Additionally, redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of Los Alamos National Security, LLC, Los Alamos National Laboratory, LANL, the U.S. Government, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY LOS ALAMOS NATIONAL SECURITY, LLC AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LOS ALAMOS NATIONAL SECURITY, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __WorkProducer__
#define __WorkProducer__
#include <new>
#include <stdio.h>
#include <limits>
#include <memory>
#include <atomic>
#include <future>
#include <deque>
#include <chrono>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <mpi.h>
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include <boost/optional.hpp>
#include <boost/bimap/bimap.hpp>
#include <boost/bimap/unordered_set_of.hpp>
#include <boost/bimap/unordered_multiset_of.hpp>
#include <boost/bimap/vector_of.hpp>
#include <boost/bimap/multiset_of.hpp>
#include <boost/bimap/support/lambda.hpp>
#include <boost/timer/timer.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/random/random_device.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/functional/hash/hash.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/unordered_map.hpp>
#include <boost/serialization/unordered_set.hpp>
#include <boost/serialization/list.hpp>
#include <boost/filesystem.hpp>
#include <boost/optional.hpp>
#include "Types.hpp"
#include "Log.hpp"
#include "Task.hpp"
#include "Pack.hpp"
#include "Constants.hpp"
#include "DDS.hpp"
#include "CustomTypedefs.hpp"
#include "TaskManager.hpp"
class AbstractPullWorkProducer {
public:
AbstractPullWorkProducer(MPI_Comm comm_, AbstractDDS *sharedStore_,std::set<int> children_, boost::property_tree::ptree &config) {
comm=comm_;
sharedStore=sharedStore_;
children=children_;
int rank;
MPI_Comm_rank(comm, &rank);
completedTasks.initialize(config,rank);
completedTasks.setBundleSize(1);
start=std::chrono::high_resolution_clock::now();
die=false;
killed=false;
runTime=std::chrono::minutes( config.get<unsigned>("Configuration.RunTime",1000000) );
relay.openBatch();
//TODO: FIX ME
maxTaskMesgSize=10000000;
sendCompleted=1;
recvCompleted=0;
};
virtual void processCompletedTasks()=0;
virtual TaskDescriptorBundle generateTasks(int consumerID, int nTasks)=0;
virtual void checkpoint_impl()=0;
virtual void report_impl()=0;
~AbstractPullWorkProducer(){
};
virtual void initialize()=0;
//virtual void processTasks()=0;
//virtual void generateTasks()=0;
//virtual void checkpoint_impl()=0;
//virtual void report_impl()=0;
void server(){
//BOOST_LOG_SEV(lg,debug) <<"#Splicer::server ";
lastReport=std::chrono::high_resolution_clock::now();
lastCheckpoint=std::chrono::high_resolution_clock::now();
//TODO: do this right
rbufSize=100000000;
rbuf=std::vector<char>(rbufSize,' ');
//post a non-blocking receive
MPI_Irecv(&(rbuf[0]),rbufSize,MPI_BYTE,MPI_ANY_SOURCE,MPI_ANY_TAG,comm,&incomingRequest);
recvCompleted=0;
initialize();
while(true) {
if(std::chrono::high_resolution_clock::now() - start > runTime ) {
LOGGERA("WP: TIME TO DIE")
die=true;
}
//update databases
timer.start("UpdateDB");
updateStores();
timer.stop("UpdateDB");
//process non-blocking receives (completed segments from WM)
timer.start("Recv");
processRecv();
timer.stop("Recv");
//process non-blocking sends (tasks to WM)
timer.start("Send");
processSend();
timer.stop("Send");
//write outputs if needed
timer.start("Report");
report();
timer.stop("Report");
//checkpoint if needed
checkpoint(false);
//if(die and recvCompleted and sendCompleted) {
if(die) {
//force a checkpoint
//checkpoint(true);
break;
LOGGERA("WP: DONE")
}
}
};
void updateStores(){
int imax=1000;
int i=0;
while(sharedStore->singleServe()>0 and i<imax) {
i++;
}
};
void processRecv(){
//did we receive new completed tasks?
if(not recvCompleted) {
MPI_Test(&incomingRequest,&recvCompleted,&recvStatus);
}
if(not recvCompleted and die) {
MPI_Cancel(&incomingRequest);
}
if(recvCompleted and not die) {
//timer.start("Recv-Mesg");
int count=0;
MPI_Get_count( &recvStatus, MPI_BYTE, &count );
int from=recvStatus.MPI_SOURCE;
int requests;
std::multimap<std::string, DataItem> results;
unpack(rbuf,results,requests,count);
//assimilate the results
timer.start("Recv-Assimilate");
completedTasks.assimilate(results);
timer.stop("Recv-Assimilate");
//release completed results
timer.start("Recv-Extract");
completedTasks.extract(ready);
timer.stop("Recv-Extract");
timer.start("Recv-Process");
processCompletedTasks();
timer.stop("Recv-Process");
if(requests>0) {
taskRequests[from]+=requests;
}
LOGGER("SPLICER RECEIVED "<<requests<<" TASK REQUESTS FROM "<<from)
//post a new receive for tasks
MPI_Irecv(&(rbuf[0]),rbufSize,MPI_BYTE,MPI_ANY_SOURCE,MPI_ANY_TAG,comm,&incomingRequest);
recvCompleted=0;
timer.stop("Recv-Mesg");
}
};
bool processSend(){
//fulfill requests
if(not sendCompleted) {
MPI_Test(&outgoingRequest,&sendCompleted,&sendStatus);
}
//according to the MPI standard, TEST after CANCEL should eventually succeed.
//in practice, it does not seem to be the case (see https://www.mail-archive.com/users@lists.open-mpi.org/msg30905.html)
if(not sendCompleted and die) {
MPI_Cancel(&outgoingRequest);
}
if(sendCompleted and not die) {
if(not taskRequests.empty()) {
// auto it=taskRequests.begin();
for(auto it=taskRequests.begin(); it!=taskRequests.end(); ) {
// DataItem d;
timer.start("Generate");
TaskDescriptorBundle tasks = generateTasks(it->first,it->second);
timer.stop("Generate");
bool deleteRequest=false;
if(tasks.count()>0) {
timer.start("Send-Mesg");
pack(sbuf,tasks);
//pack(d.data,tasks);
//TaskDescriptorBundle tt;
//unpack(sbuf,tt);
LOGGER("WORK PRODUCER FULFILLING "<<it->second<<" TASK REQUESTS FROM "
<<it->first<<" "<<tasks.count()<<" "<< sbuf.size()<<" "<<boost::hash_value(sbuf))
MPI_Issend( &(sbuf[0]),sbuf.size(),MPI_BYTE,it->first,TASK_REQUEST_TAG, comm, &outgoingRequest);
sendCompleted=0;
//taskRequests.erase(it);
deleteRequest=true;
timer.stop("Send-Mesg");
//break;
}
if(deleteRequest) it=taskRequests.erase(it);
else it++;
}
}
}
return true;
};
void report(){
//report at given intervals
if(std::chrono::high_resolution_clock::now() - lastReport> reportDelay ) {
Timer t;
timer.report();
LOGGERA("PENDING TASK REQUESTS: ")
for(auto tr : taskRequests) LOGGERA(tr.first<<" : "<<tr.second)
report_impl();
lastReport=std::chrono::high_resolution_clock::now();
}
};
void checkpoint(bool now=false){
//checkpoint at given intervals
if(now or (std::chrono::high_resolution_clock::now() - lastCheckpoint > checkpointDelay) ) {
//checkpoint
checkpoint_impl();
lastCheckpoint=std::chrono::high_resolution_clock::now();
}
};
protected:
AbstractDDS *sharedStore;
TaskMapperType mapper;
BundleType ready;
TaskDescriptorRelay relay;
ResultManager<BundleType> completedTasks;
std::map<int,int> taskRequests;
std::set<int> children;
MPI_Comm comm;
int recvCompleted;
int sendCompleted;
MPI_Status recvStatus;
MPI_Status sendStatus;
MPI_Request incomingRequest;
MPI_Request outgoingRequest;
std::vector<char> rbuf;
std::vector<char> sbuf;
int rbufSize;
unsigned maxTaskMesgSize;
std::vector<std::vector<char> > sBuf;
std::chrono::high_resolution_clock::time_point start;
std::chrono::milliseconds reportDelay;
std::chrono::milliseconds checkpointDelay;
std::chrono::minutes runTime;
std::chrono::high_resolution_clock::time_point lastReport;
std::chrono::high_resolution_clock::time_point lastCheckpoint;
bool die;
bool killed;
ExecutionTimer timer;
};
#endif
|
#pragma once
#include <Tanker/Crypto/Hash.hpp>
#include <Tanker/Crypto/PublicSignatureKey.hpp>
#include <Tanker/Crypto/Signature.hpp>
#include <Tanker/Serialization/SerializedSource.hpp>
#include <Tanker/Trustchain/Actions/Nature.hpp>
#include <Tanker/Trustchain/ServerEntry.hpp>
#include <Tanker/Trustchain/TrustchainId.hpp>
#include <nlohmann/json_fwd.hpp>
#include <cstddef>
#include <cstdint>
#include <vector>
namespace Tanker
{
namespace Trustchain
{
struct Block
{
TrustchainId trustchainId;
std::uint64_t index;
Crypto::Hash author;
Actions::Nature nature;
std::vector<std::uint8_t> payload;
Crypto::Signature signature;
Crypto::Hash hash() const;
bool verifySignature(
Crypto::PublicSignatureKey const& publicSignatureKey) const;
};
bool operator==(Block const& l, Block const& r);
bool operator!=(Block const& l, Block const& r);
std::size_t serialized_size(Block const&);
void from_serialized(Serialization::SerializedSource& ss, Block&);
std::uint8_t* to_serialized(std::uint8_t* it, Block const& b);
void to_json(nlohmann::json& j, Block const& b);
ServerEntry blockToServerEntry(Block const& b);
}
}
|
#include <iberbar/Lua/LuaCppCommon.h>
// Class 类名,如 CFoo
extern const char iberbar::Lua::uClassReflection_ClassName[] = "__cpp_classname";
// Class 所属的模块名,如 iberbar.Test
extern const char iberbar::Lua::uClassReflection_ModuleName[] = "__cpp_modulename";
// Class 全名,如 iberbar.Test.CFoo
extern const char iberbar::Lua::uClassReflection_FullName[] = "__cpp_fullname";
// Class 定义来源,1=C++,2=Lua
extern const char iberbar::Lua::uClassReflection_CType[] = "__ctype";
extern const char iberbar::Lua::uWeakTable_ForUserData[] = "__cpp_userdata";
//namespace iberbar { namespace LuaCpp {
//extern "C"
//{
// // Class 类名,如 CFoo
// const char uClassReflection_ClassName[] = "__cpp_classname";
//
// // Class 所属的模块名,如 iberbar.Test
// const char uClassReflection_ModuleName[] = "__cpp_modulename";
//
// // Class 全名,如 iberbar.Test.CFoo
// const char uClassReflection_FullName[] = "__cpp_fullname";
//
// // Class 定义来源,1=C++,2=Lua
// const char uClassReflection_CType[] = "__ctype";
//}
//}
//}
|
// Lab 1 PF Rev Q2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream fin("D:\\l180929\\Lab 1 PF Rev Q2\\Sample input.txt");
int n=0, x=0, p=0;
fin>>n;
for(int i=0; i<n; i++){
fin>>x>>p;
cout<<pow(x,p)<<endl;
}
return 0;
}
|
#include "x_pch.h"
#include "x/x_app.h"
namespace x
{
static x_App *s_pApp = nullptr;
void OnClose()
{
if (s_pApp) s_pApp->onClose();
}
void OnSize(x::x_Sint32 x, x::x_Sint32 y)
{
if (s_pApp) s_pApp->onSize(x, y);
}
x_App::x_App()
: m_pGraphics(nullptr)
, m_pPlatform(nullptr)
, m_running(false)
{
s_pApp = this;
}
x_App::~x_App()
{
}
void x_App::setGraphics(x_Graphics* pGraphics)
{
m_pGraphics = pGraphics;
}
void x_App::setPlatform(x_Platform* pPlatform)
{
m_pPlatform = pPlatform;
}
x_Bool x_App::create(x_String windowTitle, x_Sint32 width, x_Sint32 height)
{
x_Bool returnValue = false;
m_pPlatform->registerOnClose(OnClose);
m_pPlatform->registerOnSize(OnSize);
if (m_pPlatform->createWindow(windowTitle, width, height))
{
if (m_pGraphics->create(m_pPlatform->getWindowHandler(), m_pPlatform->getDeviceContextHandler()))
{
returnValue = true;
m_running = true;
}
}
return returnValue;
}
x_Sint32 x_App::run(void)
{
x_Sint32 exitCode = 0;
while (m_running)
{
exitCode = messagePump();
if (m_running)
{
m_pGraphics->clear();
m_pGraphics->draw();
m_pGraphics->present();
}
}
return exitCode;
}
x_Sint32 x_App::messagePump(void)
{
return m_pPlatform->messagePump();
}
void x_App::onClose(void)
{
m_running = false;
}
void x_App::onSize(x_Sint32 x, x_Sint32 y)
{
if (m_running) m_pGraphics->size(x, y);
}
}
|
#include "view.h"
#include "modellist.h"
#include "modellistiter.h"
View::View()
{
}
View::~View()
{}
void View::draw(SDL_Surface *screen, ModelList& modellist)
{
while (!modellist.isDone()) {
Model model(modellist.get());
SDL_Rect dest;
dest.x = model.getX();
dest.y = model.getY();
SDL_BlitSurface(modellist.get().getSurface(), NULL, screen, &dest);
modellist.next();
}
SDL_Flip(screen);
}
|
/*
When we convert graph into tree such that it has n nodes and n-1 edges and each node is reachable from other node then it
is called spanning tree.
when total cost of edges is minimum for the all spanning tree is MST.
Prims Algorithm:
1. key array
2. MST track array
3. Parent array
*/
#include<bits/stdc++.h>
using namespace std;
template<typename T>
class graph{
public:
unordered_map<int,list<pair<int,int>>> adj;
void addEdge(int u, int v, int w, bool isDirected){
adj[u].push_back(make_pair(w,v));
if(!isDirected){
adj[v].push_back(make_pair(w,u));
}
}
void printGraph(){
for(auto i: adj){
cout<<i.first<<"->";
for(auto j: i.second){
cout<<"{"<<j.first<<","<<j.second<<"},";
}
cout<<endl;
}
}
};
void MST_Prims(unordered_map<int,list<pair<int,int>>> &adj, int n, vector<tuple<int,int,int>> &ans){
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;
// vector for keys and initilize all with inf
vector<int> key(n,INT32_MAX);
// vector to keep track of nodes if they are included in MST
vector<bool> isMST(n,false);
// vector to keep track of parent
vector<int> parent(n,-1);
int src = 0;
pq.push(make_pair(0,src));
key[src] = 0;
while(!pq.empty()){
int u = pq.top().second;
pq.pop();
if(!isMST[u]){
isMST[u]=true;
for(auto x: adj[u]){
int v = x.second;
int weight = x.first;
if(isMST[v]==false && key[v]>weight){
key[v] = weight;
pq.push(make_pair(weight,v));
parent[v]=u;
}
}
}
}
for(int i=1;i<n;i++){
ans.push_back(make_tuple(parent[i],i,key[i]));
}
}
int main(){
graph<int> g;
int n,m;
cin>>n>>m;
for(int i=0;i<m;i++){
int u,v,w;
cin>>u>>v>>w;
g.addEdge(u,v,w,0);
}
g.printGraph();
vector<tuple<int,int,int>> ans;
MST_Prims(g.adj,n,ans);
for(int i=0;i<ans.size();i++){
cout<<get<0>(ans[i])<<" "<<get<1>(ans[i])<<" "<<get<2>(ans[i])<<endl;
}
return 0;
}
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
//
// Copyright (C) 2003-2012 Opera Software AS. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
//
//
#ifndef LOADICONS_PI_H
#define LOADICONS_PI_H
#include "modules/util/adt/opvector.h"
class TransferItemContainer;
/***********************************************************************************
** This class is an abstract interface for platforms where getting the icon
** associated with a file on disk is expensive. The platform may choose to
** implement this class using threading. If no separate implementation is provided,
** the code will run on the main thread but only get a single icon every 100ms.
** This code is used by the transfer manager.
***********************************************************************************/
class OpAsyncFileBitmapLoader
{
public:
/*
* Listener for status messages during loading of icons
*/
class OpAsyncFileBitmapHandlerListener
{
public:
/*
* Called on the listener for each bitmap that has been loaded for
* the given transfer item.
*
* @param item The transfer item the image is associated with
*/
virtual void OnBitmapLoaded(TransferItemContainer *item) = 0;
/*
* Called on the listener after all bitmaps have been loaded.
*
*/
virtual void OnBitmapLoadingDone() = 0;
};
static OP_STATUS Create(OpAsyncFileBitmapLoader** new_asyncfilebitmaploader);
virtual ~OpAsyncFileBitmapLoader() {}
/*
* Initialize the bitmap loader
*
* @param listener The listener that will receive progress updates
*/
virtual OP_STATUS Init(OpAsyncFileBitmapHandlerListener *listener) = 0;
/*
* Start the process of fetching icons for the transfer items.
*
* @param transferitems The transfer items to fetch icons for.
* These items are are ONLY valid for the duration of this call
* so the implementation MUST copy the relevant information and
* use that.
*/
virtual void Start(OpVector<TransferItemContainer>& transferitems) = 0;
};
#endif // LOADICONS_PI_H
|
#include <SPI.h>
#include <deprecated.h>
#include <MFRC522.h>
#include <MFRC522Extended.h>
#include <require_cpp11.h>
#include <Servo.h>
int RST_PIN = 9;
int SS_PIN = 10;
int servoPin = 8;
int kapi = 45;
byte ID[4] = {25, 11, 152, 40};
Servo motor;
MFRC522 rfid (SS_PIN, RST_PIN);
void setup() {
motor.attach(servoPin);
Serial.begin(9600);
SPI.begin();
rfid.PCD_Init();
}
void loop() {
if(!rfid.PICC_IsNewCardPresent())
return;
if(!rfid.PICC_ReadCardSerial())
return;
if (rfid.uid.uidByte[0] == ID[0] && rfid.uid.uidByte[1] == ID[1] && rfid.uid.uidByte[2] == ID[2] && rfid.uid.uidByte[3] == ID[3]){
//ekranaYazdir();
if(kapi == 45){
//Serial.println("kapi acildi");
motor.write(kapi);
//delay(1000);
kapi =90;
//send
Serial.print('1');
delay(500);
}else if (kapi == 90){
//Serial.println("kapi kapandi");
motor.write(kapi);
//delay(1000);
kapi=45;
//send
Serial.print('0');
delay(500);
}
}else {
Serial.println("yetkisiz kart");
//ekranaYazdir();
}
rfid.PICC_HaltA();
}
void ekranaYazdir(){
Serial.println("ID numara: ");
for(int sayac = 0;sayac < 4; sayac++){
Serial.println(rfid.uid.uidByte[sayac]);
Serial.println(" ");
}
Serial.println("");
}
|
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <OneButton.h>
#include <Rotary.h>
Rotary r = Rotary(2, 3);
OneButton button(10,true);
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library.
// On an arduino UNO: A4(SDA), A5(SCL)
// On an arduino LEONARDO: 2(SDA), 3(SCL), ...
#define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define LOGO_HEIGHT 16
#define LOGO_WIDTH 16
// static const unsigned char PROGMEM logo_bmp[] =
// { B00000000, B11000000,
// B00000001, B11000000,
// B00000001, B11000000,
// B00000011, B11100000,
// B11110011, B11100000,
// B11111110, B11111000,
// B01111110, B11111111,
// B00110011, B10011111,
// B00011111, B11111100,
// B00001101, B01110000,
// B00011011, B10100000,
// B00111111, B11100000,
// B00111111, B11110000,
// B01111100, B11110000,
// B01110000, B01110000,
// B00000000, B00110000 };
boolean isWorking, isErr;
int input = -2;
int count = 1;
void setup() {
Serial.begin(9600);
//rotary interrupt
PCICR |= (1 << PCIE2);
PCMSK2 |= (1 << PCINT18) | (1 << PCINT19);
sei();
// click on the encoder
button.attachDoubleClick(doubleclick);
button.attachClick(singleclick);
Serial.println("Testing Rotary with SSD1306 OLED Screen");
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
// Show initial display buffer contents on the screen --
// the library initializes this with an Adafruit splash screen.
display.display();
display.setTextColor(WHITE);
delay(2000); // Pause for 2 seconds
// Clear the buffer
display.clearDisplay();
delay(2000);
}
void loop() {
if (isWorking != true) {
button.tick();
switch (input) {
case 2: //"DOUBLE_CLICK":
display.clearDisplay();
display.setCursor(10,3);
display.println("Double clicked");
display.display();
break;
case 0: //"SINGLE_CLICK":
display.clearDisplay();
display.setCursor(10,3);
display.println("Clicked");
display.display();
break;
case 1: //"CLOCKWISE":
if (count !=3) {
count++;
displaySetup(count);
}
else{
count = 1;
displaySetup(count);
}
break;
case -1: //"COUNTERCLOCK":
if (count !=1) {
count--;
displaySetup(count);
}
else{
count = 3;
displaySetup(count);
}
break;
}
input = -2;
}
else {
// Disable all input from Rotary
isWorking = false;
}
}
void doubleclick() {
input = 2;
Serial.println("DOUBLE_CLICK");
}
void singleclick() {
input = 0;
Serial.println("SINGLE_CLICK");
}
ISR(PCINT2_vect) {
unsigned char result = r.process();
if (result == DIR_NONE) {
}
else if (result == DIR_CW) {
input = 1;
Serial.println("CLOCKWISE");
}
else if (result == DIR_CCW) {
input = -1;
Serial.println("COUNTERCLOCK");
}
}
void displaySetup(int cursorPos) {
display.clearDisplay();
display.setCursor(0,0);
display.setTextSize(1);
display.println("SELECT OUTPUT TEMP:");
display.setCursor(15,20);
display.setTextSize(1);
display.print("33");
display.write(248);
display.println("C");
display.setCursor(15,30);
display.setTextSize(1);
display.print("36");
display.write(248);
display.println("C");
display.setCursor(15 ,40);
display.setTextSize(1);
display.print("39");
display.write(248);
display.println("C");
display.setCursor(2, (cursorPos*10)+10);
display.write(16);
display.display();
}
|
#include "directorywindow.h"
#include "ui_directorywindow.h"
directoryWindow::directoryWindow(QWidget *parent) :
QDialog(parent),
ui(new Ui::directoryWindow)
{
ui->setupUi(this);
doneButton = ui->pushButton;
tree = ui->treeView;
connect(doneButton, SIGNAL(clicked()), this, SLOT(hide()));
addFiles();
}
directoryWindow::~directoryWindow()
{
delete ui;
delete doneButton;
delete tree;
}
void directoryWindow::addFiles() //shows the files from the working directory of the application
{
QFileSystemModel *model = new QFileSystemModel;
QString dir(QCoreApplication::applicationDirPath());
model->setRootPath(dir);
tree->setModel(model);
tree->setRootIndex(model->index((dir)));
tree->show();
}
|
#include "WinCommon.h"
#include "DXCommon.h"
#include "UISprite.h"
bool UISprite::m_bFirst = false;
LPDIRECT3DVERTEXBUFFER9 UISprite::m_pVB = NULL;
D3DFVF_XYZ_TEX1* UISprite::m_pVertex = NULL;
int UISprite::m_iCount = 0;
UISprite::UISprite(bool renderTarget)
{
m_bRenderTarget = renderTarget;
m_pTexture = NULL;
}
UISprite::UISprite( LPDIRECT3DTEXTURE9 ppTexture )
{
m_bRenderTarget = true;
m_pTexture = ppTexture;
m_Width = g_Mode.Width;
m_Height = g_Mode.Height;
strcpy(m_strTextureName, "RenderTarget");
// 출력할 위치
m_vPos.x = (float)0;
m_vPos.y = (float)0;
m_vPos.z = 1.0f;
}
UISprite::~UISprite(void)
{
ReleaseUI();
}
bool UISprite::InitUI( int x, int y, char* name, D3DXCOLOR color )
{
// 공통으로 사용하므로 한번만
if( !m_bFirst )
InitVTX();
D3DXIMAGE_INFO imageInfo;
if( FAILED(D3DXCreateTextureFromFileEx(
g_pDevice, // 디바이스
name, // 파일이름
0, 0, // w, h
D3DX_DEFAULT, // MipLevel
0,
D3DFMT_UNKNOWN,
D3DPOOL_MANAGED,
D3DX_FILTER_LINEAR,
D3DX_DEFAULT,
color,
&imageInfo,
NULL,
&m_pTexture
) ))
{
char msg[256];
sprintf(msg, "텍스처 로드 실패 \n FileName=%s", name);
MessageBox(NULL, msg, "Error", MB_ICONERROR);
return false;
}
// 텍스쳐 정보
m_Width = imageInfo.Width;
m_Height = imageInfo.Height;
strcpy(m_strTextureName, name);
// 출력할 위치
m_vPos.x = (float)x;
m_vPos.y = (float)y;
m_vPos.z = 1.0f;
m_iCount++;
return true;
}
bool UISprite::InitUI(void)
{
if( !m_bFirst )
InitVTX();
m_iCount++;
return true;
}
bool UISprite::InitVTX( void )
{
D3DFVF_XYZ_TEX1 Vertices[] =
{
{ D3DXVECTOR3(0, 0, 0), 0, 0 }, //UV 좌표 주의!
{ D3DXVECTOR3(1, 0, 0), 1, 0 },
{ D3DXVECTOR3(0, 1, 0), 0, 1 },
{ D3DXVECTOR3(1, 1, 0), 1, 1 },
};
m_iVtxCnt = sizeof(Vertices) / (sizeof(D3DFVF_XYZ_TEX1)*3);
int iVertexSize = sizeof(Vertices);
m_pVertex = new D3DFVF_XYZ_TEX1[iVertexSize];
memcpy(m_pVertex, Vertices, iVertexSize);
// 정점버퍼 생성
if( FAILED(g_pDevice->CreateVertexBuffer(
iVertexSize, // 정점버퍼 크기
0, // 버퍼 처리 유형
FVF_XYZ_TEX1, // 정점 플레그
D3DPOOL_MANAGED, // 정점 버퍼 위치
&m_pVB, // 성공시 리턴 포인터
NULL // 예약
)) )
{
return false;
}
// 버퍼 채우기
VOID* pBuff;
if( FAILED(m_pVB->Lock(0, iVertexSize, (void**)&pBuff, 0)) )
{
return false;
}
memcpy(pBuff, m_pVertex, iVertexSize);
m_pVB->Unlock();
m_bFirst = true;
return true;
}
void UISprite::UpdateUI( float dTime )
{
}
void UISprite::RenderUI( void )
{
// 이미지 크기로 변경
D3DXMatrixScaling(&m_mScale, (float)m_Width, (float)m_Height, 1.0f);
// 위치설정
D3DXMatrixTranslation(&m_mTrans, m_vPos.x, m_vPos.y, m_vPos.z);
// 최종행렬
m_mTM = m_mScale * m_mTrans;
// 알파테스트
DWORD alpha = (DWORD)(0.3f * 255);
g_pDevice->SetRenderState( D3DRS_ALPHATESTENABLE, TRUE );
//g_pDevice->SetRenderState( D3DRS_ALPHAREF, (DWORD)(0.3f*255) );
g_pDevice->SetRenderState( D3DRS_ALPHAREF, alpha );
g_pDevice->SetRenderState( D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);
// 모드변경
g_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
g_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
// 출력
g_pDevice->SetTexture(0, g_bWireFrame ? NULL : m_pTexture);
g_pDevice->SetStreamSource(0, m_pVB, 0, sizeof(D3DFVF_XYZ_TEX1));
g_pDevice->SetFVF(FVF_XYZ_TEX1);
g_pDevice->SetTransform(D3DTS_WORLD, &m_mTM);
g_pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2 );
g_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
g_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
}
void UISprite::RenderAlphaUI( float alpha )
{
// 알파 블렌딩
g_pDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
g_pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
g_pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_CONSTANT);
g_pDevice->SetTextureStageState(0, D3DTSS_CONSTANT, D3DXCOLOR(0, 0, 0, alpha));
g_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
g_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
g_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
RenderUI();
// 복구
g_pDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
g_pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
g_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
}
void UISprite::ReleaseUI( void )
{
SAFE_RELEASE(m_pTexture);
m_iCount--;
if( m_iCount == 0 )
{
SAFE_RELEASE(m_pVB);
SAFE_DELETE_ARRAY(m_pVertex);
}
}
|
/*
The project is developed as part of Computer Architecture class
Project Name: Functional Simulator for subset of RISCV Processor
Developer's Name:
Developer's Email id:
Date:
*/
/* myRISCVSim.cpp
Purpose of this file: implementation file for myRISCVSim
*/
#include<bits/stdc++.h>
#include "myARMSim.h"
#include"execute.hpp"
#include <cstdlib>
#include <cstdio>
#include<string>
#include"buffers.hpp"
using namespace std;
/////////////////////////////////////// updated++++++++++++++++++++++++++
int cold_missI;
int capacity_missI;
int conflict_missI;
int hitsI;
int cold_missD;
int capacity_missD;
int conflict_missD;
int hitsD;
int noSets;
//memory
unsigned char MEM[4096];
unsigned char cacheI[4096];
unsigned char cacheD[4096];
int tagI[4096];
int tagD[4096];
bool valid_bitI[4096];
bool valid_bitD[4096];
unsigned int LRUI[4096];
unsigned int LRUD[4096];
//input
int cachesizeI;
int blocksize;
int cachetype;
int cachesizeD;
//-------------------------------------------Priya meghana
int ni=0;
int c=0;
int stall=0;
int contrl_hazards=0;
int stall_data=0;
int mis_predictions=0;
int num_data_hazards=0;
int total_num_exe_inst=0;
int data_knob=0;
//Register file
extern unsigned int R[32];
int num_instructions=0;
extern int prev_PC;
//flags
int N,C,V,Z;
int ry, RZ;
//memory
unsigned int operand2;
unsigned int R[32];
int predict=1;//intitilaised here;
int flush_inst=0;//''''
int hazard_cntrl=0;
int comp=0;
int global_PC=0;
int data_transfer=0;
int ALU=0;
//int data_transfer=0;
int num_inst_cntrl=0;
int pipelining_knob=0;
//intermediate datapath and control path signals
//unsigned int instruction_word;
unsigned int operand1;
signed int jump_imm_offset=0;
unsigned int PCSRC;
//extern unsigned int PC_count=0;
unsigned int PC_add;
unsigned int return_add;
int clock_cycle=1;
unsigned int PC_count=0;
inter_stage_buffer_ID_EX B2;
inter_stage_buffer_EX_MEM B3;
inter_stage_buffer_IF_ID B1;
inter_stage_buffer_MEM_WB B4;
// int ifunct3;
// int ifunct7;
// int iopcode;
// string funct3;
// string funct7;
// string opcode;
//int iRA;
//int iRB;
//int iRd;
//int iRM;
//int RA;
//int RB;
string operation;
int read_byte(unsigned char *mem, unsigned int address);
int read_hw(unsigned char *mem, unsigned int address);
int read_dw(unsigned char *mem, unsigned int address);
void write_byte(unsigned char *mem, unsigned int address, uint8_t data);
void write_hw(unsigned char *mem, unsigned int address, uint16_t data);
void write_dw(unsigned char *mem, unsigned int address, unsigned long long int data);
int num_inst=0;
int binstr_to_dec(string x)
{
int sum=0;
//cout<<"x:"<<x<<endl;
for(int i=4;i>=0;i--)
{
int c=x[i];
sum=sum+(c-48)*pow(2,4-i);
}
//cout<<"sum:"<<sum<<endl;
return sum;
}
int binstr_to_decBigEndian(string x)
{
int sum=0;
for(int i=0;i<=3;i++)
{
int c=x[i];
sum=sum+(c-48)*pow(2,3-i);
}
return sum;
}
string bin_to_hex(string mac_bin)
{
string mac_code;
for(int i=0;i<32;i+=4)
{
string x=mac_bin.substr(i,4);
stringstream ss(x);
int a=binstr_to_dec(x);
if(a<=9)
{
char c=48+a;
mac_code+=c;
}
else
{
char c=55+a;
mac_code+=c;
}
x="";
}
return mac_code;
}
void run_RISCVsim()
{
cout<<"enter \n1.pipelining implementation\n2.without pipelining<<endl";
cout<<"\n Pipelining knob: ";
cin>>pipelining_knob;
cout<<"\n\n Data Forwarding Knob:";
cin>>data_knob;
int index=0;
if(pipelining_knob==1)
{
cout<<"DO YOU WANT REGISTER VALUES TO BE DISPALYED at the end of each cock cycle \n 1.yes\n2.no ::"<<endl;
int q;
cin>>q;
cout<<"DO YOU WANT TO KNOW THE INFORMATION IN THE PIPELINE REGISTERS \n 1.YES \n2.NO"<<endl;
int s;
cin>>s;
while(1)
{
//cout<<"clock_cycle$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ :"<<clock_cycle<<endl;
//cout<<"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% R[5] : "<<R[5]<<endl;
//cout<<"B1.RA
// if(clock_cycle>25)
// break;
cout<<"values in buffer1"<<endl;
cout<<"B1.instruc_from_mem:"<<B1.instruc_from_mem;
cout<<"B1.PC:"<<B1.PC<<endl;;
cout<<"\n\n"<<endl;
cout<<"values in buffer2"<<endl;
cout<<"B2.RA"<<B2.RA;//from IF/ID
// int RB;//from IF/ID
// string iRA;//from regfile
// string iRB;//from regfile
// int iRM;
// int reg_write;
// string iRd; //address of rd
// int MeM_to_reg;
// int branch;
// int mem_Read;
// int mem_write;
// string alu_cntrl_sgnl;
// string opcode;
// unsigned int PC;
// string func3;
// unsigned int inst_wrd;
// for(int i=0; i<32 ; i++)
// {
// cout<<"R["<<i<<"] = "<<R[i]<<"\t";
//printf("intitalise hua");
// }
// for(int j=0; j<4096; j++)
// {
// if(MEM[j]!=0)
// printf("MEM [%d] = %x ",j,MEM[j]);
// }
cout<<endl;
// for(int i=0;i<)
cout<<endl<<endl;
if(clock_cycle>=5)
write_back();
if(clock_cycle>=4)
mem();
if(clock_cycle>=3)
execute();
if(clock_cycle>=2)
decode();
if(clock_cycle>=1)
fetch();
cout<<"CLOCK CYCLE ::::"<<clock_cycle<<endl;
if(q==1)
{
for(int i=0; i<32 ; i++)
{
cout<<"R["<<i<<"] = "<<R[i]<<"\t";
//printf("intitalise hua");
}
cout<<endl<<endl;
}
if(s==1)
{
cout<<"VALUES FROM B1 REGISTERS ::"<<endl;
cout<<"B1.instruc_from_mem ::"<<B1.instruc_from_mem<<endl;
cout<<"B1.PC ::"<< B1.PC<<endl<<endl<<endl;
cout<<"VALUES FROM B2 REGISTERS ::"<<endl;
cout<<" B2.RA :: "<<B2.RA<<endl;//from IF/ID
cout<<"B2.RB :: "<<B2.RB<<endl;;//from IF/ID
cout<<"B2.iRA ::"<<B2.iRA<<endl;;//from regfile
cout<<"B2.iRB :"<<B2.iRB<<endl;;//from regfile
cout<<"B2.iRM :"<<B2.iRM<<endl;
cout<<"B2.reg_write :"<<B2.reg_write<<endl;;
cout<<"B2.iRd :"<<B2.iRd<<endl; //address of rd
cout<<"B2.MeM_to_reg :"<<B2.MeM_to_reg<<endl;
//branch;
cout<<"B2.mem_Read :"<<B2.mem_Read<<endl;
cout<<"B2.mem_write :"<<B2.mem_write<<endl;
//string alu_cntrl_sgnl;
//string opcode;
cout<<"B2.PC :"<<B2.PC<<endl;
//string func3;
//int hazard_found;
cout<<"B2.inst_wrd :"<<B2.inst_wrd<<endl<<endl<<endl;
cout<<" VALUES FROM B3 REGISTERS ::"<<endl;
cout<<"B3.RZ :"<<B3.RZ<<endl;;
cout<<"B3.PC :"<<B3.PC<<endl;
cout<<"B3.Rd_address :"<<B3.Rd_address<<endl;;
// string opcode;
//int hazard_found;
//string func3;
cout<<"B3.instruction_wrd :"<<B3.instruction_wrd<<endl;
cout<<"B3.RB :"<<B3.RB<<endl;
cout<<"B3.reg_write :"<<B3.reg_write<<endl;;
cout<<"B3.mem_Read :"<<B3.mem_Read<<endl;
cout<<"B3.mem_write :"<< B3.mem_write<<endl;
cout<<"VALUES FROM B4 REGISTER :"<<endl;
cout<<"B4.RY :"<<B4.RY<<endl;
// string opcode;
//string func3;
cout<<"B4.instruction_wrd :"<<B4.instruction_wrd<<endl;
cout<<"B4.RB :"<<B4.RB<<endl ;
//int hazard_found;
cout<<"B4.reg_write :" <<B4.reg_write<<endl;
cout<<"B4.iRd :"<<B4.iRd<<endl;
}
clock_cycle++;
//cout<<"oooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"<<opcode<<endl;
if(N==1)
{
// cout<<"i am out"<<endl;
// break;
write_back();
mem();
execute();
if(q==1)
{
for(int i=0; i<32 ; i++)
{
cout<<"R["<<i<<"] = "<<R[i]<<"\t";
//printf("intitalise hua");
}
cout<<endl<<endl;
}
clock_cycle++;
write_back();
mem();
if(q==1)
{
for(int i=0; i<32 ; i++)
{
cout<<"R["<<i<<"] = "<<R[i]<<"\t";
//printf("intitalise hua");
}
cout<<endl<<endl;
}
clock_cycle++;
write_back();
if(q==1)
{
for(int i=0; i<32 ; i++)
{
cout<<"R["<<i<<"] = "<<R[i]<<"\t";
//printf("intitalise hua");
}
cout<<endl<<endl;
}
clock_cycle++;
break;
}
//ni++;
}
for(int i=0; i<32 ; i++)
{
cout<<"R["<<i<<"] = "<<R[i]<<"\t";
//printf("intitalise hua");
}
cout<<endl<<endl;
for(int j=0; j<4096; j++)
{
if(MEM[j]!=0)
printf("MEM [%d] = %x ",j,MEM[j]);
}
cout<<"TOTAL NUMBER OF CYCLES ::"<<clock_cycle<<endl;
// num_inst=clock_cycle-4+c;
num_instructions=num_instructions-1;
cout<<"NUMBER OF INSTRUCTIONS ::"<<(num_instructions)<<endl;
cout<<"TOTAL NUMBER OF EXECUTED INSTRUCTIONS ::"<<total_num_exe_inst<<endl;
float x=clock_cycle/total_num_exe_inst;
cout<<"CLOCK_CYCLE PER INSTRUCTION ::"<<x<<endl;
//int y=
cout<<"NUMBER OF DATA TRANSFER INSTRUCTIONS ::"<<data_transfer<<endl;
cout<<"NUMBER OF ALU INSTRUCTIONS ::"<<ALU<<endl;
cout<<"NUMBER OF CONTROL INSTRUCTIONS ::"<<num_inst_cntrl<<endl;
cout<<"NUMBER OF STALLS ::"<<contrl_hazards+stall_data<<endl;
cout<<"NUMBER OF DATA HAZARDS ::"<<num_data_hazards<<endl;
cout<<"NUMBER OF CONTROL HAZARDS ::"<<contrl_hazards<<endl;
cout<<"NUMBER OF STALLS DUE TO CONTROL HAZARDS ::"<<contrl_hazards<<endl;
cout<<"NUMBER OF STALLS DUE TO DATA HAZARDS ::"<<stall_data<<endl;
cout<<"NUMBER OF MISPREDICTIONS ::"<<mis_predictions<<endl;
//PCSRC=0;
cout<<endl;
cout<<"CACHE STATS --------------"<<endl;
cout<<endl;
cout<<"total number of data hitsD: "<<hitsD<<endl;
cout<<"total number of instruction hitsI: "<<hitsI<<endl;
cout<<"total number of data cold missD: "<<cold_missD<<endl;
cout<<"total number of data capacity missD: "<<capacity_missD<<endl;
cout<<"total number of data conflict missD: "<<conflict_missD<<endl;
cout<<"total number of instruction cold missI: "<<cold_missI<<endl;
cout<<"total number of instruction capacity missI: "<<capacity_missI<<endl;
cout<<"total number of instruction conflict missI: "<<conflict_missI<<endl;
}
else{
while(1)
{
fetch();
if(N==1)
{
break;
}
decode();
execute();
mem();
write_back();
clock_cycle+=5;
}
for(int i=0; i<32 ; i++)
{
cout<<"R["<<i<<"] = "<<R[i]<<"\t";
//printf("intitalise hua");
}
cout<<endl<<endl;
for(int j=0; j<4096; j++)
{
if(MEM[j]!=0)
printf("MEM [%d] = %x ",j,MEM[j]);
}
cout<<endl;
cout<<"CACHE STATS --------------"<<endl;
cout<<"total number of data hitsD: "<<hitsD<<endl;
cout<<"total number of instruction hitsI: "<<hitsI<<endl;
cout<<"total number of data cold missD: "<<cold_missD<<endl;
cout<<"total number of data capacity missD: "<<capacity_missD<<endl;
cout<<"total number of data conflict missD: "<<conflict_missD<<endl;
cout<<"total number of instruction cold missI: "<<cold_missI<<endl;
cout<<"total number of instruction capacity missI: "<<capacity_missI<<endl;
cout<<"total number of instruction conflict missI: "<<conflict_missI<<endl;
}
for(int i=0; i<32 ; i++)
{
cout<<"R["<<i<<"] = "<<R[i]<<"\t";
//printf("intitalise hua");
}
cout<<endl<<endl;
for(int j=0; j<4096; j++)
{
if(MEM[j]!=0)
printf("MEM [%d] = %x ",j,MEM[j]);
}
cout<<endl;
}
// it is used to set the reset values
//reset all registers and memory content to 0
void reset_proc() {
for(int i=0; i<32 ; i++)
{
R[i]=0;
//printf("intitalise hua");
}
for(int j=0; j<4096 ; j++)
{
MEM[j]='\0';
cacheD[j]='\0';
tagD[j]=-1;
LRUD[j]=0;
valid_bitD[j]=0;
cacheI[j]='\0';
tagI[j]=-1;
LRUI[j]=0;
valid_bitI[j]=0;
}
cold_missD=0;
capacity_missD=0;
conflict_missD=0;
hitsD=0;
cold_missI=0;
capacity_missI=0;
conflict_missI=0;
hitsI=0;
}
//load_program_memory reads the input memory, and pupulates the instruction
// memory
void load_program_memory(char *file_name) {
FILE *fp;
unsigned int address, instruction;
fp = fopen(file_name, "r");
if(fp == NULL) {
printf("Error opening input mem file\n");
exit(1);
}
while(fscanf(fp, "%x %x", &address, &instruction) != EOF) {
num_instructions++;
//printf("%x %x ",address, instruction);
write1_word(MEM, address, instruction);
}
// cout<<"NUMBER OF INSTRUCTIONS ::"<<num_instructions<<endl;
fclose(fp);
for(int i=0; i<32 ; i++)
{
R[i]=0;
if(i==2)
{
R[i]=4092;
}
//printf("intitalise hua");
}
for(int j=0; j<4096; j++)
{
//if(MEM[j]!=0)
//printf("MEM [%d] = %d ",j,MEM[j]);
}
jump_imm_offset=0;
PCSRC=0;
PC_count=0;
PC_add=0;
N=0;
cout<<"enter instruction cache size in bytes : "<<endl;
cin>>cachesizeI;
cout<<"enter data cache size in bytes: "<<endl;
cin>>cachesizeD;
cout<<"enter cache block size in bytes : "<<endl;
cin>>blocksize;
cout<<"enter cache mapping type: "<<endl<<"1. fully associative 2. direct map 3. set associative"<<endl;
cin>>cachetype;
if(cachetype==3)
{
cout<<"enter number of sets: "<<endl;
cin>>noSets;
}
//cout<<"$$$$$$$$$$$$$$$$$$$$$$$$ N "<<N<<endl;
}
/*
//writes the data memory in "data_out.mem" file
void write_data_memory() {
FILE *fp;
unsigned int i;
fp = fopen("data_out.mem", "w");
if(fp == NULL) {
printf("Error opening dataout.mem file for writing\n");
return;
}
for(i=0; i < 4000; i = i+4){
fprintf(fp, "%x %x\n", i, read_word(MEM, i));
}
fclose(fp);
}
//should be called when instruction is swi_exit
void swi_exit() {
write_data_memory();
exit(0);
}
*/
int PC_generator()
{
//cout<<"in pc generator"<<endl;
//cout<<"PCSRC "<<PCSRC<<endl;
//return_add = PC_count+4;
//cout<<return_add<<"****************************************************************************"<<endl;
if(comp==2) //jalr
{
PC_count = jump_imm_offset;
}
else if(comp==1) //jal
{
PC_count = PC_count + jump_imm_offset ;
}
// else if(hazard_cntrl==1) //]
// {
// cout<<"BROOOOOOOOOOOOOO my PC value:"<<PC_count<<endl;
// PC_count=PC_count;
// }
else if(flush_inst==1)
{
PC_count=B2.PC+4;
}
else if(comp==3) //branch //always taken
{
PC_count+=jump_imm_offset;
// if(predict==1)
// {
// PC_count = PC_count + jump_imm_offset;
// }
// if(predict==0)
// {
// PC_count = RZ;
// }
}
else
{
PC_count+=4;
}
//before change code
/*if(PCSRC==1)
{
//cout<<"jjjjjjjjjjjjjjjjjjjj"<<jump_imm_offset<<endl;
//cout<<"pppppppppppppppppppp"<<PC_count<<endl;
//cout<<return_add<<"****************************************************************************"<<endl;
PC_count = PC_count + jump_imm_offset - 4;
}
if(opcode=="1100111" && funct3=="000")
{
PC_count = RZ;
//cout<<RZ<<endl;
}*/
}
//executes the ALU operation based on ALUop
//void execute() {}
//perform the memory operation
//void mem() {}
//writes the results back to register file
//void write_back() {}
int read1_word(unsigned char *mem, unsigned int address) {
int *data;
data = (int*) (mem + address);
//cout<<"data++++++++"<<(*(data))<<endl;
return *data;
}
void write1_word(unsigned char *mem, unsigned int address, unsigned int data) {
int *data_p;
data_p = (int*) (mem + address);
*data_p = data;
}
|
#pragma once
#include <string>
#include <GLM/glm.hpp>
#include "Scene.h"
#include "GuiElement.h"
#include "Panel.h"
class TextField : public GuiElement {
public:
TextField(Scene& scene, Font& font, glm::vec4 transform, std::string headerText);
void update();
void setTransform(glm::vec4 transform);
void setVisible(bool visible);
void clearText();
void setHeaderText(std::string headerText);
void setText(std::string text);
std::string getText();
virtual ~TextField();
private:
bool selected = false;
Color backgroundColor = Color {0.5f, 0.5f, 0.5f, 1.0f}, selectedBackgroundColor = Color {0.35f, 0.5f, 0.75f, 1.0f}, headerColor = Color {0.0f, 0.0f, 0.0f, 1.0f};
Panel* textField = nullptr;
Panel* header = nullptr;
};
|
// OpenCV.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
Mat img(Size(10,14), CV_8UC1,Scalar(0,255,255));
imshow("原图",img);
waitKey(0);//
cout << "图片已经输出\n";
cout << img.type() << endl;
cout << img << endl;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门提示:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
|
#include <sys/socket.h>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <util.hpp>
#include "plotterUtil.cpp"
//#include "HttpReq.h"
//time_t StrTime2unix(const std::string& ts)
//{
// struct tm tm {
// };
// memset(&tm, 0, sizeof(tm));
//
// sscanf(
// ts.c_str(),
// "%d-%d-%d %d:%d:%d",
// &tm.tm_year,
// &tm.tm_mon,
// &tm.tm_mday,
// &tm.tm_hour,
// &tm.tm_min,
// &tm.tm_sec);
//
// tm.tm_year -= 1900;
// tm.tm_mon--;
//
// return mktime(&tm);
//}
//
//std::string GetEnv(const char* envName)
//{
// char* podName = new char[0];
// // podName = getenv("HOME");
// if (getenv(envName) != nullptr) {
// podName = getenv(envName);
// }
// return podName;
//}
//
//std::string GenTimeNow()
//{
// time_t t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
// std::stringstream ss;
// ss << std::put_time(std::localtime(&t), "%F %X");
// std::cout << ss.str() << std::endl;
// std::string ssTime = ss.str();
// time_t timeUnix = StrTime2unix(ssTime);
//
// std::stringstream strUnix;
// strUnix << timeUnix;
// std::string ts = strUnix.str();
// return ts;
//}
int main()
{
ReportHttp("1","");
ReportHttp("2","");
ReportHttp("3","");
ReportHttp("4","");
ReportHttp("5","");
// Timer p1;
// HTTP 请求告诉服务~
// sleep(3);
// std::double_t duringTime = 0;
// if (p1.GetElapsed() != 0) {
// duringTime = p1.GetElapsed();
// }
// std::cout << "time ============" << duringTime << "s" << std::endl;
// std::ostringstream strDurTime;
// strDurTime << duringTime;
// std::string a = "http://10.1.64.143:8001/ReportChart?pod=" + pod + "&node=" + node+"&p=1";
// HttpRequest* Http;
// char http_return[4096] = {0};
// char http_msg[4096] = {0};
// std::string pod = GetEnv("JOB_POD_NAME");
// std::string node = GetEnv("JOB_NODE_NAME");
// std::string a = "http://127.0.0.1:8001/ReportChart?pod=" + pod + "&node=" + node+"&p=1";
// std::strcpy(http_msg, a.data());
// if (Http->HttpGet(http_msg, http_return)) {
// std::cout << "get" << http_return << std::endl;
// }
//
//
// std::string a2 = "http://127.0.0.1:8001/ReportChart?pod=" + pod + "&node=" + node+"&p=2";
// std::strcpy(http_msg, a2.data());
// if (Http->HttpGet(http_msg, http_return)) {
// std::cout << "get" << http_return << std::endl;
// }
//
// std::string a3 = "http://127.0.0.1:8001/ReportChart?pod=" + pod + "&node=" + node+"&p=3";
// std::strcpy(http_msg, a3.data());
// if (Http->HttpGet(http_msg, http_return)) {
// std::cout << "get" << http_return << std::endl;
// }
//
// std::string a4 = "http://127.0.0.1:8001/ReportChart?pod=" + pod + "&node=" + node+"&p=4";
// std::strcpy(http_msg, a4.data());
// if (Http->HttpGet(http_msg, http_return)) {
// std::cout << "get" << http_return << std::endl;
// }
return 0;
}
|
#ifndef LIBRARYWINDOW_H
#define LIBRARYWINDOW_H
#include <QDialog>
#include <QSqlTableModel>
#include <QSortFilterProxyModel>
namespace Ui {
class LibraryWindow;
}
class LibraryWindow : public QDialog
{
Q_OBJECT
public:
explicit LibraryWindow(QWidget *parent = 0);
~LibraryWindow();
private slots:
void on_addType_clicked();
void on_editType_clicked();
void refreshTypeView();
void refreshAttribView();
void refreshComponentView();
void refreshLocalityView();
void on_deleteType_clicked();
void on_typeTable_doubleClicked(const QModelIndex &index);
void on_addAttr_clicked();
void on_editAttr_clicked();
void on_deleteAttr_clicked();
void on_attrTable_doubleClicked(const QModelIndex &index);
void on_addComponent_clicked();
void on_editComponent_clicked();
void on_deleteComponent_clicked();
void on_addLocality_clicked();
void on_editLocality_clicked();
void on_localityTable_doubleClicked(const QModelIndex &index);
void on_deleteLocality_clicked();
private:
Ui::LibraryWindow *ui;
QSqlTableModel *typeModel;
QSortFilterProxyModel *typeSortProxy;
QSqlTableModel *attrModel;
QSortFilterProxyModel *attrSortProxy;
QSqlTableModel *componentModel;
QSortFilterProxyModel *componentSortProxy;
QSqlTableModel *localityModel;
QSortFilterProxyModel *localitySortProxy;
};
#endif // LIBRARYWINDOW_H
|
#line 2 "pop3-tokenizer.cpp"
#line 4 "pop3-tokenizer.cpp"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 35
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
#ifdef __cplusplus
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else /* ! __cplusplus */
/* C99 requires __STDC__ to be defined as 1. */
#if defined (__STDC__)
#define YY_USE_CONST
#endif /* defined (__STDC__) */
#endif /* ! __cplusplus */
#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an unsigned
* integer for use as an array index. If the signed char is negative,
* we want to instead treat it as an 8-bit unsigned char, hence the
* double cast.
*/
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
/* An opaque pointer. */
#ifndef YY_TYPEDEF_YY_SCANNER_T
#define YY_TYPEDEF_YY_SCANNER_T
typedef void* yyscan_t;
#endif
/* For convenience, these vars (plus the bison vars far below)
are macros in the reentrant scanner. */
#define yyin yyg->yyin_r
#define yyout yyg->yyout_r
#define yyextra yyg->yyextra_r
#define yyleng yyg->yyleng_r
#define yytext yyg->yytext_r
#define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno)
#define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column)
#define yy_flex_debug yyg->yy_flex_debug_r
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN yyg->yy_start = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START ((yyg->yy_start - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE POP3restart(yyin ,yyscanner )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#ifdef __ia64__
/* On IA-64, the buffer size is 16k, not 8k.
* Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case.
* Ditto for the __ia64__ case accordingly.
*/
#define YY_BUF_SIZE 32768
#else
#define YY_BUF_SIZE 16384
#endif /* __ia64__ */
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
#define YY_LESS_LINENO(n)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = yyg->yy_hold_char; \
YY_RESTORE_YY_MORE_OFFSET \
yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner )
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
yy_size_t yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
int yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via POP3restart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \
? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top]
void POP3restart (FILE *input_file ,yyscan_t yyscanner );
void POP3_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
YY_BUFFER_STATE POP3_create_buffer (FILE *file,int size ,yyscan_t yyscanner );
void POP3_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
void POP3_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
void POP3push_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
void POP3pop_buffer_state (yyscan_t yyscanner );
static void POP3ensure_buffer_stack (yyscan_t yyscanner );
static void POP3_load_buffer_state (yyscan_t yyscanner );
static void POP3_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner );
#define YY_FLUSH_BUFFER POP3_flush_buffer(YY_CURRENT_BUFFER ,yyscanner)
YY_BUFFER_STATE POP3_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
YY_BUFFER_STATE POP3_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
YY_BUFFER_STATE POP3_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
void *POP3alloc (yy_size_t ,yyscan_t yyscanner );
void *POP3realloc (void *,yy_size_t ,yyscan_t yyscanner );
void POP3free (void * ,yyscan_t yyscanner );
#define yy_new_buffer POP3_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
POP3ensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
POP3_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
POP3ensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
POP3_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
typedef unsigned char YY_CHAR;
typedef int yy_state_type;
#define yytext_ptr yytext_r
static yy_state_type yy_get_previous_state (yyscan_t yyscanner );
static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner);
static int yy_get_next_buffer (yyscan_t yyscanner );
static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
*/
#define YY_DO_BEFORE_ACTION \
yyg->yytext_ptr = yy_bp; \
yyleng = (size_t) (yy_cp - yy_bp); \
yyg->yy_hold_char = *yy_cp; \
*yy_cp = '\0'; \
yyg->yy_c_buf_p = yy_cp;
#define YY_NUM_RULES 33
#define YY_END_OF_BUFFER 34
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static yyconst flex_int16_t yy_accept[199] =
{ 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
34, 32, 32, 32, 32, 32, 31, 33, 33, 3,
33, 33, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 32, 32, 32, 19, 32, 32, 32, 32,
31, 20, 21, 22, 32, 23, 23, 23, 23, 23,
30, 0, 0, 0, 0, 31, 0, 3, 5, 0,
4, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 0, 0, 0, 19, 19, 0, 0, 0,
0, 0, 31, 20, 21, 21, 22, 24, 23, 23,
23, 23, 23, 23, 0, 0, 0, 0, 1, 2,
14, 14, 14, 14, 14, 14, 14, 9, 14, 14,
0, 0, 0, 0, 0, 0, 18, 1, 23, 23,
23, 29, 0, 0, 0, 14, 14, 14, 6, 14,
8, 10, 11, 0, 0, 0, 0, 19, 0, 0,
0, 23, 23, 25, 0, 0, 0, 0, 14, 13,
14, 0, 15, 0, 0, 0, 0, 19, 0, 0,
0, 0, 23, 23, 26, 27, 0, 0, 14, 14,
15, 15, 16, 0, 0, 19, 19, 0, 0, 23,
28, 14, 14, 17, 19, 12, 7, 0
} ;
static yyconst flex_int32_t yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
1, 1, 3, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 4, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 6, 5, 7, 8, 5, 9, 9, 9,
9, 9, 10, 9, 9, 9, 9, 5, 5, 11,
5, 12, 5, 5, 13, 5, 14, 15, 16, 5,
5, 5, 17, 5, 18, 19, 20, 21, 22, 23,
5, 24, 25, 26, 27, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 28, 5, 29, 30,
31, 5, 5, 5, 32, 5, 33, 34, 35, 36,
37, 38, 5, 39, 40, 41, 42, 5, 5, 5,
5, 5, 5, 5, 5, 5, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1
} ;
static yyconst flex_int32_t yy_meta[43] =
{ 0,
1, 2, 3, 4, 5, 5, 5, 5, 5, 5,
6, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5
} ;
static yyconst flex_int16_t yy_base[220] =
{ 0,
0, 8, 500, 499, 2, 17, 28, 0, 68, 76,
85, 94, 102, 110, 118, 126, 134, 142, 152, 162,
504, 507, 501, 85, 99, 499, 12, 507, 145, 0,
499, 488, 0, 153, 157, 496, 14, 150, 157, 166,
156, 170, 176, 165, 496, 507, 495, 181, 184, 23,
71, 492, 89, 491, 492, 489, 195, 193, 201, 202,
507, 489, 183, 184, 489, 210, 196, 0, 507, 478,
507, 0, 203, 198, 216, 214, 215, 205, 220, 208,
219, 219, 220, 216, 487, 507, 507, 249, 239, 242,
486, 485, 254, 482, 0, 249, 471, 507, 465, 453,
257, 258, 243, 261, 448, 443, 265, 249, 507, 507,
271, 253, 258, 262, 261, 259, 259, 0, 266, 262,
286, 263, 294, 431, 301, 304, 507, 507, 304, 306,
307, 507, 423, 421, 309, 311, 401, 296, 0, 292,
0, 0, 0, 404, 404, 393, 316, 507, 393, 319,
321, 323, 326, 507, 358, 358, 357, 355, 314, 0,
309, 354, 507, 352, 314, 182, 174, 507, 334, 145,
137, 336, 337, 341, 507, 507, 128, 121, 327, 328,
507, 507, 507, 87, 70, 507, 507, 349, 25, 350,
507, 2, 323, 507, 507, 0, 0, 507, 363, 369,
375, 381, 387, 393, 398, 404, 410, 416, 422, 425,
431, 437, 443, 449, 455, 461, 467, 473, 479
} ;
static yyconst flex_int16_t yy_def[220] =
{ 0,
199, 199, 200, 200, 201, 201, 198, 7, 199, 199,
202, 202, 199, 199, 199, 199, 199, 199, 203, 203,
198, 198, 198, 198, 198, 198, 198, 198, 198, 204,
198, 205, 206, 206, 206, 206, 206, 206, 206, 206,
206, 206, 198, 198, 207, 198, 207, 207, 207, 208,
207, 198, 209, 198, 198, 210, 210, 210, 210, 210,
198, 211, 198, 198, 198, 198, 198, 204, 198, 205,
198, 206, 206, 206, 206, 206, 206, 206, 206, 206,
206, 206, 198, 198, 207, 198, 198, 212, 207, 207,
208, 208, 207, 198, 209, 209, 198, 198, 198, 210,
211, 210, 210, 210, 211, 198, 198, 198, 198, 198,
206, 206, 206, 206, 206, 206, 206, 206, 206, 206,
213, 198, 212, 207, 207, 207, 198, 198, 211, 210,
210, 198, 198, 214, 198, 206, 206, 206, 206, 206,
206, 206, 206, 213, 198, 215, 198, 198, 207, 216,
207, 214, 210, 198, 214, 198, 198, 217, 206, 206,
206, 198, 198, 215, 198, 198, 218, 198, 216, 207,
207, 219, 214, 217, 198, 198, 217, 198, 206, 206,
198, 198, 198, 218, 198, 198, 198, 219, 207, 217,
198, 206, 206, 198, 198, 206, 206, 0, 198, 198,
198, 198, 198, 198, 198, 198, 198, 198, 198, 198,
198, 198, 198, 198, 198, 198, 198, 198, 198
} ;
static yyconst flex_int16_t yy_nxt[550] =
{ 0,
198, 198, 23, 28, 31, 24, 25, 26, 27, 27,
23, 196, 32, 24, 25, 26, 27, 27, 28, 31,
66, 66, 75, 75, 86, 92, 195, 32, 33, 22,
23, 22, 33, 34, 35, 36, 37, 37, 33, 33,
33, 38, 33, 33, 33, 33, 33, 33, 33, 33,
39, 33, 40, 41, 42, 33, 38, 33, 33, 33,
33, 33, 33, 33, 33, 39, 33, 40, 41, 42,
23, 194, 86, 43, 44, 26, 27, 27, 23, 93,
93, 43, 44, 26, 27, 27, 46, 47, 62, 185,
48, 49, 50, 51, 51, 46, 47, 96, 96, 48,
49, 50, 51, 51, 23, 52, 63, 24, 25, 26,
27, 27, 23, 52, 64, 24, 25, 26, 27, 27,
23, 63, 191, 24, 25, 26, 53, 53, 23, 64,
178, 24, 25, 26, 53, 53, 23, 54, 187, 24,
25, 26, 27, 27, 23, 54, 186, 24, 25, 26,
27, 27, 22, 22, 55, 22, 62, 57, 58, 59,
60, 60, 22, 22, 55, 22, 67, 57, 58, 59,
60, 60, 74, 76, 73, 77, 185, 80, 78, 62,
84, 67, 86, 183, 88, 86, 81, 74, 76, 73,
77, 79, 80, 78, 82, 84, 99, 83, 101, 90,
107, 81, 89, 65, 99, 99, 79, 108, 103, 82,
104, 104, 83, 110, 90, 107, 102, 89, 66, 66,
111, 112, 108, 103, 75, 75, 113, 114, 110, 115,
118, 102, 116, 119, 120, 111, 112, 121, 117, 122,
86, 113, 114, 86, 115, 118, 99, 116, 119, 120,
86, 124, 121, 117, 122, 86, 125, 96, 96, 106,
129, 99, 93, 93, 99, 126, 131, 133, 134, 104,
104, 125, 135, 133, 134, 130, 136, 137, 138, 139,
126, 131, 140, 141, 142, 143, 147, 135, 145, 146,
130, 136, 137, 138, 139, 86, 124, 140, 141, 142,
143, 147, 86, 149, 150, 86, 106, 129, 133, 152,
99, 157, 158, 157, 158, 182, 160, 161, 166, 167,
86, 170, 86, 171, 172, 156, 173, 151, 157, 174,
153, 160, 161, 179, 180, 86, 170, 86, 189, 156,
173, 192, 151, 178, 190, 153, 193, 197, 179, 180,
86, 189, 178, 190, 165, 181, 192, 178, 176, 175,
156, 193, 197, 22, 22, 22, 22, 22, 22, 28,
28, 28, 28, 28, 28, 30, 30, 30, 30, 30,
30, 45, 45, 45, 45, 45, 45, 56, 56, 56,
56, 56, 56, 68, 168, 165, 68, 68, 70, 70,
70, 70, 70, 70, 72, 163, 162, 159, 72, 72,
85, 85, 85, 85, 85, 85, 91, 91, 91, 91,
91, 91, 95, 156, 154, 95, 95, 95, 100, 100,
100, 105, 148, 105, 105, 105, 105, 123, 123, 123,
123, 123, 123, 144, 132, 144, 144, 144, 144, 155,
106, 155, 155, 155, 155, 164, 99, 164, 164, 164,
164, 169, 169, 169, 169, 169, 169, 177, 99, 177,
177, 177, 177, 184, 97, 184, 184, 184, 184, 188,
188, 188, 188, 188, 188, 94, 128, 127, 86, 71,
109, 106, 99, 98, 97, 94, 87, 86, 65, 71,
69, 65, 61, 198, 29, 29, 21, 198, 198, 198,
198, 198, 198, 198, 198, 198, 198, 198, 198, 198,
198, 198, 198, 198, 198, 198, 198, 198, 198, 198,
198, 198, 198, 198, 198, 198, 198, 198, 198, 198,
198, 198, 198, 198, 198, 198, 198, 198, 198
} ;
static yyconst flex_int16_t yy_chk[550] =
{ 0,
0, 0, 1, 5, 5, 1, 1, 1, 1, 1,
2, 192, 5, 2, 2, 2, 2, 2, 6, 6,
27, 27, 37, 37, 50, 50, 189, 6, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
9, 185, 51, 9, 9, 9, 9, 9, 10, 51,
51, 10, 10, 10, 10, 10, 11, 11, 24, 184,
11, 11, 11, 11, 11, 12, 12, 53, 53, 12,
12, 12, 12, 12, 13, 13, 24, 13, 13, 13,
13, 13, 14, 14, 25, 14, 14, 14, 14, 14,
15, 24, 178, 15, 15, 15, 15, 15, 16, 25,
177, 16, 16, 16, 16, 16, 17, 17, 171, 17,
17, 17, 17, 17, 18, 18, 170, 18, 18, 18,
18, 18, 19, 19, 19, 19, 34, 19, 19, 19,
19, 19, 20, 20, 20, 20, 29, 20, 20, 20,
20, 20, 35, 38, 34, 39, 167, 41, 40, 43,
44, 29, 48, 166, 48, 49, 42, 35, 38, 34,
39, 40, 41, 40, 42, 44, 58, 43, 57, 49,
63, 42, 48, 59, 59, 60, 40, 64, 58, 42,
60, 60, 43, 67, 49, 63, 57, 48, 66, 66,
73, 74, 64, 58, 75, 75, 76, 77, 67, 78,
80, 57, 79, 81, 82, 73, 74, 83, 79, 84,
89, 76, 77, 90, 78, 80, 103, 79, 81, 82,
88, 88, 83, 79, 84, 93, 89, 96, 96, 101,
101, 102, 93, 93, 104, 90, 103, 107, 107, 104,
104, 89, 108, 111, 111, 102, 112, 113, 114, 115,
90, 103, 116, 117, 119, 120, 122, 108, 121, 121,
102, 112, 113, 114, 115, 123, 123, 116, 117, 119,
120, 122, 125, 125, 125, 126, 129, 129, 130, 130,
131, 135, 135, 136, 136, 165, 138, 140, 147, 147,
150, 150, 151, 151, 151, 152, 152, 126, 153, 153,
131, 138, 140, 159, 161, 169, 169, 172, 172, 173,
173, 179, 126, 174, 174, 131, 180, 193, 159, 161,
188, 188, 190, 190, 164, 162, 179, 158, 157, 156,
155, 180, 193, 199, 199, 199, 199, 199, 199, 200,
200, 200, 200, 200, 200, 201, 201, 201, 201, 201,
201, 202, 202, 202, 202, 202, 202, 203, 203, 203,
203, 203, 203, 204, 149, 146, 204, 204, 205, 205,
205, 205, 205, 205, 206, 145, 144, 137, 206, 206,
207, 207, 207, 207, 207, 207, 208, 208, 208, 208,
208, 208, 209, 134, 133, 209, 209, 209, 210, 210,
210, 211, 124, 211, 211, 211, 211, 212, 212, 212,
212, 212, 212, 213, 106, 213, 213, 213, 213, 214,
105, 214, 214, 214, 214, 215, 100, 215, 215, 215,
215, 216, 216, 216, 216, 216, 216, 217, 99, 217,
217, 217, 217, 218, 97, 218, 218, 218, 218, 219,
219, 219, 219, 219, 219, 94, 92, 91, 85, 70,
65, 62, 56, 55, 54, 52, 47, 45, 36, 32,
31, 26, 23, 21, 4, 3, 198, 198, 198, 198,
198, 198, 198, 198, 198, 198, 198, 198, 198, 198,
198, 198, 198, 198, 198, 198, 198, 198, 198, 198,
198, 198, 198, 198, 198, 198, 198, 198, 198, 198,
198, 198, 198, 198, 198, 198, 198, 198, 198
} ;
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
#line 1 "pop3-tokenizer.l"
#line 2 "pop3-tokenizer.l"
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Arjan van Leeuwen (arjanl)
*/
/* This is a flex scanner. Use flex to create the actual scanner from pop3-tokenizer.l.
* Do not modify the scanner pop3-tokenizer.cpp itself, modify pop3-tokenizer.l instead
* and regenerate the scanner.
*
* To generate the scanner, use:
* flex pop3-tokenizer.l
*/
// Needed to differentiate from the IMAPParser::YYSTYPE, see DSK-221435
namespace POP3Parser {
union YYSTYPE;
}
using POP3Parser::YYSTYPE;
#define YY_EXTRA_TYPE IncomingParser<YYSTYPE>*
#include "adjunct/m2/src/backend/pop/pop3-parse.hpp"
#include "adjunct/m2/src/util/parser.h"
#define YY_NO_UNISTD_H
// Redefine the input macro to copy up to max_size characters from the IncomingParser into buf.
// result is the number of characters read. buf is not null-terminated.
#define YY_INPUT(buf,result,max_size) POP3get_extra(yyscanner)->GetParseInput(buf, result, max_size)
// Redefine checking for end of input
#define YY_SKIP_YYWRAP
#define POP3wrap(yyscanner) !POP3get_extra(yyscanner)->HasInput()
// Enable debugging when asked
#ifdef FLEX_DEBUG
# define SET_DEBUG POP3set_debug(1, yyscanner)
#else
# define SET_DEBUG ((void)0)
#endif
#line 682 "pop3-tokenizer.cpp"
#define INITIAL 0
#define GREETING 1
#define EXTENDED_GREETING 2
#define CAPA 3
#define RETR 4
#define DOT_STUFFED 5
#define LIST 6
#define LIST_LIST 7
#define UIDL 8
#define UIDL_UIDL 9
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
#include <unistd.h>
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif
/* Holds the entire state of the reentrant scanner. */
struct yyguts_t
{
/* User-defined. Not touched by flex. */
YY_EXTRA_TYPE yyextra_r;
/* The rest are the same as the globals declared in the non-reentrant scanner. */
FILE *yyin_r, *yyout_r;
size_t yy_buffer_stack_top; /**< index of top of stack. */
size_t yy_buffer_stack_max; /**< capacity of stack. */
YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */
char yy_hold_char;
int yy_n_chars;
int yyleng_r;
char *yy_c_buf_p;
int yy_init;
int yy_start;
int yy_did_buffer_switch_on_eof;
int yy_start_stack_ptr;
int yy_start_stack_depth;
int *yy_start_stack;
yy_state_type yy_last_accepting_state;
char* yy_last_accepting_cpos;
int yylineno_r;
int yy_flex_debug_r;
char *yytext_r;
int yy_more_flag;
int yy_more_len;
YYSTYPE * yylval_r;
}; /* end struct yyguts_t */
static int yy_init_globals (yyscan_t yyscanner );
/* This must go here because YYSTYPE and YYLTYPE are included
* from bison output in section 1.*/
# define yylval yyg->yylval_r
int POP3lex_init (yyscan_t* scanner);
int POP3lex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int POP3lex_destroy (yyscan_t yyscanner );
int POP3get_debug (yyscan_t yyscanner );
void POP3set_debug (int debug_flag ,yyscan_t yyscanner );
YY_EXTRA_TYPE POP3get_extra (yyscan_t yyscanner );
void POP3set_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
FILE *POP3get_in (yyscan_t yyscanner );
void POP3set_in (FILE * in_str ,yyscan_t yyscanner );
FILE *POP3get_out (yyscan_t yyscanner );
void POP3set_out (FILE * out_str ,yyscan_t yyscanner );
int POP3get_leng (yyscan_t yyscanner );
char *POP3get_text (yyscan_t yyscanner );
int POP3get_lineno (yyscan_t yyscanner );
void POP3set_lineno (int line_number ,yyscan_t yyscanner );
YYSTYPE * POP3get_lval (yyscan_t yyscanner );
void POP3set_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner );
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int POP3wrap (yyscan_t yyscanner );
#else
extern int POP3wrap (yyscan_t yyscanner );
#endif
#endif
#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (yyscan_t yyscanner );
#else
static int input (yyscan_t yyscanner );
#endif
#endif
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#ifdef __ia64__
/* On IA-64, the buffer size is 16k, not 8k */
#define YY_READ_BUF_SIZE 16384
#else
#define YY_READ_BUF_SIZE 8192
#endif /* __ia64__ */
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0)
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
size_t n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( yyin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(yyin); \
} \
}\
\
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner)
#endif
/* end tables serialization structures and prototypes */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int POP3lex \
(YYSTYPE * yylval_param ,yyscan_t yyscanner);
#define YY_DECL int POP3lex \
(YYSTYPE * yylval_param , yyscan_t yyscanner)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK break;
#endif
#define YY_RULE_SETUP \
YY_USER_ACTION
/** The main scanner function which does all the work.
*/
YY_DECL
{
register yy_state_type yy_current_state;
register char *yy_cp, *yy_bp;
register int yy_act;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
#line 70 "pop3-tokenizer.l"
SET_DEBUG;
IncomingParser<YYSTYPE>* parser = POP3get_extra(yyscanner);
// Enter correct state
if (parser->NeedsReset())
{
BEGIN(parser->GetRequiredState());
parser->SetNeedsReset(FALSE);
}
/* Terminator is valid in all states */
#line 941 "pop3-tokenizer.cpp"
yylval = yylval_param;
if ( !yyg->yy_init )
{
yyg->yy_init = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if ( ! yyg->yy_start )
yyg->yy_start = 1; /* first start state */
if ( ! yyin )
yyin = stdin;
if ( ! yyout )
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
POP3ensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
POP3_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
}
POP3_load_buffer_state(yyscanner );
}
while ( 1 ) /* loops until end-of-file is reached */
{
yy_cp = yyg->yy_c_buf_p;
/* Support of yytext. */
*yy_cp = yyg->yy_hold_char;
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = yyg->yy_start;
yy_match:
do
{
register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
if ( yy_accept[yy_current_state] )
{
yyg->yy_last_accepting_state = yy_current_state;
yyg->yy_last_accepting_cpos = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 199 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
++yy_cp;
}
while ( yy_current_state != 198 );
yy_cp = yyg->yy_last_accepting_cpos;
yy_current_state = yyg->yy_last_accepting_state;
yy_find_action:
yy_act = yy_accept[yy_current_state];
YY_DO_BEFORE_ACTION;
do_action: /* This label is used only to access EOF actions. */
switch ( yy_act )
{ /* beginning of action switch */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = yyg->yy_hold_char;
yy_cp = yyg->yy_last_accepting_cpos;
yy_current_state = yyg->yy_last_accepting_state;
goto yy_find_action;
case 1:
/* rule 1 can match eol */
YY_RULE_SETUP
#line 83 "pop3-tokenizer.l"
parser->MarkValidQueue(); BEGIN(0); return POP_TERMINATOR;
YY_BREAK
/* Single-line responses (exclusive) */
case 2:
YY_RULE_SETUP
#line 87 "pop3-tokenizer.l"
BEGIN(EXTENDED_GREETING); return POP_GREETING_OK;
YY_BREAK
case 3:
YY_RULE_SETUP
#line 91 "pop3-tokenizer.l"
/* Do nothing */
YY_BREAK
case 4:
/* rule 4 can match eol */
YY_RULE_SETUP
#line 92 "pop3-tokenizer.l"
StringParseElement::CopyText(yytext, yyleng, yylval->string, parser); return POP_TIMESTAMP;
YY_BREAK
case 5:
/* rule 5 can match eol */
YY_RULE_SETUP
#line 93 "pop3-tokenizer.l"
parser->MarkValidQueue(); BEGIN(0); return POP_CRLF;
YY_BREAK
/* Multi-line responses (inclusive) */
case 6:
YY_RULE_SETUP
#line 98 "pop3-tokenizer.l"
return POP_CAPA_SASL;
YY_BREAK
case 7:
#line 100 "pop3-tokenizer.l"
case 8:
YY_RULE_SETUP
#line 100 "pop3-tokenizer.l"
return POP_CAPA_STARTTLS;
YY_BREAK
case 9:
YY_RULE_SETUP
#line 101 "pop3-tokenizer.l"
return POP_CAPA_TOP;
YY_BREAK
case 10:
YY_RULE_SETUP
#line 102 "pop3-tokenizer.l"
return POP_CAPA_UIDL;
YY_BREAK
case 11:
YY_RULE_SETUP
#line 103 "pop3-tokenizer.l"
return POP_CAPA_USER;
YY_BREAK
case 12:
YY_RULE_SETUP
#line 104 "pop3-tokenizer.l"
return POP_CAPA_CRAMMD5;
YY_BREAK
case 13:
YY_RULE_SETUP
#line 105 "pop3-tokenizer.l"
return POP_CAPA_PLAIN;
YY_BREAK
case 14:
YY_RULE_SETUP
#line 106 "pop3-tokenizer.l"
return POP_CAPA_UNKNOWN;
YY_BREAK
case 15:
/* rule 15 can match eol */
YY_RULE_SETUP
#line 110 "pop3-tokenizer.l"
parser->MarkValidQueue(); yylval->string = 0; BEGIN(DOT_STUFFED); return POP_SINGLE_LINE_OK;
YY_BREAK
case 16:
/* rule 16 can match eol */
YY_RULE_SETUP
#line 111 "pop3-tokenizer.l"
parser->MarkValidQueue(); yylval->string = 0; BEGIN(0); return POP_SINGLE_LINE_ERR;
YY_BREAK
case 17:
/* rule 17 can match eol */
YY_RULE_SETUP
#line 112 "pop3-tokenizer.l"
parser->MarkValidQueue(); StringParseElement::CopyText(yytext + 5, yyleng - 7, yylval->string, parser); BEGIN(0); return POP_SINGLE_LINE_ERR;
YY_BREAK
case 18:
/* rule 18 can match eol */
YY_RULE_SETUP
#line 116 "pop3-tokenizer.l"
parser->GetTempBuffer().Append(yytext + 1, yyleng - 1); return POP_DOT_STUFFED; // dot-stuffed
YY_BREAK
case 19:
/* rule 19 can match eol */
YY_RULE_SETUP
#line 117 "pop3-tokenizer.l"
parser->GetTempBuffer().Append(yytext, yyleng); return POP_DOT_STUFFED; // normal multiline response
YY_BREAK
case 20:
YY_RULE_SETUP
#line 121 "pop3-tokenizer.l"
BEGIN(LIST_LIST); return ' '; // we accept more than one space for broken servers, bug #328529
YY_BREAK
case 21:
YY_RULE_SETUP
#line 125 "pop3-tokenizer.l"
yylval->number = atoi(yytext); BEGIN(LIST); return POP_NUMBER; // We accept anything after the normal LIST, bug #328844
YY_BREAK
case 22:
YY_RULE_SETUP
#line 129 "pop3-tokenizer.l"
BEGIN(UIDL_UIDL); return ' '; // we accept more than one space for broken servers, bug #328529
YY_BREAK
case 23:
YY_RULE_SETUP
#line 133 "pop3-tokenizer.l"
{
// We accept spaces after the UIDL for broken servers, bug #342350
StringParseElement::CopyText(yytext, yyleng, yylval->string, parser);
return POP_UIDL;
}
YY_BREAK
case 24:
/* rule 24 can match eol */
YY_RULE_SETUP
#line 138 "pop3-tokenizer.l"
BEGIN(UIDL); parser->MarkValidQueue(); return POP_CRLF;
YY_BREAK
/* Generic, for all inclusive states */
case 25:
/* rule 25 can match eol */
YY_RULE_SETUP
#line 142 "pop3-tokenizer.l"
parser->MarkValidQueue(); yylval->string = 0; return POP_SINGLE_LINE_OK;
YY_BREAK
case 26:
/* rule 26 can match eol */
YY_RULE_SETUP
#line 143 "pop3-tokenizer.l"
parser->MarkValidQueue(); StringParseElement::CopyText(yytext + 4, yyleng - 6, yylval->string, parser); return POP_SINGLE_LINE_OK;
YY_BREAK
case 27:
/* rule 27 can match eol */
YY_RULE_SETUP
#line 144 "pop3-tokenizer.l"
parser->MarkValidQueue(); yylval->string = 0; BEGIN(0); return POP_SINGLE_LINE_ERR;
YY_BREAK
case 28:
/* rule 28 can match eol */
YY_RULE_SETUP
#line 145 "pop3-tokenizer.l"
parser->MarkValidQueue(); StringParseElement::CopyText(yytext + 5, yyleng - 7, yylval->string, parser); BEGIN(0); return POP_SINGLE_LINE_ERR;
YY_BREAK
case 29:
/* rule 29 can match eol */
YY_RULE_SETUP
#line 146 "pop3-tokenizer.l"
parser->MarkValidQueue(); StringParseElement::CopyText(yytext + 2, yyleng - 4, yylval->string, parser); return POP_CONT_REQ;
YY_BREAK
case 30:
/* rule 30 can match eol */
YY_RULE_SETUP
#line 147 "pop3-tokenizer.l"
parser->MarkValidQueue(); return POP_CRLF;
YY_BREAK
case 31:
YY_RULE_SETUP
#line 148 "pop3-tokenizer.l"
yylval->number = atoi(yytext); return POP_NUMBER;
YY_BREAK
case 32:
/* rule 32 can match eol */
YY_RULE_SETUP
#line 149 "pop3-tokenizer.l"
return (int) yytext[0];
YY_BREAK
case 33:
YY_RULE_SETUP
#line 151 "pop3-tokenizer.l"
ECHO;
YY_BREAK
#line 1225 "pop3-tokenizer.cpp"
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(GREETING):
case YY_STATE_EOF(EXTENDED_GREETING):
case YY_STATE_EOF(CAPA):
case YY_STATE_EOF(RETR):
case YY_STATE_EOF(DOT_STUFFED):
case YY_STATE_EOF(LIST):
case YY_STATE_EOF(LIST_LIST):
case YY_STATE_EOF(UIDL):
case YY_STATE_EOF(UIDL_UIDL):
yyterminate();
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = yyg->yy_hold_char;
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
* POP3lex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( yyscanner );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner);
yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++yyg->yy_c_buf_p;
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
yy_cp = yyg->yy_last_accepting_cpos;
yy_current_state = yyg->yy_last_accepting_state;
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( yyscanner ) )
{
case EOB_ACT_END_OF_FILE:
{
yyg->yy_did_buffer_switch_on_eof = 0;
if ( POP3wrap(yyscanner ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* yytext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! yyg->yy_did_buffer_switch_on_eof )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
yyg->yy_c_buf_p =
yyg->yytext_ptr + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( yyscanner );
yy_cp = yyg->yy_c_buf_p;
yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
yyg->yy_c_buf_p =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars];
yy_current_state = yy_get_previous_state( yyscanner );
yy_cp = yyg->yy_c_buf_p;
yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of POP3lex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
register char *source = yyg->yytext_ptr;
register int number_to_move, i;
int ret_val;
if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0;
else
{
int num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
int yy_c_buf_p_offset =
(int) (yyg->yy_c_buf_p - b->yy_ch_buf);
if ( b->yy_is_our_buffer )
{
int new_size = b->yy_buf_size * 2;
if ( new_size <= 0 )
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
POP3realloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
}
else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = 0;
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR(
"fatal error - scanner input buffer overflow" );
yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
number_to_move - 1;
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
yyg->yy_n_chars, (size_t) num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
}
if ( yyg->yy_n_chars == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
POP3restart(yyin ,yyscanner);
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) POP3realloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
}
yyg->yy_n_chars += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state (yyscan_t yyscanner)
{
register yy_state_type yy_current_state;
register char *yy_cp;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_current_state = yyg->yy_start;
for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp )
{
register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if ( yy_accept[yy_current_state] )
{
yyg->yy_last_accepting_state = yy_current_state;
yyg->yy_last_accepting_cpos = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 199 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner)
{
register int yy_is_jam;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */
register char *yy_cp = yyg->yy_c_buf_p;
register YY_CHAR yy_c = 1;
if ( yy_accept[yy_current_state] )
{
yyg->yy_last_accepting_state = yy_current_state;
yyg->yy_last_accepting_cpos = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 199 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
yy_is_jam = (yy_current_state == 198);
return yy_is_jam ? 0 : yy_current_state;
}
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (yyscan_t yyscanner)
#else
static int input (yyscan_t yyscanner)
#endif
{
int c;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
*yyg->yy_c_buf_p = yyg->yy_hold_char;
if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
/* This was really a NUL. */
*yyg->yy_c_buf_p = '\0';
else
{ /* need more input */
int offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
++yyg->yy_c_buf_p;
switch ( yy_get_next_buffer( yyscanner ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
POP3restart(yyin ,yyscanner);
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( POP3wrap(yyscanner ) )
return EOF;
if ( ! yyg->yy_did_buffer_switch_on_eof )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput(yyscanner);
#else
return input(yyscanner);
#endif
}
case EOB_ACT_CONTINUE_SCAN:
yyg->yy_c_buf_p = yyg->yytext_ptr + offset;
break;
}
}
}
c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */
*yyg->yy_c_buf_p = '\0'; /* preserve yytext */
yyg->yy_hold_char = *++yyg->yy_c_buf_p;
return c;
}
#endif /* ifndef YY_NO_INPUT */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
* @param yyscanner The scanner object.
* @note This function does not reset the start condition to @c INITIAL .
*/
void POP3restart (FILE * input_file , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! YY_CURRENT_BUFFER ){
POP3ensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
POP3_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
}
POP3_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
POP3_load_buffer_state(yyscanner );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
* @param yyscanner The scanner object.
*/
void POP3_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* TODO. We should be able to replace this entire function body
* with
* POP3pop_buffer_state();
* POP3push_buffer_state(new_buffer);
*/
POP3ensure_buffer_stack (yyscanner);
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*yyg->yy_c_buf_p = yyg->yy_hold_char;
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
POP3_load_buffer_state(yyscanner );
/* We don't actually know whether we did this switch during
* EOF (POP3wrap()) processing, but the only time this flag
* is looked at is after POP3wrap() is called, so it's safe
* to go ahead and always set it.
*/
yyg->yy_did_buffer_switch_on_eof = 1;
}
static void POP3_load_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
yyg->yy_hold_char = *yyg->yy_c_buf_p;
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
* @param yyscanner The scanner object.
* @return the allocated buffer state.
*/
YY_BUFFER_STATE POP3_create_buffer (FILE * file, int size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) POP3alloc(sizeof( struct yy_buffer_state ) ,yyscanner );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in POP3_create_buffer()" );
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) POP3alloc(b->yy_buf_size + 2 ,yyscanner );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in POP3_create_buffer()" );
b->yy_is_our_buffer = 1;
POP3_init_buffer(b,file ,yyscanner);
return b;
}
/** Destroy the buffer.
* @param b a buffer created with POP3_create_buffer()
* @param yyscanner The scanner object.
*/
void POP3_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
POP3free((void *) b->yy_ch_buf ,yyscanner );
POP3free((void *) b ,yyscanner );
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a POP3restart() or at EOF.
*/
static void POP3_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner)
{
int oerrno = errno;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
POP3_flush_buffer(b ,yyscanner);
b->yy_input_file = file;
b->yy_fill_buffer = 1;
/* If b is the current buffer, then POP3_init_buffer was _probably_
* called from POP3restart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
b->yy_is_interactive = 0;
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
* @param yyscanner The scanner object.
*/
void POP3_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
POP3_load_buffer_state(yyscanner );
}
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
* @param yyscanner The scanner object.
*/
void POP3push_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (new_buffer == NULL)
return;
POP3ensure_buffer_stack(yyscanner);
/* This block is copied from POP3_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*yyg->yy_c_buf_p = yyg->yy_hold_char;
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
yyg->yy_buffer_stack_top++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from POP3_switch_to_buffer. */
POP3_load_buffer_state(yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
* @param yyscanner The scanner object.
*/
void POP3pop_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!YY_CURRENT_BUFFER)
return;
POP3_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
YY_CURRENT_BUFFER_LVALUE = NULL;
if (yyg->yy_buffer_stack_top > 0)
--yyg->yy_buffer_stack_top;
if (YY_CURRENT_BUFFER) {
POP3_load_buffer_state(yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
}
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
static void POP3ensure_buffer_stack (yyscan_t yyscanner)
{
int num_to_alloc;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1;
yyg->yy_buffer_stack = (struct yy_buffer_state**)POP3alloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in POP3ensure_buffer_stack()" );
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
yyg->yy_buffer_stack_top = 0;
return;
}
if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
/* Increase the buffer to prepare for a possible push. */
int grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
yyg->yy_buffer_stack = (struct yy_buffer_state**)POP3realloc
(yyg->yy_buffer_stack,
num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in POP3ensure_buffer_stack()" );
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
}
}
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE POP3_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return 0;
b = (YY_BUFFER_STATE) POP3alloc(sizeof( struct yy_buffer_state ) ,yyscanner );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in POP3_scan_buffer()" );
b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = 0;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
POP3_switch_to_buffer(b ,yyscanner );
return b;
}
/** Setup the input buffer state to scan a string. The next call to POP3lex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* POP3_scan_bytes() instead.
*/
YY_BUFFER_STATE POP3_scan_string (yyconst char * yystr , yyscan_t yyscanner)
{
return POP3_scan_bytes(yystr,strlen(yystr) ,yyscanner);
}
/** Setup the input buffer state to scan the given bytes. The next call to POP3lex() will
* scan from a @e copy of @a bytes.
* @param yybytes the byte buffer to scan
* @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE POP3_scan_bytes (yyconst char * yybytes, int _yybytes_len , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
int i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = _yybytes_len + 2;
buf = (char *) POP3alloc(n ,yyscanner );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in POP3_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = POP3_scan_buffer(buf,n ,yyscanner);
if ( ! b )
YY_FATAL_ERROR( "bad buffer in POP3_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
{
(void) fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
yytext[yyleng] = yyg->yy_hold_char; \
yyg->yy_c_buf_p = yytext + yyless_macro_arg; \
yyg->yy_hold_char = *yyg->yy_c_buf_p; \
*yyg->yy_c_buf_p = '\0'; \
yyleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/** Get the user-defined data for this scanner.
* @param yyscanner The scanner object.
*/
YY_EXTRA_TYPE POP3get_extra (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyextra;
}
/** Get the current line number.
* @param yyscanner The scanner object.
*/
int POP3get_lineno (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (! YY_CURRENT_BUFFER)
return 0;
return yylineno;
}
/** Get the current column number.
* @param yyscanner The scanner object.
*/
int POP3get_column (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (! YY_CURRENT_BUFFER)
return 0;
return yycolumn;
}
/** Get the input stream.
* @param yyscanner The scanner object.
*/
FILE *POP3get_in (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyin;
}
/** Get the output stream.
* @param yyscanner The scanner object.
*/
FILE *POP3get_out (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyout;
}
/** Get the length of the current token.
* @param yyscanner The scanner object.
*/
int POP3get_leng (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyleng;
}
/** Get the current token.
* @param yyscanner The scanner object.
*/
char *POP3get_text (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yytext;
}
/** Set the user-defined data. This data is never touched by the scanner.
* @param user_defined The data to be associated with this scanner.
* @param yyscanner The scanner object.
*/
void POP3set_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyextra = user_defined ;
}
/** Set the current line number.
* @param line_number
* @param yyscanner The scanner object.
*/
void POP3set_lineno (int line_number , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* lineno is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
yy_fatal_error( "POP3set_lineno called with no buffer" , yyscanner);
yylineno = line_number;
}
/** Set the current column.
* @param line_number
* @param yyscanner The scanner object.
*/
void POP3set_column (int column_no , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* column is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
yy_fatal_error( "POP3set_column called with no buffer" , yyscanner);
yycolumn = column_no;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param in_str A readable stream.
* @param yyscanner The scanner object.
* @see POP3_switch_to_buffer
*/
void POP3set_in (FILE * in_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyin = in_str ;
}
void POP3set_out (FILE * out_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyout = out_str ;
}
int POP3get_debug (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yy_flex_debug;
}
void POP3set_debug (int bdebug , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_flex_debug = bdebug ;
}
/* Accessor methods for yylval and yylloc */
YYSTYPE * POP3get_lval (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yylval;
}
void POP3set_lval (YYSTYPE * yylval_param , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yylval = yylval_param;
}
/* User-visible API */
/* POP3lex_init is special because it creates the scanner itself, so it is
* the ONLY reentrant function that doesn't take the scanner as the last argument.
* That's why we explicitly handle the declaration, instead of using our macros.
*/
int POP3lex_init(yyscan_t* ptr_yy_globals)
{
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
*ptr_yy_globals = (yyscan_t) POP3alloc ( sizeof( struct yyguts_t ), NULL );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
return 1;
}
/* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
return yy_init_globals ( *ptr_yy_globals );
}
/* POP3lex_init_extra has the same functionality as POP3lex_init, but follows the
* convention of taking the scanner as the last argument. Note however, that
* this is a *pointer* to a scanner, as it will be allocated by this call (and
* is the reason, too, why this function also must handle its own declaration).
* The user defined value in the first argument will be available to POP3alloc in
* the yyextra field.
*/
int POP3lex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals )
{
struct yyguts_t dummy_yyguts;
POP3set_extra (yy_user_defined, &dummy_yyguts);
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
*ptr_yy_globals = (yyscan_t) POP3alloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
return 1;
}
/* By setting to 0xAA, we expose bugs in
yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
POP3set_extra (yy_user_defined, *ptr_yy_globals);
return yy_init_globals ( *ptr_yy_globals );
}
static int yy_init_globals (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from POP3lex_destroy(), so don't allocate here.
*/
yyg->yy_buffer_stack = 0;
yyg->yy_buffer_stack_top = 0;
yyg->yy_buffer_stack_max = 0;
yyg->yy_c_buf_p = (char *) 0;
yyg->yy_init = 0;
yyg->yy_start = 0;
yyg->yy_start_stack_ptr = 0;
yyg->yy_start_stack_depth = 0;
yyg->yy_start_stack = NULL;
/* Defined in main.c */
#ifdef YY_STDINIT
yyin = stdin;
yyout = stdout;
#else
yyin = (FILE *) 0;
yyout = (FILE *) 0;
#endif
/* For future reference: Set errno on error, since we are called by
* POP3lex_init()
*/
return 0;
}
/* POP3lex_destroy is for both reentrant and non-reentrant scanners. */
int POP3lex_destroy (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
POP3_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
YY_CURRENT_BUFFER_LVALUE = NULL;
POP3pop_buffer_state(yyscanner);
}
/* Destroy the stack itself. */
POP3free(yyg->yy_buffer_stack ,yyscanner);
yyg->yy_buffer_stack = NULL;
/* Destroy the start condition stack. */
POP3free(yyg->yy_start_stack ,yyscanner );
yyg->yy_start_stack = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* POP3lex() is called, initialization will occur. */
yy_init_globals( yyscanner);
/* Destroy the main struct (reentrant only). */
POP3free ( yyscanner , yyscanner );
yyscanner = NULL;
return 0;
}
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner)
{
register int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
{
register int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *POP3alloc (yy_size_t size , yyscan_t yyscanner)
{
return (void *) malloc( size );
}
void *POP3realloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return (void *) realloc( (char *) ptr, size );
}
void POP3free (void * ptr , yyscan_t yyscanner)
{
free( (char *) ptr ); /* see POP3realloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
#line 151 "pop3-tokenizer.l"
|
#include "suratkeluar.h"
#include "ui_suratkeluar.h"
suratkeluar::suratkeluar(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::suratkeluar)
{
ui->setupUi(this);
this->on_btndashboard_clicked();
this->on_skrefresh_clicked();
}
suratkeluar::~suratkeluar()
{
delete ui;
}
QString suratkeluar::changeDate(QString datein)
{
QString y,m,d;
y = datein.mid(0,4);
m = datein.mid(5,2);
d = datein.mid(8,2);
switch (m.toInt()) {
case 1:
m = "Jan";
break;
case 2:
m = "Feb";
break;
case 3:
m = "Mar";
break;
case 4:
m = "Apr";
break;
case 5:
m = "Mei";
break;
case 6:
m = "Jun";
break;
case 7:
m = "Jul";
break;
case 8:
m = "Ags";
break;
case 9:
m = "Sep";
break;
case 10:
m = "Okt";
break;
case 11:
m = "Nov";
break;
case 12:
m = "Des";
break;
default:
break;
}
return d+" "+m+" "+y;
}
QString suratkeluar::dateChange(QString datein)
{
//12 jan 2017
QString y,m,d;
d = datein.mid(0,2);
m = datein.mid(3,3);
y = datein.mid(7,4);
if(m == "Jan")
m = "01";
else if(m == "Feb")
m = "02";
else if(m == "Mar")
m = "03";
else if(m == "Apr")
m = "04";
else if(m == "Mei")
m = "05";
else if(m == "Jun")
m = "06";
else if(m == "Jul")
m = "07";
else if(m == "Ags")
m = "08";
else if(m == "Sep")
m = "09";
else if(m == "Okt")
m = "10";
else if(m == "Nov")
m = "11";
else if(m == "Des")
m = "12";
return d+"/"+m+"/"+y;
}
void suratkeluar::on_btndashboard_clicked()
{
ui->skeditwidget->close();
this->on_skrefresh_clicked();
ui->dashboard->show();
ui->tambah->close();
ui->setting->close();
//dashboard
ui->bgdashboard->setStyleSheet("QPushButton#bgdashboard{"+this->bggreen+"}"); //bgdashboard green
ui->btndashboard->setStyleSheet("QPushButton#btndashboard{"+this->btngreen+"}"); //btndashboard green
//tambah
ui->bgtambah->setStyleSheet("QPushButton#bgtambah{"+this->bggrey+"}"); //bgtambah grey
ui->btntambah->setStyleSheet("QPushButton#btntambah{"+this->btngrey+"}"); //btntambah grey
//setting
ui->bgsetting->setStyleSheet("QPushButton#bgsetting{"+this->bggrey+"}"); //bgsetting grey
ui->btnsetting->setStyleSheet("QPushButton#btnsetting{"+this->btngrey+"}"); //btnsetting grey
}
void suratkeluar::on_btntambah_clicked()
{
ui->tambah->show();
ui->dashboard->close();
ui->setting->close();
//dashboard
ui->bgdashboard->setStyleSheet("QPushButton#bgdashboard{"+this->bggrey+"}"); //bgdashboard grey
ui->btndashboard->setStyleSheet("QPushButton#btndashboard{"+this->btngrey+"}"); //btndashboard grey
//tambah
ui->bgtambah->setStyleSheet("QPushButton#bgtambah{"+this->bggreen+"}"); //bgtambah green
ui->btntambah->setStyleSheet("QPushButton#btntambah{"+this->btngreen+"}"); //btntambah green
//setting
ui->bgsetting->setStyleSheet("QPushButton#bgsetting{"+this->bggrey+"}"); //bgsetting grey
ui->btnsetting->setStyleSheet("QPushButton#btnsetting{"+this->btngrey+"}"); //btnsetting grey
ui->no->clear();
ui->alamattujuan->clear();
ui->tglkirim->clear();
ui->tglsurat->clear();
ui->nosurat->clear();
ui->perihal->clear();
ui->keterangan->clear();
ui->klasifikasi->clear();
}
void suratkeluar::on_btnsetting_clicked()
{
ui->setting->show();
ui->dashboard->close();
ui->tambah->close();
//dashboard
ui->bgdashboard->setStyleSheet("QPushButton#bgdashboard{"+this->bggrey+"}"); //bgdashboard grey
ui->btndashboard->setStyleSheet("QPushButton#btndashboard{"+this->btngrey+"}"); //btndashboard grey
//tambah
ui->bgtambah->setStyleSheet("QPushButton#bgtambah{"+this->bggrey+"}"); //bgtambah grey
ui->btntambah->setStyleSheet("QPushButton#btntambah{"+this->btngrey+"}"); //btntambah grey
//setting
ui->bgsetting->setStyleSheet("QPushButton#bgsetting{"+this->bggreen+"}"); //bgsetting green
ui->btnsetting->setStyleSheet("QPushButton#btnsetting{"+this->btngreen+"}"); //btnsetting green
}
void suratkeluar::on_icondashboard_clicked()
{
this->on_btndashboard_clicked();
}
void suratkeluar::on_iconsetting_clicked()
{
this->on_btnsetting_clicked();
}
void suratkeluar::on_icontambah_clicked()
{
this->on_btntambah_clicked();
}
void suratkeluar::on_skkategori_currentIndexChanged(int index)
{
if(index == 2 || index == 3){
ui->skkwtextedit->setPlaceholderText("format : 01 Jan 2001");
}else{
ui->skkwtextedit->setPlaceholderText("masukkan kata kunci");
}
}
void suratkeluar::on_skcari_clicked()
{
QString keyword = ui->skkwtextedit->toPlainText();
QList<QStandardItem *> findlist;
int row = ui->skkategori->currentIndex();
findlist = model->findItems(keyword,Qt::MatchContains,row);
if(findlist.count() == 0){
ui->sksearchresult->setText("\""+keyword+"\" tidak ditemukan di kolom \""+ui->skkategori->currentText()+"\"");
ui->sksearchresult->setStyleSheet("QLabel#searchresult{color: #ff0000;font: 10pt 'Comic Sans MS';}");
}else{
ui->sksearchresult->setText("\""+keyword+"\" ditemukan di kolom \""+ui->skkategori->currentText()+"\"\n("+QVariant(findlist.count()).toString()+")");
ui->sksearchresult->setStyleSheet("QLabel#searchresult{color: #00ff00;font: 10pt 'Comic Sans MS';}");
}
connection conn = connection(); // add connection
if(conn.ok){ // if db connection is valid
QStringList header;
header << "NO" << "ALAMAT TUJUAN"
<< "TGL KIRIM" << "TGL SURAT"
<< "NO SURAT" << "PERIHAL"
<< "KETERANGAN" << "KLASIFIKASI SURAT";
QSqlQuery query = QSqlQuery(conn.db);
query.exec("SELECT * FROM skeluar");
model = new QStandardItemModel(query.size(),8,this);
model->setHorizontalHeaderLabels(header);
int r = 0; //set row for looping
while(query.next()){
for(int i = 0; i < 8; i++){
if(i == 0){
QString str = query.value(0).toString();
if(str.length() == 3)
model->setItem(r,0,new QStandardItem("0"+str));
else if(str.length() == 2)
model->setItem(r,0,new QStandardItem("00"+str));
else if(str.length() == 1)
model->setItem(r,0,new QStandardItem("000"+str));
else
model->setItem(r,0,new QStandardItem(str));
}else if(i == 2 || i == 3){
QString dt = query.value(i).toString(); //save date from sql to Qstring
dt = this->changeDate(dt); //convert sql date format to human readable format
model->setItem(r,i,new QStandardItem(dt)); //set item
}else
model->setItem(r,i,new QStandardItem(query.value(i).toString())); //set item
model->item(r,i)->setTextAlignment(Qt::AlignCenter); //set item Hcenter
}
r++; //increment row for looping
ui->sktabelsmasuk->resizeRowToContents(r);
}
for(int i = 0; i < findlist.count(); i++){
model->item(findlist.at(i)->index().row(),findlist.at(i)->index().column())->setBackground(QBrush(QColor(141, 255, 128,220)));
}
if(findlist.count() == 0){
ui->information->setText("pencarian tidak ditemukan");
ui->information->setStyleSheet("QLabel#information_2{font: 16pt 'Comic Sans MS';color: #ff0000;font-weight: bold;}");
}else {
ui->information->clear();
ui->information->setStyleSheet("QLabel#information_2{font: 16pt 'Comic Sans MS';color: #00ff00;font-weight: bold;}");
}
ui->sktabelsmasuk->setModel(model);
ui->sktabelsmasuk->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->sktabelsmasuk->setColumnWidth(0,35);
ui->sktabelsmasuk->setColumnWidth(1,205);
ui->sktabelsmasuk->setColumnWidth(2,80);
ui->sktabelsmasuk->setColumnWidth(3,80);
ui->sktabelsmasuk->setColumnWidth(4,180);
ui->sktabelsmasuk->setColumnWidth(5,215);
ui->sktabelsmasuk->setColumnWidth(6,100);
ui->sktabelsmasuk->setColumnWidth(7,110);
}
conn.db.close();
}
void suratkeluar::on_skurutkan_currentIndexChanged(int index)
{
if(ui->skaz->isChecked())
ui->sktabelsmasuk->sortByColumn(index,Qt::AscendingOrder);
if(ui->skza->isChecked())
ui->sktabelsmasuk->sortByColumn(index,Qt::DescendingOrder);
}
void suratkeluar::on_skaz_clicked()
{
this->on_skurutkan_currentIndexChanged(ui->skurutkan->currentIndex());
ui->sktabelsmasuk->resizeRowsToContents();
}
void suratkeluar::on_skza_clicked()
{
this->on_skurutkan_currentIndexChanged(ui->skurutkan->currentIndex());
ui->sktabelsmasuk->resizeRowsToContents();
}
void suratkeluar::on_skrefresh_clicked()
{
ui->sksearchresult->clear();
ui->warning->clear();
ui->information->clear();
ui->skaz->setChecked(true);
ui->skurutkan->setCurrentIndex(0);
ui->skkwtextedit->clear();
ui->skkategori->setCurrentIndex(0);
connection conn = connection(); // add connection
if(conn.ok){ // if db connection is valid
QStringList header;
header << "NO" << "ALAMAT TUJUAN"
<< "TGL KIRIM" << "TGL SURAT"
<< "NO SURAT" << "PERIHAL"
<< "KETERANGAN" << "KLASIFIKASI SURAT";
QSqlQuery query = QSqlQuery(conn.db);
query.exec("SELECT * FROM skeluar");
model = new QStandardItemModel(query.size(),8,this);
model->setHorizontalHeaderLabels(header);
int r = 0; //set row for looping
while(query.next()){
for(int i = 0; i < 8; i++){
if(i == 0){
QString str = query.value(0).toString();
if(str.length() == 3)
model->setItem(r,0,new QStandardItem("0"+str));
else if(str.length() == 2)
model->setItem(r,0,new QStandardItem("00"+str));
else if(str.length() == 1)
model->setItem(r,0,new QStandardItem("000"+str));
else
model->setItem(r,0,new QStandardItem(str));
}else if(i == 2 || i == 3){
QString dt = query.value(i).toString(); //save date from sql to Qstring
dt = this->changeDate(dt); //convert sql date format to human readable format
model->setItem(r,i,new QStandardItem(dt)); //set item
}else
model->setItem(r,i,new QStandardItem(query.value(i).toString())); //set item
model->item(r,i)->setTextAlignment(Qt::AlignCenter); //set item Hcenter
}
r++; //increment row for looping
}
ui->sktabelsmasuk->resizeRowsToContents();
ui->sktabelsmasuk->setModel(model);
ui->sktabelsmasuk->resizeRowsToContents();
ui->sktabelsmasuk->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->sktabelsmasuk->setColumnWidth(0,35);
ui->sktabelsmasuk->setColumnWidth(1,205);
ui->sktabelsmasuk->setColumnWidth(2,80);
ui->sktabelsmasuk->setColumnWidth(3,80);
ui->sktabelsmasuk->setColumnWidth(4,180);
ui->sktabelsmasuk->setColumnWidth(5,215);
ui->sktabelsmasuk->setColumnWidth(6,100);
ui->sktabelsmasuk->setColumnWidth(7,110);
}
conn.db.close();
}
void suratkeluar::on_skhapus_clicked()
{
QModelIndexList selectedr = ui->sktabelsmasuk->selectionModel()->selectedRows();
if(selectedr.count() != 0){
int r[selectedr.count()];
int no[selectedr.count()];
QMessageBox::StandardButton reply;
QString nomer;
for(int i = 0; i < selectedr.count(); i++){
r[i] = selectedr.at(i).row();
no[i] = this->model->item(r[i])->text().toInt();
}
connection conn = connection();
if(conn.ok){
QSqlQuery query = QSqlQuery(conn.db);
reply = QMessageBox::warning(this,"HAPUS SURAT","Apakah Anda yakin ingin menghapus surat",QMessageBox::No|QMessageBox::Yes);
if(selectedr.count() > 1){
if(reply == QMessageBox::Yes){
for(int i = 1; i <= selectedr.count(); i++){
query.exec("DELETE FROM skeluar WHERE no in ("+QVariant(no[i-1]).toString()+")");
}
}
this->on_skrefresh_clicked();
}else{
if(reply == QMessageBox::Yes){
query.exec("DELETE FROM skeluar WHERE no = "+QVariant(no[0]).toString());
query.clear();
query.exec("SELECT alamat_tujuan FROM skeluar WHERE no = "+QVariant(no[0]).toString());
if(query.size() == 0){
ui->information->setText("berhasil dihapus");
ui->information->setStyleSheet("QLabel#information_2{font: 16pt 'Comic Sans MS';color: #00ff00;font-weight: bold;}");
this->on_skrefresh_clicked();
}else{
ui->warning->setText("gagal dihapus");
ui->warning->setStyleSheet("QLabel#information_2{font: 16pt 'Comic Sans MS';color: #ff0000;font-weight: bold;}");
}
}
}
}
}else{
QMessageBox::information(this,"HAPUS","Anda harus memilih surat yang akan dihapus",QMessageBox::Close);
}
}
void suratkeluar::on_btnreset_clicked()
{
ui->no->clear();
ui->alamattujuan->clear();
ui->tglkirim->clear();
ui->tglsurat->clear();
ui->nosurat->clear();
ui->perihal->clear();
ui->keterangan->clear();
ui->klasifikasi->clear();
}
void suratkeluar::on_btntambah_2_clicked()
{
ui->warning->clear();
ui->information->clear();
if(ui->no->text().isEmpty()){
ui->warning->setText("NO HARUS DIISI !");
ui->no->setFocus();
}else if(ui->alamattujuan->text().isEmpty()){
ui->warning->setText("ALAMAT PENGIRIM HARUS DIISI !");
ui->alamattujuan->setFocus();
}else if(ui->tglkirim->text().isEmpty()){
ui->warning->setText("TANGGAL TERIMA HARUS DIISI !");
ui->tglkirim->setFocus();
}else if(ui->tglsurat->text().isEmpty()){
ui->warning->setText("TANGGAL SURAT HARUS DIISI !");
ui->tglsurat->setFocus();
}else if(ui->nosurat->text().isEmpty()){
ui->warning->setText("NO SURAT HARUS DIISI !");
ui->nosurat->setFocus();
}else if(ui->perihal->text().isEmpty()){
ui->warning->setText("PERIHAL HARUS DIISI !");
ui->perihal->setFocus();
}else if(ui->keterangan->text().isEmpty()){
ui->warning->setText("KETERANGAN HARUS DIISI !");
ui->keterangan->setFocus();
}else if(ui->klasifikasi->text().isEmpty()){
ui->warning->setText("KLASIFIKASI HARUS DIISI !");
ui->klasifikasi->setFocus();
}else{
QString no = ui->no->text();
QString alamattujuan = ui->alamattujuan->text();
QString tglkirim = ui->tglkirim->text();
QString tglsurat = ui->tglsurat->text();
QString nosurat = ui->nosurat->text();
QString perihal = ui->perihal->text();
QString keterangan = ui->keterangan->text();
QString klasifikasi = ui->klasifikasi->text();
connection conn = connection();
if(conn.ok){
QSqlQuery query = QSqlQuery(conn.db);
query.exec("SELECT alamat_tujuan FROM skeluar WHERE no = "+no);
if(query.size() == 0){
query.prepare("INSERT INTO skeluar (no, alamat_tujuan, tgl_kirim, tgl_surat, nomor_surat, perihal, keterangan, klasifikasi_surat) \
VALUES (?,?,?,?,?,?,?,?)");
query.addBindValue(no);
query.addBindValue(alamattujuan);
query.addBindValue(tglkirim);
query.addBindValue(tglsurat);
query.addBindValue(nosurat);
query.addBindValue(perihal);
query.addBindValue(keterangan);
query.addBindValue(klasifikasi);
query.exec();
query.exec("SELECT alamat_tujuan FROM skeluar WHERE no = "+no);
if(query.size() == 1){
ui->information_8->setText("BERHASIL DITAMBAHKAN");
ui->warning->clear();
this->on_btnreset_clicked();
}else{
ui->warning->setText("GAGAL MENAMBAHKAN DATA");
ui->information_8->clear();
}
}else{
ui->warning->setText("DATA DENGAN NO "+no+" SUDAH ADA");
ui->no->setFocus();
ui->information_8->clear();
}
}
conn.db.close();
}
}
void suratkeluar::on_no_returnPressed()
{
this->on_btntambah_2_clicked();
}
void suratkeluar::on_alamattujuan_returnPressed()
{
this->on_btntambah_2_clicked();
}
void suratkeluar::on_nosurat_returnPressed()
{
this->on_btntambah_2_clicked();
}
void suratkeluar::on_perihal_returnPressed()
{
this->on_btntambah_2_clicked();
}
void suratkeluar::on_keterangan_returnPressed()
{
this->on_btntambah_2_clicked();
}
void suratkeluar::on_klasifikasi_returnPressed()
{
this->on_btntambah_2_clicked();
}
void suratkeluar::on_skeditkembali_clicked()
{
ui->skeditwidget->close();
ui->skeditwarning->clear();
ui->skeditno->clear();
ui->skeditalamattujuan->clear();
ui->skedittglkirim->clear();
ui->skedittglsurat->clear();
ui->skeditnosurat->clear();
ui->skeditperihal->clear();
ui->skeditketerangan->clear();
ui->skeditklasifikasi->clear();
}
void suratkeluar::on_skeditbtnubah_clicked()
{
if(ui->skeditno->text().isEmpty()){
ui->skeditwarning->setText("NO HARUS DIISI !");
ui->skeditno->setFocus();
}else if(ui->skeditalamattujuan->text().isEmpty()){
ui->skeditwarning->setText("ALAMAT PENGIRIM HARUS DIISI !");
ui->skeditalamattujuan->setFocus();
}else if(ui->skedittglkirim->text().isEmpty()){
ui->skeditwarning->setText("TANGGAL TERIMA HARUS DIISI !");
ui->skedittglkirim->setFocus();
}else if(ui->skedittglsurat->text().isEmpty()){
ui->skeditwarning->setText("TANGGAL SURAT HARUS DIISI !");
ui->skedittglsurat->setFocus();
}else if(ui->skeditnosurat->text().isEmpty()){
ui->skeditwarning->setText("NO SURAT HARUS DIISI !");
ui->skeditnosurat->setFocus();
}else if(ui->skeditperihal->text().isEmpty()){
ui->skeditwarning->setText("PERIHAL HARUS DIISI !");
ui->skeditperihal->setFocus();
}else if(ui->skeditketerangan->text().isEmpty()){
ui->skeditwarning->setText("KETERANGAN HARUS DIISI !");
ui->skeditketerangan->setFocus();
}else if(ui->skeditklasifikasi->text().isEmpty()){
ui->skeditwarning->setText("KLASIFIKASI HARUS DIISI !");
ui->skeditklasifikasi->setFocus();
}else{
QString no = QVariant(ui->skeditno->text().toInt()).toString();
QString alamattujuan = ui->skeditalamattujuan->text();
QString tglkirim = ui->skedittglkirim->text();
QString tglsurat = ui->skedittglsurat->text();
QString nosurat = ui->skeditnosurat->text();
QString perihal = ui->skeditperihal->text();
QString keterangan = ui->skeditketerangan->text();
QString klasifikasi = ui->skeditklasifikasi->text();
connection conn = connection();
if(conn.ok){
QSqlQuery query = QSqlQuery(conn.db);
query.prepare("UPDATE skeluar SET no=?, alamat_tujuan=?,tgl_kirim=?,tgl_surat=?,nomor_surat=?,perihal=?,keterangan=?,klasifikasi_surat=? WHERE no = "+no);
query.addBindValue(no);
query.addBindValue(alamattujuan);
query.addBindValue(tglkirim);
query.addBindValue(tglsurat);
query.addBindValue(nosurat);
query.addBindValue(perihal);
query.addBindValue(keterangan);
query.addBindValue(klasifikasi);
query.exec();
if(query.numRowsAffected() != 0){
QMessageBox::information(this,"INFORMASI","DATA BERHASIL DI EDIT",QMessageBox::Ok);
this->on_skrefresh_clicked();
this->on_skeditkembali_clicked();
}else{
ui->skeditwarning->setText("GAGAL EDIT DATA");
}
}
conn.db.close();
}
}
void suratkeluar::on_skedit_clicked()
{
QModelIndexList selectedr = ui->sktabelsmasuk->selectionModel()->selectedRows();
if(selectedr.count() != 0){
if(selectedr.count() == 1){
int row = selectedr.at(0).row();
ui->skeditno->setText(this->model->item(row,0)->text());
ui->skeditalamattujuan->setText(this->model->item(row,1)->text());
ui->skedittglkirim->setDate(QDate::fromString(dateChange(this->model->item(row,2)->text()),"dd/MM/yyyy"));
ui->skedittglsurat->setDate(QDate::fromString(dateChange(this->model->item(row,3)->text()),"dd/MM/yyyy"));
ui->skeditnosurat->setText(this->model->item(row,4)->text());
ui->skeditperihal->setText(this->model->item(row,5)->text());
ui->skeditketerangan->setText(this->model->item(row,6)->text());
ui->skeditklasifikasi->setText(this->model->item(row,7)->text());
ui->skeditwidget->show();
}else{
QMessageBox::information(this,"EDIT","PILIH SATU YANG AKAN DIEDIT",QMessageBox::Ok);
}
}
}
|
#pragma once
namespace qp
{
typedef boost::optional<std::string> optional_string;
typedef boost::optional<size_t> optional_size_t;
typedef boost::signals2::connection Connection;
typedef boost::signals2::scoped_connection ScopedConnection;
}
|
#ifndef TREEFACE_SCENE_NODE_MANAGER_H
#define TREEFACE_SCENE_NODE_MANAGER_H
#include "treeface/base/Common.h"
#include <treecore/ClassUtils.h>
#include <treecore/Identifier.h>
#include <treecore/RefCountHolder.h>
#include <treecore/RefCountObject.h>
namespace treecore {
class String;
class var;
} // namespace treecore
namespace treeface {
class GeometryManager;
class MaterialManager;
class SceneNode;
class VisualObject;
class SceneNodeManager: public treecore::RefCountObject
{
public:
SceneNodeManager() = delete;
SceneNodeManager( GeometryManager* geo_mgr, MaterialManager* mat_mgr );
TREECORE_DECLARE_NON_COPYABLE( SceneNodeManager );
TREECORE_DECLARE_NON_MOVABLE( SceneNodeManager );
virtual ~SceneNodeManager();
SceneNode* add_nodes( const treecore::var& data );
/**
* @brief get named node object
* @param name
* @return If has node object with name, return node object; otherwise
* return nullptr.
*/
SceneNode* get_node( const treecore::Identifier& name );
protected:
VisualObject* create_visual_object( const treecore::var& data );
void build_node( const treecore::var& data, SceneNode* node );
private:
struct Impl;
Impl* m_impl = nullptr;
};
} // namespace treeface
#endif // TREEFACE_SCENE_NODE_MANAGER_H
|
#ifndef ASSIGNMENT_H
#define ASSIGNMENT_H
#include <stdio.h>
#include <iostream>
#include <list>
#include "date.h"
using namespace std;
enum Status{ assigned = 1, completed = 2, late = 3 };
class assignment{
private:
Date dueDate;
string description;
Date assignedDate;
Status status;
public:
assignment();
assignment(const assignment& other);
const assignment& operator=(const assignment& rhs);
Date getDueDate();
string getDescription();
Date getAssignedDate();
Status getStatus();
void setDueDate(Date date);
void setDescription(string desc);
void setAssignedDate(Date date);
void setStatus(int stat);
friend istream& operator>>(istream& in, assignment& current);
friend ostream& operator<<(ostream& out, assignment& current);
bool operator <(const assignment& rhs) const;
bool operator >(const assignment& rhs) const;
bool operator ==(const assignment& rhs) const;
};
#endif
|
/*
Copyright 2021 University of Manchester
Licensed under the Apache License, Version 2.0(the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http: // www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <map>
#include <string>
#include <utility>
#include "state_interface.hpp"
using orkhestrafs::dbmstodspi::GraphProcessingFSMInterface;
namespace orkhestrafs::dbmstodspi {
/**
* @brief State for setting up nodes.
*/
class InteractiveState : public StateInterface {
private:
void PrintOptions(GraphProcessingFSMInterface* fsm);
auto GetOption(GraphProcessingFSMInterface* fsm) -> int;
auto GetStdInput() -> std::string;
auto GetInteger() -> int;
auto GetDouble() -> double;
auto GetExecutionPlanFile(const std::pair<std::string, std::string>& input)
-> std::string;
void PrintOutGivenOptions(const std::vector<std::string> list_of_options);
auto GetBitstreamToLoad(
const std::map<QueryOperationType, OperationPRModules> bitstream_map)
-> ScheduledModule;
auto GetQueryFromInput() -> std::pair<std::string, std::string>;
std::map<QueryOperationType, std::string> operation_names_ = {
{QueryOperationType::kAddition, "Addition"},
{QueryOperationType::kAggregationSum, "Aggregation sum"},
{QueryOperationType::kFilter, "Filter"},
{QueryOperationType::kJoin, "Join"},
{QueryOperationType::kLinearSort, "Linear sorter"},
{QueryOperationType::kMergeSort, "Merge sorter"},
{QueryOperationType::kMultiplication, "Multiplication"},
{QueryOperationType::kSobel, "Sobel"},
{QueryOperationType::kBlackWhite, "Convert to Monochrome"},
};
public:
~InteractiveState() override = default;
auto Execute(GraphProcessingFSMInterface* fsm)
-> std::unique_ptr<StateInterface> override;
};
} // namespace orkhestrafs::dbmstodspi
|
#include <stdio.h>
#include "DataTypes.h"
#include "Memory.h"
#include "apsoc_cv_vdma.h"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "Random.h"
#include "Embedder.h"
#include "Rsa.h"
#include "Steganography.h"
#include "WebServer.h"
#include "Certificate.h"
#define GRANTED_PIN 0x123A
using namespace cv;
int main()
{
Certificate::GenerateRandomCertificate("private.rsa", "public.rsa");
Certificate::FromFile("private.rsa");
Certificate::FromFile("public.rsa");
printf("%x\n", GetTrueRandomNumber());
//return 0;
while(1)
CheckWebServer();
/* char text[500];
int data2[500];
strcpy(text,"Testul suprem este acela care functioneaza corect indifrente de circumstante");
DWORD changes;
uchar data[2000];
Embedder embedder;
Steganography steg;
Mat imgOriginal=imread("picture.png");
imwrite("out.png", steg.Embed(imgOriginal, text, 70));
imgOriginal = imread("out.png");
int length = 0;
char *te = steg.Extract(imgOriginal, &length);
printf("In the image was detected %x bytes %s \n", length, te);
*/
//VDMA vdmaOut = VdmaOutInit(VDMA_OUT_ADDRESS);
// unsigned char *out_address = (unsigned char*)vdmaOut.OutputBuffer;
Mat inFrame(900,1440,CV_8UC3 );
Mat inFrame2(1024,1280,CV_8UC3 );
//inFrame2=imread("picture.png");
//imwrite("picture2.png", Sobel::GetInstance()->SobelInHardware((inFrame2)));
return 0;
}
|
/*
* queue.hpp
*
* define your methods in coherence with the following
* function signatures
* use the abstraction of linked lists
* to implement the functionality of queues
*/
#ifndef QUEUE_HPP_
#define QUEUE_HPP_
#include "list.hpp"
namespace cs202
{
template <class T>
class queue : protected list<T>
{
public:
/*
* Constructs a new queue.
*/
queue() {
// nothing to see here, list handles everything
}
/*
* Pushes t to at the back of the queue.
*/
void push(const T& t) {
this->append(t);
}
/*
* Returns the element at the front of the queue.
* Also removes the front element from the queue.
*/
T pop() {
if (this->first_ == nullptr) {
throw std::range_error("Can't dequeue, queue is empty!");
}
T data = this->first_->data_;
this->remove(this->first_->data_);
return data;
}
/*
* Returns the element at the front of the queue.
* Does not remove the front element.
*/
T front() {
return this->first_->data_;
}
/*
* Returns the number of elements currently in the queue.
*/
inline int size() {
return this->length();
}
/*
* Returns a boolean indicating whether the queue is empty or not.
*/
inline bool empty() {
return (size() == 0);
}
/*
* Destructor
* Fress the memory occupied by the queue elements.
*/
virtual ~queue() {
// Nothing to do here, all's handled by the base class
}
};
}
#endif
|
#pragma once
#include "PacketType.h"
#include "Packet.h"
#include <string>
#include <memory>
#include "Global.h"
namespace PacketInfo
{
// Chat/string messages
class ChatMessage
{
public:
ChatMessage(const std::string & str);
std::shared_ptr<Packet> toPacket();
private:
std::string m_message;
};
// Update positions on server
class PositionUpdate
{
public:
PositionUpdate(const float t_xPos, const float t_yPos);
PositionUpdate(const int t_id, const float t_xPos, const float t_yPos);
std::shared_ptr<Packet> toPacket();
private:
int m_id;
float m_xPos;
float m_yPos;
};
// update the player color
class ColorUpdate
{
public:
ColorUpdate(const int col);
ColorUpdate(const int t_id, const int col);
std::shared_ptr<Packet> toPacket();
private:
int m_id;
int m_col;
};
// Signal that the game has ended
class EndGame
{
public:
EndGame(const int end);
std::shared_ptr<Packet> toPacket();
private:
int m_end;
};
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
*
* Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef IM_OP_INPUTACTION_H
#define IM_OP_INPUTACTION_H
#include "modules/hardcore/keys/opkeys.h"
#include "modules/pi/OpKeys.h"
class OpInputContext;
class OpTypedObject;
/**
* Represents a tooltip and a status text.
*/
class OpInfoText
{
public:
OpInfoText() : max_line_width(100), max_lines(50), m_auto_truncate(TRUE) {}
/**
* Empty the status and tooltip texts.
*/
void Empty() { m_status_text.Empty(); m_tooltip_text.Empty(); }
/**
* Set the status text. If auto truncate is enabled the text will be
* truncated after 'max_line_width' characters.
*/
OP_STATUS SetStatusText(const uni_char* text);
/**
* Set the tooltip text.
*/
OP_STATUS SetTooltipText(const uni_char* text) { return m_tooltip_text.Set(text); }
/**
* Add text of the form 'label: text' to the current tooltip text. The text
* will be truncated automatically.
*/
OP_STATUS AddTooltipText(const uni_char* label, const uni_char* text);
/**
* Returns a reference to the status text string.
*/
const OpString& GetStatusText() { return m_status_text; }
/**
* Returns a reference to the tooltip text string.
*/
const OpString& GetTooltipText() { return m_tooltip_text; }
/**
* Copy status and tooltip texts from another OpInfoText.
*/
OP_STATUS Copy(OpInfoText& src);
/**
* If auto truncate is set SetStatusText() will automatically truncate strings.
*/
void SetAutoTruncate(BOOL auto_truncate) {m_auto_truncate = auto_truncate;}
BOOL HasStatusText() const { return m_status_text.HasContent(); }
BOOL HasTooltipText() const { return m_tooltip_text.HasContent(); }
private:
const int max_line_width, max_lines;
OpString m_status_text;
OpString m_tooltip_text;
BOOL m_auto_truncate;
};
class OpInputAction
{
public:
#include "modules/hardcore/actions/generated_actions_enum.h"
enum ActionState
{
STATE_ENABLED = 0x01, ///< is action to be considered available?
STATE_DISABLED = 0x02, ///< is action to be considered unavailable? (disabled menuitem, button etc)
STATE_SELECTED = 0x04, ///< is action to be considered selected?
STATE_UNSELECTED = 0x08, ///< is action to be considered unselected?
STATE_ATTENTION = 0x10, ///< is action demanding user attention?
STATE_INATTENTION = 0x20 ///< is action not demanding user attention?
};
enum ActionMethod
{
METHOD_MOUSE,
METHOD_MENU,
METHOD_KEYBOARD,
METHOD_OTHER
};
enum ActionOperator
{
OPERATOR_NONE = 0x01,
OPERATOR_OR = 0x02, ///< execute the next action only if the current action was not handled
OPERATOR_AND = 0x04, ///< always execute the next action
OPERATOR_NEXT = 0x08, ///< execute the next action only if the current action was not handled
/**
* The plus operator assigns two actions to one OpButton.
* The first action is executed on a normal click, the second action on a long click.
*
* Example: the "back"-button can be configured with the action "Back + Action": a normal click executes action "Back", a long click executes the second action "Action".
* You can combine several sequences with a "+" like "Reload | Stop + Action1 & Action2", which will then execute "Reload | Stop" on a short click and "Action1 & Action2" on a long click.
*/
OPERATOR_PLUS = 0x10
};
/**
* Simple constructor.
*/
OpInputAction();
OpInputAction(Action action);
// LOWLEVEL KEY actions
OpInputAction(Action action, OpKey::Code key, ShiftKeyState shift_keys = 0, BOOL repeat = FALSE, OpKey::Location location = OpKey::LOCATION_STANDARD, ActionMethod action_method = METHOD_OTHER);
// ACTION_LOWLEVEL_PREFILTER_ACTION
OpInputAction(OpInputAction* child_action, Action action);
~OpInputAction();
/**
* Copy the contents of another OpInputAction.
*
* @param src_action Action to copy data from.
* @return OpStatus::OK or OpStatus::ERROR_NO_MEMORY
*/
OP_STATUS Clone(OpInputAction* src_action);
ActionMethod GetActionMethod() {return m_action_method;}
ActionOperator GetActionOperator() {return m_action_operator;}
Action GetAction() {return m_action;}
INTPTR GetActionData() {return m_action_data;}
const uni_char* GetActionDataString() {return m_action_data_string.CStr();}
const uni_char* GetActionDataStringParameter() {return m_action_data_string_parameter.CStr();}
const uni_char* GetActionText() {return m_action_text.CStr();}
Str::LocaleString GetActionTextID();
OpInfoText& GetActionInfo() {return m_action_info;}
const char* GetActionImage(BOOL use_predefined = TRUE) {return m_action_image.HasContent() || !use_predefined ? m_action_image.CStr() : GetStringFromAction(m_action);}
INT32 GetActionState() {return m_action_state;}
void GetActionPosition(OpRect& rect) {rect = m_action_position;}
OpTypedObject* GetActionObject() {return m_action_object;}
const uni_char* GetKeyValue() {return m_key_value.CStr();}
ShiftKeyState GetShiftKeys() {return m_shift_keys;}
BOOL GetKeyRepeat() {return m_key_repeat;}
OpKey::Location GetKeyLocation() {return m_key_location;}
INT32 GetRepeatCount() {return m_repeat_count;}
OpPlatformKeyEventData* GetPlatformKeyEventData() {return m_key_event_data; }
OpInputAction* GetChildAction() {return m_child_action;}
OpInputAction* GetNextInputAction(ActionOperator after_this_operator = OPERATOR_NONE);
OpInputContext* GetFirstInputContext() {return m_first_input_context;}
Action GetReferrerAction() {return m_referrer_action;}
OpKey::Code GetActionKeyCode() {return static_cast<OpKey::Code>(m_action_data);}
BOOL IsLowlevelAction();
BOOL IsMoveAction();
BOOL IsRangeAction();
BOOL IsUpdateAction() {return m_action < LAST_ACTION;}
BOOL IsKeyboardInvoked() {return m_action_method == METHOD_KEYBOARD;}
BOOL IsMouseInvoked() {return m_action_method == METHOD_MOUSE;}
BOOL IsMenuInvoked() {return m_action_method == METHOD_MENU;}
BOOL IsGestureInvoked() {return m_gesture_invoked;}
BOOL IsActionDataStringEqualTo(const uni_char* string) {return m_action_data_string.CompareI(string) == 0;}
BOOL HasActionDataString() {return m_action_data_string.HasContent();}
BOOL HasActionDataStringParameter() {return m_action_data_string_parameter.HasContent();}
BOOL HasActionText() {return m_action_text.HasContent();}
BOOL HasActionTextID() {return m_action_text_id != 0;}
BOOL HasActionImage() {return m_action_image.HasContent();}
BOOL WasReallyHandled() {return m_was_really_handled;}
BOOL Equals(OpInputAction* action);
void SetEnabled(BOOL enabled);
void SetSelected(BOOL selected);
void SetSelectedByToggleAction(Action true_action, BOOL toggle);
void SetAttention(BOOL attention);
void SetActionData(INTPTR data) { m_action_data = data; }
void SetKeyCode(OpKey::Code k) { m_action_data = static_cast<INTPTR>(k); }
void SetShiftKeys(ShiftKeyState s) { m_shift_keys = s; }
void SetActionDataString(const uni_char* string);
void SetActionDataStringParameter(const uni_char* string);
void SetActionText(const uni_char* string);
void SetActionTextID(Str::LocaleString string_id);
OP_STATUS SetActionImage(const char* string);
void SetActionState(INT32 state) {m_action_state = state;}
void SetActionPosition(const OpRect& rect);
void SetActionPosition(const OpPoint& point);
void SetActionObject(OpTypedObject* object) {m_action_object = object; }
void SetRepeatCount(INT32 repeat_count) {m_repeat_count = repeat_count; }
void SetPlatformKeyEventData(OpPlatformKeyEventData *data);
void SetActionOperator(ActionOperator action_operator) { m_action_operator = action_operator; }
void SetActionMethod(ActionMethod action_method) { m_action_method = action_method; }
void SetNextInputAction(OpInputAction* action) { m_next_input_action = action; }
void SetFirstInputContext(OpInputContext* first_input_context) {m_first_input_context = first_input_context; if (m_next_input_action) m_next_input_action->SetFirstInputContext(first_input_context);}
void SetWasReallyHandled(BOOL really_handled) {m_was_really_handled = really_handled;}
void SetGestureInvoked(BOOL gesture) { m_gesture_invoked = gesture; }
void SetReferrerAction(Action referrer_action) { m_referrer_action = referrer_action; }
/** Set the character value produced by this key action.
*
* @param value The character value string.
* @return OpStatus::ERR_NO_MEMORY or OpStatus::OK.
*/
OP_STATUS SetActionKeyValue(const uni_char *value);
/** Set the character value produced by this key action.
*
* @param value The character value, UTF-8 encoded.
* @param length The length of 'value'.
* @return OpStatus::ERR_NO_MEMORY or OpStatus::OK.
*/
OP_STATUS SetActionKeyValue(const char *value, unsigned length);
/**
* Convert the action to a string representation.
*
* @param string Target string.
* @return OpStatus::ERR_NO_MEMORY or OpStatus::OK.
*/
OP_STATUS ConvertToString(OpString& string);
static OP_STATUS CreateInputActionsFromString(const uni_char* string, OpInputAction*& input_action, INTPTR default_value = 0, BOOL keyboard_invoked = FALSE);
static OP_STATUS CreateInputActionsFromString(const char* string8, OpInputAction*& input_action, INTPTR default_value = 0, BOOL keyboard_invoked = FALSE)
{
OpString string; RETURN_IF_ERROR(string.Set(string8)); return CreateInputActionsFromString(string.CStr(), input_action, default_value, keyboard_invoked);
}
static OpInputAction* CreateToggleAction(Action action1, Action action2, INTPTR action_data = 0, const uni_char* action_data_string = NULL);
static OpInputAction* CopyInputActions(OpInputAction* source_action, INT32 stop_at_operator = OPERATOR_NONE);
static void DeleteInputActions(OpInputAction* input_action);
/**
* Get a string representation from an action enum value.
*/
static OP_STATUS GetStringFromAction(OpInputAction::Action action, OpString8& string);
static const char* GetStringFromAction(OpInputAction::Action action);
static OP_STATUS GetLocaleStringFromAction(OpInputAction::Action action, OpString& string);
private:
void SetMembers(Action action);
ActionOperator m_action_operator;
Action m_action;
INTPTR m_action_data;
OpString m_action_data_string;
OpString m_action_data_string_parameter;
OpString m_action_text;
int m_action_text_id;
OpInfoText m_action_info;
OpString8 m_action_image;
INT32 m_action_state;
OpRect m_action_position;
OpTypedObject* m_action_object;
ShiftKeyState m_shift_keys;
OpString m_key_value;
BOOL m_key_repeat;
OpKey::Location m_key_location;
INT32 m_repeat_count;
OpPlatformKeyEventData* m_key_event_data;
OpInputAction* m_child_action;
ActionMethod m_action_method;
OpInputAction* m_next_input_action;
OpInputContext* m_first_input_context;
BOOL m_was_really_handled; // kludge until I bother to change BOOL return value of doing actions to an HANDLED enum
BOOL m_gesture_invoked;
Action m_referrer_action;
};
class OpInputStateListener
{
public:
virtual ~OpInputStateListener() {} // gcc warn: virtual methods => virtual destructor.
virtual void OnUpdateInputState(BOOL full_update) = 0;
};
class OpInputState : public Link
{
public:
OpInputState() : m_listener(NULL), m_wants_only_full_update(FALSE) {}
virtual ~OpInputState() {SetEnabled(FALSE);}
void SetInputStateListener(OpInputStateListener* listener) {m_listener = listener;}
void SetWantsOnlyFullUpdate(BOOL wants_only_full_update) {m_wants_only_full_update = wants_only_full_update;}
BOOL GetWantsOnlyFullUpdate() {return m_wants_only_full_update;}
void SetEnabled(BOOL enabled);
BOOL IsEnabled() {return InList();}
void Update(BOOL full_update) {if (m_listener) m_listener->OnUpdateInputState(full_update);}
private:
OpInputStateListener* m_listener;
BOOL m_wants_only_full_update;
};
#endif // !IM_OP_INPUTACTION_H
|
// Copyright (c) 2007-2013 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// This is a purely local version demonstrating different versions of making
// the calculation of a fibonacci asynchronous.
#include <pika/chrono.hpp>
#include <pika/future.hpp>
#include <pika/init.hpp>
#include <fmt/ostream.h>
#include <fmt/printf.h>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <string>
#include <tuple>
#include <utility>
///////////////////////////////////////////////////////////////////////////////
std::uint64_t threshold = 2;
///////////////////////////////////////////////////////////////////////////////
PIKA_NOINLINE std::uint64_t fibonacci_serial(std::uint64_t n)
{
if (n < 2) return n;
return fibonacci_serial(n - 1) + fibonacci_serial(n - 2);
}
///////////////////////////////////////////////////////////////////////////////
std::uint64_t add(pika::future<std::uint64_t> f1, pika::future<std::uint64_t> f2)
{
return f1.get() + f2.get();
}
///////////////////////////////////////////////////////////////////////////////
struct when_all_wrapper
{
using data_type = std::tuple<pika::future<std::uint64_t>, pika::future<std::uint64_t>>;
std::uint64_t operator()(pika::future<data_type> data) const
{
data_type v = data.get();
return std::get<0>(v).get() + std::get<1>(v).get();
}
};
///////////////////////////////////////////////////////////////////////////////
pika::future<std::uint64_t> fibonacci_future_one(std::uint64_t n);
struct fibonacci_future_one_continuation
{
explicit fibonacci_future_one_continuation(std::uint64_t n)
: n_(n)
{
}
std::uint64_t operator()(pika::future<std::uint64_t> res) const
{
return add(fibonacci_future_one(n_ - 2), std::move(res));
}
std::uint64_t n_;
};
std::uint64_t fib(std::uint64_t n) { return fibonacci_future_one(n).get(); }
pika::future<std::uint64_t> fibonacci_future_one(std::uint64_t n)
{
// if we know the answer, we return a future encapsulating the final value
if (n < 2) return pika::make_ready_future(n);
if (n < threshold) return pika::make_ready_future(fibonacci_serial(n));
// asynchronously launch the calculation of one of the sub-terms
// attach a continuation to this future which is called asynchronously on
// its completion and which calculates the other sub-term
return pika::async(&fib, n - 1).then(fibonacci_future_one_continuation(n));
}
///////////////////////////////////////////////////////////////////////////////
std::uint64_t fibonacci(std::uint64_t n)
{
// if we know the answer, we return the final value
if (n < 2) return n;
if (n < threshold) return fibonacci_serial(n);
// asynchronously launch the creation of one of the sub-terms of the
// execution graph
pika::future<std::uint64_t> f = pika::async(&fibonacci, n - 1);
std::uint64_t r = fibonacci(n - 2);
return f.get() + r;
}
///////////////////////////////////////////////////////////////////////////////
std::uint64_t fibonacci_fork(std::uint64_t n)
{
// if we know the answer, we return the final value
if (n < 2) return n;
if (n < threshold) return fibonacci_serial(n);
// asynchronously launch the creation of one of the sub-terms of the
// execution graph
pika::future<std::uint64_t> f = pika::async(pika::launch::fork, &fibonacci_fork, n - 1);
std::uint64_t r = fibonacci_fork(n - 2);
return f.get() + r;
}
///////////////////////////////////////////////////////////////////////////////
pika::future<std::uint64_t> fibonacci_future(std::uint64_t n)
{
// if we know the answer, we return a future encapsulating the final value
if (n < 2) return pika::make_ready_future(n);
if (n < threshold) return pika::make_ready_future(fibonacci_serial(n));
// asynchronously launch the creation of one of the sub-terms of the
// execution graph
pika::future<std::uint64_t> f = pika::async(&fibonacci_future, n - 1);
pika::future<std::uint64_t> r = fibonacci_future(n - 2);
return pika::async(&add, std::move(f), std::move(r));
}
///////////////////////////////////////////////////////////////////////////////
pika::future<std::uint64_t> fibonacci_future_fork(std::uint64_t n)
{
// if we know the answer, we return a future encapsulating the final value
if (n < 2) return pika::make_ready_future(n);
if (n < threshold) return pika::make_ready_future(fibonacci_serial(n));
// asynchronously launch the creation of one of the sub-terms of the
// execution graph
pika::future<std::uint64_t> f = pika::async(pika::launch::fork, &fibonacci_future_fork, n - 1);
pika::future<std::uint64_t> r = fibonacci_future_fork(n - 2);
return pika::async(&add, std::move(f), std::move(r));
}
///////////////////////////////////////////////////////////////////////////////
pika::future<std::uint64_t> fibonacci_future_when_all(std::uint64_t n)
{
// if we know the answer, we return a future encapsulating the final value
if (n < 2) return pika::make_ready_future(n);
if (n < threshold) return pika::make_ready_future(fibonacci_serial(n));
// asynchronously launch the creation of one of the sub-terms of the
// execution graph
pika::future<pika::future<std::uint64_t>> f = pika::async(&fibonacci_future, n - 1);
pika::future<std::uint64_t> r = fibonacci_future(n - 2);
return pika::when_all(f.get(), r).then(when_all_wrapper());
}
pika::future<std::uint64_t> fibonacci_future_unwrapped_when_all(std::uint64_t n)
{
// if we know the answer, we return a future encapsulating the final value
if (n < 2) return pika::make_ready_future(n);
if (n < threshold) return pika::make_ready_future(fibonacci_serial(n));
// asynchronously launch the creation of one of the sub-terms of the
// execution graph
pika::future<std::uint64_t> f = pika::async(&fibonacci_future, n - 1);
pika::future<std::uint64_t> r = fibonacci_future(n - 2);
return pika::when_all(f, r).then(when_all_wrapper());
}
/////////////////////////////////////////////////////////////////////////////
pika::future<std::uint64_t> fibonacci_future_all(std::uint64_t n)
{
// if we know the answer, we return a future encapsulating the final value
if (n < 2) return pika::make_ready_future(n);
if (n < threshold) return pika::make_ready_future(fibonacci_serial(n));
// asynchronously launch the calculation of both of the sub-terms
pika::future<std::uint64_t> f1 = fibonacci_future_all(n - 1);
pika::future<std::uint64_t> f2 = fibonacci_future_all(n - 2);
// create a future representing the successful calculation of both sub-terms
return pika::async(&add, std::move(f1), std::move(f2));
}
/////////////////////////////////////////////////////////////////////////////
pika::future<std::uint64_t> fibonacci_future_all_when_all(std::uint64_t n)
{
// if we know the answer, we return a future encapsulating the final value
if (n < 2) return pika::make_ready_future(n);
if (n < threshold) return pika::make_ready_future(fibonacci_serial(n));
// asynchronously launch the calculation of both of the sub-terms
pika::future<std::uint64_t> f1 = fibonacci_future_all(n - 1);
pika::future<std::uint64_t> f2 = fibonacci_future_all(n - 2);
// create a future representing the successful calculation of both sub-terms
// attach a continuation to this future which is called asynchronously on
// its completion and which calculates the final result
return pika::when_all(f1, f2).then(when_all_wrapper());
}
///////////////////////////////////////////////////////////////////////////////
int pika_main(pika::program_options::variables_map& vm)
{
pika::scoped_finalize f;
// extract command line argument, i.e. fib(N)
std::uint64_t n = vm["n-value"].as<std::uint64_t>();
std::string test = vm["test"].as<std::string>();
std::uint64_t max_runs = vm["n-runs"].as<std::uint64_t>();
if (max_runs == 0)
{
std::cerr << "fibonacci_futures: wrong command line argument value for option 'n-runs', "
"should not be zero"
<< std::endl;
return -1;
}
threshold = vm["threshold"].as<unsigned int>();
if (threshold < 2 || threshold > n)
{
std::cerr << "fibonacci_futures: wrong command line argument value for option 'threshold', "
"should be in between 2 and n-value, value specified: "
<< threshold << std::endl;
return -1;
}
bool executed_one = false;
std::uint64_t r = 0;
using namespace std::chrono;
if (test == "all" || test == "0")
{
// Keep track of the time required to execute.
auto start = high_resolution_clock::now();
for (std::size_t i = 0; i != max_runs; ++i)
{
// Create a Future for the whole calculation, execute it locally,
// and wait for it.
r = fibonacci_serial(n);
}
std::uint64_t d = duration_cast<nanoseconds>(high_resolution_clock::now() - start).count();
constexpr char const* fmt = "fibonacci_serial({}) == {},elapsed time:,{},[s]\n";
fmt::print(std::cout, fmt, n, r, d / max_runs);
executed_one = true;
}
if (test == "all" || test == "1")
{
// Keep track of the time required to execute.
auto start = high_resolution_clock::now();
for (std::size_t i = 0; i != max_runs; ++i)
{
// Create a Future for the whole calculation, execute it locally,
// and wait for it.
r = fibonacci_future_one(n).get();
}
std::uint64_t d = duration_cast<nanoseconds>(high_resolution_clock::now() - start).count();
constexpr char const* fmt = "fibonacci_future_one({}) == {},elapsed time:,{},[s]\n";
fmt::print(std::cout, fmt, n, r, d / max_runs);
executed_one = true;
}
if (test == "all" || test == "2")
{
// Keep track of the time required to execute.
auto start = high_resolution_clock::now();
for (std::size_t i = 0; i != max_runs; ++i)
{
// Create a Future for the whole calculation, execute it locally, and
// wait for it.
r = fibonacci(n);
}
std::uint64_t d = duration_cast<nanoseconds>(high_resolution_clock::now() - start).count();
constexpr char const* fmt = "fibonacci({}) == {},elapsed time:,{},[s]\n";
fmt::print(std::cout, fmt, n, r, d / max_runs);
executed_one = true;
}
if (test == "all" || test == "9")
{
// Keep track of the time required to execute.
auto start = high_resolution_clock::now();
for (std::size_t i = 0; i != max_runs; ++i)
{
// Create a Future for the whole calculation, execute it locally, and
// wait for it. Use continuation stealing
r = fibonacci_fork(n);
}
std::uint64_t d = duration_cast<nanoseconds>(high_resolution_clock::now() - start).count();
constexpr char const* fmt = "fibonacci_fork({}) == {},elapsed time:,{},[s]\n";
fmt::print(std::cout, fmt, n, r, d / max_runs);
executed_one = true;
}
if (test == "all" || test == "3")
{
// Keep track of the time required to execute.
auto start = high_resolution_clock::now();
for (std::size_t i = 0; i != max_runs; ++i)
{
// Create a Future for the whole calculation, execute it locally, and
// wait for it.
r = fibonacci_future(n).get();
}
std::uint64_t d = duration_cast<nanoseconds>(high_resolution_clock::now() - start).count();
constexpr char const* fmt = "fibonacci_future({}) == {},elapsed time:,{},[s]\n";
fmt::print(std::cout, fmt, n, r, d / max_runs);
executed_one = true;
}
if (test == "all" || test == "8")
{
// Keep track of the time required to execute.
auto start = high_resolution_clock::now();
for (std::size_t i = 0; i != max_runs; ++i)
{
// Create a Future for the whole calculation, execute it locally, and
// wait for it. Use continuation stealing.
r = fibonacci_future_fork(n).get();
}
std::uint64_t d = duration_cast<nanoseconds>(high_resolution_clock::now() - start).count();
constexpr char const* fmt = "fibonacci_future_fork({}) == {},elapsed time:,{},[s]\n";
fmt::print(std::cout, fmt, n, r, d / max_runs);
executed_one = true;
}
if (test == "all" || test == "6")
{
// Keep track of the time required to execute.
auto start = high_resolution_clock::now();
for (std::size_t i = 0; i != max_runs; ++i)
{
// Create a Future for the whole calculation, execute it locally, and
// wait for it.
r = fibonacci_future_when_all(n).get();
}
std::uint64_t d = duration_cast<nanoseconds>(high_resolution_clock::now() - start).count();
constexpr char const* fmt = "fibonacci_future_when_all({}) == {},elapsed time:,{},[s]\n";
fmt::print(std::cout, fmt, n, r, d / max_runs);
executed_one = true;
}
if (test == "all" || test == "7")
{
// Keep track of the time required to execute.
auto start = high_resolution_clock::now();
for (std::size_t i = 0; i != max_runs; ++i)
{
// Create a Future for the whole calculation, execute it locally, and
// wait for it.
r = fibonacci_future_unwrapped_when_all(n).get();
}
std::uint64_t d = duration_cast<nanoseconds>(high_resolution_clock::now() - start).count();
constexpr char const* fmt =
"fibonacci_future_unwrapped_when_all({}) == {},elapsed time:,{},[s]\n";
fmt::print(std::cout, fmt, n, r, d / max_runs);
executed_one = true;
}
if (test == "all" || test == "4")
{
// Keep track of the time required to execute.
auto start = high_resolution_clock::now();
for (std::size_t i = 0; i != max_runs; ++i)
{
// Create a future for the whole calculation, execute it locally, and
// wait for it.
r = fibonacci_future_all(n).get();
}
std::uint64_t d = duration_cast<nanoseconds>(high_resolution_clock::now() - start).count();
constexpr char const* fmt = "fibonacci_future_all({}) == {},elapsed time:,{},[s]\n";
fmt::print(std::cout, fmt, n, r, d / max_runs);
executed_one = true;
}
if (test == "all" || test == "5")
{
// Keep track of the time required to execute.
auto start = high_resolution_clock::now();
for (std::size_t i = 0; i != max_runs; ++i)
{
// Create a Future for the whole calculation, execute it locally, and
// wait for it.
r = fibonacci_future_all_when_all(n).get();
}
std::uint64_t d = duration_cast<nanoseconds>(high_resolution_clock::now() - start).count();
constexpr char const* fmt =
"fibonacci_future_all_when_all({}) == {},elapsed time:,{},[s]\n";
fmt::print(std::cout, fmt, n, r, d / max_runs);
executed_one = true;
}
if (!executed_one)
{
std::cerr << "fibonacci_futures: wrong command line argument value for option 'tests', "
"should be either 'all' or a number between zero and 7, value specified: "
<< test << std::endl;
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
// Configure application-specific options
pika::program_options::options_description desc_commandline(
"Usage: " PIKA_APPLICATION_STRING " [options]");
using pika::program_options::value;
// clang-format off
desc_commandline.add_options()
("n-value", value<std::uint64_t>()->default_value(10),
"n value for the Fibonacci function")
("n-runs", value<std::uint64_t>()->default_value(1),
"number of runs to perform")
("threshold", value<unsigned int>()->default_value(2),
"threshold for switching to serial code")
("test", value<std::string>()->default_value("all"),
"select tests to execute (0-9, default: all)");
// clang-format on
// Initialize and run pika
pika::init_params init_args;
init_args.desc_cmdline = desc_commandline;
return pika::init(pika_main, argc, argv, init_args);
}
|
#pragma once
using namespace Jaraffe::Component;
namespace Jaraffe
{
class GameObject
{
// ****************************************************************************
// Constructor/Destructor)
// ----------------------------------------------------------------------------
private:
GameObject();
virtual ~GameObject();
public:
static GameObject* Create();
// ****************************************************************************
// Template Functions)
// ----------------------------------------------------------------------------
public:
// Component Insert
template<class _component_t>
void InsertComponent(_component_t* p_newComponent);
// Component Remove ( Map Remove And Return Remove Value )
template<class _component_t>
void RemoveComponent();
// Get Component
template<class _component_t>
_component_t* GetComponent(void);
// ****************************************************************************
// Public Functions)
// ----------------------------------------------------------------------------
public:
void Init();
void Update();
void Render();
void Release();
// ****************************************************************************
// Private Members)
// ----------------------------------------------------------------------------
private:
std::unordered_map<size_t, BaseComponent*> m_mapComponents;
};
#pragma region Template Functions
template<class _component_t>
void Jaraffe::GameObject::InsertComponent(_component_t* p_newComponent)
{
size_t componentId = get_component<_component_t>::type::GetComponentID();
if (m_mapComponents.find(componentId) != m_mapComponents.end())
m_mapComponents[componentId]->Release();
p_newComponent->SetOwner(this);
m_mapComponents[componentId] = p_newComponent;
}
template<class _component_t>
void Jaraffe::GameObject::RemoveComponent()
{
size_t componentId = get_component<_component_t>::type::GetComponentID();
auto iterFind = m_mapComponents.find(componentId);
if (iterFind == m_mapComponents.end())
return;
*iterFind->Release();
m_mapComponents.erase(iterFind);
}
template<class _component_t>
_component_t* Jaraffe::GameObject::GetComponent(void)
{
size_t componentId = get_component<_component_t>::type::GetComponentID();
if (m_mapComponents.find(componentId) == m_mapComponents.end())
return nullptr;
return reinterpret_cast<_component_t*>(m_mapComponents[componentId]);
}
#pragma endregion
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2004-2006 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Tord Akerbęk
*/
#include "core/pch.h"
#ifdef PREFS_DOWNLOAD
#include "modules/prefsloader/ploader.h"
#include "modules/prefs/prefsmanager/prefsmanager.h"
#include "modules/hardcore/mem/mem_man.h"
void PLoader::Commit()
{
if (m_has_changes)
{
TRAPD(rc, g_prefsManager->CommitL());
if (OpStatus::IsError(rc))
{
if (OpStatus::IsRaisable(rc))
{
g_memory_manager->RaiseCondition(rc);
}
}
else
{
m_has_changes = FALSE;
}
}
}
#endif
|
// ListCtrlTestView.h : CListCtrlTestView 类的接口
//
#pragma once
class CListCtrlTestView : public CListView
{
protected: // 仅从序列化创建
CListCtrlTestView();
DECLARE_DYNCREATE(CListCtrlTestView)
// 特性
public:
CListCtrlTestDoc* GetDocument() const;
afx_msg void OnPaint();
CListCtrl listCtrl;
// 操作
public:
//CListCtrl listCtrl;
// 重写
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual void OnInitialUpdate(); // 构造后第一次调用
// 实现
public:
virtual ~CListCtrlTestView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// 生成的消息映射函数
protected:
afx_msg void OnFilePrintPreview();
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
afx_msg void OnContextMenu(CWnd* pWnd, CPoint point);
//afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // ListCtrlTestView.cpp 中的调试版本
inline CListCtrlTestDoc* CListCtrlTestView::GetDocument() const
{ return reinterpret_cast<CListCtrlTestDoc*>(m_pDocument); }
#endif
|
#ifndef TEXTFIELDDESCRIPTORCONTAINER_H
#define TEXTFIELDDESCRIPTORCONTAINER_H
#include <QtGui/QWidget>
#include <QtGui/QLineEdit>
#include <QString>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include <google/protobuf/generated_message_util.h>
#include "FieldDescriptorContainer.h"
//Forward Declarations
template<class Object> class FieldDescriptorContainer;
class TextFieldDescriptorContainer : public FieldDescriptorContainer<class Object>
{
private:
QLineEdit * m_textField;
public:
TextFieldDescriptorContainer(google::protobuf::FieldDescriptor * field):FieldDescriptorContainer<Object>(field){}
~TextFieldDescriptorContainer()
{
delete m_field;
delete &m_value;
delete &m_defaultValue;
}
virtual QWidget * getWidget(QWidget * parent = 0);
virtual QWidget * getParent();
virtual Object * getValue();
virtual void setValue(Object * value);
virtual QString toString();
virtual bool buildMsg(google::protobuf::Message * msg);
};
#endif // TEXTFIELDDESCRIPTORCONTAINER_H
|
// Created on: 2001-09-12
// Created by: Alexander GRIGORIEV
// Copyright (c) 2001-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef LDOM_CDATASection_HeaderFile
#define LDOM_CDATASection_HeaderFile
#include <LDOM_Text.hxx>
// Class LDOM_CDATASection
class LDOM_CDATASection : public LDOM_Text
{
public:
// ---------- PUBLIC METHODS ----------
LDOM_CDATASection () {}
// Empty constructor
LDOM_CDATASection (const LDOM_CDATASection& theOther): LDOM_Text (theOther) {}
// Copy constructor
LDOM_CDATASection& operator = (const LDOM_NullPtr * theNull)
{ return (LDOM_CDATASection&) LDOM_CharacterData::operator = (theNull);}
// Nullify
LDOM_CDATASection& operator = (const LDOM_CDATASection& theOther)
{ return (LDOM_CDATASection&) LDOM_CharacterData::operator= (theOther);}
// Assignment
protected:
friend class LDOM_Document;
LDOM_CDATASection (const LDOM_BasicText& theText,
const Handle(LDOM_MemManager)& theDoc)
: LDOM_Text (theText, theDoc) {}
};
#endif
|
#include "HX711.h"
bool HX711::is_ready() {
return DATA == 0;
}
void HX711::set_gain(int gain) {
switch (gain) {
case 128: // channel A, gain factor 128
GAIN = 1;
break;
case 64: // channel A, gain factor 64
GAIN = 3;
break;
case 32: // channel B, gain factor 32
GAIN = 2;
break;
}
PD_SCK = 0;
}
uint32_t HX711::readRaw() {
uint32_t res = 0;
while (!is_ready());
for(int i = 0; i < 24; i++) {
PD_SCK = 1;
res = res << 1;
PD_SCK = 0;
if (DATA == 1) {
res++;
}
}
for (int i = 0; i < GAIN; i++) {
PD_SCK = 1;
PD_SCK = 0;
}
res ^= 0x00800000;
return res;
}
long HX711::read() {
return readRaw() - OFFSET;
}
long HX711::read_average(int times) {
long sum = 0;
for (int i = 0; i < times; i++) {
sum += readRaw();
}
return sum / times;
}
double HX711::get_value(int times) {
return read_average(times) - OFFSET;
}
float HX711::get_units(int times) {
return get_value(times) / SCALE;
}
void HX711::tare(int times) {
double sum = read_average(times);
set_offset(sum);
}
void HX711::set_scale(float scale) {
SCALE = scale;
}
float HX711::get_scale() {
return SCALE;
}
void HX711::set_offset(long offset) {
OFFSET = offset;
}
long HX711::get_offset() {
return OFFSET;
}
void HX711::power_down() {
PD_SCK = 0;
PD_SCK = 1;
}
void HX711::power_up() {
PD_SCK = 0;
}
|
/*
Petar 'PetarV' Velickovic
Algorithm: First-Fit Bin Packing
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
#define MID (left+right)/2
#define MAX_N 1000001
#define MAX_TREE (MAX_N << 2)
typedef long long lld;
typedef unsigned long long llu;
using namespace std;
/*
The bin packing problem attempts to put n items of sizes 0 < s_i < 1 into bins of capacity 1.
The first-fit algorithm utilises a greedy approach to the problem: it works by placing each
item into the first bin it encounters that has enough free space (potentially creating a new
bin if necessary). This implementation takes advantage of a segment tree data structure to
quickly locate the first fit (assuming we know the number of items, n, in advance).
Complexity: O(n log n) time
O(n) space
Approximation ratio: 2
*/
// the number of items to distribute
int n;
// the segment tree; it is an "almost complete" binary tree
// and hence may be represented by an array
double ST[MAX_TREE];
// We have inserted an item of size val into the x-th bin
// Toplevel call: Update(1, x, val, 1, n)
void Update(int idx, int x, double val, int left, int right)
{
if (left == right)
{
// leaf node, left == right == x
ST[idx] += val;
return;
}
// check which subtree the x-th bin belongs to and recurse
if (x <= MID) Update(2*idx, x, val, left, MID);
else Update(2*idx+1, x, val, MID+1, right);
// store the new minimum fill level of the current (sub)tree
ST[idx] = min(ST[2*idx], ST[2*idx+1]);
}
// Determine the first fit bin for a given value
// Toplevel call: Query(1, val, 1, n)
int Query(int idx, double val, int left, int right)
{
if (left == right)
{
// leaf node: we have found the first-fit bin!
return left;
}
// check whether the left subtree contains a fitting bin
if (ST[2*idx] <= 1.0 - val) return Query(2*idx, val, left, MID);
else return Query(2*idx+1, val, MID+1, right);
}
// Fit an item of size val
inline void FirstFit(double val)
{
int first_fit = Query(1, val, 1, n);
Update(1, first_fit, val, 1, n);
printf("Placed item of value %lf in bin ID %d!\n", val, first_fit);
}
int main()
{
scanf("%d", &n);
for (int i=0;i<n;i++)
{
double curr;
scanf("%lf", &curr);
FirstFit(curr);
}
return 0;
}
|
#include <iostream>
#include <vector>
#include <tuple>
#include "MatlabEngine.hpp"
#include "MatlabDataArray.hpp"
#include "octonav/visualize.hpp"
using namespace std;
using namespace octomap;
using matlab::data::Array;
std::unique_ptr<matlab::engine::MATLABEngine> mlp = matlab::engine::startMATLAB();
tuple<Array, Array, Array> vectorToXYZ(const std::vector<point3d> &path){
vector<double> x;
vector<double> y;
vector<double> z;
for (auto p : path)
{
x.push_back(p.x());
y.push_back(p.y());
z.push_back(p.z());
}
matlab::data::ArrayFactory f;
matlab::data::Array xp_arr = f.createArray({x.size()}, x.begin(), x.end());
matlab::data::Array yp_arr = f.createArray({y.size()}, y.begin(), y.end());
matlab::data::Array zp_arr = f.createArray({z.size()}, z.begin(), z.end());
return {xp_arr, yp_arr, zp_arr};
}
void visualize(OcTree &octree, const std::vector<point3d> &path1, const std::vector<point3d> &path2)
{
octree.writeBinary("/home/damow/octomap-navigation/out/tmp.bt");
mlp->eval(u"map = importOccupancyMap3D('/home/damow/octomap-navigation/out/tmp.bt');");
auto [x1, y1, z1] = vectorToXYZ(path1);
auto [x2, y2, z2] = vectorToXYZ(path2);
mlp->setVariable(u"x1", std::move(x1));
mlp->setVariable(u"y1", std::move(y1));
mlp->setVariable(u"z1", std::move(z1));
mlp->setVariable(u"x2", std::move(x2));
mlp->setVariable(u"y2", std::move(y2));
mlp->setVariable(u"z2", std::move(z2));
mlp->eval(u"figure;");
mlp->eval(u"show(map);");
mlp->eval(u"hold on;");
mlp->eval(u"q = plot3(x1,y1,z1, 'r-', 'LineWidth', 5);");
mlp->eval(u"q = plot3(x2,y2,z2, 'm-', 'LineWidth', 5);");
mlp->eval(u"axis tight");
mlp->eval(u"camlight headlight");
mlp->eval(u"saveas(gcf,'/home/damow/octomap-navigation/out/viz.png')");
}
|
#ifndef SOLVERPROPERTYWIDGET_H
#define SOLVERPROPERTYWIDGET_H
//--------------------------------------------------------------------------------------------------------------
#include <QWidget>
#include <QLabel>
#include <QDoubleSpinBox>
#include <QGridLayout>
#include <QPushButton>
#include <memory>
#include "FluidSystem/fluidsystem.h"
#include "FluidSystem/fluidsolverproperty.h"
//--------------------------------------------------------------------------------------------------------------
/// @author Idris Miles
/// @version 1.0
/// @date 01/06/2017
//--------------------------------------------------------------------------------------------------------------
namespace Ui {
class SolverPropertyWidget;
}
/// @class SolverProperyWidget
/// @brief Inherits from QWidget. Widget for manipulating FluidSolverProperty class.
class SolverPropertyWidget : public QWidget
{
Q_OBJECT
public:
/// @brief comnstructor
explicit SolverPropertyWidget(QWidget *parent = 0, FluidSolverProperty _property = FluidSolverProperty());
/// @brief destructor
virtual ~SolverPropertyWidget();
/// @brief Setter for the m_property attribute
virtual void SetProperty(const FluidSolverProperty &_property);
/// @brief Geter for the m_property attribute
virtual FluidSolverProperty GetProperty() const;
signals:
/// @brief Qt Signal to communicate that the FluidProperty has changed to other classes
void PropertyChanged(const FluidSolverProperty &_property);
public slots:
/// @brief Qt Slot to be connected to any changes on this widget, emits PropertyChanged(m_property)
virtual void OnPropertyChanged();
private:
Ui::SolverPropertyWidget *ui;
FluidSolverProperty m_property;
};
//--------------------------------------------------------------------------------------------------------------
#endif // SOLVERPROPERTYWIDGET_H
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
typedef long long LL;
const int mov[4][2] = {0,1,-1,0,0,-1,1,0};
int G[110][110],x[110],y[110],p[110];
int main() {
int t;
int r,c,n,m;char ch;
scanf("%d",&t);
while (t--) {
scanf("%d%d%d%d",&r,&c,&n,&m);
memset(G,0,sizeof(G));
for (int i = 1;i <= n; i++) {
scanf("%d%d%*c%c",&x[i],&y[i],&ch);
if (ch == 'N') p[i] = 0;
else if (ch == 'W') p[i] = 1;
else if (ch == 'S') p[i] = 2;
else p[i] = 3;
G[x[i]][y[i]] = i;
}
bool ok = true;
int w,re;
while (m--) {
scanf("%d%*c%c%d",&w,&ch,&re);
while (re-- && ok) {
if (ch == 'L') p[w] = (p[w] + 1)%4;
if (ch == 'R') p[w] = (p[w] + 3)%4;
if (ch == 'F') {
G[x[w]][y[w]] = 0;
x[w] += mov[p[w]][0];y[w] += mov[p[w]][1];
if (x[w] < 1 || x[w] > r || y[w] < 1 || y[w] > c) {
printf("Robot %d crashes into the wall\n",w);
ok = false;
} else if (G[x[w]][y[w]]) {
printf("Robot %d crashes into robot %d\n",w,G[x[w]][y[w]]);
ok = false;
} else G[x[w]][y[w]] = w;
//cout << x[w] << " " << y[w] << endl;
}
}
}
if (ok) puts("OK");
}
return 0;
}
|
#ifndef CIRCLE_HELPER_H
#define CIRCLE_HELPER_H
#define GLM_FORCE_RADIANS
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <vector>
#include <fstream> // std::ifstream
#include <iostream>
#include <utility>
namespace CircleHelper{
std::vector<glm::dvec4> getCircle(glm::dvec3 _center, glm::dvec3 _normal, double _degrees, size_t _number_of_points = 256);
double getDegrees(glm::dvec3 _vector, glm::dvec3 _normal, const glm::dvec3& _center = glm::dvec3(0,0,0));
double getDegrees(glm::dvec3 _vector, const std::vector<glm::dvec4> &_circle, const glm::dvec3& _center = glm::dvec3(0,0,0));
/*!
\brief Triangulation with defined number of points and given opening angle
\param _center Origin of the circle
\param _degrees Opening angle of the circle, with which you define the radius
\param _normal Normal of circle to estimate the rotation
\param _number_of_points Number of points to sample and triangulate in the circle
\return A pair of glm::dvec4 vertices vector and glm::ivec3 indices vector which represent the circle
The function creates points in a circle wrt. the center which describes the origin of the circle, \
the normal which is being used to rotate the 2D circle in the 3D space, the degrees which describes the \
opening angle, with that the radius will be estimated and the number of points, which will be sampled and \
triangulated. For the triangulation, the Fade2D library is being used, which implements the delauney \
triangulation.
*/
std::pair<std::vector<glm::dvec4>, std::vector<glm::ivec3>> getTriangulationOfCircle(glm::dvec3 _center, glm::dvec3 _normal, double _degrees, size_t _number_of_points = 256);
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.