text
stringlengths 8
6.88M
|
|---|
#include <SPI.h>
#define SS PA4
static const int spiClk = 250000; // 250kHz
auto& ser = Serial1;
void setup() {
pinMode(SS, OUTPUT);
digitalWrite(SS, HIGH);
ser.begin(115200);
ser.println("Hello from stm32 spi master");
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV8);//divide the clock by 8
}
void loop() {
byte data = 0b01010101; // junk data to illustrate usage
digitalWrite(SS, LOW); //pull SS slow to prep other end for transfer
int res = SPI.transfer(data);
digitalWrite(SS, HIGH); //pull ss high to signify end of data transfer
ser.print("stm32 master: slave returned: ");
ser.println(res);
delay(1000);
}
|
#include <QNetworkDatagram>
#include <QDebug>
#include <QNetworkInterface>
#include <QNetworkConfiguration>
#include "udpfinderclient.h"
UdpFinderClient::UdpFinderClient(QHostAddress address, QObject *parent) : QObject(parent)
{
m_udpSocket.bind(address, 5556);
m_myAddress = address;
connect(&m_udpSocket, SIGNAL(readyRead()), this, SLOT(dataRecieved()));
connect(&m_timer, SIGNAL(timeout()), this, SLOT(timerElapsed()));
m_timer.start(2000);
timerElapsed();
}
void UdpFinderClient::timerElapsed()
{
QNetworkDatagram datagramm;
datagramm.setSender(m_myAddress, 5556);
datagramm.setDestination(QHostAddress::Broadcast, 5555);
datagramm.setData("hello");
m_udpSocket.writeDatagram(datagramm);
}
void UdpFinderClient::dataRecieved()
{
while (m_udpSocket.hasPendingDatagrams())
{
QNetworkDatagram datagram = m_udpSocket.receiveDatagram();
QByteArray data = datagram.data();
//qDebug() << "Client: find server " << datagram.senderAddress().toString() << data.length();
if(data.length() != static_cast<int>(sizeof(UdpSendData)))
continue;
UdpSendData *structData = reinterpret_cast<UdpSendData *>(data.data());
ESPDeviceInformation deviceInformation;
deviceInformation.setAddress(datagram.senderAddress().toString());
deviceInformation.setId(structData->id);
deviceInformation.setType(structData->type);
deviceInformation.setName(QString::fromUtf8(reinterpret_cast<const char*>(structData->deviceName), structData->deviceNameSize));
emit searchDone(&deviceInformation);
// qDebug() << "Client: find server " << datagram.senderAddress().toString() << data.length();
}
}
|
#include "StdAfx.h"
#include "NumWalker.h"
#include <algorithm>
using namespace std;
NumWalker::NumWalker(void)
{
counter = 0;
face = 'N';
skin = 6;
}
NumWalker::~NumWalker(void)
{
}
void NumWalker::step()
{
counter--;
}
void NumWalker::takeInput(char in)
{
if(counter < 1 && in >= '1' && in <= '9')
{
counter = 10;
int newX = getMyX();
int newY = getMyY();
if(in % 3 == 1)
{
newX--;
}
else if(in % 3 == 0)
{
newX++;
}
if(in < '4')
{
newY++;
}
else if(in > '6')
{
newY--;
}
newX = max(min(newX, 5), 0);
newY = max(min(newY, 5), 0);
bool debug = here->tryToMoveToCell(here->getDungeon()->getCell(newX, newY), false);
int x = 1;
}
}
|
#include "movie.h"
#include <iostream>
#include <cstring>
using namespace std;
// Constructor
Movie::Movie(char* _director, char* _duration, char* _rating, char* _year, char* _title):Media() {
director = new char[24];
rating = new char[24];
duration = new char[10];
strcpy(director, _director);
strcpy(rating, _rating);
strcpy(duration, _duration);
strcpy(title, _title);
strcpy(year, _year);
id = 3;
}
// Deconstructor
Movie::~Movie(){
delete [] director;
delete [] duration;
delete [] rating;
}
// Accessors
char* Movie::getDirector() {
return director;
}
char* Movie::getDuration() {
return duration;
}
char* Movie::getRating() {
return rating;
}
void Movie::printInfo(){
cout << "MOVIE |" << " Title: " << title << " / Year: " << year << " / Director: " << director << " / Duration: " << duration << " / Rating: " << rating << endl;
}
|
#include "Ray.h"
#include <cfloat>
Ray::Ray(Vector3 vOrg, Vector3 vDir){
Origin = vOrg;
Direction = vDir;
t = FLT_MAX;
}
|
#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <ctime>
#include <fstream>
void game_play(std::vector<int> vector)
{
for (int i = 0; i < vector.size(); i++)
{
std::cout << vector[i] << std::endl;
}
}
void play_game()
{
std::vector<int> guesses;
int count = 0;
int random = rand() % 16;
std::cout << random;
while (true)
{
int ur_guess;
std::cin >> ur_guess;
guesses.push_back(ur_guess);
count++;
//guesses[count++] = ur_guess;
if (ur_guess == random)
{
std::cout <<"you got it!!"<<std::endl;
break;
}else if (ur_guess < random)
{
std::cout << "Pls try a higher number \n";
}else
{
std::cout << "Pls try a lower number \n";
}
//to sotore the highest score,
std::ifstream input("high_scored_list.txt");
int high_score;
input >> high_score;
std::ofstream output("high_scored_list.txt");
if (count < high_score)
{
output << count;
}else
{
output << high_score;
}
game_play(guesses);
}
}
int main ()
{
srand(time(NULL));
int any_guess;
do
{
std::cout << "press 0 to quit or 1 to continue \t";
std::cin >> any_guess;
switch (any_guess)
{
case 0:
std::cout << "you r quitting \n";
return 0;
case 1:
play_game();
// std::cout << " game continuies... \n";
break;
default:
break;
}
} while (any_guess != 0);
}
|
// Copyright (c) 2020 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 _Image_SupportedFormats_HeaderFile
#define _Image_SupportedFormats_HeaderFile
#include <Image_CompressedFormat.hxx>
#include <NCollection_Array1.hxx>
#include <Standard_Type.hxx>
//! Structure holding information about supported texture formats.
class Image_SupportedFormats : public Standard_Transient
{
DEFINE_STANDARD_RTTIEXT(Image_SupportedFormats, Standard_Transient)
public:
//! Empty constructor.
Standard_EXPORT Image_SupportedFormats();
//! Return TRUE if image format is supported.
bool IsSupported (Image_Format theFormat) const { return myFormats.Value (theFormat); }
//! Set if image format is supported or not.
void Add (Image_Format theFormat) { myFormats.SetValue (theFormat, true); }
//! Return TRUE if there are compressed image formats supported.
bool HasCompressed() const { return myHasCompressed; }
//! Return TRUE if compressed image format is supported.
bool IsSupported (Image_CompressedFormat theFormat) const { return myFormats.Value (theFormat); }
//! Set if compressed image format is supported or not.
void Add (Image_CompressedFormat theFormat)
{
myFormats.SetValue (theFormat, true);
myHasCompressed = true;
}
//! Reset flags.
void Clear()
{
myFormats.Init (false);
myHasCompressed = false;
}
protected:
NCollection_Array1<bool> myFormats; //!< list of supported formats
Standard_Boolean myHasCompressed; //!< flag indicating that some compressed image formats are supported
};
#endif // _Image_SupportedFormats_HeaderFile
|
/* leetcode 498
*
*
*
*/
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
int row = matrix.size();
if (row == 0) {
vector<int> ans;
return ans;
}
int col = matrix.at(0).size();
vector<int> ans;
int sums = row + col - 2;
int cnt = 0;
for (int sum = 0; sum <= sums; sum++) {
vector<int> tmp;
for (int i = 0; i < row; i++) {
int j = sum - i;
if (j < col && j >= 0) {
tmp.push_back(matrix[i][j]);
}
}
cnt++;
if (cnt % 2 == 1) {
reverse(tmp.begin(), tmp.end());
}
for (int n = 0; n < tmp.size(); n++) {
ans.push_back(tmp.at(n));
}
}
return ans;
}
};
/************************** run solution **************************/
vector<int> _solution_run(vector<vector<int>>& matrix)
{
Solution leetcode_498;
return leetcode_498.findDiagonalOrder(matrix);
}
#ifdef USE_SOLUTION_CUSTOM
vector<vector<int>> _solution_custom(TestCases &tc)
{
return {};
}
#endif
/************************** get testcase **************************/
#ifdef USE_GET_TEST_CASES_IN_CPP
vector<string> _get_test_cases_string()
{
return {};
}
#endif
|
#include <GL/glut.h>
#include<math.h>
#include <stdio.h>
#include <stdlib.h>
int clicks = 0,x0,y,cenX,cenY,a=40,b=80;
void DrawEllipse(int x0, int y0){
glColor3f(0.0, 0.0, 0.0);
glPointSize(2.0);
float p1 = b*b+a*a/4-a*a*b;
float dx, dy;
float x = 0;
float y = b;
float p2 = ((b * b) * ((x + 0.5) * (x + 0.5))) + ((a * a) * ((y - 1) * (y - 1))) - (a * a * b * b);
dx = 2*b*b*x;
dy = 2*a*a*y;
glBegin(GL_POINTS);
while (b*b*x < a*a*y)
{
x++;
if (p1 < 0)
{
dx = dx + (2 * b * b);
p1 = p1 + dx + (b * b);
}
else
{
y--;
dx = dx + (2 * b * b);
dy = dy - (2 * a * a);
p1 = p1 + dx - dy + (b * b);
}
glVertex2i(x + x0, y + y0);
glVertex2i(-x + x0, y + y0);
glVertex2i(x + x0, -y + y0);
glVertex2i(-x + x0, -y + y0);
}
glEnd();
glBegin(GL_POINTS);
while (1)
{
y--;
if (p2 > 0)
{
dy = dy - (2 * a * a);
p2 = p2 + (a * a) - dy;
}
else
{
x++;
dx = dx + (2 * b * b);
dy = dy - (2 * a * a);
p2 = p2 + dx - dy + (a * a);
}
glVertex2i(x + x0, y + y0);
glVertex2i(-x + x0, y + y0);
glVertex2i(x + x0, -y + y0);
glVertex2i(-x + x0, -y + y0);
if(y<0)
break;
}
glEnd();
glFlush();
}
void plot(int p, int q){
glBegin(GL_POINTS);
glVertex2f(p,q);
glEnd();
}
void mouse1(int button, int state, int mousex, int mousey)
{
if(button==GLUT_LEFT_BUTTON && state==GLUT_UP)
{
clicks++;
x0 = mousex;
y = 480-mousey;
cenX = mousex;
cenY = 480-mousey;
glColor3f(0,0,0);
}
glutPostRedisplay();
}
void mouse2(int button, int state, int mousex, int mousey)
{
if(button==GLUT_LEFT_BUTTON && state==GLUT_UP)
{
clicks++;
x0 = mousex;
y = 480-mousey;
cenX = mousex;
cenY = 480-mousey;
glColor3f(0,0,0);
}
glutPostRedisplay();
}
void midPointCircle(int x0, int y0) {
glColor3f(1.0, 1.0, 1.0);
glPointSize(2.0);
float r = 80;
float x = 0, y = r;
float p = 1 - r;
glBegin(GL_POINTS);
while (x != y)
{
x++;
if (p < 0) {
p += 2 * (x + 1) + 1;
}
else {
y--;
p += 2 * (x + 1) + 1 - 2 * (y - 1);
}
glVertex2i(x+x0, y+y0);
glVertex2i(-x+x0, y+y0);
glVertex2i(x+x0, -y+y0);
glVertex2i(-x+x0, -y+y0);
glVertex2i(y+x0, x+y0);
glVertex2i(-y+x0, x+y0);
glVertex2i(y+x0, -x+y0);
glVertex2i(-y+x0, -x+y0);
}
glEnd();
glFlush();
}
void display1()
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0.0, 0.0, 0.0, 0.0);
glColor3f(1,1, 1);
char* st1= "Circle ";
glRasterPos2i(260, 450);
for( int i=0; i<strlen(st1); i++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, st1[i]);
}
char* st= "Parth Miglani 500067488";
glRasterPos2i(165, 425);
for( int i=0; i<strlen(st); i++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, st[i]);
}
char* st3= "Center of circle = ";
glRasterPos2i(250, 50);
for( int i=0; i<strlen(st3); i++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, st3[i]);
}
char buffer[10]={"\0"};
sprintf(buffer,"%d",cenX);
char buffer1[10]={"\0"};
sprintf(buffer1,"%d",cenY-2*cenY);
glRasterPos2i(450, 50);
for( int i=0; i<strlen(buffer); i++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, buffer[i]);
}
for( int i=0; i<strlen(buffer1); i++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, buffer1[i]);
}
if(clicks)
midPointCircle(x0,y);
glFlush();
}
void display2()
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(1, 1, 1.0, 0);
if(clicks)
DrawEllipse(x0,y);
glColor3f(0, 0, 0);
char* st1= "Ellipse";
glRasterPos2i(250, 450);
for( int i=0; i<strlen(st1); i++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, st1[i]);
}
char* st= "Parth Miglani 500067488";
glRasterPos2i(150, 425);
for( int i=0; i<strlen(st); i++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, st[i]);
}
char* st3= "Center of ellipse = ";
glRasterPos2i(250, 50);
for( int i=0; i<strlen(st3); i++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, st3[i]);
}
char buffer[10]={"\0"};
sprintf(buffer,"%d",cenX);
char buffer1[10]={"\0"};
sprintf(buffer1,"%d",cenY-2*cenY);
glRasterPos2i(450, 50);
for( int i=0; i<strlen(buffer); i++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, buffer[i]);
}
for( int i=0; i<strlen(buffer1); i++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, buffer1[i]);
}
glColor3f(1.0, 1.0, 1.0);
glFlush();
}
void displayMain(void)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
glFlush();
}
void keyboard(unsigned char key, int mousex, int mousey){
if(key==27){
exit(0);
}
}
int main(int argc,char** argv)
{
glutInit(&argc,argv);
glutInitWindowSize(1290,500);
glutInitWindowPosition(0,0);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
int mw = glutCreateWindow("Lab 5 : Circle and Ellipse");
glutDisplayFunc(displayMain);
int sw1 = glutCreateSubWindow(mw, 0, 10, 640, 480);
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
glClearColor(0.0, 0.0, 0.0, 1.0);
glutDisplayFunc(display1);
glutMouseFunc(mouse1);
int sw2 = glutCreateSubWindow(mw, 640 + 10, 10, 640, 480);
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
glClearColor(1.0, 1.0, 1.0, 1.0);
glutDisplayFunc(display2);
glutMouseFunc(mouse2);
glutKeyboardFunc(keyboard);
glutMainLoop();
}
|
#ifndef RRG_FRAMERATE_H
#define RRG_FRAMERATE_H
#include "interval.h"
namespace RRG {
class FrameRate {
public:
FrameRate();
virtual ~FrameRate();
void Update() {
// increase the counter by one
m_fpscount++;
// one second elapsed? (= 1000 milliseconds)
if (m_fpsinterval.value() > 1000) {
// save the current counter value to m_fps
m_fps = m_fpscount;
// reset the counter and the interval
m_fpscount = 0;
m_fpsinterval = Interval();
}
}
unsigned int Get() const {
return m_fps;
}
private:
protected:
unsigned int m_fps;
unsigned int m_fpscount;
Interval m_fpsinterval;
};
}
#endif
|
#pragma once
#include "plbase/PluginBase.h"
#pragma pack(push,4)
class PLUGIN_API CReference
{
public:
class CReference *m_pNext;
class CEntity **m_ppEntity;
};
#pragma pack(pop)
VALIDATE_SIZE(CReference, 8);
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int hIndex(vector<int>& citations) {
//ๅบๆฌๆๆณ๏ผไบๅๆฅๆพ
int res=0;
int n=citations.size();
int low=0,high=n-1;
while(low<=high)
{
int mid=(low+high)/2;
cout<<mid<<endl;
if(citations[mid]>=n-mid)
{
res=n-mid;
high=mid-1;
}
else
low=mid+1;
}
return res;
}
};
int main()
{
Solution solute;
vector<int> num={0,1,1,3,3,5,6};
cout<<solute.hIndex(num)<<endl;
return 0;
}
|
#include "Shape.h"
namespace Shapez
{
}
|
#include <string>
#include <iostream>
#include <cstring>
// e : ํ์ฌ ๊ณ๋ ๊ฐ๊ฒฉ (1 <= e <= 10^14)
// ์ด์ ๊ณ๋ ๊ฐ๊ฒฉ์ m ์ ๋ฐฐ์ (2 <= m <= 20)
// ์ถ๋ ฅ์, ๊ฐ๋ฅํ ๊ฐ๊ฒฉ์ ์๋ฅผ 1,000,000,007๋ก ๋๋ ๋๋จธ์ง
std::string e;
//e ์์ ์ค๋ณต๋๋ ์ซ์๊ฐ ์์ ๋ ๊ฐ์ฅ ๋จผ์ ์ค๋ ๊ฒ๋ง ๊ณ์ฐ ํ๊ธฐ ์ํด
//e์ ์๋ฆฟ์๋ฅผ ์ ๋ ฌ ํ ๊ฒ
std::string digits;
// e์ ์๋ฆฟ์
int n;
int m;
const int MOD = 1000000007;
int cache[1<<14] [20] [2];
// e์ ์๋ฆฟ์๋ฅผ ์ฌ๋ฐฐ์ด ํ์ฌ, ๋ง๋ค ์ ์๋ ๊ฐ๊ฒฉ๋ค์ ์ ๋ถ ๋ง๋๋ ์์ ํ์ ์๊ณ ๋ฆฌ์ฆ
// price : ์ง๊ธ๊น์ง ๋ง๋ ๊ฐ๊ฒฉ
// taken : ์๋ฆฟ์๊ฐ ์ฌ์ฉ ๋์๋์ง ์ฌ๋ถ
void generate(std::string price, bool taken[15])
{
//๊ธฐ์ ์ฌ๋ก
// e์ ์๋ฆฟ์๋ก ๋ง๋ค ์ ์๋ ์ซ์๋ค์ ๋ชจ๋ ์ถ๋ ฅํ๋ค.
// ์ง๊ธ ๋ง๋ค์ด์ง ์ซ์(e์ ์ด๋ฃจ์ด์ง ๋ฌธ์์ด์ ์กฐํฉ) ์ ์๋ฆฟ์๊ฐ e์ ์๋ฆฟ์์ ์ผ์น
if (price.size() == n)
{
// ํ์ฌ ๊ฐ๊ฒฉ ๋ณด๋ค ์ ์ด์ผ ํจ
if (price < e)
std::cout << price << std::endl;
return;
}
for (int i = 0; i < n ; i++)
{
// ์ด๋ฒ์ ์ฌ์ฉํ ์๋ฆฟ์ ๋ฐ๋ก ์์๋ฆฌ๊ฐ ์๊ฑฐ๋, i ==0
// ์ด๋ฒ ์๋ฆฟ์๋ ๋ค๋ฅด๊ฑฐ๋
// ์ด๋ฏธ ์ฌ์ฉ๋ ๊ฒฝ์ฐ
std::cout << "taken[" << i << "]" << taken[i] << std::endl;
if ( !taken[i] && (i == 0 || digits[i-1] != digits[i] || taken[i-1]))
{
// ํ์ฌ ์๋ฆฟ์ ์ฌ์ฉํด๋ ๋จ
std::cout <<" "<<std::endl;
taken[i] = true;
generate(price + digits[i], taken);
taken[i] = false;
}
}
}
// ๊ณผ๊ฑฐ ๊ฐ๊ฒฉ์ ์์๋ฆฌ ๋ถํฐ ์ฑ์ ๋๊ฐ. ์์๋ฆฌ๊ฐ ์์์ง ํฐ์ง ๋น๊ต
// index : ์ด๋ฒ์ ์ฑ์ธ ์๋ฆฟ์์ ์ธ๋ฑ์ค
// taken : ์ง๊ธ๊น์ง ์ฌ์ฉํ ์๋ฆฟ์๋ค์ ์งํฉ
// mod : ์ง๊ธ๊น์ง ๋ง๋ ๊ฐ๊ฒฉ์ m์ ๋ํ ๋๋จธ์ง
// less : ์ง๊ธ๊น์ง ๋งใท๋ ๊ฐ๊ฒฉ์ด ์ด๋ฏธ e๋ณด๋ค ์์ผ๋ฉด 1, ์๋๋ฉด 0
int price(int index, int taken, int mod, int less)
{
//๊ธฐ์ ์ฌ๋ก
// ์ด๋ฒ์ ์ฑ์ธ ์๋ฆฟ์๊ฐ ์ ์ฒด ์๋ฆฟ์์ ์ผ์น ํ ๊ฒฝ์ฐ
if (index == n)
{
// m์ ๋ฐฐ์์ด๊ฑฐ๋ e๋ณด๋ค ์์ ๊ฒฝ์ฐ
return (less && mod == 0) ? 1: 0;
}
int &ret = cache [taken][mod][less];
if (ret != -1) return ret;
ret = 0;
for (int next = 0; next < n; next++)
{
if ((taken & (1<<next)) == 0)
{
// ๊ณผ๊ฑฐ ๊ฐ๊ฒฉ์ ํญ์ ์ ๊ฐ๊ฒฉ ๋ณด๋ค ์์์ผ ํ๋ค.
//์ง๊ธ๊น์ง ๋ง๋ ๊ฐ๊ฒฉ์ด e ๋ณด๋ค ์๊ณ
// && e์ index ๋ digits ์ ๋ค์ ๋ณด๋ค ์์์ผ ํจ(e=3124 ์ด๋ฉด price =31 ๋ค์ 4 ๋ชป์ด)
if (!less && e[index] < digits[next])
continue;
//๊ฐ์ ์ซ์๋ ํ๋ฒ๋ง ์ ํ
if (next > 0 && digits[next -1] == digits[next] && (taken & (1<<(next-1)))== 0)
continue;
int nextTaken = taken | (1<<next);
int nextMod = (mod *10 + digits[next] - '0' ) %m;
int nextLess = less|| e[index] > digits[next];
ret += price(index+1, nextTaken, nextMod, nextLess);
ret %= MOD;
}
}
return ret;
}
int main(void)
{
std::cout<<"9.16 generate" <<std::endl;
std::cout <<"e = 321" << std::endl;
e = "321";
digits = "123";
n = 3;
std::string price = "";
bool taken[15];
std::memset(taken, 0, sizeof(bool)*15);
generate(price, taken);
return 1;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser.
** It may not be distributed under any circumstances.
*/
#ifndef VISITEDSEARCH_H
#define VISITEDSEARCH_H
#include "modules/search_engine/Cursor.h"
#include "modules/search_engine/ResultBase.h"
#include "modules/search_engine/Vector.h"
#include "modules/search_engine/RankIndex.h"
#include "modules/hardcore/mh/mh.h"
#if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
#include "modules/search_engine/log/Log.h"
#endif
#ifdef SEARCH_ENGINE_PHRASESEARCH
#include "modules/search_engine/PhraseSearch.h"
#endif
#define RANK_TITLE 0.5F
#define RANK_H1 0.6F
#define RANK_H2 0.7F
#define RANK_H3 0.8F
#define RANK_H4 0.85F
#define RANK_H5 0.88F
#define RANK_H6 0.89F
#define RANK_I 0.9F
#define RANK_EM 0.91F
#define RANK_P 0.95F
class RecordHandleRec;
struct FileWord;
/**
* @brief fulltext indexing/searching designed to hold URLs
* @author Pavel Studeny <pavels@opera.com>
*/
class VisitedSearch : public MessageObject, private NonCopyable
{
public:
/** handle to create a record for a URL */
typedef RecordHandleRec *RecordHandle;
VisitedSearch(void);
~VisitedSearch(void)
{
OP_ASSERT(m_pending.GetCount() == 0);
if (m_index.GetCount() != 0)
OpStatus::Ignore(Close());
}
/**
* change the maximum size of the index;
* depending on the size and flush phase, the change may not come into effect immediately
* @param max_size new index size in MB
*/
void SetMaxSize(OpFileLength max_size);
/**
* change the maximum size to contain approximately max_items.
* Could be analyzed later, because mapping to history items is not always 1:1 this could be improved.
* @param max_items maximal number of items the full index should roughly contain
*/
void SetMaxItems(int max_items);
#ifdef SELFTEST
void SetSubindexSize(OpFileLength ssize) {m_subindex_size = ssize;}
#endif
/**
* Open/create the index in the given directory.
* Must be called before using other methods except IsOpen.
* @param directory full path without terminating path separator
*/
CHECK_RESULT(OP_STATUS Open(const uni_char *directory));
/**
* flush all cached data and closes all resources
* @param force_close close all resources even if all operations cannot be completed e.g. because out of disk space
* @return if force_close was set, returns error anyway, but the resources are released
*/
CHECK_RESULT(OP_STATUS Close(BOOL force_close = TRUE));
BOOL IsOpen(void)
{
return m_index.GetCount() > 0;
}
/**
* erase all data
* @param reopen if FALSE, close the index when all data is cleared
*/
CHECK_RESULT(OP_STATUS Clear(BOOL reopen = TRUE));
/*** indexing part ***/
/**
* Open a new record for writing. Not closing the record by CloseRecord or AbortRecord is evil.
* VisitedSearch must be opened before using this method.
* @param url address of the topmost document in the current window
* @param title the <title> tag from the header of the document
* @return 0 on out of memory or if indexing is disabled/uninitialized
*/
RecordHandle CreateRecord(const char *url, const uni_char *title = NULL);
/**
* add the title of the document if it wasn't available at the time of CreateRecord
* @param handle handle created by CreateRecord
* @param title the <title> tag from the header of the document
*/
CHECK_RESULT(OP_STATUS AddTitle(RecordHandle handle, const uni_char *title));
/**
* add a block of text with the same ranking
* @param handle handle created by CreateRecord
* @param text plain text words
* @param ranking float value from an open interval of (0, 1), should be one of the RANK_XXX
* @param is_contination if TRUE, this text block should be considered a continuation of the previous
*/
CHECK_RESULT(OP_STATUS AddTextBlock(RecordHandle handle, const uni_char *text, float ranking, BOOL is_continuation = FALSE));
/**
* make the data available for writing, no further changes will be possible
* @param handle handle created by CreateRecord
* @return aborts the record on error
*/
CHECK_RESULT(OP_STATUS CloseRecord(RecordHandle handle));
/**
* cancel insertion of this document to the index, handle becomes invalid after this
* @param handle handle created by CreateRecord
*/
void AbortRecord(RecordHandle handle);
/**
* attach a small picture of the document
* @param url URL of existing record created by CreateRecord
* @param picture data in a format known to the caller
* @param size size of the picture in bytes
*/
CHECK_RESULT(OP_STATUS AssociateThumbnail(const char *url, const void *picture, int size));
/**
* associate a locally saved copy of the web page with the current handle
* @param url URL of existing record created by CreateRecord
* @param fname full path to a single file
*/
CHECK_RESULT(OP_STATUS AssociateFileName(const char *url, const uni_char *fname));
/**
* begin transaction and prepare data from the cache to be written to disk;
* all Inserts or Deletes until Commit will not be included in this transaction;
* an error cancels the whole transaction and the data are returned back to cache
*
* @param max_ms maximum time to spend by PreFlush in miliseconds, 0 means unlimited
* @return OpBoolean::IS_TRUE if finished successfully, OpBoolean::IS_FALSE if time limit was reached (call PreFlush again)
* @see BlockStorage for more information about the transaction modes
*/
CHECK_RESULT(OP_BOOLEAN PreFlush(int max_ms = 0));
/**
* write the data prepared by PreFlush;
* calling PreFlush before Flush is optional, but a delay (roughly 30s) between PreFlush and Flush
* reduces the time spent in operating system calls;
* an error cancels the whole transaction and the data are returned back to cache
*
* @param max_ms maximum time to spend by PreFlush in miliseconds, 0 means unlimited
* @return OpBoolean::IS_TRUE if finished successfully, OpBoolean::IS_FALSE if time limit was reached (call Flush again)
*/
CHECK_RESULT(OP_BOOLEAN Flush(int max_ms = 0));
/**
* finish the transaction begun by PreFlush;
* calling Flush before Commit is optional, but a delay (roughly 30s) between Flush and Commit
* reduces the time spent in operating system calls
* @return not supposed to fail under normal circumstances if Flush was called and finished successfully
*/
CHECK_RESULT(OP_STATUS Commit(void));
/*** searching part ***/
enum Sort
{
RankSort, /**< sort the results by ranking, best ranking first */
DateSort, /**< sort the results by date, latest date first */
Autocomplete /**< like RankSort, but no results for empty query */
};
/** one row of a result */
struct Result
{
char *url;
uni_char *title;
unsigned char *thumbnail;
int thumbnail_size;
uni_char *filename;
time_t visited;
float ranking;
#ifndef SELFTEST
protected:
#endif
UINT32 id; // for sorting purposes
bool invalid;
UINT16 prev_idx;
UINT32 prev;
UINT16 next_idx;
UINT32 next;
mutable uni_char *plaintext;
mutable unsigned char *compressed_plaintext;
mutable int compressed_plaintext_size;
friend class RankIterator;
friend class AllDocIterator;
friend class TimeIterator;
friend class VisitedSearch;
friend class FastPrefixIterator;
public:
Result(void);
CHECK_RESULT(OP_STATUS SetCompressedPlaintext(const unsigned char *buf, int size));
uni_char *GetPlaintext() const;
BOOL operator<(const Result &right) const
{
float s, a;
s = ranking - right.ranking;
a = (ranking + right.ranking) / 100000.0F;
if (s < a && s > -a)
{
if (id == (UINT32)-1 && right.id == (UINT32)-1)
{
if (visited == right.visited)
return op_strcmp(url, right.url) != 0;
return visited > right.visited;
}
return id < right.id;
}
return s < 0.0;
}
CHECK_RESULT(static OP_STATUS ReadResult(Result &res, BlockStorage *metadata));
static BOOL Later(const void *left, const void *right);
static BOOL CompareId(const void *left, const void *right);
static void DeleteResult(void *item);
CHECK_RESULT(static OP_STATUS Assign(void *dst, const void *src));
#ifdef ESTIMATE_MEMORY_USED_AVAILABLE
static size_t EstimateMemoryUsed(const void *item);
#endif
};
struct SearchSpec
{
OpString query;
Sort sort_by;
int max_items;
int max_chars;
OpString start_tag;
OpString end_tag;
int prefix_ratio;
};
struct SearchResult : public NonCopyable
{
OpString8 url;
OpString title;
unsigned char *thumbnail;
int thumbnail_size;
OpString filename;
OpString excerpt;
time_t visited;
float ranking;
SearchResult() : thumbnail(NULL), thumbnail_size(0), visited(0), ranking(0) {}
~SearchResult() { OP_DELETEA(thumbnail); }
CHECK_RESULT(OP_STATUS CopyFrom(const Result & result, SearchSpec * search_spec));
};
/**
* lookup documents contatining all the given words. Full ranking
* @param text plain text words
* @param sort_by sort results by relevance or a date of viewing
* @param phrase_flags flags built up from PhraseMatcher::PhraseFlags, controlling what kind of phrase search is performed
* @return iterator to be deleted by a caller, NULL on error
*/
#ifdef SEARCH_ENGINE_PHRASESEARCH
SearchIterator<Result> *Search(const uni_char *text, Sort sort_by = RankSort, int phrase_flags = PhraseMatcher::AllPhrases);
#else
SearchIterator<Result> *Search(const uni_char *text, Sort sort_by = RankSort, int phrase_flags = 0/*PhraseMatcher::NoPhrases*/);
#endif
/**
* lookup documents contating all the words contained in text, last one as a prefix
* ranking or other sorting is not involved as a trade off for a fast response
* @param text searched phrase
* @param phrase_flags flags built up from PhraseMatcher::PhraseFlags, controlling what kind of
* phrase search is performed. PhraseMatcher::PrefixSearch is implied.
* @return iterator to be deleted by a caller, NULL on error
*/
SearchIterator<Result> *FastPrefixSearch(const uni_char *text, int phrase_flags = 0/*PhraseMatcher::NoPhrases*/);
/**
* disable the result from appearing in any further search results
*/
CHECK_RESULT(OP_STATUS InvalidateResult(const Result &row));
/**
* disable the url from appearing in any further search results
*/
CHECK_RESULT(OP_STATUS InvalidateUrl(const char *url));
CHECK_RESULT(OP_STATUS InvalidateUrl(const uni_char *url));
/**
* find the indexed words for autocompletition
* @param prefix word prefix to search
* @param result resulting words, mustn't be NULL, the fields must be freed by caller
* @param result_size maximum number of results on input, number of results on output
*/
CHECK_RESULT(OP_STATUS WordSearch(const uni_char *prefix, uni_char **result, int *result_size));
/*** message part ***/
virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2);
/**
* cancel the data being written by PreFlush/Flush/Commit
*/
void AbortFlush(void);
protected:
enum Flags
{
PreFlushed = 4096, /*< PreFlush had finished successfully before Flush */
Flushed = 8192, /*< Flush had finished successfully before Commit */
PreFlushing = 32768, /*< time limit occured during PreFlush */
UseNUR = 65536 /*< PreFlush hadn't been called before Flush, use alternative write strategy */
};
CHECK_RESULT(OP_STATUS IndexTextBlock(RecordHandle handle, const uni_char *text, float ranking, BOOL fine_segmenting = FALSE));
CHECK_RESULT(OP_STATUS IndexURL(RecordHandle handle, const char *url, float ranking));
CHECK_RESULT(OP_STATUS Insert(TVector<FileWord *> &cache, RecordHandle h, const uni_char *word, float rank));
void CancelPreFlushItem(int i);
CHECK_RESULT(OP_STATUS WriteMetadata(void));
CHECK_RESULT(OP_STATUS FindLastIndex(UINT32 *prev, UINT16 *prev_idx, const char *url, RankIndex *current_index));
CHECK_RESULT(OP_STATUS InsertHandle(RecordHandle handle));
CHECK_RESULT(OP_STATUS CompressText(RecordHandle handle));
CHECK_RESULT(OP_STATUS WipeData(BSCursor::RowID id, unsigned short r_index));
void CheckMaxSize_RemoveOldIndexes();
// Posts a message in a threadsafe manner when necessary
void PostMessage(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2, unsigned long delay=0);
int m_flags;
OpFileLength m_max_size; //total size of document index, matched to History size in desktop browser.
int m_pos;
int m_flush_errors;
TVector<RankIndex *> m_index; //array of indexes, the newest index is at index 0.
TVector<FileWord *> m_cache; //word lists inserted but not yet written to disk.
TVector<FileWord *> m_preflush; //word lists that are being written.
TVector<RecordHandle> m_pending; //contains documents that are being parsed.
TVector<RecordHandle> m_meta; //plain text, hash etc.
TVector<RecordHandle> m_meta_pf; //meta data that is being written.
OpFileLength m_subindex_size; //10 times less than m_max_size above.
#if defined SEARCH_ENGINE_LOG && (SEARCH_ENGINE_LOG & SEARCH_ENGINE_LOG_VISITEDSEARCH)
OutputLogDevice *m_log;
#endif
OP_STATUS AddWord(VisitedSearch::RecordHandle handle, const uni_char *text, float ranking);
private:
CHECK_RESULT(OP_STATUS AbortPreFlush(OP_STATUS err));
CHECK_RESULT(OP_STATUS AbortFlush(OP_STATUS err));
#ifdef SEARCH_ENGINE_PHRASESEARCH
class VisitedSearchDocumentSource : public DocumentSource<Result>
{
virtual const uni_char *GetDocument(const Result &item)
{
return item.GetPlaintext();
}
};
VisitedSearchDocumentSource m_doc_source;
#endif
};
#ifdef VPS_WRAPPER
class AsyncVisitedSearch
{
public:
static AsyncVisitedSearch *Create(void);
virtual ~AsyncVisitedSearch(void) {}
virtual void SetMaxSize(OpFileLength max_size) = 0;
virtual void SetMaxItems(int max_items) = 0;
CHECK_RESULT(virtual OP_STATUS Open(const uni_char *directory)) = 0;
CHECK_RESULT(virtual OP_STATUS Close(BOOL force_close = TRUE)) = 0;
virtual BOOL IsOpen(void) = 0;
CHECK_RESULT(virtual OP_STATUS Clear(BOOL reopen = TRUE)) = 0;
virtual VisitedSearch::RecordHandle CreateRecord(const char *url, const uni_char *title = NULL) = 0;
CHECK_RESULT(virtual OP_STATUS AddTitle(VisitedSearch::RecordHandle handle, const uni_char *title)) = 0;
CHECK_RESULT(virtual OP_STATUS AddTextBlock(VisitedSearch::RecordHandle handle, const uni_char *text, float ranking, BOOL is_continuation = FALSE)) = 0;
CHECK_RESULT(virtual OP_STATUS CloseRecord(VisitedSearch::RecordHandle handle)) = 0;
virtual void AbortRecord(VisitedSearch::RecordHandle handle) = 0;
CHECK_RESULT(virtual OP_STATUS Search(const uni_char *text,
VisitedSearch::Sort sort_by,
int max_items,
int excerpt_max_chars,
const OpStringC & excerpt_start_tag,
const OpStringC & excerpt_end_tag,
int excerpt_prefix_ratio,
MessageObject * callback)) = 0;
virtual SearchIterator<VisitedSearch::Result> *Search(const uni_char *text,
VisitedSearch::Sort sort_by = VisitedSearch::RankSort,
#ifdef SEARCH_ENGINE_PHRASESEARCH
int phrase_flags = PhraseMatcher::AllPhrases
#else
int phrase_flags = 0/*PhraseMatcher::NoPhrases*/
#endif
) = 0;
CHECK_RESULT(virtual OP_STATUS InvalidateUrl(const char *url)) = 0;
CHECK_RESULT(virtual OP_STATUS InvalidateUrl(const uni_char *url)) = 0;
};
#endif
#endif // VISITEDSEARCH_H
|
#ifndef BOOK_H
#define BOOK_H
#include <QString>
class Book
{
public:
Book();
void setBook(int id, QString author, QString name, int year, QString publishingHouse, int pageCount);
int getId();
QString getAuthor();
QString getName();
QString getPublishingHouse();
int getYear();
int getPageCount();
private:
int id;
QString author;
QString name;
QString publishingHouse;
int year;
int pageCount;
};
#endif // BOOK_H
|
#include "GameOverScreen.h"
#include "AssetLib.h"
bool GameOverMenu::loaded = false;
// Set our start values and load our menu textures if it's our first time at the screen.
GameOverMenu::GameOverMenu()
{
setCurrentSelection(0);
setChangedSelection(false);
setExiting(false);
beatScore = false;
setSelectedTexture("Select");
setBackgroundTexture("GameOverBackground");
setFontMap("Font");
if (!loaded)
{
loadTexture(backgroundTexture, "../textures/gameover.png", 1, 1);
}
}
#pragma region GettersAndSetters
std::string GameOverMenu::getBackgroundTexture()
{
return backgroundTexture;
}
// Our getters
std::string GameOverMenu::getSelectedTexture()
{
return selectedTexture;
}
std::string GameOverMenu::getFontMap()
{
return fontMap;
}
int GameOverMenu::getCurrentSelection()
{
return currentSelection;
}
bool GameOverMenu::getChangedSelection()
{
return changedSelection;
}
bool GameOverMenu::getStateChange()
{
return stateChange;
}
// Our setters
void GameOverMenu::setBackgroundTexture(std::string s)
{
backgroundTexture = s;
}
void GameOverMenu::setSelectedTexture(std::string s)
{
selectedTexture = s;
}
void GameOverMenu::setFontMap(std::string s)
{
fontMap = s;
}
void GameOverMenu::setCurrentSelection(int s)
{
currentSelection = s;
}
void GameOverMenu::setChangedSelection(bool b)
{
changedSelection = b;
}
void GameOverMenu::setStateChange(bool b)
{
stateChange = b;
}
void GameOverMenu::setExiting(bool b)
{
exiting = b;
}
#pragma endregion
// Where we check for button/key input.
void GameOverMenu::Input()
{
// If we're not at the splash screen, move through menu options and allow selecting
if (BUTTON_TWO)
{
Select();
}
if (BUTTON_DOWN && !getChangedSelection())
{
if (currentSelection < 2)
currentSelection++;
setChangedSelection(true);
}
else if (BUTTON_UP && !getChangedSelection())
{
if (currentSelection > 0)
currentSelection--;
setChangedSelection(true);
}
if (MOVEMENT_INACTIVE) setChangedSelection(false);
}
// Tell our game state it's time to change states.
void GameOverMenu::Select()
{
setStateChange(true);
}
// Draw the splash screen and menu.
void GameOverMenu::Draw()
{
if (exiting)
{
RENDER(getTexture(backgroundTexture), 0, TEXTURE_HEIGHT(getTexture(backgroundTexture)), TEXTURE_WIDTH(getTexture(backgroundTexture)), TEXTURE_HEIGHT(getTexture(backgroundTexture)), 0, false);
DRAW_TEXT(getTexture(fontMap), EXIT_TEXT, 50, 300, 16, 16, 0, 0, WHITE);
}
else
{
RENDER(getTexture(backgroundTexture), 0, TEXTURE_HEIGHT(getTexture(backgroundTexture)), TEXTURE_WIDTH(getTexture(backgroundTexture)), TEXTURE_HEIGHT(getTexture(backgroundTexture)), 0, false);
if (beatScore)
{
DRAW_TEXT(getTexture(fontMap), GAMEOVER_WIN_TEXT, 100, 300, 12, 12, 0, 0, WHITE);
}
else
{
DRAW_TEXT(getTexture(fontMap), GAMEOVER_LOSE_TEXT, 100, 300, 12, 12, 0, 0, WHITE);
}
DRAW_TEXT(getTexture(fontMap), GAMEOVER_OPTION_ONE, 40, 100, 16, 16, 0, 0, WHITE);
DRAW_TEXT(getTexture(fontMap), GAMEOVER_OPTION_TWO, 60, 80, 16, 16, 0, 0, WHITE);
DRAW_TEXT(getTexture(fontMap), GAMEOVER_OPTION_THREE, 80, 60, 16, 16, 0, 0, WHITE);
switch (getCurrentSelection())
{
case 0:
RENDER(getTexture(selectedTexture), 20, 100, 20, 20, 0, 0);
break;
case 1:
RENDER(getTexture(selectedTexture), 40, 80, 20, 20, 0, 0);
break;
case 2:
RENDER(getTexture(selectedTexture), 60, 60, 20, 20, 0, 0);
break;
}
}
}
|
#ifndef _DX11_RENDER_WINDOW_H_
#define _DX11_RENDER_WINDOW_H_
#include "RenderTarget.h"
#include "d3d11.h"
namespace HW{
/** This class is used to store a render target as window
* A render window for dx11 has color and depth/stencil buf and their resourceView
* And the viewport
* @Remarks: This class just represent the main window target, no other use for the original framework
*/
class DX11RenderWindow : public RenderTarget{
public:
DX11RenderWindow();
DX11RenderWindow(const String& name, RenderSystem* system);
virtual ~DX11RenderWindow();
virtual void setDimension(unsigned int width, unsigned int height);
virtual unsigned int getWidth() const{ return m_uWidth; }
virtual unsigned int getHeight() const{ return m_uHeight; }
virtual void setColorBufferFormat(Texture::PixelFormat format);
virtual void setDepthBufferFormat(Texture::PixelFormat format);
virtual void setColorBufferUsage(HardwareUsage usage);
virtual void setDepthBufferUsage(HardwareUsage usage);
virtual void createInternalRes();
virtual void releaseInternalRes();
virtual void setWindowPos(unsigned int ix, unsigned int iy);
virtual void bindTarget(int index = 0);
private:
// The width is just the width of viewport, not buffer
unsigned int m_uWidth;
unsigned int m_uHeight;
unsigned int m_uWindowPosX;
unsigned int m_uWindowPosY;
DXGI_FORMAT m_ColorBufFormat;
DXGI_FORMAT m_DepthBufFormat;
DXGI_USAGE m_ColorBufUsage;
DXGI_USAGE m_DepthBufUsage;
D3D11_VIEWPORT m_WindowViewport;
ID3D11RenderTargetView* m_pColorBufView;
ID3D11DepthStencilView* m_pDepthBufView;
};
}
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* 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.
*
* @author Arjan van Leeuwen (arjanl)
* @author Cihat Imamoglu (cihati)
*/
#include "core/pch.h"
#include "adjunct/quick_toolkit/widgets/NullWidget.h"
#include "adjunct/quick_toolkit/widgets/QuickGrid/QuickStackLayout.h"
#include "adjunct/quick_toolkit/widgets/QuickRadioButton.h"
QuickStackLayout::QuickStackLayout(Orientation orientation)
: m_orientation(orientation)
{
}
QuickStackLayout::~QuickStackLayout()
{
for (unsigned i = 0; i < m_cells.GetCount(); i++)
OP_DELETE(m_cells[i]);
}
unsigned QuickStackLayout::GetColumnCount() const
{
if (m_orientation == VERTICAL)
return 1;
return m_cells.GetCount();
}
unsigned QuickStackLayout::GetRowCount() const
{
if (m_orientation == HORIZONTAL)
return 1;
return m_cells.GetCount();
}
GridCell* QuickStackLayout::GetCell(unsigned col, unsigned row)
{
if (m_orientation == HORIZONTAL)
{
OP_ASSERT(row == 0 && col < m_cells.GetCount() &&
m_cells[col]);
return m_cells[col];
}
else
{
OP_ASSERT(col == 0 && row < m_cells.GetCount() &&
m_cells[row]);
return m_cells[row];
}
}
OP_STATUS QuickStackLayout::InsertWidget(QuickWidget *widget, int pos)
{
OpAutoPtr<GridCell> cell (OP_NEW(GridCell, ()));
if (!cell.get())
{
OP_DELETE(widget);
return OpStatus::ERR_NO_MEMORY;
}
cell->SetContent(widget);
cell->SetContainer(this);
cell->SetParentOpWidget(GetParentOpWidget());
if (pos == -1)
pos = m_cells.GetCount();
RETURN_IF_ERROR(m_cells.Insert(pos,cell.get()));
cell.release();
Invalidate();
if (widget && widget->GetTypedObject<QuickRadioButton>())
RETURN_IF_ERROR(RegisterToButtonGroup(widget->GetTypedObject<QuickRadioButton>()->GetOpWidget()));
return OpStatus::OK;
}
OP_STATUS QuickStackLayout::InsertEmptyWidget(unsigned min_width, unsigned min_height, unsigned pref_width, unsigned pref_height, int pos)
{
QuickWidget* widget = OP_NEW(NullWidget, ());
if (!widget)
return OpStatus::ERR_NO_MEMORY;
widget->SetMinimumWidth(min_width);
widget->SetMinimumHeight(min_height);
widget->SetPreferredWidth(pref_width);
widget->SetPreferredHeight(pref_height);
return InsertWidget(widget, pos);
}
void QuickStackLayout::RemoveWidget(int pos)
{
OP_DELETE(m_cells[pos]);
m_cells.Remove(pos);
Invalidate();
}
void QuickStackLayout::RemoveAllWidgets()
{
for (unsigned i = 0; i < m_cells.GetCount(); i++)
OP_DELETE(m_cells[i]);
m_cells.Remove(0, m_cells.GetCount());
Invalidate();
}
|
๏ปฟ/*
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.
*/
#include "input_manager.hpp"
#include <memory>
using orkhestrafs::core::core_input::InputManager;
using orkhestrafs::core_interfaces::Config;
auto InputManager::Parse(std::string input_filename,
std::string config_filename)
-> std::pair<std::unique_ptr<ExecutionPlanGraphInterface>, Config> {
auto config = config_creator_.GetConfig(config_filename);
auto graph = graph_creator_->MakeGraph(input_filename, nullptr);
return std::make_pair(std::move(graph), std::move(config));
}
|
// Solaris needs non-empty content so ensure
// we have at least one symbol
int Solaris_requires_a_symbol_here = 0;
|
#ifndef _FA_MONITOR_COMM_NAMEPIPE
#define _FA_MONITOR_COMM_NAMEPIPE
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include "Comm.h"
#include "fmt.h"
class NamePipe : public Comm {
public:
NamePipe() : Comm(1) {}
NamePipe(char* pipename)
: Comm(1),
pipename_(pipename)
{
//open();
}
~NamePipe()
{
//close();
}
HANDLE open();
void receive();
void close();
HANDLE handle() { return handle_; }
private:
char* pipename_;
HANDLE handle_;
};
#endif
|
#include "gtest/gtest.h"
#include "buddy/bdd.h"
// ::std
#include <iostream>
#include <vector>
#include <utility>
#include <limits>
#include <sstream>
#include <string>
#include <cstdlib>
#include <map>
#include <boost/cast.hpp>
#include <boost/static_assert.hpp>
// ::wali::domains::binrel
#include "wali/domains/binrel/BinRel.hpp"
#include "wali/domains/binrel/nwa_detensor.hpp"
#include "wali/domains/binrel/ProgramBddContext.hpp"
using namespace std;
using namespace wali;
using namespace wali::domains::binrel;
using namespace wali::domains::binrel::details;
#if (NWA_DETENSOR == 1)
namespace
{
TEST(Nwa_detensor, paperExample){
program_bdd_context_t brm = new ProgramBddContext();
map<string, int> vars;
vars["x1"] = 2;
vars["x2"] = 2;
brm->setIntVars(vars);
bdd b = brm->Assign("x1", brm->Not(brm->From("x1")));
binrel_t M = new BinRel(brm.get_ptr(), b);
binrel_t eye = boost::polymorphic_downcast<BinRel*>(M->one().get_ptr());
binrel_t s = boost::polymorphic_downcast<BinRel*>(((M->tensor(M.get_ptr()))->combine(eye->tensor(eye.get_ptr()).get_ptr())).get_ptr());
bdd z = s->getBdd();
//bdd_fnprintdot_levels("mtmpiti.dot", z);
binrel_t x = boost::polymorphic_downcast<BinRel*>(s->detensorTranspose().get_ptr());
z = x->getBdd();
ASSERT_TRUE(x->equal(x->one().get_ptr()));
//bdd_fnprintdot_levels("detensored.dot", z);
//b = brm->Assume(brm->From("x1"), brm->From("x1"));
//bdd_fnprintdot_levels("id.dot", b);
}
TEST(Nwa_detensor, alltrue)
{
program_bdd_context_t brm = new ProgramBddContext();
map<string, int> vars;
vars["x1"] = 2;
vars["x2"] = 2;
vars["x3"] = 2;
brm->setIntVars(vars);
sem_elem_tensor_t b1 = new BinRel(brm.get_ptr(), bddtrue);
sem_elem_tensor_t b2 = new BinRel(brm.get_ptr(), bddtrue);
sem_elem_tensor_t b3 = b2->transpose();
sem_elem_tensor_t b4 = b3->tensor(b1.get_ptr());
sem_elem_tensor_t b5 = b4->detensorTranspose();
sem_elem_tensor_t b6 = boost::polymorphic_downcast<SemElemTensor*>(b2->extend(boost::polymorphic_downcast<SemElem*>(b1.get_ptr())).get_ptr());
ASSERT_TRUE(b6->equal(b5));
}
TEST(Nwa_detensor, failing1)
{
program_bdd_context_t brm = new ProgramBddContext();
map<string, int> vars;
vars["x1"] = 2;
vars["x2"] = 2;
vars["x3"] = 2;
brm->setIntVars(vars);
bdd b = brm->setPost("x2") & brm->setPre("x3") & brm->unsetPost("x3");
sem_elem_tensor_t b1 = new BinRel(brm.get_ptr(), b);
sem_elem_tensor_t b2 = new BinRel(brm.get_ptr(), b);
sem_elem_tensor_t b3 = b2->transpose();
sem_elem_tensor_t b4 = b3->tensor(b1.get_ptr());
sem_elem_tensor_t b5 = b4->detensorTranspose();
sem_elem_tensor_t b6 = boost::polymorphic_downcast<SemElemTensor*>(b2->extend(boost::polymorphic_downcast<SemElem*>(b1.get_ptr())).get_ptr());
ASSERT_TRUE(b6->equal(b5));
}
TEST(Nwa_detensor, smallRandom)
{
program_bdd_context_t brm = new ProgramBddContext();
map<string, int> vars;
vars["x1"] = 2;
vars["x2"] = 2;
vars["x3"] = 2;
vars["x4"] = 2;
vars["x5"] = 2;
brm->setIntVars(vars);
for(unsigned i =0; i < 1000; ++i){
sem_elem_tensor_t b1 = new BinRel(brm.get_ptr(), brm->tGetRandomTransformer(false, 0));
sem_elem_tensor_t b2 = new BinRel(brm.get_ptr(), brm->tGetRandomTransformer(false, 0));
sem_elem_tensor_t b3 = b2->transpose();
sem_elem_tensor_t b4 = b3->tensor(b1.get_ptr());
sem_elem_tensor_t b5 = b4->detensorTranspose();
sem_elem_tensor_t b6 = boost::polymorphic_downcast<SemElemTensor*>(b2->extend(boost::polymorphic_downcast<SemElem*>(b1.get_ptr())).get_ptr());
ASSERT_TRUE(b6->equal(b5));
}
}
}
#endif
// Yo, Emacs!
// Local Variables:
// c-file-style: "ellemtel"
// c-basic-offset: 2
// End:
|
#pragma once
#include<queue>
#include"phrasetable.h"
using namespace std;
void get_cmd(int argc, char *argv[]);
int turn_lowercase_and_WordLine_count(char *);
char *Get_phrase(char *str, int pos, int len);
void pos_word(char *str,queue<int>&);
int Get_end(char *str, int i);
void Data_output(phrasetable);
|
// Program to reverse the string entered by the user.
// The user can enter any no. of strings that he/she wants to.
#include <iostream>
#include <vector>
using namespace std;
int main()
{ int n;
char c = '1';
string A;
while(c =='1')
{
cout<<"Enter the string"<<endl;
cin>>A;
n = A.length();
for(int i=n-1;i>=0;i--)
{
cout<<A[i];
}
cout<<"\n"<<"Enter 1 if you want to enter another string 0 if you don't want ton"; // 1 if you want to enter another string.
cin>>c;
}
return 0;
}
|
#include <sys/stat.h>
#include "m6502/src/System.hxx"
#include "OSystem.hxx"
#include "atariemu.h"
#include <string>
#include <cstring>
namespace {
int fileExists(const char *filename)
{
struct stat buffer;
return (stat (filename, &buffer) == 0);
}
const int RAM_SIZE = 128;
const int PADDLE_DELTA=23000, PADDLE_MIN=27450,PADDLE_MAX=790196,PADDLE_DEFAULT_VALUE=(PADDLE_MAX+PADDLE_MIN)/2;
emuGame gameStr2Enum(const char* gamename) {
#define ADDGAME(name) if (strcmp(gamename,#name)==0) return emu_##name;
ADDGAME(beam_rider)
ADDGAME(breakout)
ADDGAME(enduro)
ADDGAME(pong)
ADDGAME(qbert)
ADDGAME(seaquest)
ADDGAME(space_invaders)
#undef ADDGAME
printf("couldn't find game of name %s",gamename);
abort();
}
/* reads a byte at a memory location between 0 and 128 */
int readRam(const System* system, int offset) {
// peek modifies data-bus state, but is logically const from
// the point of view of the RL interface
// JDS: Huh?
System* sys = const_cast<System*>(system);
return sys->peek((offset & 0x7F) + 0x80);
}
/* extracts a decimal value from a byte */
int getDecimalScore(int index, const System* system) {
int score = 0;
int digits_val = readRam(system, index);
int right_digit = digits_val & 15;
int left_digit = digits_val >> 4;
score += ((10 * left_digit) + right_digit);
return score;
}
/* extracts a decimal value from 2 bytes */
int getDecimalScore(int lower_index, int higher_index, const System* system) {
int score = 0;
int lower_digits_val = readRam(system, lower_index);
int lower_right_digit = lower_digits_val & 15;
int lower_left_digit = (lower_digits_val - lower_right_digit) >> 4;
score += ((10 * lower_left_digit) + lower_right_digit);
if (higher_index < 0) {
return score;
}
int higher_digits_val = readRam(system, higher_index);
int higher_right_digit = higher_digits_val & 15;
int higher_left_digit = (higher_digits_val - higher_right_digit) >> 4;
score += ((1000 * higher_left_digit) + 100 * higher_right_digit);
return score;
}
/* extracts a decimal value from 3 bytes */
int getDecimalScore(int lower_index, int middle_index, int higher_index, const System* system) {
int score = getDecimalScore(lower_index, middle_index, system);
int higher_digits_val = readRam(system, higher_index);
int higher_right_digit = higher_digits_val & 15;
int higher_left_digit = (higher_digits_val - higher_right_digit) >> 4;
score += ((100000 * higher_left_digit) + 10000 * higher_right_digit);
return score;
}
// clip integer
int clipi(int x, int lo, int hi) {
return (x < lo) ? lo : (x > hi ? hi : x);
}
void setAction(emuState* e, const emuAction& a) {
Event* event = e->o->event();
// paddles
int prevPaddlePos = event->get(Event::PaddleZeroResistance);
event->set(Event::PaddleZeroResistance, clipi(prevPaddlePos + a.horiz*PADDLE_DELTA, PADDLE_MIN, PADDLE_MAX));
event->set(Event::PaddleZeroFire, a.fire);
// joystick
event->set(Event::JoystickZeroFire, a.fire);
event->set(Event::JoystickZeroDown, a.vert==-1);
event->set(Event::JoystickZeroUp, a.vert==1);
event->set(Event::JoystickZeroLeft, a.horiz==-1);
event->set(Event::JoystickZeroRight, a.horiz==1);
}
}
emuState* emuNewState(const char* game, const char* rom_dir) {
std::string sromfile = std::string(rom_dir) + std::string("/") + std::string(game) + std::string(".bin");
const char* romfile=sromfile.c_str();
if (!fileExists(romfile)) {
fprintf( stderr, "romfile %s doesn't exist!\n" , romfile);
return NULL;
}
// allocations
emuState* e = new emuState();
e->o = new OSystem();
e->s = new Settings(e->o);
OSystem* o=e->o; // for brevity
// Settings
e->s->setBool("display_screen", true);
// o->settings().loadConfig();
o->settings().validate();
o->create();
o->createConsole(romfile);
o->settings().setString("rom_file", romfile);
// o->settings().setString("cpu","low");
o->console().setPalette("standard");
MediaSource& ms = o->console().mediaSource();
e->screenWidth = ms.width();
e->screenHeight = ms.height();
e->game = gameStr2Enum(game);
e->score = 0;
e->lives = 0;
return e;
}
void resetKeys(Event* event) {
event->set(Event::ConsoleReset, 0);
event->set(Event::JoystickZeroFire, 0);
event->set(Event::JoystickZeroUp, 0);
event->set(Event::JoystickZeroDown, 0);
event->set(Event::JoystickZeroRight, 0);
event->set(Event::JoystickZeroLeft, 0);
event->set(Event::JoystickOneFire, 0);
event->set(Event::JoystickOneUp, 0);
event->set(Event::JoystickOneDown, 0);
event->set(Event::JoystickOneRight, 0);
event->set(Event::JoystickOneLeft, 0);
// also reset paddle fire
event->set(Event::PaddleZeroFire, 0);
event->set(Event::PaddleOneFire, 0);
}
void emuReset(emuState* e) {
// reset all keys
// reset paddles
Event* event = e->o->event();
resetKeys(event);
event->set(Event::PaddleZeroResistance,PADDLE_DEFAULT_VALUE);
// reset variables
e->score=0;
e->lives=0;
// whatever this does
e->o->console().system().reset();
// press the reset button
emuAction a = {};
setAction(e,a);
MediaSource& ms = e->o->console().mediaSource();
// press the reset button
event->set(Event::ConsoleReset, true);
for (int i=0;i < 5; ++i) {
ms.update();
}
// noop steps
event->set(Event::ConsoleReset, false);
for (int i=0;i < 40; ++i) {
ms.update();
}
}
void emuDeleteState(emuState* e) {
// delete e->s;
delete e->o;
delete e;
}
void emuScreenShape(emuState* e, int& nrows, int& ncols, int& nchan) {
nrows = e->screenHeight;
ncols = e->screenWidth;
nchan = 3;
}
void emuGetImage(emuState* e, char* imgBuf) {
const uInt8* inputData = e->o->console().mediaSource().currentFrameBuffer();
const uInt32* palette = e->o->console().getPalette();
int npix = e->screenHeight*e->screenWidth;
for (int i=0; i < npix; ++i) {
uInt32 pv = palette[inputData[i]];
*imgBuf++ = pv & 0xff;
*imgBuf++ = (pv >> 8) & 0xff;
*imgBuf++ = (pv >> 16) & 0xff;
}
}
int emuRamSize() {
return RAM_SIZE;
}
void emuGetRam(emuState* e, char* ramBuf) {
for (int i=0; i < RAM_SIZE; ++i) {
ramBuf[i] = e->o->console().system().peek(i + 0x80);
}
}
void emuStep(emuState* e, const emuAction& a, int& m_reward, bool& m_terminal, bool& roundOver) {
System& system = e->o->console().system();
setAction(e,a);
e->o->console().mediaSource().update();
int& m_score=e->score;
int& m_lives=e->lives;
int livesBeforeStep = m_lives;
// bool m_started=1;
switch (e->game) {
case emu_beam_rider : {
// update the reward
int score = getDecimalScore(9, 10, 11, &system);
m_reward = score - m_score;
m_score = score;
int new_lives = readRam(&system, 0x85) + 1;
// Decrease lives *after* the death animation; this is necessary as the lives counter
// blinks during death
if (new_lives == m_lives - 1) {
if (readRam(&system, 0x8C) == 0x01)
m_lives = new_lives;
}
else
m_lives = new_lives;
// update terminal status
int byte_val = readRam(&system, 5);
m_terminal = byte_val == 255;
byte_val = byte_val & 15;
m_terminal = m_terminal || byte_val < 0;
break;
}
case emu_breakout : {
// update the reward
int x = readRam(&system, 77);
int y = readRam(&system, 76);
reward_t score = 1 * (x & 0x000F) + 10 * ((x & 0x00F0) >> 4) + 100 * (y & 0x000F);
m_reward = score - m_score;
m_score = score;
// update terminal status
int byte_val = readRam(&system, 57);
m_terminal = byte_val == 0;
m_lives = byte_val;
break;
}
case emu_enduro : {
// update the reward
int score = 0;
int level = readRam(&system, 0xAD);
if (level != 0) {
int cars_passed = getDecimalScore(0xAB, 0xAC, &system);
if (level == 1) cars_passed = 200 - cars_passed;
else if (level >= 2) cars_passed = 300 - cars_passed;
else assert(false);
// First level has 200 cars
if (level >= 2) {
score = 200;
// For every level after the first, 300 cars
score += (level - 2) * 300;
}
score += cars_passed;
}
m_reward = score - m_score;
m_score = score;
// update terminal status
//int timeLeft = readRam(&system, 0xB1);
int deathFlag = readRam(&system, 0xAF);
m_terminal = deathFlag == 0xFF;
break;
}
case emu_pong : {
// update the reward
int x = readRam(&system, 13); // cpu score
int y = readRam(&system, 14); // player score
reward_t score = y - x;
m_reward = score - m_score;
m_score = score;
// update terminal status
// game is over when a player reaches 21,
// or too many steps have elapsed since the last reset
m_terminal = x == 21 || y == 21;
break;
}
case emu_qbert : {
// xxx
int lives_value = readRam(&system, 0x88);
m_terminal = (lives_value == 0xFE) ||
(lives_value == 0x02 && m_lives == 0xFF);
m_lives = lives_value;
// update the reward
// Ignore reward if reset the game via the fire button; otherwise the agent
// gets a big negative reward on its last step
if (!m_terminal) {
int score = getDecimalScore(0xDB, 0xDA, 0xD9, &system);
m_reward = score - m_score;
m_score = score;
}
else {
m_reward = 0;
}
break;
}
case emu_seaquest : {
// update the reward
reward_t score = getDecimalScore(0xBA, 0xB9, 0xB8, &system);
m_reward = score - m_score;
m_score = score;
// update terminal status
m_terminal = readRam(&system, 0xA3) != 0;
m_lives = readRam(&system, 0xBB) + 1;
break;
}
case emu_space_invaders : {
// update the reward
int score = getDecimalScore(0xE8, 0xE6, &system);
m_reward = score - m_score;
m_score = score;
m_lives = readRam(&system, 0xC9);
// update terminal status
// If bit 0x80 is on, then game is over
int some_byte = readRam(&system, 0x98);
m_terminal = (some_byte & 0x80) || m_lives == 0;
break;
}
default: abort();
}
roundOver = (m_lives < livesBeforeStep);
}
|
#include <octomap/octomap.h>
#include <octomap/ColorOcTree.h>
using namespace std;
using namespace octomap;
int main(int /*argc*/, char** argv) {
std::string filename(argv[1]);
std::ifstream infile(filename.c_str(), std::ios_base::in |std::ios_base::binary);
if (!infile.is_open()) {
cout << "file "<< filename << " could not be opened for reading.\n";
return -1;
}
ColorOcTree tree (0.1);
tree.readData(infile);
infile.close();
cout << "color tree read from "<< filename <<"\n";
tree.writeColorHistogram("histogram.eps");
return 0;
}
|
#if !defined(DM_PLATFORM_IOS)
extern "C" void siwa()
{
}
#endif
|
//
// user_types.hpp
// rod-cut
//
// Created by mndx on 26/10/2021.
//
#ifndef user_types_h
#define user_types_h
typedef struct optimum_cut_info {
int cut_index;
int max_rev;
} opt_cut_info;
typedef struct table_element {
bool is_set;
opt_cut_info optimum_cut_info;
} t_elem;
#endif /* user_types_h */
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 2000-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* Yngve Pettersen
*/
#ifndef _COOKIE_MANAGER_H_
#define _COOKIE_MANAGER_H_
class Cookie_Item_Handler;
class CookieDomain;
class Cookie;
#include "modules/util/opfile/opfile.h"
#include "modules/hardcore/mh/messobj.h"
// Cookie memory use accounting
#undef DEBUG_COOKIE_MEMORY_SIZE
class Cookie_Manager
{
private:
URL_CONTEXT_ID context_id;
#ifdef COOKIES_CONTROL_PER_CONTEXT
BOOL cookies_enabled_for_context;
#endif
# ifdef DISK_COOKIES_SUPPORT
BOOL cookie_file_read;
# endif
CookieDomain *cookie_root;
Head unprocessed_cookies;
#ifdef _ASK_COOKIE
BOOL processing_cookies;
#endif
/** Temporary buffers for working on cookie paths and cookie
* domains. Neither should be very long so it doesn't matter
* a lot that we have two per URL context. In the long run
* we will try to refactor it though.
*/
size_t cookie_temp_buffer_len;
char * cookie_processing_buf1;
char * cookie_processing_buf2;
int max_cookies;
int cookies_count;
int max_cookies_in_domain;
int max_cookie_len;
#ifdef DEBUG_COOKIE_MEMORY_SIZE
unsigned long cookie_mem_size;
#endif
OpFileFolder cookie_file_location;
BOOL updated_cookies;
AutoDeleteHead ContextManagers;
public:
Cookie_Manager();
void InitL(OpFileFolder loc, URL_CONTEXT_ID a_id = 0);
virtual ~Cookie_Manager();
void PreDestructStep();
/** check the paramdomain append ".local" for locals domains
*
* @param paramdomain, must be allocated
* @param isFileURL is this a file URL
* @return OP_STATUS
*/
static OP_STATUS CheckLocalNetworkAndAppendDomain(char* paramdomain, BOOL isFileURL = FALSE);
/** check the paramdomain for local network and append ".local" for locals domains
*
* @param paramdomain OpString
* @param isFileURL is this a file URL
* @return OP_STATUS
*/
static OP_STATUS CheckLocalNetworkAndAppendDomain(OpString& paramdomain, BOOL isFileURL = FALSE);
private:
void InternalInit();
void InternalDestruct();
OP_STATUS CheckCookieTempBuffers(size_t len);
public:
/** This returns a pointer to a shared global buffer so only one return value can be used at a time. */
const char* GetCookiesL(URL_Rep *,
int& version,
int &max_version,
BOOL already_have_password,
BOOL already_have_authentication,
BOOL &have_password,
BOOL &has_password,
URL_CONTEXT_ID context_id = 0,
BOOL for_http=FALSE
);
void HandleCookiesL(URL_Rep *, HeaderList &cookies, URL_CONTEXT_ID context_id = 0);
void HandleSingleCookieL(URL_Rep *url, const char *cookiearg,
const char *request,
int version
, URL_CONTEXT_ID context_id = 0
, Window* win = NULL
);
void HandleSingleCookieL(Head ¤tly_parsed_cookies, URL_Rep *url, const char *cookiearg,
const char *request,
int version,
BOOL set_from_http = FALSE,
Window* win = NULL
);
void StartProcessingCookies(BOOL reset_process=FALSE);
private:
void StartProcessingCookiesAction(BOOL reset_process);
public:
void SetCookie(Cookie_Item_Handler *cookie);
#ifdef _ASK_COOKIE
BOOL CheckAcceptCookieUpdates(Cookie_Item_Handler *cookie_item);
#ifdef ENABLE_COOKIE_CREATE_DOMAIN
void CreateCookieDomain(const char *domain_name);
void CreateCookieDomain(ServerName *domain_sn);
#endif
void RemoveSameCookiesFromQueue(Cookie_Item_Handler *set_item);
#endif
#if defined _ASK_COOKIE || defined COOKIE_USE_DNS_LOOKUP || defined PUBSUFFIX_ENABLED
int HandlingCookieForURL(URL_Rep *, URL_CONTEXT_ID context_id = 0);
#endif
void SetMaxTotalCookies(int max) {max_cookies = (max >= 0 ? max : 300);};
int GetMaxCookies() { return max_cookies; }
int GetCookiesCount() { return cookies_count; }
void IncCookiesCount() { cookies_count++; }
void DecCookiesCount() { cookies_count--; }
int GetMaxCookiesInDomain() { return max_cookies_in_domain; }
size_t GetMaxCookieLen() { return max_cookie_len; }
#ifdef DEBUG_COOKIE_MEMORY_SIZE
unsigned long GetCookieMemorySize(){return cookie_mem_size;}
void AddCookieMemorySize(unsigned long len){cookie_mem_size += len;}
void SubCookieMemorySize(unsigned long len){cookie_mem_size = (cookie_mem_size >= len ? cookie_mem_size - len : 0);}
#endif
void FreeUnusedResources();
#ifdef QUICK_COOKIE_EDITOR_SUPPORT
void BuildCookieEditorListL(URL_CONTEXT_ID id = 0);
#endif
#ifdef NEED_URL_COOKIE_ARRAY
OP_STATUS BuildCookieList(
Cookie ** cookieArray,
int * size_returned,
URL_Rep *url);
OP_STATUS BuildCookieList(
Cookie ** cookieArray,
int * size_returned,
uni_char * domain,
uni_char * path,
BOOL is_export = FALSE,
BOOL match_subpaths = FALSE);
OP_STATUS RemoveCookieList(uni_char * domainstr, uni_char * pathstr, uni_char * namestr);
#endif // NEED_URL_COOKIE_ARRAY
void CheckCookiesReadL();
#ifdef DISK_COOKIES_SUPPORT
void ReadCookiesL();
void WriteCookiesL(BOOL requested_by_platform = FALSE);
void AutoSaveCookies();
#endif
void ClearCookiesCommitL( BOOL delete_filters=FALSE );
void CleanNonPersistenCookies();
#ifdef _SSL_USE_SMARTCARD_
void CleanSmartCardAuthenticatedCookies(ServerName *server);
#endif
void AddContextL(URL_CONTEXT_ID id, OpFileFolder loc, BOOL share_with_main_context);
OP_STATUS SetShareCookiesWithMainContext(URL_CONTEXT_ID id, BOOL share)
{
CookieContextItem* context = FindContext(id);
if (context)
{
FindContext(id)->SetShareWithMainContext(share);
return OpStatus::OK;
}
else
return OpStatus::ERR;
}
void RemoveContext(URL_CONTEXT_ID id);
BOOL ContextExists(URL_CONTEXT_ID id);
void IncrementContextReference(URL_CONTEXT_ID id);
void DecrementContextReference(URL_CONTEXT_ID id);
BOOL GetContextIsTemporary(URL_CONTEXT_ID id);
#ifdef COOKIES_CONTROL_PER_CONTEXT
/** Set cookies enabled flag for a context; not possible to update default context */
void SetCookiesEnabledForContext(URL_CONTEXT_ID id, BOOL flag);
/** Get cookies enabled flag for a context; default context is always TRUE, non-existent context FALSE */
BOOL GetCookiesEnabledForContext(URL_CONTEXT_ID id);
#endif
#ifdef COOKIE_MANUAL_MANAGEMENT
/** Request saving all cookie data to file */
void RequestSavingCookies();
#endif
private:
class CookieContextItem : public Link
{
public:
URL_CONTEXT_ID context_id;
unsigned int references;
BOOL share_with_main_context;
BOOL predestruct_done;
Cookie_Manager *context;
public:
CookieContextItem(): context_id(0),references(1), share_with_main_context(FALSE), predestruct_done(FALSE), context(NULL){};
virtual ~CookieContextItem(){if(InList()) Out(); OP_DELETE(context);}
void ConstructL(URL_CONTEXT_ID id, OpFileFolder loc, BOOL a_share_with_main_context){
context_id = id;
share_with_main_context = a_share_with_main_context;
context = OP_NEW_L(Cookie_Manager, ());
context->InitL(loc, context_id);
}
virtual void PreDestructStep(){
if(predestruct_done)
return;
references ++;
predestruct_done = TRUE;
#ifdef DISK_COOKIES_SUPPORT
if(context)
{
TRAPD(op_err, context->WriteCookiesL());
OpStatus::Ignore(op_err);
}
#endif
if(context)
context->PreDestructStep();
references --;
};
void SetShareWithMainContext(BOOL share)
{
share_with_main_context = share;
}
};
CookieContextItem *FindContext(URL_CONTEXT_ID id);
public:
#ifdef _OPERA_DEBUG_DOC_
void GetCookieMemUsed(DebugUrlMemory &debug);
#endif
#ifdef WIC_COOKIES_LISTENER
public:
void IterateAllCookies();
#endif // WIC_COOKIES_LISTENER
private:
class CookieMessageHandler : public MessageObject
{
public:
~CookieMessageHandler();
void InitL();
void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2);
};
CookieMessageHandler message_handler;
};
#endif // _COOKIE_MANAGER_H_
|
#include "NhanVienVP.h"
NhanVienVP::NhanVienVP()
{
}
NhanVienVP::NhanVienVP(unsigned soNgayLamViec)
{
this->soNgayLamViec = soNgayLamViec;
}
NhanVienVP::~NhanVienVP()
{
}
long NhanVienVP::tinhLuong()
{
return soNgayLamViec * 100000;
}
void NhanVienVP::nhap()
{
NhanVien::nhap();
cout << "Nhap so ngay lam viec: ";
cin >> soNgayLamViec;
cin.ignore();
}
void NhanVienVP::xuat()
{
NhanVien::xuat();
cout << "Loai nhan vien: nhan vien van phong" << endl;
cout << "So ngay lam viec: " << soNgayLamViec << endl;
cout << "Luong " << tinhLuong() << " vnd" << endl;
}
|
#ifndef CAFFE_UTIL_MATH_FUNCTIONS_SPARSE_H_
#define CAFFE_UTIL_MATH_FUNCTIONS_SPARSE_H_
#include <stdint.h>
#include <cmath> // for std::fabs and std::signbit
#include <fstream>
#include <sstream>
#include "glog/logging.h"
#include "caffe/common.hpp"
#include "caffe/util/device_alternate.hpp"
#include "caffe/util/mkl_alternate.hpp"
#ifdef USE_MKL
#include <mkl.h>
#endif // USE_MKL
namespace caffe {
/*
The Intel MKL compressed sparse row (CSR) format is specified by four arrays: the values, columns, pointerB, and pointerE. The following table describes the arrays in terms of the values, row, and column positions of the non-zero elements in a sparse matrix A.
values : A real or complex array that contains the non-zero elements of A. Values of the non-zero elements of A are mapped into the values array using the row-major storage mapping described above.
columns : Element i of the integer array columns is the number of the column in A that contains the i-th value in the values array.
pointerB : Element j of this integer array gives the index of the element in the values array that is first non-zero element in a row j of A. Note that this index is equal to pointerB(j) - pointerB(1)+1 .
pointerE : An integer array that contains row indices, such that pointerE(j)-pointerB(1) is the index of the element in the values array that is last non-zero element in a row j of A.
Available in three or four vector formats
Four vector format is also called NIST Blas format.
Three vector format if called CSR3
Three Array Variation of CSR Format:
values :
columns :
rowIndex :
*/
class MM_Time {
public:
MM_Time(int _m, int _n, int _k, double _time) {
m = _m; n = _n; k = _k; ms_time = _time;
}
inline std::string show() {
std::ostringstream out;
out << m << " " << k << " " << n << " " << ms_time/1000.; // convert to ms
return std::string(out.str());
}
private:
int m,n,k;
double ms_time;
};
class Sparse_Matrix {
// CSR3 format , All for zero-based indexing
public:
//Dtype *values;
//int *colums;
//int *rowIndex;
void TestConvert();
void TestMVProduct(int m, int n, const double zero_ratio = 0.3);
MM_Time TestMMProduct(const int m, const int k, const int n , const double zero_ratio = 0.3);
int Convert(float *A, const int, const int, float *acsr, int *columns, int *rowIndex);
//void DisplayMatrix(const float *A, const int m, const int n);
};
} // namespace caffe
#endif // CAFFE_UTIL_MATH_FUNCTIONS_SPARSE_H_
|
#pragma once
#define CONCAT(a,b) a##b
#define REGISTER_STARTUP_FUNCTION(name,function,order) static registeredfunctions::StartupFunction CONCAT(name,_startup)(#name,function,order)
#define REGISTER_SHUTDOWN_FUNCTION(name,function,order) static registeredfunctions::ShutdownFunction CONCAT(name,_shutdown)(#name,function,order)
#define REGISTER_SCRIPT_INIT(name,function,order) \
static void function (script::ScriptEngine*); \
static registeredfunctions::ScriptFunction CONCAT(name,_script)(#name,function,order)
namespace script
{
class ScriptEngine;
}
namespace registeredfunctions
{
class StartupFunction;
class ShutdownFunction;
class ScriptFunction;
void addStartupFunction(StartupFunction& startup);
void addShutdownFunction(ShutdownFunction& shutdown);
void addScriptFunction(ScriptFunction& script);
void fireStartupFunctions();
void fireShutdownFunctions();
void fireScriptFunctions(script::ScriptEngine* se);
typedef boost::function < void(void) > voidFunction;
typedef boost::function < void(script::ScriptEngine*) > scriptFunction;
template <typename T>
class OrderedFunction
{
public:
string name;
int order;
T func;
OrderedFunction(string name, T func, int order) : name(name), func(func), order(order) {};
bool operator< (const OrderedFunction<T>& other) const
{
return order < other.order;
}
};
class StartupFunction : public OrderedFunction<voidFunction>
{
public:
StartupFunction(string name, voidFunction func, int order) :
OrderedFunction(name, func, order)
{
addStartupFunction(*this);
}
};
class ShutdownFunction : public OrderedFunction<voidFunction>
{
public:
ShutdownFunction(string name, voidFunction func, int order) :
OrderedFunction(name, func, order)
{
addShutdownFunction(*this);
}
};
class ScriptFunction : public OrderedFunction<scriptFunction>
{
public:
ScriptFunction(string name, scriptFunction func, int order) :
OrderedFunction(name, func, order)
{
addScriptFunction(*this);
}
};
}
|
//
// main.cpp
// Lab 3 - Hybrid Car
//
// Created by Jesse Millar on 9/9/13.
// Copyright (c) 2013 Jesse Millar. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
int milesPerYear;
double gasPrice;
double hybridCarCost;
int hybridMilesPerGallon;
double hybridResale;
double nonHybridCarCost;
int nonHybridMilesPerGallon;
double nonHybridResale;
string buyerPreference;
int main()
{
// Get the dataz!
do
{
cout << "On average, how many miles do you drive in a year?\n\t";
cin >> milesPerYear;
} while (milesPerYear <= 0);
do
{
cout << "What is the current price of a gallon of gas?\n\t$";
cin >> gasPrice;
} while (gasPrice <= 0);
do
{
cout << "What is the cost of the hybrid car you're thinking about buying?\n\t$";
cin >> hybridCarCost;
} while (hybridCarCost <= 0);
do
{
cout << "How many miles per gallon does this hybrid get?\n\t";
cin >> hybridMilesPerGallon;
} while (hybridMilesPerGallon <= 0);
do
{
cout << "And what is its estimated resale value after five years?\n\t$";
cin >> hybridResale;
} while (hybridResale <= 0);
do
{
cout << "For comparison, what is the cost of a similar, non-hybrid car?\n\t$";
cin >> nonHybridCarCost;
} while (nonHybridCarCost <= 0);
do
{
cout << "How many miles per gallon does this non-hybrid get?\n\t";
cin >> nonHybridMilesPerGallon;
} while (nonHybridMilesPerGallon <= 0);
do
{
cout << "And what is its estimated resale value after five years?\n\t$";
cin >> nonHybridResale;
} while (nonHybridResale <= 0);
do
{
cout << "Do you care more about \"total\" price or \"gas\" cost?\n\t";
cin >> buyerPreference;
} while (!(buyerPreference == "total" || buyerPreference == "gas"));
// Output the dataz!
int hybridGasUse = (milesPerYear * 5) / hybridMilesPerGallon;
int hybridTotalCost = (((milesPerYear * 5) / hybridMilesPerGallon) * gasPrice) + (hybridCarCost - hybridResale);
int nonHybridGasUse = (milesPerYear * 5) / nonHybridMilesPerGallon;
int nonHybridTotalCost = (((milesPerYear * 5) / nonHybridMilesPerGallon) * gasPrice) + (nonHybridCarCost - nonHybridResale);
if (buyerPreference == "total")
{
if (hybridTotalCost < nonHybridTotalCost)
{
cout << "\nThe hybrid...\n";
cout << "\tWill use " << hybridGasUse << " gallons of gas in five years\n";
cout << "\tWhich will cost $" << hybridTotalCost << " over the five years\n\n";
cout << "The non-hybrid...\n";
cout << "\tWill use " << nonHybridGasUse << " gallons of gas in five years\n";
cout << "\tWhich will cost $" << nonHybridTotalCost << " over the five years";
}
else
{
cout << "\nThe non-hybrid...\n";
cout << "\tWill use " << nonHybridGasUse << " gallons of gas in five years\n";
cout << "\tWhich will cost $" << nonHybridTotalCost << " over the five years\n\n";
cout << "The hybrid...\n";
cout << "\tWill use " << hybridGasUse << " gallons of gas in five years\n";
cout << "\tWhich will cost $" << hybridTotalCost << " over the five years";
}
}
else
{
if (hybridGasUse < nonHybridGasUse)
{
cout << "\nThe hybrid...\n";
cout << "\tWill use " << hybridGasUse << " gallons of gas in five years\n";
cout << "\tWhich will cost $" << hybridTotalCost << " over the five years\n\n";
cout << "The non-hybrid...\n";
cout << "\tWill use " << nonHybridGasUse << " gallons of gas in five years\n";
cout << "\tWhich will cost $" << nonHybridTotalCost << " over the five years";
}
else
{
cout << "\nThe non-hybrid...\n";
cout << "\tWill use " << nonHybridGasUse << " gallons of gas in five years";
cout << "\tWhich will cost $" << nonHybridTotalCost << " over the five years\n\n";
cout << "The hybrid...\n";
cout << "\tWill use " << hybridGasUse << " gallons of gas in five years";
cout << "\tWhich will cost $" << hybridTotalCost << " over the five years";
}
}
return 0;
}
|
#ifndef STUDENTENVERWALTUNG_H
#define STUDENTENVERWALTUNG_H
#include <iostream>
#include <vector>
#include <student.h>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
class Studentenverwaltung
{
public:
Studentenverwaltung();
void add(Student s){
studenten.push_back(s);
}
void remove(Student s){
int index = 0;
for (auto it : studenten) {
if (it.matr() == s.matr())
break;
else
index++;
}
studenten.erase(studenten.begin() + index);
}
void toCSV(string path);
void fromCSV(string path);
friend ostream& operator<<(ostream& os, const Studentenverwaltung& sv){
for (auto &s: sv.studenten){
os << s << endl;
}
return os;
}
private:
vector<Student> studenten;
};
#endif // STUDENTENVERWALTUNG_H
|
#pragma once
#include "common.h"
namespace StreamCompaction {
namespace CPU {
StreamCompaction::Common::PerformanceTimer& timer();
void scan(int n, int *odata, const int *idata);
int compactWithoutScan(int n, int *odata, const int *idata);
int compactWithScan(int n, int *odata, const int *idata);
void stdSort(int* start, int* end);
}
}
|
void main(){
clrscr();
printf("hello students");
getch();
}
|
// Created on: 2001-01-04
// 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 _Graphic3d_ArrayOfPoints_HeaderFile
#define _Graphic3d_ArrayOfPoints_HeaderFile
#include <Graphic3d_ArrayOfPrimitives.hxx>
//! Contains points array definition.
class Graphic3d_ArrayOfPoints : public Graphic3d_ArrayOfPrimitives
{
DEFINE_STANDARD_RTTIEXT(Graphic3d_ArrayOfPoints, Graphic3d_ArrayOfPrimitives)
public:
//! Creates an array of points (Graphic3d_TOPA_POINTS).
//! The array must be filled using the AddVertex(Point) method.
//! @param theMaxVertexs maximum number of points
//! @param theArrayFlags array flags
Graphic3d_ArrayOfPoints (Standard_Integer theMaxVertexs,
Graphic3d_ArrayFlags theArrayFlags)
: Graphic3d_ArrayOfPrimitives (Graphic3d_TOPA_POINTS, theMaxVertexs, 0, 0, theArrayFlags) {}
//! Creates an array of points (Graphic3d_TOPA_POINTS).
//! The array must be filled using the AddVertex(Point) method.
//! @param theMaxVertexs maximum number of points
//! @param theHasVColors when TRUE, AddVertex(Point,Color) should be used for specifying vertex color
//! @param theHasVNormals when TRUE, AddVertex(Point,Normal) should be used for specifying vertex normal
Graphic3d_ArrayOfPoints (Standard_Integer theMaxVertexs,
Standard_Boolean theHasVColors = Standard_False,
Standard_Boolean theHasVNormals = Standard_False)
: Graphic3d_ArrayOfPrimitives (Graphic3d_TOPA_POINTS, theMaxVertexs, 0, 0,
(theHasVColors ? Graphic3d_ArrayFlags_VertexColor : Graphic3d_ArrayFlags_None)
| (theHasVNormals ? Graphic3d_ArrayFlags_VertexNormal : Graphic3d_ArrayFlags_None)) {}
};
DEFINE_STANDARD_HANDLE(Graphic3d_ArrayOfPoints, Graphic3d_ArrayOfPrimitives)
#endif // _Graphic3d_ArrayOfPoints_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef COLUMN_H
#define COLUMN_H
#include "modules/widgets/OpButton.h"
class OpTreeView;
/**
* @brief A class representing a column
* @author
*
*
*/
class OpTreeView::Column :
public OpButton
{
public:
// -------------------------
// Public member functions:
// -------------------------
/**
*
* @param tree_view
* @param index
*/
Column(OpTreeView* tree_view,
INT32 index);
/**
*
* @param point
*/
virtual void OnMouseMove(const OpPoint &point);
/**
*
*
*/
virtual void OnMouseLeave();
/**
*
* @param point
* @param button
* @param nclicks
*/
virtual void OnMouseDown(const OpPoint &point,
MouseButton button,
UINT8 nclicks);
/**
*
* @param point
* @param button
* @param nclicks
*/
virtual void OnMouseUp(const OpPoint &point,
MouseButton button,
UINT8 nclicks);
/**
*
* @param point
*/
virtual void OnSetCursor(const OpPoint &point);
/**
*
* @param visible
*
* @return
*/
BOOL SetColumnVisibility(BOOL visible)
{
if (m_is_column_visible == visible)
return FALSE; m_is_column_visible = visible;
return m_is_column_user_visible;
}
/**
*
* @param visible
*
* @return
*/
BOOL SetColumnUserVisibility(BOOL visible)
{
if (m_is_column_user_visible == visible)
return FALSE;
m_is_column_user_visible = visible;
return m_is_column_visible;
}
/**
*
* @param matchability
*/
void SetColumnMatchability(BOOL matchability)
{ m_is_column_matchable = matchability; }
/**
*
*
* @return
*/
BOOL IsColumnVisible()
{return m_is_column_visible;}
/**
*
*
* @return
*/
BOOL IsColumnUserVisible()
{return m_is_column_user_visible;}
/**
*
*
* @return
*/
BOOL IsColumnReallyVisible()
{return m_is_column_visible && m_is_column_user_visible;}
/**
*
*
* @return
*/
BOOL IsColumnMatchable()
{return m_is_column_matchable;}
// -------------------------
// Public member variables:
// -------------------------
OpTreeView* m_tree_view;
INT32 m_column_index;
INT32 m_weight;
INT32 m_fixed_width;
INT32 m_width;
BOOL m_has_dropdown;
INT32 m_image_fixed_width;
BOOL m_fixed_image_drawarea;
private:
// -------------------------
// Private member variables:
// -------------------------
BOOL m_is_column_visible;
BOOL m_is_column_user_visible;
BOOL m_is_column_matchable;
};
#endif // COLUMN_H
|
/*
* OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees
* https://octomap.github.io/
*
* Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg
* All rights reserved.
* License: New BSD
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Freiburg nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <octomap/octomap.h>
#include <octomap/OcTree.h>
using namespace std;
using namespace octomap;
void print_query_info(point3d query, OcTreeNode* node) {
if (node != NULL) {
cout << "occupancy probability at " << query << ":\t " << node->getOccupancy() << endl;
}
else
cout << "occupancy probability at " << query << ":\t is unknown" << endl;
}
int main(int /*argc*/, char** /*argv*/) {
cout << endl;
cout << "generating example map" << endl;
OcTree tree (0.1); // create empty tree with resolution 0.1
// insert some measurements of occupied cells
for (int x=-20; x<20; x++) {
for (int y=-20; y<20; y++) {
for (int z=-20; z<20; z++) {
point3d endpoint ((float) x*0.05f, (float) y*0.05f, (float) z*0.05f);
tree.updateNode(endpoint, true); // integrate 'occupied' measurement
}
}
}
// insert some measurements of free cells
for (int x=-30; x<30; x++) {
for (int y=-30; y<30; y++) {
for (int z=-30; z<30; z++) {
point3d endpoint ((float) x*0.02f-1.0f, (float) y*0.02f-1.0f, (float) z*0.02f-1.0f);
tree.updateNode(endpoint, false); // integrate 'free' measurement
}
}
}
cout << endl;
cout << "performing some queries:" << endl;
point3d query (0., 0., 0.);
OcTreeNode* result = tree.search (query);
print_query_info(query, result);
query = point3d(-1.,-1.,-1.);
result = tree.search (query);
print_query_info(query, result);
query = point3d(1.,1.,1.);
result = tree.search (query);
print_query_info(query, result);
cout << endl;
tree.writeBinary("simple_tree.bt");
cout << "wrote example file simple_tree.bt" << endl << endl;
cout << "now you can use octovis to visualize: octovis simple_tree.bt" << endl;
cout << "Hint: hit 'F'-key in viewer to see the freespace" << endl << endl;
}
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
double num, avg;
int pos = 0;
double sum = 0.0;
for(int i=0; i<6; i++)
{
cin>>num;
if(num>0)
{
pos++;
sum = sum+num;
}
}
avg = sum/pos;
cout<<pos<<" valores positivos\n";
cout<<setprecision(2)<<avg<<"\n";
return 0;
}
|
#ifndef GUIEVENTDISPATCHER_H_
#define GUIEVENTDISPATCHER_H_
#include <QObject>
#include <QImage>
#include <QMutex>
#include <QWaitCondition>
#include "StdIncl.hpp"
#include "Logger.hpp"
namespace uipf
{
namespace gui
{
enum GraphViewSelectionType {
NONE /*no selection (transparent)*/,
CURRENT /*the currently selected (blue)*/,
ERROR/*Node with errors (red)*/,
GOOD /*nodes that good e.g. passed a steps (green)*/
};
}
//A class that handles communication between QTGUI components and module-classes
//by exposing signals.
//so module classes can trigger the GUI without the need of implementing QObject
class GUIEventDispatcher : public QObject
{
Q_OBJECT
public:
static GUIEventDispatcher* instance();
protected:
// protected properties accessable by the MainWindow, used for displaying image windows
friend class MainWindow;
// used by triggerCreateWindow to transfer the image into the GUI thread
QImage image_;
// mutex and condition to communicate with the GUI thread to figure out when the image was
// rendered and memory can be freed by our thread.
QMutex mutex;
QWaitCondition imageRendered;
private:
// holds the singleton instance of the GUIEventDispatcher
static GUIEventDispatcher *instance_;
GUIEventDispatcher();
GUIEventDispatcher( const GUIEventDispatcher& );
~GUIEventDispatcher();
// helper class to ensure GUIEventDispatcher gets deleted when the context is gone
class Guard {
public: ~Guard() {
if( GUIEventDispatcher::instance_ != 0 ) {
delete GUIEventDispatcher::instance_;
}
}
};
friend class Guard;
signals: //for QT to connect
void reportProgressEvent(const float& val);
void logEvent(const Logger::LogType& eType, const std::string& strMessage);
void createWindow(const std::string& strTitle);
void closeWindow(const std::string& strTitle);
void clearSelectionInGraphView();
void selectNodesInGraphView(const std::vector<std::string>& vcProcessingStepNames,uipf::gui::GraphViewSelectionType eType,bool bUnselectOthers);
public: //methods for model to call and trigger GUI
void triggerReportProgress(const float& );
void triggerLogEvent(const Logger::LogType& eType, const std::string& strMessage);
void triggerCreateWindow(const std::string& strTitle, const cv::Mat& oMat);
void triggerCloseWindow(const std::string& strTitle);
void triggerClearSelectionInGraphView();
void triggerSelectSingleNodeInGraphView(const std::string& strProcessingStepName,uipf::gui::GraphViewSelectionType eType=uipf::gui::GraphViewSelectionType::CURRENT, bool bUnselectOthers=true);
void triggerSelectNodesInGraphView(const std::vector<std::string>& vcProcessingStepNames,uipf::gui::GraphViewSelectionType eType=uipf::gui::GraphViewSelectionType::CURRENT, bool bUnselectOthers=true);
};
} //namespace
#endif /* GUIEVENTDISPATCHER_H_ */
|
/*
The MIT License (MIT)
Copyright (c) 2017 Paul Marc Liu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <iostream>
#include <cmath>
#include "error_defs.hpp"
#include "model.hpp"
using namespace std;
/**
* Computes the bearing angle (North is 0)
* @param theta
* @param start
* @param end
* @return
*/
int CModel_Data::ComputeThetaAngle(double *theta, BoardPosition start, BoardPosition end){
if ((end.row_pos == start.row_pos) && (end.col_pos == start.col_pos))
return MODEL_ERROR; // atan2 will fail here - div by zero
*theta = atan2(end.col_pos - start.col_pos, end.row_pos - start.row_pos);
*theta = RAD2DEG * (*theta); //convert to degrees
return SUCCESS_OK;
}
|
/**
* Copyright (c) 2007-2012, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 vtab_impl_hh
#define vtab_impl_hh
#include <map>
#include <string>
#include <vector>
#include <sqlite3.h>
#include "logfile_sub_source.hh"
#include "pcrepp/pcre2pp.hh"
#include "robin_hood/robin_hood.h"
class textview_curses;
enum {
VT_COL_LINE_NUMBER,
VT_COL_PARTITION,
VT_COL_LOG_TIME,
VT_COL_LOG_ACTUAL_TIME,
VT_COL_IDLE_MSECS,
VT_COL_LEVEL,
VT_COL_MARK,
VT_COL_LOG_COMMENT,
VT_COL_LOG_TAGS,
VT_COL_LOG_ANNOTATIONS,
VT_COL_FILTERS,
VT_COL_MAX
};
class logfile_sub_source;
struct log_cursor {
struct opid_hash {
unsigned int value : 6;
};
struct string_constraint {
unsigned char sc_op;
std::string sc_value;
std::shared_ptr<lnav::pcre2pp::code> sc_pattern;
string_constraint(unsigned char op, std::string value);
bool matches(const std::string& sf) const;
};
template<typename T>
struct integral_constraint {
unsigned char ic_op;
T ic_value;
static bool op_is_supported(unsigned char op)
{
switch (op) {
case SQLITE_INDEX_CONSTRAINT_EQ:
case SQLITE_INDEX_CONSTRAINT_IS:
case SQLITE_INDEX_CONSTRAINT_NE:
case SQLITE_INDEX_CONSTRAINT_ISNOT:
case SQLITE_INDEX_CONSTRAINT_GT:
case SQLITE_INDEX_CONSTRAINT_LE:
case SQLITE_INDEX_CONSTRAINT_LT:
case SQLITE_INDEX_CONSTRAINT_GE:
return true;
default:
return false;
}
}
integral_constraint(unsigned char op, T value)
: ic_op(op), ic_value(value)
{
}
bool matches(const T& value) const
{
switch (this->ic_op) {
case SQLITE_INDEX_CONSTRAINT_EQ:
case SQLITE_INDEX_CONSTRAINT_IS:
return value == this->ic_value;
case SQLITE_INDEX_CONSTRAINT_NE:
case SQLITE_INDEX_CONSTRAINT_ISNOT:
return value != this->ic_value;
case SQLITE_INDEX_CONSTRAINT_GT:
return value > this->ic_value;
case SQLITE_INDEX_CONSTRAINT_LE:
return value <= this->ic_value;
case SQLITE_INDEX_CONSTRAINT_LT:
return value < this->ic_value;
case SQLITE_INDEX_CONSTRAINT_GE:
return value >= this->ic_value;
default:
return false;
}
}
};
struct column_constraint {
column_constraint(int32_t col, string_constraint cons)
: cc_column(col), cc_constraint(std::move(cons))
{
}
int32_t cc_column;
string_constraint cc_constraint;
};
vis_line_t lc_curr_line;
int lc_sub_index;
vis_line_t lc_end_line;
using level_constraint = integral_constraint<log_level_t>;
nonstd::optional<level_constraint> lc_level_constraint;
intern_string_t lc_format_name;
intern_string_t lc_pattern_name;
nonstd::optional<opid_hash> lc_opid;
std::vector<string_constraint> lc_log_path;
logfile* lc_last_log_path_match{nullptr};
logfile* lc_last_log_path_mismatch{nullptr};
std::vector<string_constraint> lc_unique_path;
logfile* lc_last_unique_path_match{nullptr};
logfile* lc_last_unique_path_mismatch{nullptr};
std::vector<column_constraint> lc_indexed_columns;
std::vector<vis_line_t> lc_indexed_lines;
enum class constraint_t {
none,
unique,
};
void update(unsigned char op, vis_line_t vl, constraint_t cons);
void set_eof() { this->lc_curr_line = this->lc_end_line = 0_vl; }
bool is_eof() const
{
return this->lc_indexed_lines.empty()
&& this->lc_curr_line >= this->lc_end_line;
}
};
const std::string LOG_BODY = "log_body";
const std::string LOG_TIME = "log_time";
class log_vtab_impl {
public:
struct vtab_column {
vtab_column(const std::string name = "",
int type = SQLITE3_TEXT,
const std::string collator = "",
bool hidden = false,
const std::string comment = "",
unsigned int subtype = 0)
: vc_name(name), vc_type(type), vc_collator(collator),
vc_hidden(hidden), vc_comment(comment), vc_subtype(subtype)
{
}
vtab_column& with_comment(const std::string comment)
{
this->vc_comment = comment;
return *this;
}
std::string vc_name;
int vc_type;
std::string vc_collator;
bool vc_hidden;
std::string vc_comment;
int vc_subtype;
};
static std::pair<int, unsigned int> logline_value_to_sqlite_type(
value_kind_t kind);
log_vtab_impl(const intern_string_t name)
: vi_name(name), vi_tags_name(intern_string::lookup(
fmt::format(FMT_STRING("{}.log_tags"), name)))
{
this->vi_attrs.resize(128);
}
virtual ~log_vtab_impl() = default;
intern_string_t get_name() const { return this->vi_name; }
intern_string_t get_tags_name() const { return this->vi_tags_name; }
std::string get_table_statement();
virtual bool is_valid(log_cursor& lc, logfile_sub_source& lss);
virtual void filter(log_cursor& lc, logfile_sub_source& lss) {}
virtual bool next(log_cursor& lc, logfile_sub_source& lss) = 0;
virtual void get_columns(std::vector<vtab_column>& cols) const {}
virtual void get_foreign_keys(std::vector<std::string>& keys_inout) const;
virtual void get_primary_keys(std::vector<std::string>& keys_out) const {}
virtual void extract(logfile* lf,
uint64_t line_number,
logline_value_vector& values);
struct column_index {
robin_hood::unordered_map<std::string, std::vector<vis_line_t>>
ci_value_to_lines;
uint32_t ci_index_generation{0};
vis_line_t ci_max_line{0};
};
std::map<int32_t, column_index> vi_column_indexes;
bool vi_supports_indexes{true};
int vi_column_count{0};
string_attrs_t vi_attrs;
protected:
const intern_string_t vi_name;
const intern_string_t vi_tags_name;
};
class log_format_vtab_impl : public log_vtab_impl {
public:
log_format_vtab_impl(const log_format& format)
: log_vtab_impl(format.get_name()), lfvi_format(format)
{
}
virtual bool next(log_cursor& lc, logfile_sub_source& lss);
protected:
const log_format& lfvi_format;
};
using sql_progress_callback_t = int (*)(const log_cursor&);
using sql_progress_finished_callback_t = void (*)();
struct _log_vtab_data {
bool lvd_looping{true};
sql_progress_callback_t lvd_progress;
sql_progress_finished_callback_t lvd_finished;
source_location lvd_location;
attr_line_t lvd_content;
};
extern thread_local _log_vtab_data log_vtab_data;
class sql_progress_guard {
public:
sql_progress_guard(sql_progress_callback_t cb,
sql_progress_finished_callback_t fcb,
source_location loc,
const attr_line_t& content)
{
log_vtab_data.lvd_looping = true;
log_vtab_data.lvd_progress = cb;
log_vtab_data.lvd_finished = fcb;
log_vtab_data.lvd_location = loc;
log_vtab_data.lvd_content = content;
}
~sql_progress_guard()
{
if (log_vtab_data.lvd_finished) {
log_vtab_data.lvd_finished();
}
log_vtab_data.lvd_looping = true;
log_vtab_data.lvd_progress = nullptr;
log_vtab_data.lvd_finished = nullptr;
log_vtab_data.lvd_location = source_location{};
log_vtab_data.lvd_content.clear();
}
};
class log_vtab_manager {
public:
using iterator = std::map<intern_string_t,
std::shared_ptr<log_vtab_impl>>::const_iterator;
log_vtab_manager(sqlite3* db, textview_curses& tc, logfile_sub_source& lss);
~log_vtab_manager();
textview_curses* get_view() const { return &this->vm_textview; }
logfile_sub_source* get_source() { return &this->vm_source; }
std::string register_vtab(std::shared_ptr<log_vtab_impl> vi);
std::string unregister_vtab(intern_string_t name);
std::shared_ptr<log_vtab_impl> lookup_impl(intern_string_t name) const
{
auto iter = this->vm_impls.find(name);
if (iter != this->vm_impls.end()) {
return iter->second;
}
return nullptr;
}
iterator begin() const { return this->vm_impls.begin(); }
iterator end() const { return this->vm_impls.end(); }
private:
sqlite3* vm_db;
textview_curses& vm_textview;
logfile_sub_source& vm_source;
std::map<intern_string_t, std::shared_ptr<log_vtab_impl>> vm_impls;
};
#endif
|
#pragma once
#include <stdio.h>
#include "user_defined_functions.h"
#include <Windows.h>
#define STATUS_HIBERNATE 0x00
#define STATUS_SLEEP 0x20
#define STATUS_ON 0x40
#define STATUS_POWER 0x60
extern char ACK[5];
extern char NACK[10]; // both of these have been defined in the initACKNACK.cppS
extern HANDLE hSerial; //From the file DataComm.cpp
//void ParseFrame(const unsigned char *Frame, int frameCnt)
void ParseFrame(void *pt)
{
/*
INPUT:
Frame array that contains the packet and the total number of elements in that array.
OUTPUT:
Call to writeDataToPort() with the appropriate reply.
DESC:
Now, we are sending just one frame at a time. Hence, now we can say that we can harcode the value such that
0 --> start byte
1 --> datagram type
ADDITIONAL WORK:
Each command will have various test cases that will have to be covered. So keep on thinking on that.
*/
const unsigned char status0x14[] = { 0x9C, 0x05, 0x17, 0x02, 0x00, 0x01, 0xD7, 0x68, 0x56, 0x00, 0x00, 0x00, 0x14, 0x00, 0x02, 0xD7, 0x68, 0xAA, 0x00, 0x00, 0x00, 0x60, 0xC9 }; //reply for high voltage query.
const char status0x13[] = { 0x9C, 0x04, 0x20, 0x21, 0x22, 0xC9 };
const unsigned char status0X11[] = { 0x9C, 0x02, 0x11, 0x01, 0x64, 0x50, 0x0B, 0xB8, 0xD7, 0x68, 0x56, 0x00, 0xC0, 0x00, 0x00, 0x00, 0xC9 };
const unsigned char status0x17[] = { 0x9c, 0x03, 0x18, 0x16, 0x01, 0x03, 0x1B, 0x10, 0x00, 0x0A, 0x10, 0x9C, 0x22, 0xC9, 0x3C, 0xC9, 0xA5, 0x0E, 0x0B, 0x2C, 0x8C, 0x9C, 0x77, 0xC9 };
const unsigned char status0x15_Temp[] = { 0x9c, 0x05, 0x17, 0x02, 0x00, 0x01, 0xd7, 0x68, 0x56, 0x00, 0x00, 0x00, 0x14, 0x00, 0x02, 0xd7, 0x68, 0xAA, 0x00, 0x00, 0x00, 0x60, 0xc9 };
unsigned char Frame[300];
int frameCnt;
unsigned char lengthPacket;// = Frame[2]; //which is also frameCnt, probably.
unsigned char actCommand;// = Frame[3];
unsigned char dataPacketType;// = Frame[1];
char replyToSend[100];
int noPosh = 0; //this is activated to indicate that the datagram received with parent command as 0x12, has no request related to hib, pow, sleep, on.
//it is just related to Off Alarm.
int ackFlag = 0;
int i; //just for the for loop
//total data bytes = lengthPacket - (1start + 1packetType + 1Length + 1actCommand + 1 stopbyte)
unsigned char cntDataBytes;// = lengthPacket - 5;
static int isRealStream;
int counter;//temporary for 0x17 case
DWORD dwBytesWritten;
PARSE_THREAD *args = (PARSE_THREAD *)pt;
frameCnt = args->count-1;
for (i = 0; i < frameCnt; i++)
{
Frame[i] = args->Frame[i];
}
lengthPacket = Frame[2]; //which is also frameCnt, probably.
actCommand = Frame[3];
dataPacketType = Frame[1];
cntDataBytes = lengthPacket - 5;
if (0 <= ValidatePacketType(dataPacketType))
{
if (-1 == SearchArrCmd(dataPacketType, actCommand))
{
printf("\nCommand - %X is invalid for DataPacketType - %X!", actCommand, dataPacketType);
printf("\nSending NACK...");
writeDataToPort(NACK);
}
else
{
//when the control comes here, it is implicitly implied that the packetType and also the actual command are very much valid.
switch (actCommand)
{
case 0x12: //status
/*
0th byte --> start Frame
1st byte --> datagram packet
2nd byte --> length
3rd byte --> actual command, which in this case is 0x12
4th byte --> Firmware version
5th byte --> battery voltage
6th byte --> operating mode (hibernate, sleep, on or highpower) all have been defined as macros.
*/
switch (Frame[6])
{
case STATUS_HIBERNATE:
printf("\nReceived request for HIBERNATE...");
//PrintCommand(Frame, frameCnt+1);
//writeDataToPort(ACK);
break;
case STATUS_SLEEP:
printf("\nReceived request for SLEEP...");
//PrintCommand(Frame, frameCnt+1);
//writeDataToPort(ACK);
break;
case STATUS_ON:
printf("\nReceived request for ON...");
//PrintCommand(Frame, frameCnt+1);
//writeDataToPort(ACK);
break;
case STATUS_POWER:
printf("\nReceived request for POWER...");
//PrintCommand(Frame, frameCnt+1);
//writeDataToPort(ACK);
break;
default:
/*printf("\nNot a valid status request! Sending NACK!");
writeDataToPort(NACK);*/
noPosh = 1;
break;
}
//Processing the same frame for the alarm bytes
CheckAlarmBytes(Frame, noPosh, &ackFlag);
CheckTimeBytes(Frame, noPosh, &ackFlag); //in both these functions, ackFlag will act as __out__ parameter.
if (2 == ackFlag) // ackFlag will be hardcoded 2, because both these above functions increment it.
{
printf("\nSending Acknowledgement...");
writeDataToPort(ACK);
//reset the ackFlag to 0 for further processing...
ackFlag = 0;
}
break;
case 0x16: //capture data set
printf("\nCapture dataset... \nSending Acknowledgement...");
writeDataToPort(ACK);
break;
case 0x13: //get data set info
printf("\nReceived request for data set info...");
sprintf(replyToSend, "%X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X ",
status0x14[0], status0x14[1], status0x14[2],
status0x14[3], status0x14[4], status0x14[5],
status0x14[6], status0x14[7], status0x14[8],
status0x14[9], status0x14[10], status0x14[11],
status0x14[12], status0x14[13], status0x14[14],
status0x14[15], status0x14[16], status0x14[17],
status0x14[18], status0x14[19], status0x14[20],
status0x14[21], status0x14[22]);
PrintCommand(status0x14, 23);
printf("\nSending information about Data Sets...");
writeDataToPort(replyToSend);
break;
case 0x14://data set transfer command -- NAK or (ACK + respective data set corresponding to the id sent). For now, ACK.
//have to remove this hardcoded method in printing though.. later..
//we are sending the measurement dataset as a response to this command. Length of reply packet is 0x18 ie. 24
//hence we have to send status0x17[] as reply.
//minimum data of 4 bytes assumed. Confirm this later.
if (cntDataBytes<4)
{
printf("\nData Set to transfer not mentioned!");
printf("\nSending NACK!");
writeDataToPort(NACK);
}
else
{
printf("\nReceived request for DataSet Transfer, with dataSetID: %X %X.\nSending Acknowledgement...", Frame[7], Frame[8]);
//writeDataToPort(ACK);
/*sprintf(replyToSend, "%X %X %X %X %X %X %X %X %X %X %X %X %X %X",
status0x15[0], status0x15[1], status0x15[2], status0x15[3],
status0x15[4], status0x15[5], status0x15[6], status0x15[7],
status0x15[8], status0x15[9], status0x15[10], status0x15[11],
status0x15[12], status0x15[13]);*/
sprintf(replyToSend, "%X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X ",
status0x17[0], status0x17[1], status0x17[2], status0x17[3],
status0x17[4], status0x17[5], status0x17[6], status0x17[7],
status0x17[8], status0x17[9], status0x17[10], status0x17[11],
status0x17[12], status0x17[13], status0x17[14], status0x17[15], status0x17[16], status0x17[17],
status0x17[18], status0x17[19], status0x17[20], status0x17[21], status0x17[22], status0x17[23]);
writeDataToPort(replyToSend);
printf("\nSending transfer response...");
PrintCommand(status0x17, 24);
}
break;
case 0x15://erase data set
//minimum data of say around 4 bytes is assumed. Confirm this.
if (cntDataBytes<4)
{
printf("\nData Set to transfer not mentioned!");
printf("\nSending NACK!");
writeDataToPort(NACK);
}
else
{
printf("\nReceived request for erasing dataset...\nSending Acknowledgement...");
writeDataToPort(ACK);
printf("\nErasing data set with ID: %X %X ", Frame[7], Frame[8]);
printf("\nAfter Deletion, sending...");
PrintCommand(status0x15_Temp, 23);
sprintf(replyToSend, "%X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X ",
status0x15_Temp[0], status0x15_Temp[1], status0x15_Temp[2], status0x15_Temp[3], status0x15_Temp[4],
status0x15_Temp[5], status0x15_Temp[6], status0x15_Temp[7], status0x15_Temp[8], status0x15_Temp[9],
status0x15_Temp[10], status0x15_Temp[11], status0x15_Temp[12], status0x15_Temp[13], status0x15_Temp[14],
status0x15_Temp[15], status0x15_Temp[16], status0x15_Temp[17], status0x15_Temp[18], status0x15_Temp[19],
status0x15_Temp[20], status0x15_Temp[21], status0x15_Temp[22]);
writeDataToPort(replyToSend);
}
break;
case 0x11://get status.
printf("\nReceived request for status...\nSending status record...");
sprintf(replyToSend, "%X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X",
status0X11[0], status0X11[1], status0X11[2], status0X11[3],
status0X11[4], status0X11[5], status0X11[6], status0X11[7],
status0X11[8], status0X11[9], status0X11[10], status0X11[11],
status0X11[12], status0X11[13], status0X11[14], status0X11[15],
status0X11[16]);
PrintCommand(status0X11, 17); //this is just to display on our side, what reply we are sending.
writeDataToPort(replyToSend);
break;
case 0x17:
switch (Frame[frameCnt - 1])
{
case 0xFF: //true
isRealStream = 1;
counter = 0;
printf("\nBegin real-time streaming -- TRUE... ");
//writeDataToPort(ACK);
printf("\nReceived request for Real time DataSet Transfer... ");
PrintCommand(status0x17, 24);
sprintf(replyToSend, "%X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X ",
status0x17[0], status0x17[1], status0x17[2], status0x17[3],
status0x17[4], status0x17[5], status0x17[6], status0x17[7],
status0x17[8], status0x17[9], status0x17[10], status0x17[11],
status0x17[12], status0x17[13], status0x17[14], status0x17[15], status0x17[16], status0x17[17],
status0x17[18], status0x17[19], status0x17[20], status0x17[21],
status0x17[22], status0x17[23]);
counter = 0;
while (isRealStream)
{
writeDataToPort(replyToSend);
/*if (WriteFile(hSerial, replyToSend, 24, &dwBytesWritten, NULL))
{
printf("\n Sending Real time data (%d) to COM port... ", ++counter);
printf("\nTotal Bytes Written (Live Streaming): %d", dwBytesWritten);
continue;
}
else
{
printf("\nWriteFile failed: %d", GetLastError());
}*/
//Sleep(1500); //this thread will sleep and continue it's work.
}
break;
case 0x00: //false
isRealStream = 0;
printf("\nStop real-time streaming....");
//writeDataToPort(ACK);
break;
/*default:
printf("\nMissing argument to indicate beginning of streaming real time! Sending NACK!");
writeDataToPort(NACK);*/
break;
default:
printf("\nMissing argument 'TRUE/FALSE'!");
printf("\nSending NACK!");
writeDataToPort(NACK);
break;
}
break;
case 0x18://request to send test signal.
//the output expected is TEST DATA PATTERN 1
printf("\nReceived \"test\" request...");
printf("\nSending pattern 1...");
sprintf(replyToSend, "test data <pattern-1>");//this is temporary, and is going to be updated by the actual packet, which is not known to us at this point.
writeDataToPort(replyToSend);
break;
}
}
}
else
{
printf("\nInvalid type of packet received!");
printf("\nSending NACK!");
writeDataToPort(NACK);
}
}
|
#pragma once
#include "bricks/core/returnpointer.h"
#include "bricks/core/string.h"
#include "bricks/core/value.h"
#include "bricks/threading/threadlocalstorage.h"
#include <jni.h>
namespace Bricks { namespace Java {
class JClass;
namespace JniVersion {
enum Enum {
Unknown = 0,
JNI1_1 = JNI_VERSION_1_1,
JNI1_2 = JNI_VERSION_1_2,
JNI1_4 = JNI_VERSION_1_4,
JNI1_6 = JNI_VERSION_1_6
};
}
class JVM : public Object
{
protected:
bool owner;
JavaVM* vm;
Threading::ThreadLocalStorage<JNIEnv*> environments;
public:
#if !BRICKS_ENV_ANDROID
JVM(JniVersion::Enum version = JniVersion::JNI1_4);
#endif
JVM(JavaVM* vm);
~JVM();
JNIEnv* GetEnv();
ReturnPointer<JClass> GetClass(const String& name);
static void SetCurrentVM(JVM* vm);
static ReturnPointer<JVM> GetCurrentVM();
};
} }
|
#include <iostream>
int gcd(int a, int b)
{
while (b)
{
a %= b;
std::swap(a, b);
}
return a;
}
int main()
{
std::ios_base::sync_with_stdio(false);
std::cin.tie(0);
int n;
std::cin >> n;
for (int i = 0; i < n; ++i)
{
int a, b;
std::cin >> a >> b;
std::cout << (a * b / gcd(a, b)) << '\n';
}
return 0;
}
|
// Created on: 1995-10-19
// Created by: Bruno DUMORTIER
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-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 _BRepOffset_Offset_HeaderFile
#define _BRepOffset_Offset_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <BRepOffset_Status.hxx>
#include <TopoDS_Face.hxx>
#include <TopTools_DataMapOfShapeShape.hxx>
#include <GeomAbs_JoinType.hxx>
#include <GeomAbs_Shape.hxx>
#include <TopTools_ListOfShape.hxx>
class TopoDS_Edge;
class TopoDS_Vertex;
// resolve name collisions with X11 headers
#ifdef Status
#undef Status
#endif
//! This class compute elemenary offset surface.
//! Evaluate the offset generated :
//! 1 - from a face.
//! 2 - from an edge.
//! 3 - from a vertex.
class BRepOffset_Offset
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT BRepOffset_Offset();
Standard_EXPORT BRepOffset_Offset(const TopoDS_Face& Face, const Standard_Real Offset, const Standard_Boolean OffsetOutside = Standard_True, const GeomAbs_JoinType JoinType = GeomAbs_Arc);
//! This method will be called when you want to share
//! the edges soon generated from an other face.
//! e.g. when two faces are tangents the common edge
//! will generate only one edge ( no pipe).
//!
//! The Map will be fill as follow:
//!
//! Created(E) = E'
//! with: E = an edge of <Face>
//! E' = the image of E in the offsetting of
//! another face sharing E with a
//! continuity at least G1
Standard_EXPORT BRepOffset_Offset(const TopoDS_Face& Face, const Standard_Real Offset, const TopTools_DataMapOfShapeShape& Created, const Standard_Boolean OffsetOutside = Standard_True, const GeomAbs_JoinType JoinType = GeomAbs_Arc);
Standard_EXPORT BRepOffset_Offset(const TopoDS_Edge& Path, const TopoDS_Edge& Edge1, const TopoDS_Edge& Edge2, const Standard_Real Offset, const Standard_Boolean Polynomial = Standard_False, const Standard_Real Tol = 1.0e-4, const GeomAbs_Shape Conti = GeomAbs_C1);
Standard_EXPORT BRepOffset_Offset(const TopoDS_Edge& Path, const TopoDS_Edge& Edge1, const TopoDS_Edge& Edge2, const Standard_Real Offset, const TopoDS_Edge& FirstEdge, const TopoDS_Edge& LastEdge, const Standard_Boolean Polynomial = Standard_False, const Standard_Real Tol = 1.0e-4, const GeomAbs_Shape Conti = GeomAbs_C1);
//! Tol and Conti are only used if Polynomial is True
//! (Used to perform the approximation)
Standard_EXPORT BRepOffset_Offset(const TopoDS_Vertex& Vertex, const TopTools_ListOfShape& LEdge, const Standard_Real Offset, const Standard_Boolean Polynomial = Standard_False, const Standard_Real Tol = 1.0e-4, const GeomAbs_Shape Conti = GeomAbs_C1);
Standard_EXPORT void Init (const TopoDS_Face& Face, const Standard_Real Offset, const Standard_Boolean OffsetOutside = Standard_True, const GeomAbs_JoinType JoinType = GeomAbs_Arc);
Standard_EXPORT void Init (const TopoDS_Face& Face, const Standard_Real Offset, const TopTools_DataMapOfShapeShape& Created, const Standard_Boolean OffsetOutside = Standard_True, const GeomAbs_JoinType JoinType = GeomAbs_Arc);
Standard_EXPORT void Init (const TopoDS_Edge& Path, const TopoDS_Edge& Edge1, const TopoDS_Edge& Edge2, const Standard_Real Offset, const Standard_Boolean Polynomial = Standard_False, const Standard_Real Tol = 1.0e-4, const GeomAbs_Shape Conti = GeomAbs_C1);
Standard_EXPORT void Init (const TopoDS_Edge& Path, const TopoDS_Edge& Edge1, const TopoDS_Edge& Edge2, const Standard_Real Offset, const TopoDS_Edge& FirstEdge, const TopoDS_Edge& LastEdge, const Standard_Boolean Polynomial = Standard_False, const Standard_Real Tol = 1.0e-4, const GeomAbs_Shape Conti = GeomAbs_C1);
//! Tol and Conti are only used if Polynomial is True
//! (Used to perform the approximation)
Standard_EXPORT void Init (const TopoDS_Vertex& Vertex, const TopTools_ListOfShape& LEdge, const Standard_Real Offset, const Standard_Boolean Polynomial = Standard_False, const Standard_Real Tol = 1.0e-4, const GeomAbs_Shape Conti = GeomAbs_C1);
//! Only used in Rolling Ball. Pipe on Free Boundary
Standard_EXPORT void Init (const TopoDS_Edge& Edge, const Standard_Real Offset);
const TopoDS_Shape& InitialShape() const;
Standard_EXPORT const TopoDS_Face& Face() const;
Standard_EXPORT TopoDS_Shape Generated (const TopoDS_Shape& Shape) const;
Standard_EXPORT BRepOffset_Status Status() const;
protected:
private:
TopoDS_Shape myShape;
BRepOffset_Status myStatus;
TopoDS_Face myFace;
TopTools_DataMapOfShapeShape myMap;
};
#include <BRepOffset_Offset.lxx>
#endif // _BRepOffset_Offset_HeaderFile
|
#include <iostream>
#include <stdio.h>
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <conio.h>
#include <string.h>
using namespace std;
HANDLE console =GetStdHandle(STD_OUTPUT_HANDLE);
COORD CursorPosition;
inline void d()
{
unsigned long ms=(10);
Sleep( ms );
}
void title();
void game_start();
void clear_console();
void g(int x, int y);
void vertical(int x,int y);
void horizontal(int x,int y);
void dash_a_box1();
void dash_a_box2();
void dash_a_box3();
void dash_b_box1();
void dash_b_box2();
void dash_b_box3();
void dash_c_box1();
void dash_c_box2();
void dash_c_box3();
void baseline();
void display_board();
int input();
int check_process(char from,char inser);
int check_win();
int ar1[3]= {1,2,3},ar2[3]= {0},ar3[3]= {0};
int top1=3,top2=0,top3=0,sol=0,mov=0;
int main()
{
HWND console = GetConsoleWindow();
system("color 0b");
MoveWindow(console, 400,0, 800,740, TRUE);
title();
game_start();
int win=0;
display_board();
while(win==0)
{
win=input();
while(sol==1)
{
g(42,29);
printf("Invalid Move\n");
win=input();
}
display_board();
}
g(37,31);
if(win==1)
{
printf("****Congratulations you won the game in %d moves****",mov);
g(0,40);
}
return 0;
}
void title()
{
int i;
for(i=32; i<90; i++)
{
g(i,3);
printf("*");
g(i,8);
printf("*");
}
for(i=3; i<9; i++)
{
g(32,i);
printf("*");
g(89,i);
printf("*");
}
//t
g(35,4);
printf("__");
g(36,5);
printf("|");
g(36,6);
printf("|");
g(36,4);
printf("__");
//o
g(39,5);
printf("|");
g(39,6);
printf("|");
g(40,4);
printf("__");
g(40,6);
printf("__");
g(42,5);
printf("|");
g(42,6);
printf("|");
//w
g(43,5);
printf("|");
g(43,6);
printf("|");
g(44,6);
printf("/");
g(45,6);
printf("\\");
g(46,5);
printf("|");
g(46,6);
printf("|");
//e
g(47,5);
printf("|");
g(47,6);
printf("|");
g(48,4);
printf("__");
g(48,5);
printf("__");
g(48,6);
printf("__");
//r
g(51,5);
printf("|");
g(51,6);
printf("|");
g(52,4);
printf("_");
g(52,5);
printf("_");
g(53,5);
printf("|");
g(52,6);
printf("\\");
//s
g(55,4);
printf("__");
g(54,5);
printf("|");
g(55,5);
printf("_");
g(56,6);
printf("|");
g(54,6);
printf("__");
//o
g(59,5);
printf("|");
g(59,6);
printf("|");
g(60,4);
printf("__");
g(60,6);
printf("__");
g(62,5);
printf("|");
g(62,6);
printf("|");
//f
g(63,5);
printf("|");
g(63,6);
printf("|");
g(64,4);
printf("__");
g(64,5);
printf("__");
//h
g(68,5);
printf("|");
g(68,6);
printf("|");
g(69,5);
printf("__");
g(71,5);
printf("|");
g(71,6);
printf("|");
//a
g(72,6);
printf("/");
g(73,5);
printf("/");
g(75,6);
printf("\\");
g(74,5);
printf("\\");
//n
g(76,5);
printf("|");
g(76,6);
printf("|");
g(77,5);
printf("\\");
g(78,6);
printf("\\");
g(79,5);
printf("|");
g(79,6);
printf("|");
//o
g(80,5);
printf("|");
g(80,6);
printf("|");
g(81,4);
printf("__");
g(81,6);
printf("__");
g(83,5);
printf("|");
g(83,6);
printf("|");
//i
g(84,4);
printf("__");
g(85,5);
printf("|");
g(85,6);
printf("|");
g(85,4);
printf("__");
g(84,6);
printf("_");
g(86,6);
printf("_");
}
//helper functions
int check_win()
{
int i,flag1=0,flag2=0,flag3=0;
for(i=0; i<3; i++)
{
if(ar1[i]!=0)
flag1=1;
if(ar2[i]!=0)
flag2=1;
if(ar3[i]==0)
flag3=1;
}
if(flag1==0&&flag2==0&&flag3==0)
return 1;
else
return 0;
}
int input()
{
g(42,25);
printf("Enter a place name to remove from : ");
char from;
scanf(" %c",&from);
g(42,27);
printf("Enter a place name to insert into : ");
char inser;
scanf(" %c",&inser);
mov++;
int res=check_process(from,inser);
if(res==0)
sol=1;
else
sol=0;
if(res==1)
{
return check_win();
}
else return 0;
}
int check_process(char from,char inser)
{
int a1,b1;
if((from=='a'||from=='A'))
{
a1=top1;
}
else if((from=='b'||from=='B'))
{
a1=top2;
}
else if((from=='c'||from=='C'))
{
a1=top3;
}
if((inser=='a'||inser=='A'))
{
b1=top1;
}
else if((inser=='b'||inser=='B'))
{
b1=top2;
}
else if((inser=='c'||inser=='C'))
{
b1=top3;
}
if(a1==0&&b1==0)
return 0;
if((from=='a'||from=='A')&&(inser=='b'||inser=='B'))
{
if(top1!=0&&top2==0||ar1[top1-1]>ar2[top2-1])
{
ar2[top2]=ar1[top1-1];
ar1[top1-1]=0;
top1--;
top2++;
return 1;
}
else
return 0;
}
else if((from=='a'||from=='A')&&(inser=='c'||inser=='C'))
{
if(top1!=0&&ar1[top1-1]>ar3[top3-1]||top3==0)
{
ar3[top3]=ar1[top1-1];
ar1[top1-1]=0;
top1--;
top3++;
return 1;
}
else
return 0;
}
else if((from=='b'||from=='B')&&(inser=='a'||inser=='A'))
{
if(top2!=0&&ar2[top2-1]>ar1[top1-1]||top1==0)
{
ar1[top1]=ar2[top2-1];
ar2[top2-1]=0;
top2--;
top1++;
return 1;
}
else
return 0;
}
else if((from=='b'||from=='B')&&(inser=='c'||inser=='C'))
{
if(top2!=0&&ar2[top2-1]>ar3[top3-1]||top3==0)
{
ar3[top3]=ar2[top2-1];
ar2[top2-1]=0;
top2--;
top3++;
return 1;
}
else
return 0;
}
else if((from=='c'||from=='C')&&(inser=='a'||inser=='A'))
{
if(top3!=0&&ar3[top3-1]>ar1[top1-1]||top1==0)
{
ar1[top1]=ar3[top3-1];
ar3[top3-1]=0;
top3--;
top1++;
return 1;
}
else
return 0;
}
else if((from=='c'||from=='C')&&(inser=='b'||inser=='B'))
{
if(top3!=0&&ar3[top3-1]>ar2[top2-1]||top2==0)
{
ar2[top2]=ar3[top3-1];
ar3[top3-1]=0;
top3--;
top2++;
return 1;
}
else
return 0;
}
else
return 0;
}
void display_board()
{
clear_console();
title();
int i;
for(i=0; i<3; i++)
{
if(ar1[i]!=0)
{
if(ar1[i]==1)
{
dash_a_box1();
}
else if(ar1[i]==2)
{
dash_a_box2();
}
else if(ar1[i]==3)
{
dash_a_box3();
}
}
}
for(i=0; i<3; i++)
{
if(ar2[i]!=0)
{
if((ar2[i])==1)
{
dash_b_box1();
}
else if(ar2[i]==2)
{
dash_b_box2();
}
else if(ar2[i]==3)
{
dash_b_box3();
}
}
}
for(i=0; i<3; i++)
{
if(ar3[i]!=0)
{
if(ar3[i]==1)
{
dash_c_box1();
}
else if(ar3[i]==2)
{
dash_c_box2();
}
else if(ar3[i]==3)
{
dash_c_box3();
}
}
}
baseline();
}
void clear_console()
{
system("cls");
}
void g(int x, int y)
{
CursorPosition.X = x;
CursorPosition.Y = y;
SetConsoleCursorPosition(console,CursorPosition);
}
void vertical(int x,int y)
{
HWND console = GetConsoleWindow();
system("color 0b");
MoveWindow(console, 400,0, 800,740, TRUE);
g(x,y);
printf("|");
}
void horizontal(int x,int y)
{
HWND console = GetConsoleWindow();
system("color 0b");
MoveWindow(console, 400,0, 800,740, TRUE);
g(x,y);
printf("-");
}
void dash_a_box1()
{
int i;
for(i=20; i<40; i++)
{
horizontal(i,17);
horizontal(i,20);
}
vertical(20,18);
vertical(20,19);
vertical(39,19);
vertical(39,18);
g(30,19);
printf("1");
}
void dash_a_box2()
{
int i,j=0;
if(top1==1)
j=3;
else if(top1==2&&ar1[0]==2)
j=3;
for(i=22; i<38; i++)
{
horizontal(i,14+j);
horizontal(i,17+j);
}
vertical(22,16+j);
vertical(22,15+j);
vertical(37,15+j);
vertical(37,16+j);
g(30,16+j);
printf("2");
}
void dash_a_box3()
{
int i,j=0;
if(top1==1)
j=6;
else if(top1==2)
j=3;
for(i=24; i<36; i++)
{
horizontal(i,11+j);
horizontal(i,14+j);
}
vertical(24,13+j);
vertical(24,12+j);
vertical(35,12+j);
vertical(35,13+j);
g(30,13+j);
printf("3");
}
void dash_b_box1()
{
int i;
for(i=50; i<70; i++)
{
horizontal(i,17);
horizontal(i,20);
}
vertical(69,19);
vertical(69,18);
vertical(50,19);
vertical(50,18);
g(60,19);
printf("1");
}
void dash_b_box2()
{
int i,j=0;
if(top2==1)
j=3;
else if(top2==2&&ar2[0]==2)
j=3;
for(i=52; i<68; i++)
{
horizontal(i,14+j);
horizontal(i,17+j);
}
vertical(52,15+j);
vertical(52,16+j);
vertical(67,15+j);
vertical(67,16+j);
g(60,16+j);
printf("2");
}
void dash_b_box3()
{
int i,j=0;
if(top2==1)
j=6;
else if(top2==2)
j=3;
for(i=54; i<66; i++)
{
horizontal(i,11+j);
horizontal(i,14+j);
}
vertical(54,12+j);
vertical(54,13+j);
vertical(65,12+j);
vertical(65,13+j);
g(60,13+j);
printf("3");
}
void dash_c_box1()
{
int i;
for(i=80; i<100; i++)
{
horizontal(i,17);
horizontal(i,20);
}
vertical(80,19);
vertical(80,18);
vertical(99,19);
vertical(99,18);
g(90,19);
printf("1");
}
void dash_c_box2()
{
int i,j=0;
if(top3==1)
j=3;
else if(top3==2&&ar3[0]==2)
j=3;
for(i=82; i<98; i++)
{
horizontal(i,14+j);
horizontal(i,17+j);
}
vertical(82,15+j);
vertical(82,16+j);
vertical(97,15+j);
vertical(97,16+j);
g(90,16+j);
printf("2");
}
void dash_c_box3()
{
int i,j=0;
if(top3==1)
j=6;
else if(top3==2)
j=3;
for(i=84; i<96; i++)
{
horizontal(i,11+j);
horizontal(i,14+j);
}
vertical(84,12+j);
vertical(84,13+j);
vertical(95,12+j);
vertical(95,13+j);
g(90,13+j);
printf("3");
}
void baseline()
{
int i;
for(i=15; i<105; i++)
{
horizontal(i,20);
}
g(27,22);
printf("A Place");
g(57,22);
printf("B Place");
g(87,22);
printf("C Place");
}
void game_start()
{
//first dash
dash_a_box3();
dash_a_box2();
dash_a_box1();
//second dash
dash_b_box1();
dash_b_box2();
dash_b_box3();
//third dash
dash_c_box1();
dash_c_box2();
dash_c_box3();
baseline();
g(45,25);
printf("Input any key to play the game : \n") ;
char cha;
g(78,25);
scanf(" %c",&cha);
}
|
#include "MatrixFunctions.h"
#include "Matrix.h"
#include <algorithm>
#include <stdio.h>
#include <iostream>
using namespace MatrixFns;
//A library of functions that act on matrices
//template <typename T>
const char MatrixFns::MatrixFunctions::unstablePivot[] = "Pivot is < epsilon, result is unstable";
template <typename T>
MatrixFns::PLUFactorisation<T> MatrixFunctions::getPLUFactors(const Matrix<T> &B, float epsilon) {
Matrix<T> &A = const_cast<Matrix<T>&>(B);
int no_rows = A.get_no_rows();
int no_cols = A.get_no_cols();
Matrix<T> L = Matrix<T>(no_rows, no_rows);
Matrix<int> P = Matrix<int>(no_rows, no_rows);
P.identity();
Matrix<T> U = Matrix<T>(A);
//iterate over each row in the matrix, swap if necessary and eliminate all below
//finds the largest pivot
int pivotMaxIndex = 0;
Matrix<int> currentPermutation = Matrix<int>(no_rows, no_rows);
T maxPivotValue;
T coefficient;
Matrix<T> tempL = Matrix<T>(no_rows, no_rows);
tempL.identity();
T nextPossiblePivot;
//iterate over each row and swap as necessary
for (int currentRowIndex = 0; currentRowIndex < A.get_no_rows(); currentRowIndex++) {
//get current row
pivotMaxIndex = currentRowIndex;
maxPivotValue = A.get_element(currentRowIndex, currentRowIndex);
for (int counter = currentRowIndex + 1; counter < A.get_no_rows(); counter++) {
//find biggest pivot below rowIndex
nextPossiblePivot = A.get_element(counter, currentRowIndex);
if (nextPossiblePivot > maxPivotValue) {
//cout << nextPossiblePivot << " > " << maxPivotValue << endl;
maxPivotValue = nextPossiblePivot;
pivotMaxIndex = counter;
}
}
if (pivotMaxIndex != currentRowIndex) {
//update P
currentPermutation.identity();
currentPermutation.swap_rows(pivotMaxIndex, currentRowIndex);
P = Matrix<int>(currentPermutation * P);
}
if (maxPivotValue < epsilon) {
//if 0, finished
//throw(unstablePivot);
return MatrixFns::PLUFactorisation<T> { P, L, U };
}
else {
for (int currentColIndex = currentRowIndex + 1; currentColIndex < A.get_no_rows(); currentColIndex++) {
coefficient = -maxPivotValue / U.get_element(currentRowIndex, currentColIndex);
tempL.set_element(currentRowIndex, currentColIndex, coefficient);
U = Matrix<T>(tempL * U);
L = Matrix<T>(tempL * L);
}
}
}
return MatrixFns::PLUFactorisation<T> { P, L, U };
}
template<typename T>
Matrix<T> MatrixFns::MatrixFunctions::getSubMatrix(Matrix<T>& A, int start_row, int start_col, int end_row, int end_col)
{
//Matrix<T>& B = const_cast<Matrix<T&>>(A);
Matrix<T> returnMatrix = Matrix<T>(end_row - start_row, end_col - start_col);
for (int row_counter = start_row; row_counter < end_row; row_counter++) {
for (int col_counter = start_col; col_counter < end_col; col_counter++) {
returnMatrix.set_element(row_counter - start_row, col_counter - start_col, A.get_element(row_counter, col_counter));
}
}
return returnMatrix;
}
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,m;
cin>>n>>m;
//Adjaceny matrix:Use only for a small input sets not for 10 to the power 5********************
//declaration of adjaceny matrix
int adj[n][m];
//take edges as input
for(int i=0;i<m;i++){
int u,v;
cin>>u>>v;
adj[u][v]=1;
adj[v][u]=1;
}
//Adjaceny list **********************************************************
vector<int>adj[n+1]; //use vector<pair<int,int>> if its a weighted graph
for(int i=0;i<m;i++){
int u,v; //wt if weighted graph
cin>>u>>v; //>>wt
adj[u].push_back(v); //adj[u].push_back({v,wt}) for weighted graph;
adj[v].push_back(u); //use this if bidirectional
//adj[v].push_back({u,wt}) for weighted graph; ;
}
return 0;
}
|
#pragma once
#include <openssl/conf.h>
#include <openssl/evp.h>
#include <openssl/err.h>
//#include <openssl/applink.c>
#include <openssl/buffer.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <string>
#include <vector>
#include <chilkat\include\CkJavaKeyStore.h>
#include <chilkat\include\CkCert.h>
#include <chilkat\include\CkPrivateKey.h>
#include <chilkat\include\CkCertChain.h>
#include <chilkat\include\C_CkCert.h>
#include <chilkat\include\CkGlobal.h>
class AES256
{
public:
AES256();
~AES256();
AES256(std::string &strPathToTheKeyStore, std::string &strKeystorePassword,
std::string &strKeyIdentifier, std::string &strKeyPassword);
bool EncryptFile(std::string &strFileName, std::string &strPathToTheKeyStore, std::string &strKeystorePassword,
std::string &strKeyIdentifier, std::string &strKeyPassword, const EVP_CIPHER *cipher_mode, unsigned char *iv = nullptr);
bool DecryptFile(std::string &strFileName, std::string &strPathToTheKeyStore, std::string &strKeystorePassword,
std::string &strKeyIdentifier, std::string &strKeyPassword, const EVP_CIPHER *cipher_mode);
bool EncryptMessage(unsigned char* strMessage, int strMessageLen, const EVP_CIPHER *cipher_mode,
unsigned char **encryptedMessage, int *encryptedMsgLen, unsigned char **outIV);
bool DecryptMessage(unsigned char *strMessage, int strMessageLen, const EVP_CIPHER *cipher_mode,
unsigned char *iv, unsigned char **decryptedMessage, int *decryptedMsgLen);
void ReadKey(std::string &strPathToTheKeyStore, std::string &strKeystorePassword,
std::string &strKeyIdentifier, std::string &strKeyPassword);
protected:
virtual bool GenerateRandomIV(unsigned char **iv, bool &bOutAllocated);
unsigned int CalcCiphertextLen(unsigned int plaintextLen);
int m_iKeySizeInBytes;
int m_iIVSize;
unsigned char *m_key;
private:
void HandleErrors(void);
bool LoadKeystore(std::string &strPathToTheKeyStore, std::string &strKeystorePassword, CkJavaKeyStore &outJceks);
bool LoadSecretKey(CkJavaKeyStore &jceks, std::string &strSecretKeyAlias, std::string &strKeyPassword, std::string &outSecretKey);
int FindSecretKeyPosition(CkJavaKeyStore &jceks, std::string &strSecretKeyAlias);
bool SaveCipherToFile(unsigned char *ciphertext, int ciphertextLen, unsigned char *iv, std::string &strFileName);
bool SavePlainToFile(unsigned char *plaintext, int plaintextLen, std::string &strFileName);
int Encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
unsigned char *iv, unsigned char *ciphertext, const EVP_CIPHER *cipher_mode);
int Decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
unsigned char *iv, unsigned char *plaintext, const EVP_CIPHER *cipher_mode);
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2002 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Alexander Remen (alexr)
*/
#ifndef MAIL_PANEL_H
#define MAIL_PANEL_H
#if defined M2_SUPPORT
#include "adjunct/desktop_pi/desktop_file_chooser.h"
#include "adjunct/m2/src/engine/listeners.h"
#include "adjunct/m2_ui/models/accesstreeview.h"
#include "adjunct/quick/panels/HotlistPanel.h"
#include "adjunct/quick_toolkit/widgets/OpAccordion.h"
#include "modules/widgets/OpWidgetFactory.h"
#include "modules/hardcore/timer/optimer.h"
/***********************************************************************************
**
** MailPanel
**
***********************************************************************************/
class OpProgressBar;
class MailPanel
: public HotlistPanel
, public CategoryListener
, public EngineListener
, public ProgressInfoListener
, public MailNotificationListener
, public DesktopFileChooserListener
, public OpAccordion::OpAccordionListener
{
public:
MailPanel();
virtual OP_STATUS Init();
virtual void GetPanelText(OpString& text, Hotlist::PanelTextType text_type);
virtual const char* GetPanelImage() {return "Panel Mail";}
virtual BOOL GetPanelAttention() { return m_needs_attention; }
virtual void OnLayoutPanel(OpRect& rect);
virtual void OnFullModeChanged(BOOL full_mode);
virtual void OnFocus(BOOL focus,FOCUS_REASON reason);
virtual void OnDeleted();
/** Get list of categories from indexer and populate the mail panel
* @param reset - whether it should reset to the default list
*/
OP_STATUS PopulateCategories(BOOL reset = FALSE);
virtual Type GetType() {return PANEL_TYPE_MAIL;}
// OpWidgetListener
virtual void OnDragMove(OpWidget* widget, OpDragObject* drag_object, INT32 pos, INT32 x, INT32 y) { m_accordion->OnDragMove(widget, drag_object, pos, x, y); }
virtual void OnDragDrop(OpWidget* widget, OpDragObject* drag_object, INT32 pos, INT32 x, INT32 y) { m_accordion->OnDragDrop(widget, drag_object, pos, x, y); }
virtual void OnDragLeave(OpWidget* widget, OpDragObject* drag_object) { m_accordion->OnDragLeave(widget, drag_object); };
// == OpInputContext ======================
virtual BOOL OnInputAction(OpInputAction* action);
virtual const char* GetInputContextName() {return "Mail Panel";}
// == CategoryListener =================
virtual OP_STATUS CategoryAdded(UINT32 index_id) { return AddCategory(index_id); }
virtual OP_STATUS CategoryRemoved(UINT32 index_id);
virtual OP_STATUS CategoryUnreadChanged(UINT32 index_id, UINT32 unread_messages);
virtual OP_STATUS CategoryNameChanged(UINT32 index_id);
virtual OP_STATUS CategoryVisibleChanged(UINT32 index_id, BOOL visible);
// == EngineListener =================
virtual void OnImporterProgressChanged(const Importer* importer, const OpStringC& infoMsg, OpFileLength current, OpFileLength total, BOOL simple = FALSE) {}
virtual void OnImporterFinished(const Importer* importer, const OpStringC& infoMsg) {}
virtual void OnIndexChanged(UINT32 index_id) {}
virtual void OnActiveAccountChanged() { PopulateCategories(); }
virtual void OnReindexingProgressChanged(INT32 progress, INT32 total) {}
// == ProgressInfoListener ==========================
virtual void OnProgressChanged(const ProgressInfo& progress);
virtual void OnSubProgressChanged(const ProgressInfo& progress);
virtual void OnStatusChanged(const ProgressInfo& progress);
// == MailNotificationListener ======================
virtual void NeedNewMessagesNotification(Account* account, unsigned count);
virtual void NeedNoMessagesNotification(Account* account) {}
virtual void NeedSoundNotification(const OpStringC& sound_path) {}
virtual void OnMailViewActivated(MailDesktopWindow* mail_window, BOOL active);
// == OpTimerListener ==========================
virtual void OnTimeOut(OpTimer* timer);
// == FileChooserListener ==========================
virtual void OnFileChoosingDone(DesktopFileChooser* chooser, const DesktopFileChooserResult& result);
// == OpAccordionListener ==========================
virtual void OnItemExpanded( UINT32 id, BOOL expanded);
virtual void OnItemMoved(UINT32 id, UINT32 new_position);
void SetSelectedIndex(index_gid_t index_id);
OP_STATUS ExportMailIndex(UINT32 index_id);
OP_STATUS GetUnreadBadgeWidth(INT32& w);
private:
OpProgressBar* m_status_bar_main;
OpButton* m_status_bar_stop;
OpProgressBar* m_status_bar_sub;
BOOL m_status_timer_started;
OpTimer m_status_timer;
OpAccordion* m_accordion;
OpVector<AccessTreeView> m_access_views; // added as children in the accordion and deleted there
BOOL m_needs_attention;
DesktopFileChooser* m_chooser;
DesktopFileChooserRequest m_request;
index_gid_t m_export_index;
INT32 m_unread_badge_width;
OP_STATUS AddCategory(UINT32 index_id);
OP_STATUS InitAccessView(OpTreeView* access_view, IndexTypes::Id category_id);
const char* GetNewIconForAccount(UINT32 index_id);
};
#endif //M2_SUPPORT
#endif // MAIL_PANEL_H
|
#pragma once
#include "libpytorch.h"
std::ofstream debugfile("pytorchcpp.txt");
// have only used once or twice for debugging
std::mutex m; // to ensure Metatrader only calls on GPU
c10::TensorOptions dtype32_option = th::TensorOptions().dtype(th::kFloat32).requires_grad(false);
c10::TensorOptions dtype64_option = th::TensorOptions().dtype(th::kFloat64).requires_grad(false);
c10::TensorOptions dtypeL_option = th::TensorOptions().dtype(th::kLong).requires_grad(false);
c10::TensorOptions dtype_option = dtype32_option;
th::Device deviceCPU = th::Device(th::kCPU);
th::Device deviceifGPU = deviceCPU;
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
if (th::cuda::is_available()) {
// debugfile << "CUDA is available! Running on GPU." << std::endl;
deviceifGPU = th::Device(th::kCUDA);
}
//debugfile << "process attach" << std::endl;
break;
case DLL_PROCESS_DETACH:
// detach from process
//debugfile << "process deattach" << std::endl;
break;
case DLL_THREAD_ATTACH:
// attach from thread
//debugfile << "thread attach" << std::endl;
break;
case DLL_THREAD_DETACH:
// detach from thread
//debugfile << "thread deattach" << std::endl;
break;
}
return TRUE; // succesful
}
|
//////////////////////////////////////////////////////////////////////
///Copyright (C) 2011-2012 Benjamin Quach
//
//This file is part of the "Lost Horizons" video game demo
//
//"Lost Horizons" is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
//
///////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "alertbox.h"
#define WAITTIME 5000
#define FADETIME 5000;
//displays important text around your ship
CAlertBox::CAlertBox(irr::IrrlichtDevice *graphics)
{
font = graphics->getGUIEnvironment()->getFont("res/font/astro.xml");
this->graphics = graphics;
window_size = graphics->getVideoDriver()->getScreenSize();
time_start =-1;
}
//main run function
//called from gameloop
void CAlertBox::run()
{
//loops through annoucements
//then displays them
for(int i=0;i<text.size();i++)
{
text[i]->setVisible(true);
float difference = (graphics->getTimer()->getTime() +time_start)/1000;
text[i]->setOverrideColor(video::SColor(alpha[i],255,255,255));
//need a better way to move text up
if(text.size()>1)
{
//BUG : above 2 text popups gives me an error about vector out of range
//text[0]->setRelativePosition(position2di(0,-25));
int tmp = i*25;
text[i]->setRelativePosition(position2di(0,tmp));
}
if(difference >= 5/1000)
{
if(alpha[i]>0)
alpha[i]--;
time_start = graphics->getTimer()->getTime();
}
if(alpha[i]<5)
{
text[i]->setVisible(false);
text[i]->remove();
text.erase(text.begin()+i);
alpha.erase(alpha.begin()+i);
}
}
}
void CAlertBox::addText(const wchar_t *texttoadd,WARNING_TYPES type)
{
//add text to the front of the vector
//so popup changes are easier
gui::IGUIStaticText *temp = graphics->getGUIEnvironment()->addStaticText(texttoadd,rect<s32>(0,0,window_size.Width,window_size.Height/1.5),false,true);
temp->setOverrideFont(font);
temp->setTextAlignment(gui::EGUIA_CENTER,gui::EGUIA_CENTER);
temp->setVisible(false);
temp->setEnabled(false);
if(type==NORMAL)
temp->setOverrideColor(video::SColor(255,255,255,255));
if(type==WARNING)
temp->setOverrideColor(video::SColor(255,255,255,0));
if(type==ALERT)
temp->setOverrideColor(video::SColor(255,255,0,0));
//text.push_back(temp);
text.insert(text.begin(),temp);
alpha.insert(alpha.begin(),255);
//alpha.push_back(255);
}
|
// BEGIN CUT HERE
// PROBLEM STATEMENT
// You have two lists of numbers, X and Y, each containing
// exactly N elements. You can optionally apply any number
// of circular shifts to each list. A circular shift means
// removing the last element from a list and re-inserting it
// before the first element. For example, {1, 2, 3} would
// become {3, 1, 2}, and {3, 1, 2} would become {2, 3, 1}.
// After you apply any circular shifts, the final score is
// calculated as:
//
// X[0]*Y[0] + X[1]*Y[1] + ... + X[N-1]*Y[N-1]
//
// You are given ints Z0, A, B and M. Generate a list Z of
// length 2*N, using the following recursive definition:
//
// Z[0] = Z0 MOD M
// Z[i] = (Z[i-1]*A+B) MOD M (note that Z[i-1]*A+B may
// overflow a 32-bit integer)
//
// Then, generate lists X and Y, each of length N, using the
// following definitions:
//
// X[i] = Z[i] MOD 100
// Y[i] = Z[i+N] MOD 100
//
// Return the maximal final score you can achieve.
//
//
//
//
// DEFINITION
// Class:CircularShifts
// Method:maxScore
// Parameters:int, int, int, int, int
// Returns:int
// Method signature:int maxScore(int N, int Z0, int A, int B,
// int M)
//
//
// NOTES
// -In the statement, "A MOD B" represents the remainder of
// integer division of A by B. For example, 14 MOD 5 = 4 and
// 20 MOD 4 = 0.
// -The author's solution does not depend on any properties
// of the pseudorandom generator. It would solve any input of
// allowed size within the given limits.
//
//
// CONSTRAINTS
// -N will be between 1 and 60,000, inclusive.
// -Z0, A and B will each be between 0 and 1,000,000,000,
// inclusive.
// -M will be between 1 and 1,000,000,000, inclusive.
//
//
// EXAMPLES
//
// 0)
// 5
// 1
// 1
// 0
// 13
//
// Returns: 5
//
// Both lists contain only ones, so no matter how many shifts
// you perform, the score will always be 5.
//
// 1)
// 4
// 1
// 1
// 1
// 20
//
// Returns: 70
//
// The lists are {1, 2, 3, 4} and {5, 6, 7, 8}. The maximal
// score is achieved by not making any shifts.
//
// 2)
// 10
// 23
// 11
// 51
// 4322
//
// Returns: 28886
//
// The lists are (23, 4, 95, 20, 17, 94, 63, 44, 13, 96) and
// (87, 54, 13, 18, 61, 24, 17, 94, 53, 2).
//
// 3)
// 1000
// 3252
// 3458736
// 233421
// 111111111
//
// Returns: 2585408
//
//
//
// 4)
// 141
// 96478
// 24834
// 74860
// 92112
//
// Returns: 419992
//
// END CUT HERE
#line 117 "CircularShifts.cc"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include <set>
#include <cassert>
#include <list>
#include <deque>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
using namespace std;
#define fi(n) for(int i=0;i<(n);i++)
#define fj(n) for(int j=0;j<(n);j++)
#define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
typedef vector <int> VI;
typedef vector <string> VS;
typedef vector <VI> VVI;
class CircularShifts
{
public:
int maxScore(int N, long long Z0, long long A, long long B, int M) {
VI x(N),y(N);
VI z(2*N);
z[0 ] = Z0 % M;
f(i,1,2*N) {
z[i] = (z[i-1]*A+B)%M
}
fi(N){
x[i] = z[i] % 100;
y[i] = z[i + N] % 100;
}
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 5; int Arg1 = 1; int Arg2 = 1; int Arg3 = 0; int Arg4 = 13; int Arg5 = 5; verify_case(0, Arg5, maxScore(Arg0, Arg1, Arg2, Arg3, Arg4)); }
void test_case_1() { int Arg0 = 4; int Arg1 = 1; int Arg2 = 1; int Arg3 = 1; int Arg4 = 20; int Arg5 = 70; verify_case(1, Arg5, maxScore(Arg0, Arg1, Arg2, Arg3, Arg4)); }
void test_case_2() { int Arg0 = 10; int Arg1 = 23; int Arg2 = 11; int Arg3 = 51; int Arg4 = 4322; int Arg5 = 28886; verify_case(2, Arg5, maxScore(Arg0, Arg1, Arg2, Arg3, Arg4)); }
void test_case_3() { int Arg0 = 1000; int Arg1 = 3252; int Arg2 = 3458736; int Arg3 = 233421; int Arg4 = 111111111; int Arg5 = 2585408; verify_case(3, Arg5, maxScore(Arg0, Arg1, Arg2, Arg3, Arg4)); }
void test_case_4() { int Arg0 = 141; int Arg1 = 96478; int Arg2 = 24834; int Arg3 = 74860; int Arg4 = 92112; int Arg5 = 419992; verify_case(4, Arg5, maxScore(Arg0, Arg1, Arg2, Arg3, Arg4)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
CircularShifts ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include "outdecl.hpp"
void test_user2() {
out(6);
}
#include "out.cpp"
|
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include "client.h"
#include "Graph.h"
int main() {
std::string line;
int start = 0, end = 0, weight = 0, index = 1;
std::ifstream inputStream;
std::ofstream outputStream;
std::string file;
std::cout << "Enter the file to read data: ";
std::cin >> file;
inputStream.open(file, std::ios::in);
outputStream.open("out"+file);
std::vector<client *> clients;
if (!inputStream.is_open()) {
std::cout << "Unable top open " << "S" << ". Terminating...";
perror("Error when attempting to open the input file.");
exit(1);
}
clients.push_back(new client(0,0,0,0));
while (inputStream >> start && inputStream >> end && inputStream >> weight) {
auto *newClient = new client(start, end, weight, index);
clients.push_back(newClient);
index++;
}
inputStream.close();
auto *graph = new Graph(clients);
std::vector<client*> r = graph->topSort(clients);
auto x = graph->optimalPath(r);
outputStream<<"Input read from "+file << std::endl<<std::endl;
std::cout<<"There are "<<clients.size()-2 << " clients in this file" << std::endl << std::endl;
outputStream<<"There are "<<clients.size()-2 << " clients in this file" << std::endl << std::endl;
outputStream<<"Optimal revenue earned is " << x[0]->pathWeight() << std::endl <<std::endl;
outputStream<<"Clients contributing to this optimal revenue: ";
std::cout<<"Optimal revenue earned is " << x[0]->pathWeight() << std::endl <<std::endl;
std::cout<<"Clients contributing to this optimal revenue: ";
for (int i = 0; i <= x.size()-2; i++) {
std::cout << x[i]->clientIndex();
outputStream<< x[i]->clientIndex();
if(i != x.size()-2){
std::cout << ", ";
outputStream<< ", ";
}
}
outputStream.close();
}
|
#pragma once
#include <string>
namespace BeeeOn {
/*
* @brief The class is intended to contain a specific
* ModuleType Type name.
*/
class CustomTypeID {
public:
enum {
MAX_LENGTH = 64
};
CustomTypeID();
CustomTypeID(const std::string &id);
std::string toString() const;
static CustomTypeID parse(const std::string &input);
bool isNull() const;
bool operator ==(const CustomTypeID &id) const;
bool operator !=(const CustomTypeID &id) const;
bool operator <(const CustomTypeID &id) const;
bool operator >(const CustomTypeID &id) const;
bool operator <=(const CustomTypeID &id) const;
bool operator >=(const CustomTypeID &id) const;
private:
std::string m_value;
};
}
|
#ifndef VULKAN_IMAGE_INFO
#define VULKAN_IMAGE_INFO
#include "vulkan.h"
#include "macro.h"
class ImageInfo {
public:
ImageInfo();
ImageInfo(VkDevice& vkDevice);
ImageInfo(VkDevice& vkDevice, uint32_t width, uint32_t height);
virtual ~ImageInfo();
ImageInfo& operator=(ImageInfo other);
uint32_t width, height;
VkImage image;
VkImageView imageView;
VkDeviceMemory memory;
VkSampler sampler;
VkDevice* mVkDevice;
private:
};
/*
struct VulkanTexture {
VkSampler sampler;
VkImage image;
VkImageLayout imageLayout;
VkDeviceMemory deviceMemory;
VkImageView view;
uint32_t width, height;
uint32_t mipLevels;
uint32_t layerCount;
VkDescriptorImageInfo descriptor;
};
*/
#endif
|
//
// main.cpp
// Task2
//
// Created by Simon Burrows on 09/02/2015.
// Copyright (c) 2015 Simon Burrows. All rights reserved.
//
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cmath>
#include <string.h>
#include <stdio.h>
using namespace std;
bool isNumber(string str);
int readData(double data[], int N, string fileName);
int getDataLength(string fileName);
string openFile();
double calculateMean(double data [], int N);
double calculateSDev(double mean, double data[], int N);
double calculateMeanError(double sDev, int N);
bool finished = false;
int main() {
double *data;
double mean;
double sDev;
double meanError;
//bool finished = false;
string fileName;// = openFile();
int N;// = getDataLength(fileName);
while (!finished) {
fileName = openFile();
if (!finished) {
N = getDataLength(fileName);
data = new double[N];
readData(data, N, fileName);
mean = calculateMean(data, N);
sDev = calculateSDev(mean, data, N);
meanError = calculateMeanError(sDev, N);
cout << "Standard deviaion: " << sDev;
cout << "\nError in the mean: " << meanError << "\n";
delete [] data;
}
}
return 0;
}
double calculateMean(double data[], int N) {
double total(0);
double mean;
for (int i=0; i<N; i++) {
total += data[i];
}
mean = total / N;
return mean;
}
double calculateSDev(double mean, double data[], int N) {
double sumDifferenceSquared(0);
double sDev;
for (int i=0; i<N; i++) {
sumDifferenceSquared += pow(data[i] - mean, 2);
}
sDev = pow((1/((float)(N-1))) * sumDifferenceSquared, 0.5);
return sDev;
}
double calculateMeanError(double sDev, int N) {
double meanError = sDev / pow((float) N, 0.5);
return meanError;
}
int getDataLength(string fileName) {
double dataLength = 0;
std:f:ifstream infile;
infile.open(fileName);
while (infile.good()) {
string value;
infile >> value;
if (!infile.eof()){
cout << value << "\n";
if (isNumber(value)) {
dataLength ++;
}
}
}
cout << "N: " << dataLength;
infile.close();
return dataLength;
}
int readData(double data[], int N, string fileName) {
std::ifstream infile;
infile.open(fileName);
for (int i=0; i<N; i++) {
if (infile.good()) {
infile >> data[i];
}
else {
cout<< "err";
}
}
infile.close();
return 0;
}
string openFile() {
bool fileOpened = false;
string fileName;
while (!fileOpened && !finished) {
cout << "Enter the name of a file of data to analyse it, or type 'end' to finish.\n";
cin >> fileName;
if (fileName == "end") {
finished = true;
}
else {
std::ifstream infile;
infile.open(fileName);
if (infile.good()) {
fileOpened = true;
}
else {
cout << "Failed to open file \n";
}
}
}
return fileName;
}
bool isNumber(string str){
string foo* = str;
for(int i = 0;i < (sizeof(foo)/sizeof(*foo) - 1);i++) {
if((int)str[i] < 10) {
return true;
}
else {
return false;
}
}
}
|
#include "Firebase_Client_Version.h"
#if !FIREBASE_CLIENT_VERSION_CHECK(40319)
#error "Mixed versions compilation."
#endif
/*
* TCP Client Base class, version 1.0.10
*
* Created June 9, 2023
*
* The MIT License (MIT)
* Copyright (c) 2023 K. Suwatchai (Mobizt)
*
*
* Permission is hereby granted, free of charge, to any person returning 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.
*/
#ifndef FB_TCP_CLIENT_BASE_H
#define FB_TCP_CLIENT_BASE_H
#include <Arduino.h>
#include "mbfs/MB_MCU.h"
#include "FB_Utils.h"
#include <IPAddress.h>
#include <Client.h>
typedef enum
{
fb_cert_type_undefined = -1,
fb_cert_type_none = 0,
fb_cert_type_data,
fb_cert_type_file
} fb_cert_type;
typedef enum
{
fb_tcp_client_type_undefined,
fb_tcp_client_type_internal,
fb_tcp_client_type_external
} fb_tcp_client_type;
class FB_TCP_Client_Base
{
friend class FirebaseData;
friend class FB_CM;
friend class Firebase_Signer;
friend class FirebaseESP32;
friend class FirebaseESP8266;
friend class FCMObject;
friend class FB_Functions;
friend class FB_Storage;
friend class GG_CloudStorage;
friend class FB_RTDB;
friend class FB_Firestore;
friend class FIREBASE_CLASS;
friend class Firebase_ESP_Client;
public:
FB_TCP_Client_Base()
{
certType = fb_cert_type_undefined;
};
virtual ~FB_TCP_Client_Base(){};
virtual void ethDNSWorkAround(){};
virtual bool networkReady() { return false; }
virtual void networkReconnect(){};
virtual void disconnect(){};
virtual fb_tcp_client_type type() { return fb_tcp_client_type_undefined; }
virtual bool isInitialized() { return false; }
virtual int hostByName(const char *name, IPAddress &ip) { return 0; }
int virtual setError(int code)
{
if (!response_code)
return -1000;
*response_code = code;
return *response_code;
}
virtual bool begin(const char *host, uint16_t port, int *response_code)
{
this->host = host;
this->port = port;
this->response_code = response_code;
return true;
}
virtual bool connect()
{
if (!client)
return false;
if (connected())
return true;
lastConnMillis = millis();
if (!client->connect(host.c_str(), port))
return setError(FIREBASE_ERROR_TCP_ERROR_CONNECTION_REFUSED);
client->setTimeout(timeoutMs);
return connected();
}
virtual void stop()
{
if (!client)
return;
return client->stop();
};
virtual bool connected()
{
if (client)
return client->connected();
return false;
}
virtual int write(uint8_t *data, int len)
{
if (!data || !client)
return setError(FIREBASE_ERROR_TCP_ERROR_SEND_REQUEST_FAILED);
if (len == 0)
return setError(FIREBASE_ERROR_TCP_ERROR_SEND_REQUEST_FAILED);
if (!networkReady())
return setError(FIREBASE_ERROR_TCP_ERROR_NOT_CONNECTED);
// call base or derived connect.
if (!connected() && (lastConnMillis == 0 || millis() - lastConnMillis > connTimeout))
connect();
if (!connected())
return setError(FIREBASE_ERROR_TCP_ERROR_CONNECTION_REFUSED);
int res = client->write(data, len);
if (res != len)
return setError(FIREBASE_ERROR_TCP_ERROR_SEND_REQUEST_FAILED);
setError(FIREBASE_ERROR_HTTP_CODE_OK);
return len;
}
virtual int send(const char *data, int len = 0)
{
if (len == 0)
len = strlen(data);
return write((uint8_t *)data, len);
}
virtual int print(const char *data)
{
return send(data);
}
virtual int print(int data)
{
char *buf = MemoryHelper::createBuffer<char *>(mbfs, 64);
sprintf(buf, (const char *)MBSTRING_FLASH_MCR("%d"), data);
int ret = send(buf);
MemoryHelper::freeBuffer(mbfs, buf);
return ret;
}
virtual int println(const char *data)
{
int len = send(data);
if (len < 0)
return len;
int sz = send((const char *)MBSTRING_FLASH_MCR("\r\n"));
if (sz < 0)
return sz;
return len + sz;
}
virtual int println(int data)
{
char *buf = MemoryHelper::createBuffer<char *>(mbfs, 64);
sprintf(buf, (const char *)MBSTRING_FLASH_MCR("%d\r\n"), data);
int ret = send(buf);
MemoryHelper::freeBuffer(mbfs, buf);
return ret;
}
virtual int available()
{
if (!client)
return setError(FIREBASE_ERROR_TCP_ERROR_CONNECTION_REFUSED);
return client->available();
}
virtual int read()
{
if (!client)
return setError(FIREBASE_ERROR_TCP_ERROR_CONNECTION_REFUSED);
int r = client->read();
if (r < 0)
return setError(FIREBASE_ERROR_TCP_RESPONSE_READ_FAILED);
return r;
}
virtual int readBytes(uint8_t *buf, int len)
{
if (!client)
return setError(FIREBASE_ERROR_TCP_ERROR_CONNECTION_REFUSED);
int r = client->readBytes(buf, len);
if (r != len)
return setError(FIREBASE_ERROR_TCP_RESPONSE_READ_FAILED);
setError(FIREBASE_ERROR_HTTP_CODE_OK);
return r;
}
virtual int readBytes(char *buf, int len) { return readBytes((uint8_t *)buf, len); }
void baseSetCertType(fb_cert_type type) { certType = type; }
void baseSetTimeout(uint32_t timeoutSec) { timeoutMs = timeoutSec * 1000; }
virtual void flush()
{
if (!client)
return;
while (client->available() > 0)
client->read();
}
fb_cert_type getCertType() { return certType; }
void keepAlive(int tcpKeepIdleSeconds, int tcpKeepIntervalSeconds, int tcpKeepCount)
{
#if defined(USE_CONNECTION_KEEP_ALIVE_MODE)
this->tcpKeepIdleSeconds = tcpKeepIdleSeconds;
this->tcpKeepIntervalSeconds = tcpKeepIntervalSeconds;
this->tcpKeepCount = tcpKeepCount;
isKeepAlive = tcpKeepIdleSeconds > 0 && tcpKeepIntervalSeconds > 0 && tcpKeepCount > 0;
#endif
}
bool isKeepAliveSet() { return tcpKeepIdleSeconds > -1 && tcpKeepIntervalSeconds > -1 && tcpKeepCount > -1; };
private:
void setConfig(FirebaseConfig *config, MB_FS *mbfs)
{
this->config = config;
this->mbfs = mbfs;
}
int tcpTimeout()
{
return timeoutMs;
}
void setSPIEthernet(SPI_ETH_Module *eth) { this->eth = eth; }
fb_cert_type certType = fb_cert_type_undefined;
protected:
MB_String host;
uint16_t port = 0;
Client *client = nullptr;
bool reserved = false;
unsigned long dataStart = 0;
unsigned long dataTime = 0;
MB_FS *mbfs = nullptr;
unsigned long lastConnMillis = 0;
unsigned long connTimeout = 1000;
// lwIP TCP Keepalive idle in seconds.
int tcpKeepIdleSeconds = -1;
// lwIP TCP Keepalive interval in seconds.
int tcpKeepIntervalSeconds = -1;
// lwIP TCP Keepalive count.
int tcpKeepCount = -1;
bool isKeepAlive = false;
// In esp8266, this is actually Arduino base Stream (char read) timeout.
// This will override internally by WiFiClientSecureCtx::_connectSSL
// to 5000 after SSL handshake was done with success.
int timeoutMs = 120000; // 120 sec
bool clockReady = false;
time_t now = 0;
int *response_code = nullptr;
SPI_ETH_Module *eth = NULL;
FirebaseConfig *config = nullptr;
};
#endif
|
#include "vm.h"
VM::VM(const cmdline::parser &cmd, Ran &myran) {
Lx = cmd.get<double>("Lx");
Ly = cmd.exist("Ly") ? cmd.get<double>("Ly") : Lx;
v0 = cmd.get<double>("v0");
double rho0 = cmd.get<double>("rho0");
N = int(Lx * Ly * rho0);
eta = cmd.get<double>("eta");
extra_torque = cmd.get<double>("ext_torque") * PI;
double eps = cmd.get<double>("eps");
if (eps > 0) {
int tot = int(Lx * Ly);
random_torque = new double[tot];
double d = 1.0 / (tot - 1);
for (int i = 0; i < tot; i++)
random_torque[i] = (-0.5 + i * d) * eps * 2 * PI;
myran.shuffle(random_torque, tot);
} else {
random_torque = nullptr;
}
if (cmd.exist("dt")) {
double dt = cmd.get<double>("dt");
V_conti::h = dt;
V_conti::sqrt_24_Dr_h = std::sqrt(24 * eta * dt);
}
#ifdef _MSC_VER
std::cout << "System size: " << Lx << " x " << Ly << "\n";
std::cout << "eta = " << eta << "\n";
std::cout << "eps = " << eps << "\n";
std::cout << "extra torque = " << extra_torque << "\n";
#endif
}
VM::~VM() {
if (random_torque) {
delete[] random_torque;
random_torque = nullptr;
}
}
void VM::output_data(double * x, double * y, double * vx, double * vy) const {
for (int i = 0; i < N; i++) {
get_x(i, x[0], y[0]);
get_v(i, vx[0], vy[0]);
}
}
void VM::ini(const cmdline::parser & cmd, Ran & myran) {
if (cmd.exist("defect_sep")) {
double d = cmd.get<double>("defect_sep");
double alpha = cmd.get<int>("defect_mode") * PI * 0.5;
create_defect_pair(myran, d, alpha);
#ifdef _MSC_VER
std::cout << "create a pair of defects with separation of "
<< d * 2 << "\n";
#endif
} else {
create_random(myran);
#ifdef _MSC_VER
std::cout << "create particles with random positions and velocities\n";
#endif
}
}
void VM::create_random(Ran & myran) {
double *x = new double[N];
double *y = new double[N];
double *vx = new double[N];
double *vy = new double[N];
for (int i = 0; i < N; i++) {
x[i] = myran.doub() * Lx;
y[i] = myran.doub() * Ly;
myran.circle_point_picking(vx[i], vy[i]);
}
input_data(x, y, vx, vy);
delete[] x;
delete[] y;
delete[] vx;
delete[] vy;
}
void VM::create_defect_pair(Ran &myran,
double defect_sep,
double rot_angle) {
double *x = new double[N];
double *y = new double[N];
double *vx = new double[N];
double *vy = new double[N];
for (int i = 0; i < N; i++) {
x[i] = myran.doub() * Lx;
y[i] = myran.doub() * Ly;
double X = x[i] - 0.5 * Lx;
double Y = y[i] - 0.5 * Ly;
double phi1 = std::atan2(Y, X - defect_sep);
double phi2 = std::atan2(Y, X + defect_sep);
double phi = phi1 - phi2 + rot_angle;
vx[i] = std::cos(phi);
vy[i] = std::sin(phi);
}
input_data(x, y, vx, vy);
delete[] x;
delete[] y;
delete[] vx;
delete[] vy;
}
void VM::get_v_mean(double & vx_m, double & vy_m) const {
vx_m = 0;
vy_m = 0;
for (int i = 0; i < N; i++) {
double vx, vy;
get_v(i, vx, vy);
vx_m += vx;
vy_m += vy;
}
vx_m /= N;
vy_m /= N;
}
|
#pragma once
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class Message {
private:
vector<string> subjectvec;
vector<string> datavec;
public:
// map<string, string> message; //map gets rid of duplicates though
void store(string subject, string data) {
subjectvec.push_back(subject);
datavec.push_back(data);
}
void clear() {
subjectvec.clear();
datavec.clear();
}
vector<string> get_subjects() {
return subjectvec;
}
vector<string> get_datas() {
return datavec;
}
string get_subject(int index) {
if(subjectvec.size() >= index) {
return subjectvec[index-1];
}
else{
return "";
}
}
string get_data(int index) {
if(datavec.size() >= index) {
return datavec[index-1];
}
else{
return "";
}
}
};
|
#pragma once
#include <cstdint>
#include <vector>
#include <glm/glm.hpp>
class PixelMap
{
public:
PixelMap() = default;
PixelMap(std::vector<uint8_t> pixels, glm::ivec2 size);
const uint8_t* pixels() const;
const glm::ivec2& size() const;
private:
std::vector<uint8_t> mPixels;
glm::ivec2 mSize;
};
|
#include "DarkGDK.h"
#include "Buttons.h"
#include "Global.h"
//===============================================================================================================================================
// PAUSE BUTTON
//===============================================================================================================================================
void Buttons::buttonPause()
{
if (dbSpriteCollision(1, 2) == 1 && dbMouseClick() == 1)
{
pause = 1;
startPauseTimer = 1;
}
}
//===============================================================================================================================================
// PLAY BUTTON
//===============================================================================================================================================
void Buttons::buttonPlay()
{
//This is so that you can press play to reset the game when the game is over - instead of reset button
if (dbSpriteCollision(1, 3) == 1 && dbMouseClick() == 1 && gameOver == 1)
{
//This kicks down to the reset button, then since the playreset checker is on, it will get reset in settings,
//then kicked back up to play button, but the regular play button will run this time.
pressedPlayReset = 1;
buttonReset();
}
//This is the normal play button which starts the game.
else if (dbSpriteCollision(1, 3) == 1 && dbMouseClick() == 1)
{
phase = 2;
startPauseTimer = 0;
startTime = startTime + (pauseTime * 1000);
pauseTime = 0;
pauseFirst = 0;
pause = 0;
}
}
//===============================================================================================================================================
// RESET BUTTON
//===============================================================================================================================================
void Buttons::buttonReset()
{
if ((dbSpriteCollision(1, 4) == 1 && dbMouseClick() == 1) || pressedPlayReset == 1)
{
//??????????????????????????????????????????????????
//Delete all the mascots
//This is the only thing I had originally, and for the most part it works fine
//The only time it seems to not work is when you press reset in the instant a mascot spawns
for (int x = 101; x < 110; x++) //These sprite ID's are set in the explicit constructor of the mascot class. Should be (101 - 109)
{
dbDeleteSprite(x);
}
//added this here after success with hiding mascots in main.cpp.
//this does not work - problem persists
for (int z = 101; z < 110; z++)
{
dbHideSprite(z);
}
//??????????????????????????????????????????????????
//delete game over overlay image
dbDeleteSprite(30);
//reset game state variables
missed = 0;
homeHits = 0;
score = 0;
gameOver = 0;
levelTime = 0;
level = 1;
difficultyLevel = 3000;
scoreIncrement = 100;
//this makes it to where the next high score can be set
highScoreSet = false;
//reset timer variables
phase = 1; //INIT phase
first = 0;
timerTime = 0;
currentTime = 0;
pause = 0;
//This is for if the play button is pressed to reset the game when the game is over.
if (pressedPlayReset == 1) //Send back to play function so that it starts playing automatically.
{
pressedPlayReset = 0;
buttonPlay();
}
}
}
//===============================================================================================================================================
// SETTINGS BUTTON
//===============================================================================================================================================
void Buttons::buttonSettings()
{
if (dbSpriteCollision(1, 5) == 1 && dbMouseClick() == 1)
{
dbDeleteSprite(2);
dbDeleteSprite(3);
dbDeleteSprite(4);
dbDeleteSprite(5);
//RESET BUTTON STUFF. Could not call reset button from this correctly
//Delete all the mascots
for (int x = 101; x < 110; x++)
{
dbDeleteSprite(x);
}
//delete game over overlay image
dbDeleteSprite(30);
//reset game state variables
missed = 0;
homeHits = 0;
score = 0;
gameOver = 0;
levelTime = 0;
level = 1;
difficultyLevel = 3000;
scoreIncrement = 100;
highScoreSet = false;
//reset timer variables
phase = 3; //This is the phase for settings
first = 0;
timerTime = 0;
currentTime = 0;
pause = 0;
//SETTINGS MENU VARIABLES
justOpened = true;
settingsActive = true;
}
}
|
#include <iostream>
#include "vector.hpp"
int main() {
Vector myVec;
myVec.buildArr(10, 8);
int index = 5;
std::cout << index << "-th element is:\t" << myVec.getElem(index) << "\n";
index = 25;
myVec.getElem(index);
myVec.push(10);
myVec.push(10);
myVec.push(10);
myVec.push(10);
myVec.push(10);
int size = myVec.getSize();
int* myVector = myVec.getVector();
myVec.printVec();
Vector otherVec = myVec;
otherVec.printVec();
otherVec.pop();
otherVec.pop();
otherVec.pop();
otherVec.pop();
otherVec.pop();
std::cout << "otherVec size:\t" << otherVec.getSize() << std::endl;
otherVec.printVec();
return 0;
}
|
#include "Integrator.hpp"
int Base_interp::locate(const double x)
{
int ju, jm, jl;
if (n < 2 || mm < 2 || mm > n) {
wcout << "locate size error" << endl;
throw("locate size error");
}
bool ascnd = (xx[n-1] >= xx[0]);
jl = 0;
ju = n-1;
while (ju+jl > 1) {
jm = (ju+jl) >> 1;
if (x >= xx[jm] == ascnd)
jl = jm;
else
ju = jm;
}
cor = abs(jl-jsav) > dj ? 0 : 1;
jsav = jl;
return max(0, min(n-mm, jl-((mm-2) >> 1)));
}
int Base_interp::hunt(const double x)
{
int jl=jsav, jm, ju, inc=1;
if (n<2||mm<2||mm>n) {
wcout << "hunt size error" << endl;
throw("hunt size error");
}
bool ascnd=(xx[n-1] >= xx[0]);
if (jl<0||jl> n-1) {
jl=0;
ju=n-1;
} else {
if (x >= xx[jl] == ascnd) {
for (;;) {
ju = jl + inc;
if (ju >= n-1) {
ju = n-1;
break;
}
else if (x < xx[ju] == ascnd) break;
else {
jl = ju; inc += inc;
}
}
} else {
ju = jl;
for (;;) {
jl = jl - inc; if (jl <= 0) {
jl = 0;
break;
}
else if (x >= xx[jl] == ascnd) break;
else {
ju = jl; inc += inc;
}
}
}
}
while (ju-jl > 1) {
jm = (ju+jl) >> 1;
if (x >= xx[jm] == ascnd) jl=jm;
else ju=jm;
}
cor = abs(jl-jsav) > dj?0:1;
jsav = jl;
return max(0,min(n-mm,jl-((mm-2)>>1)));
}
double Poly_interp::rawinterp(int jl, double x)
{
int i,m,ns=0;
double y,den,dif,dift,ho,hp,w;
const double *xa = &xx[jl], *ya = &yy[jl];
vector<double> c, d;
c.resize(mm);
d.resize(mm);
dif=abs(x-xa[0]);
for (i=0;i<mm;i++) {
if ((dift=abs(x-xa[i])) < dif) {
ns=i;
dif=dift;
}
c[i]=ya[i];
d[i]=ya[i];
}
y=ya[ns--];
for (m=1;m<mm;m++) {
for (i=0;i<mm-m;i++) {
ho=xa[i]-x;
hp=xa[i+m]-x;
w=c[i+1]-d[i];
if ((den=ho-hp) == 0.0) {
wcout << "Poly_interp error" << endl;
throw("Poly_interp error");
}
den=w/den;
d[i]=hp*den;
c[i]=ho*den;
}
y += (dy=(2*(ns+1) < (mm-m) ? c[ns+1] : d[ns--]));
}
return y;
}
/*
template<class T>
double integrate_levin(T &f, const int nterm)
{
const double pi = boost::math::constants::pi<double>();
double beta = 1.0, a = 0.0, b = 0.0, sum = 0.0;
double ans;
if (nterm > 100)
{
cout << "nterm too large" << endl;
throw("nterm too large");
}
else {
Levin series(100,0.0);
for (int n = 0; n<=nterm;n++) {
b+=pi;
cout << " qromb " << endl;
double s = qromb(f, a, b, 1.0E-8);
cout << " qromb done " << endl;
a=b;
sum += s;
double omega = (beta+n)*s;
ans = series.next(sum, omega, beta);
cout << setw(5) << n << fixed << setprecision(14) << setw(21) << sum << setw(21) << ans << endl;
}
}
return ans;
}*/
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Matt Olan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <util/octet_ops.h>
// 5.7.3 The Table OCT_EXP
const int octet_ops::m_OCT_EXP[] = {
1, 2, 4, 8, 16, 32, 64, 128, 29, 58, 116, 232, 205, 135, 19,
38, 76, 152, 45, 90, 180, 117, 234, 201, 143, 3, 6, 12, 24, 48,
96, 192, 157, 39, 78, 156, 37, 74, 148, 53, 106, 212, 181, 119, 238,
193, 159, 35, 70, 140, 5, 10, 20, 40, 80, 160, 93, 186, 105, 210,
185, 111, 222, 161, 95, 190, 97, 194, 153, 47, 94, 188, 101, 202, 137,
15, 30, 60, 120, 240, 253, 231, 211, 187, 107, 214, 177, 127, 254, 225,
223, 163, 91, 182, 113, 226, 217, 175, 67, 134, 17, 34, 68, 136, 13,
26, 52, 104, 208, 189, 103, 206, 129, 31, 62, 124, 248, 237, 199, 147,
59, 118, 236, 197, 151, 51, 102, 204, 133, 23, 46, 92, 184, 109, 218,
169, 79, 158, 33, 66, 132, 21, 42, 84, 168, 77, 154, 41, 82, 164,
85, 170, 73, 146, 57, 114, 228, 213, 183, 115, 230, 209, 191, 99, 198,
145, 63, 126, 252, 229, 215, 179, 123, 246, 241, 255, 227, 219, 171, 75,
150, 49, 98, 196, 149, 55, 110, 220, 165, 87, 174, 65, 130, 25, 50,
100, 200, 141, 7, 14, 28, 56, 112, 224, 221, 167, 83, 166, 81, 162,
89, 178, 121, 242, 249, 239, 195, 155, 43, 86, 172, 69, 138, 9, 18,
36, 72, 144, 61, 122, 244, 245, 247, 243, 251, 235, 203, 139, 11, 22,
44, 88, 176, 125, 250, 233, 207, 131, 27, 54, 108, 216, 173, 71, 142,
1, 2, 4, 8, 16, 32, 64, 128, 29, 58, 116, 232, 205, 135, 19,
38, 76, 152, 45, 90, 180, 117, 234, 201, 143, 3, 6, 12, 24, 48,
96, 192, 157, 39, 78, 156, 37, 74, 148, 53, 106, 212, 181, 119, 238,
193, 159, 35, 70, 140, 5, 10, 20, 40, 80, 160, 93, 186, 105, 210,
185, 111, 222, 161, 95, 190, 97, 194, 153, 47, 94, 188, 101, 202, 137,
15, 30, 60, 120, 240, 253, 231, 211, 187, 107, 214, 177, 127, 254, 225,
223, 163, 91, 182, 113, 226, 217, 175, 67, 134, 17, 34, 68, 136, 13,
26, 52, 104, 208, 189, 103, 206, 129, 31, 62, 124, 248, 237, 199, 147,
59, 118, 236, 197, 151, 51, 102, 204, 133, 23, 46, 92, 184, 109, 218,
169, 79, 158, 33, 66, 132, 21, 42, 84, 168, 77, 154, 41, 82, 164,
85, 170, 73, 146, 57, 114, 228, 213, 183, 115, 230, 209, 191, 99, 198,
145, 63, 126, 252, 229, 215, 179, 123, 246, 241, 255, 227, 219, 171, 75,
150, 49, 98, 196, 149, 55, 110, 220, 165, 87, 174, 65, 130, 25, 50,
100, 200, 141, 7, 14, 28, 56, 112, 224, 221, 167, 83, 166, 81, 162,
89, 178, 121, 242, 249, 239, 195, 155, 43, 86, 172, 69, 138, 9, 18,
36, 72, 144, 61, 122, 244, 245, 247, 243, 251, 235, 203, 139, 11, 22,
44, 88, 176, 125, 250, 233, 207, 131, 27, 54, 108, 216, 173, 71, 142
};
// 5.7.4 The Table OCT_LOG
const int octet_ops::m_OCT_LOG[] = {
888, 888, 888, 888, 888, 888, 888, 888, 888, 888, 888, 888, 888, 888, 888,
0, 1, 25, 2, 50, 26, 198, 3, 223, 51, 238, 27, 104, 199, 75,
4, 100, 224, 14, 52, 141, 239, 129, 28, 193, 105, 248, 200, 8, 76,
113, 5, 138, 101, 47, 225, 36, 15, 33, 53, 147, 142, 218, 240, 18,
130, 69, 29, 181, 194, 125, 106, 39, 249, 185, 201, 154, 9, 120, 77,
228, 114, 166, 6, 191, 139, 98, 102, 221, 48, 253, 226, 152, 37, 179,
16, 145, 34, 136, 54, 208, 148, 206, 143, 150, 219, 189, 241, 210, 19,
92, 131, 56, 70, 64, 30, 66, 182, 163, 195, 72, 126, 110, 107, 58,
40, 84, 250, 133, 186, 61, 202, 94, 155, 159, 10, 21, 121, 43, 78,
212, 229, 172, 115, 243, 167, 87, 7, 112, 192, 247, 140, 128, 99, 13,
103, 74, 222, 237, 49, 197, 254, 24, 227, 165, 153, 119, 38, 184, 180,
124, 17, 68, 146, 217, 35, 32, 137, 46, 55, 63, 209, 91, 149, 188,
207, 205, 144, 135, 151, 178, 220, 252, 190, 97, 242, 86, 211, 171, 20,
42, 93, 158, 132, 60, 57, 83, 71, 109, 65, 162, 31, 45, 67, 216,
183, 123, 164, 118, 196, 23, 73, 236, 127, 12, 111, 246, 108, 161, 59,
82, 41, 157, 85, 170, 251, 96, 134, 177, 187, 204, 62, 90, 203, 89,
95, 176, 156, 169, 160, 81, 11, 245, 22, 235, 122, 117, 44, 215, 79,
174, 213, 233, 230, 231, 173, 232, 116, 214, 244, 234, 168, 80, 88, 175
};
// 5.7.2 Arithmetic Operations on Octets
uint8_t octet_ops::get_exp(int i)
{
return m_OCT_EXP[i];
}
uint8_t octet_ops::get_log(int i)
{
return m_OCT_LOG[i - 1];
}
uint8_t octet_ops::addition(uint8_t u, uint8_t v)
{
return (uint8_t)(u ^ v);
}
uint8_t octet_ops::subtraction(uint8_t u, uint8_t v)
{
return addition(u, v);
}
uint8_t octet_ops::product(uint8_t u, uint8_t v)
{
if (u == 0 || v == 0) {
return 0;
}
return (uint8_t)get_exp(get_log(u) + get_log(v));
}
uint8_t octet_ops::division(uint8_t u, uint8_t v)
{
if (v == 0) {
throw std::invalid_argument("Denominator cannot be 0.");
}
if (u == 0) {
return 0;
}
return (uint8_t)get_exp((get_log(u) - get_log(v)) + 255);
}
uint8_t octet_ops::alpha_power(int i)
{
return get_exp(i);
}
// 5.7.5 Operations on Symbols
// TODO(pbhandari): Convert uint8_t arrays to vectors.
void octet_ops::beta_product(uint8_t beta, uint8_t *U)
{
// TODO(pbhandari): Check that U != null and length of U > 0.
if (beta == 1) {
return;
}
for (int i = 0; i < static_cast<int>(sizeof(U) / sizeof(U[0])); i++) {
U[i] = product(beta, U[i]);
}
}
// TODO(pbhandari): Convert uint8_t arrays to vectors.
void octet_ops::beta_division(uint8_t *U, uint8_t beta)
{
// TODO(pbhandari): Check that U != null and length of U > 0.
if (beta == 1) {
return;
}
for (int i = 0; i < static_cast<int>(sizeof(U) / sizeof(U[0])); i++) {
U[i] = division(U[i], beta);
}
}
// TODO(pbhandari): Convert uint8_t arrays to vectors.
void octet_ops::beta_product(uint8_t beta, uint8_t U[], int pos, int length)
{
// TODO(pbhandari): Check that U != null and length of U > 0.
if (beta == 1) {
return;
}
for (int i = 0; i < length; i++) {
U[i + pos] = product(beta, U[i + pos]);
}
}
// TODO(pbhandari): Convert uint8_t arrays to vectors.
void octet_ops::beta_division(uint8_t U[], uint8_t beta, int pos, int length)
{
// TODO(pbhandari): Check that U != null and length of U > 0.
if (beta == 1) {
return;
}
for (int i = 0; i < length; i++) {
U[i + pos] = division(U[i + pos], beta);
}
}
|
#pragma once
#include "Interface/IRuntimeModule.h"
#include "Interface/IEvent.h"
#include "Event/Event.h"
#include "Utils/Timer.h"
#include "Utils/ThreadSafeQueue.h"
#include <entt/entt.hpp>
#include <functional>
#include <queue>
#include <list>
#include <map>
struct GLFWwindow;
constexpr uint16_t EVENTMANAGER_NUM_QUEUES = 2;
namespace Rocket
{
using EventCallbackFn = std::function<void(EventPtr &)>;
using EventListenerFnptr = bool(*)(EventPtr&);
using EventListenerDelegate = entt::delegate<bool(EventPtr&)>;
// std::function cannot compare, so use entt
//using EventListenerDelegate = std::function<bool(EventPtr&)>;
using EventListenerList = std::list<EventListenerDelegate>;
using EventListenerMap = Map<EventType, EventListenerList>;
using EventQueue = std::list<EventPtr>;
using EventThreadQueue = ThreadSafeQueue<EventPtr>;
#define REGISTER_DELEGATE_CLASS(f,x) EventListenerDelegate{entt::connect_arg<&f>, x}
#define REGISTER_DELEGATE_FN(f) EventListenerDelegate{entt::connect_arg<&f>}
class EventManager : implements IRuntimeModule
{
public:
RUNTIME_MODULE_TYPE(EventManager);
EventManager(bool global = true) : m_Global(global)
{
if(m_Global)
{
RK_CORE_ASSERT(!s_Instance, "Global EventManager already exists!");
s_Instance = this;
}
}
virtual ~EventManager() = default;
virtual int Initialize() final;
virtual void Finalize() final;
virtual void Tick(Timestep ts) final;
void OnEvent(EventPtr& event);
[[maybe_unused]] bool Update(uint64_t maxMillis = 100);
[[maybe_unused]] bool AddListener(const EventListenerDelegate& eventDelegate, const EventType& type);
[[maybe_unused]] bool RemoveListener(const EventListenerDelegate& eventDelegate, const EventType& type);
[[maybe_unused]] bool TriggerEvent(EventPtr& event) const;
[[maybe_unused]] bool QueueEvent(const EventPtr& event);
[[maybe_unused]] bool ThreadSafeQueueEvent(const EventPtr& event);
[[maybe_unused]] bool AbortEvent(const EventType& type, bool allOfType = false);
// Getter for the main global event manager.
static EventManager* Get(void);
private:
void SetupCallback();
void SetupListener();
// Window attributes
void SetEventCallback(const EventCallbackFn& callback) { m_Data.EventCallback = callback; }
private:
struct WindowData
{
std::string Title;
EventCallbackFn EventCallback;
};
bool m_Global;
GLFWwindow* m_WindowHandle = nullptr;
WindowData m_Data;
int32_t m_ActiveEventQueue;
EventQueue m_EventQueue[2];
EventThreadQueue m_EventThreadQueue;
EventListenerMap m_EventListener;
ElapseTimer m_Timer;
private:
static EventManager* s_Instance;
};
EventManager* GetEventManager();
extern EventManager* g_EventManager;
}
|
#pragma once
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include"MemoryFile.h"
MemoryFile::MemoryFile(CString fileName)
{
hFile = CreateFile(fileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS /*CREATE_ALWAYS*/, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
throw new exCreateFile;
hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READWRITE, NULL, nMaxPoolSize, NULL);
if (!hFileMapping)
throw new exCreateFileMapping;
szMap = (int*)MapViewOfFile(hFileMapping, FILE_MAP_READ | FILE_MAP_WRITE, NULL, NULL, nBytesToMap);
if (szMap == NULL)
throw new exCreateFileMapping;
positionInFile = 0;
}
MemoryFile::~MemoryFile()
{
UnmapViewOfFile(szMap);
CloseHandle(hFileMapping);
CloseHandle(hFile);
}
void MemoryFile::addNumber(int number)
{
szMap[positionInFile++] = (int)number;
}
int MemoryFile::getSize()
{
return positionInFile;
}
void MemoryFile::setPosition(int number)
{
positionInFile = number;
}
wchar_t MemoryFile::getChar(int index)
{
return szMap[index];
}
MemoryFile& operator << (MemoryFile& memMap, const int number)
{
memMap.addNumber(number);
return memMap;
}
MemoryFile& operator >> (MemoryFile& memMap, int& number)
{
number = memMap.szMap[memMap.positionInFile++];
return memMap;
}
|
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
#include <string>
using namespace std;
int val[111], dem[111], n;
int temp, ind, maxCount;
void input() {
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d", &val[i]);
}
void sort() {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (val[i] > val[j]) {
temp = val[i];
val[i] = val[j];
val[j] = temp;
}
}
}
}
void count() {
maxCount = 0;
ind = 0;
for (int i = 0; i < n - 1; i++) {
temp = 1;
for (int j = i + 1; j < n; j++) {
if (val[i] == val[j]) {
temp++;
}
}
if (maxCount <= temp) {
maxCount = temp;
ind = i;
}
}
}
void solve() {
sort();
count();
}
void output(int itest) {
printf("%d %d\n", val[ind], maxCount);
}
int main()
{
int ntest, itest;
freopen("tieuhoc6.inp", "r", stdin);
scanf("%d", &ntest);
for (int itest = 0; itest < ntest; itest++) {
input();
solve();
output(itest);
}
getchar();
return 0;
}
|
/***********************************************************
Starter code for Assignment 3
This code was originally written by Jack Wang for
CSC418, SPRING 2005
implements scene_object.h
***********************************************************/
#include <cmath>
#include <iostream>
#include "scene_object.h"
bool UnitSquare::intersect( Ray3D& ray, const Matrix4x4& worldToModel,
const Matrix4x4& modelToWorld ) {
// TODO: implement intersection code for UnitSquare, which is
// defined on the xy-plane, with vertices (0.5, 0.5, 0),
// (-0.5, 0.5, 0), (-0.5, -0.5, 0), (0.5, -0.5, 0), and normal
// (0, 0, 1).
//
// Your goal here is to fill ray.intersection with correct values
// should an intersection occur. This includes intersection.point,
// intersection.normal, intersection.none, intersection.t_value.
//
// HINT: Remember to first transform the ray into object space
// to simplify the intersection test.
// The ray is shot out in camera coordinates. But remember that
// we had previously changed that to world coordinates!
// We need to change this back to camera coordinates to make
// things easier
// We need to take this and turn it into world coordinates by
// multiplying it with modeltoWorld
Ray3D object_space_ray = Ray3D(worldToModel * ray.origin, worldToModel * ray.dir);
object_space_ray.intersection = ray.intersection;
// Now we're in camera coordinates
// We want to see if it intersects with the unit square
// Since this lies on the xy plane, we just see when it hits z = 0
// Ray is p(t) = q + rt where q is the ray.origin and r is ray.dir (unit vector)
// Just look at the Z element.
// q_z + r_z*t = 0
// If t is negative, there is no intersection (we're shooting off to the other direction)
// If t is positive, then do a check
// Check if the x and y coordinates lie between the unit square
double ray_test_t = -(object_space_ray.origin[2]/object_space_ray.dir[2]);
Point3D plane_intersect_point = object_space_ray.origin + ray_test_t * object_space_ray.dir;
// std::cout << "plane_intersect_point: "<< plane_intersect_point[0]<< " " << plane_intersect_point[1] << " " << plane_intersect_point[2] << ".\n";
if (ray_test_t > 0) {
if (plane_intersect_point[0]<=0.5 && plane_intersect_point[0]>=-0.5
&& plane_intersect_point[1]<=0.5 && plane_intersect_point[1]>=-0.5) {
if(ray.intersection.none || ray_test_t < ray.intersection.t_value){
Intersection intersection_point;
intersection_point.point = modelToWorld * plane_intersect_point;
Vector3D normal(0, 0, 1);
intersection_point.normal = worldToModel.transpose() * normal;
intersection_point.t_value = ray_test_t;
intersection_point.none = false;
ray.intersection = intersection_point;
return true;
}
}
}
// Do not reset ray.intersection.non to true!! It might have gone through the
return false;
}
bool UnitSphere::intersect( Ray3D& ray, const Matrix4x4& worldToModel,
const Matrix4x4& modelToWorld ) {
// TODO: implement intersection code for UnitSphere, which is centred
// on the origin.
//
// Your goal here is to fill ray.intersection with correct values
// should an intersection occur. This includes intersection.point,
// intersection.normal, intersection.none, intersection.t_value.
//
// HINT: Remember to first transform the ray into object space
// to simplify the intersection test.
// Ray3D object_space_ray
// object_space_ray.origin = worldToModel * ray.origin;
// object_space_ray.dir = worldToModel * ray.dir;
// Intersect with the unit sphere centered around the origin
// Draw a vector from center of circle (0,0,0) to the ray origin
// Project that onto yo
Ray3D object_space_ray = Ray3D(worldToModel * ray.origin, worldToModel * ray.dir);
object_space_ray.intersection = ray.intersection;
object_space_ray.dir.normalize(); // We need to normalize to get the correct
// q - c where c = (0, 0, 0)
Vector3D ray_to_circle_center(-1*object_space_ray.origin[0], -1*object_space_ray.origin[1], -1*object_space_ray.origin[2]);
// y^2 = |q - c|^2 - |(q - c) . r|^2
double ray_test_y_squared = pow(ray_to_circle_center.length(),2) - pow(ray_to_circle_center.dot(object_space_ray.dir),2);
// k^2 = d^2 - y^2 where d = 1
double ray_test_k_squared = 1 - ray_test_y_squared;
// if (ray_test_k_squared > 0) {
// std::cout << "K found: "<< ray_test_k_squared << ".\n";
// }
// if k exists, there is at least one point of intersection
if (ray_test_k_squared >= 0) {
double k = sqrt(ray_test_k_squared);
Vector3D ray_including_k;
Vector3D ray_to_intersection;
ray_including_k = object_space_ray.dir.dot(ray_to_circle_center) * object_space_ray.dir;
// multiply with ray_including_k to reduce length to length - k
double length_factor = (ray_including_k.length() - k);
ray_to_intersection = length_factor * object_space_ray.dir;
double t_value = (ray_to_intersection.length() / object_space_ray.dir.length());
if (ray.intersection.none || t_value < ray.intersection.t_value){
// (x,y,z) = r + q
double x = ray_to_intersection[0] + object_space_ray.origin[0];
double y = ray_to_intersection[1] + object_space_ray.origin[1];
double z = ray_to_intersection[2] + object_space_ray.origin[2];
Point3D intersection_point(x, y, z);
ray.intersection.point = modelToWorld * intersection_point;
// Normal vector at the point of intersection
Vector3D normal(intersection_point[0], intersection_point[1], intersection_point[2]);
ray.intersection.normal = worldToModel.transpose() * normal;
ray.intersection.normal.normalize();
// All the t_value variables should have the same value
ray.intersection.t_value = t_value;
ray.intersection.none = false;
return true;
}
}
return false;
}
|
// Question 40 => Find the row with maximum number of 1s
#include<bits/stdc++.h>
using namespace std;
int row_with_max_ones(vector<vector<bool>> mat, int n, int m){
int j = m-1;
while(j>=0 && mat[0][j] == 1){
j--;
}
int row = 0;
for(int i=1; i<n; i++){
while(j>=0 && mat[i][j] == 1){
j--;
row = i;
}
}
return row;
}
int main(){
int t;
cin>>t;
while(t--){
int n,m;
cin>>n>>m;
vector<vector<bool>>mat(n, vector<bool>(m));
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
int d;
cin>>d;
mat[i][j] = d;
}
}
cout<<row_with_max_ones(mat, n, m)<<endl;
}
}
|
#ifndef MATRIX_H
#define MATRIX_H
#include <c++/cstdlib>
#include <c++/ostream>
#include <c++/iomanip>
#include "matrix_lib.h"
using namespace std;
namespace matrix {
template<typename T, size_t N, size_t M>
class Matrix {
public:
Matrix() {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
values[i][j] = 0;
}
}
}
Matrix(const T values[N][M]) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
this->values[i][j] = values[i][j];
}
}
}
Matrix(const Matrix<T, N, M> &rhs) : Matrix(rhs.values) {}
Matrix<T, N, M> &operator=(const Matrix<T, N, M> &rhs) {
if (this != &rhs) {
memcpy(values, rhs.values, sizeof(values));
}
return *this;
}
T const *operator[](int i) const {
return &values[i][0];
}
T *operator[](int i) {
return &values[i][0];
}
int rows() const {
return N;
}
int cols() const {
return M;
}
T norm() const {
T max = 0;
for (int i = 0; i < rows(); ++i) {
T sum = 0;
for (int j = 0; j < cols(); ++j) {
sum += abs(values[i][j]);
}
max = sum > max ? sum : max;
}
return max;
}
Matrix<T, N, M> &operator+=(const Matrix<T, N, M> &rhs) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
values[i][j] += rhs.values[i][j];
}
}
return *this;
}
Matrix<T, N, M> &operator-=(const Matrix<T, N, M> &rhs) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
values[i][j] -= rhs.values[i][j];
}
}
return *this;
}
friend Matrix<T, N, M> operator+(Matrix<T, N, M> lhs, const Matrix<T, N, M> &rhs) {
lhs += rhs;
return lhs;
}
friend Matrix<T, N, M> operator-(Matrix<T, N, M> lhs, const Matrix<T, N, M> &rhs) {
lhs -= rhs;
return lhs;
}
friend ostream &operator<<(ostream &os, const Matrix<T, N, M> &matrix) {
os << setprecision(2);
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
os << setw(11) << matrix[i][j];
}
os << '\n';
}
return os;
}
virtual ~Matrix() {}
private:
T values[N][M];
T abs(T value) const {
return value >= 0 ? value : -value;
}
};
template<typename T, size_t N1, size_t M1, size_t N2, size_t M2>
Matrix<T, N1, M2> operator*(Matrix<T, M1, N1> lhs, const Matrix<T, M2, N2> &rhs) {
if (M2 != N1) {
return Matrix<T, N1, M2>();
}
Matrix<T, N1, M2> res;
for (int i = 0; i < N1; i++) {
for (int j = 0; j < M2; j++) {
for (int k = 0; k < M1; k++) {
res[i][j] += lhs[i][k] * rhs[k][j];
}
}
}
return res;
}
template<size_t N>
Matrix<double, N, N> invert(const Matrix<double, N, N> &matrix) {
double inverted[N][N];
double work[N];
double cond;
int ipvt[N];
double **lu = new double *[N];
for (int i = 0; i < N; ++i) {
lu[i] = new double[N];
for (int j = 0; j < N; ++j) {
lu[i][j] = matrix[i][j];
}
}
decomp(N, lu, &cond, ipvt, work);
for (int i = 0; i < N; i++) {
double vector[N];
for (int j = 0; j < N; j++) {
vector[j] = 0;
}
vector[i] = 1.0;
solve(N, lu, vector, ipvt);
for (int j = 0; j < N; j++) {
inverted[j][i] = vector[j];
}
vector[i] = 0;
}
Matrix<double, N, N> res;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
res[i][j] = inverted[i][j];
}
}
return res;
}
template<typename T, size_t N>
Matrix<T, N, N> identity() {
Matrix<T, N, N> res;
for (int i = 0; i < N; i++) {
res[i][i] = 1;
}
return res;
}
}
#endif
|
#include"vector.h"
void InputVector(double a[], int n)
{
for (int i = 0; i < n; i++)
{
cout << "\nNhap phan tu thu " << i + 1 << " trong vector: ";
cin >> a[i];
}
}
void OutputVector(double a[], int n)
{
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
void multiVector(double a[], int n, double x)
{
cout << "\nTich cua vector voi 1 so: " << endl;
for (int i = 0; i < n; i++)
{
cout << a[i] * x << " ";
}
}
void addVector(double a[], double b[], int n)
{
cout << "\nTong 2 vector: " << endl;
for (int i = 0; i < n; i++)
{
cout << a[i] + b[i] << " ";
}
}
|
#include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <set>
#include <stack>
#include <cstdio>
#include <cstring>
#include <climits>
#include <cstdlib>
using namespace std;
int main() {
/*freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);*/
int n, l, m, u, k;
cin >> n >> l;
vector<vector<int> > graph;
graph.resize(n+1);
for (int i = 1; i <= n; i++) {
cin >> m;
while (m--) {
cin >> u;
graph[u].push_back(i);
}
}
cin >> k;
while (k--) {
vector<bool> visited(n + 1, false);
vector<int> d(n + 1, INT_MAX);
queue<int> q;
int sum = 0, level = 0;
cin >> u;
q.push(u);
d[u] = 0;
while (!q.empty()) {
int t = q.front(); q.pop();
if (d[t] > l) break;
if (visited[t]) continue;
visited[t] = true;
for (auto item : graph[t]) {
q.push(item);
d[item] = min(d[item], d[t] + 1);
}
if (t != u)
sum++;
}
cout << sum << endl;
}
return 0;
}
|
#ifndef DNN_GEOMETRY_EUCLIDEAN_DYNAMIC_H
#define DNN_GEOMETRY_EUCLIDEAN_DYNAMIC_H
#include <vector>
#include <algorithm>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/vector.hpp>
#include <cmath>
#include <hera/common/infinity.h>
namespace hera
{
namespace ws
{
namespace dnn
{
template<class Real_>
class DynamicPointVector
{
public:
using Real = Real_;
struct PointType
{
void* p;
Real& operator[](const int i)
{
return (static_cast<Real*>(p))[i];
}
const Real& operator[](const int i) const
{
return (static_cast<Real*>(p))[i];
}
// TODO: fix to return matching for point clouds
// unreliable hack for now: traits will set static member dim here
size_t get_id() const { return *((size_t*) ((Real*)(p) + dim)); }
static unsigned dim;
};
struct iterator;
typedef iterator const_iterator;
public:
DynamicPointVector(size_t point_capacity = 0):
point_capacity_(point_capacity) {}
PointType operator[](size_t i) const { return {(void*) &storage_[i*point_capacity_]}; }
inline void push_back(PointType p);
inline iterator begin();
inline iterator end();
inline const_iterator begin() const;
inline const_iterator end() const;
size_t size() const { return storage_.size() / point_capacity_; }
void clear() { storage_.clear(); }
void swap(DynamicPointVector& other) { storage_.swap(other.storage_); std::swap(point_capacity_, other.point_capacity_); }
void reserve(size_t sz) { storage_.reserve(sz * point_capacity_); }
void resize(size_t sz) { storage_.resize(sz * point_capacity_); }
private:
size_t point_capacity_;
std::vector<char> storage_;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int version) { ar & point_capacity_ & storage_; }
};
template<class Real_>
unsigned DynamicPointVector<Real_>::PointType::dim = 0;
template<typename Real>
struct DynamicPointTraits
{
typedef DynamicPointVector<Real> PointContainer;
typedef typename PointContainer::PointType PointType;
struct PointHandle
{
void* p;
bool operator==(const PointHandle& other) const { return p == other.p; }
bool operator!=(const PointHandle& other) const { return !(*this == other); }
bool operator<(const PointHandle& other) const { return p < other.p; }
bool operator>(const PointHandle& other) const { return p > other.p; }
};
typedef Real Coordinate;
typedef Real DistanceType;
DynamicPointTraits(unsigned dim = 0):
dim_(dim) { PointType::dim = dim; }
DistanceType distance(PointType p1, PointType p2) const
{
Real result = 0.0;
if (hera::is_infinity(internal_p)) {
// max norm
for (unsigned i = 0; i < dimension(); ++i)
result = std::max(result, fabs(coordinate(p1,i) - coordinate(p2,i)));
} else if (internal_p == Real(1.0)) {
// l1-norm
for (unsigned i = 0; i < dimension(); ++i)
result += fabs(coordinate(p1,i) - coordinate(p2,i));
} else if (internal_p == Real(2.0)) {
result = sqrt(sq_distance(p1,p2));
} else {
assert(internal_p > 1.0);
for (unsigned i = 0; i < dimension(); ++i)
result += std::pow(fabs(coordinate(p1,i) - coordinate(p2,i)), internal_p);
result = std::pow(result, Real(1.0) / internal_p);
}
return result;
}
DistanceType distance(PointHandle p1, PointHandle p2) const { return distance(PointType({p1.p}), PointType({p2.p})); }
DistanceType sq_distance(PointType p1, PointType p2) const { Real res = 0; for (unsigned i = 0; i < dimension(); ++i) { Real c1 = coordinate(p1,i), c2 = coordinate(p2,i); res += (c1 - c2)*(c1 - c2); } return res; }
DistanceType sq_distance(PointHandle p1, PointHandle p2) const { return sq_distance(PointType({p1.p}), PointType({p2.p})); }
unsigned dimension() const { return dim_; }
Real& coordinate(PointType p, unsigned i) const { return ((Real*) p.p)[i]; }
Real& coordinate(PointHandle h, unsigned i) const { return ((Real*) h.p)[i]; }
// it's non-standard to return a reference, but we can rely on it for code that assumes this particular point type
size_t& id(PointType p) const { return *((size_t*) ((Real*) p.p + dimension())); }
size_t& id(PointHandle h) const { return *((size_t*) ((Real*) h.p + dimension())); }
PointHandle handle(PointType p) const { return {p.p}; }
PointType point(PointHandle h) const { return {h.p}; }
void swap(PointType p1, PointType p2) const { std::swap_ranges((char*) p1.p, ((char*) p1.p) + capacity(), (char*) p2.p); }
bool cmp(PointType p1, PointType p2) const { return std::lexicographical_compare((Real*) p1.p, ((Real*) p1.p) + dimension(), (Real*) p2.p, ((Real*) p2.p) + dimension()); }
bool eq(PointType p1, PointType p2) const { return std::equal((Real*) p1.p, ((Real*) p1.p) + dimension(), (Real*) p2.p); }
// non-standard, and possibly a weird name
size_t capacity() const { return sizeof(Real)*dimension() + sizeof(size_t); }
PointContainer container(size_t n = 0) const { PointContainer c(capacity()); c.resize(n); return c; }
PointContainer container(size_t n, const PointType& p) const;
typename PointContainer::iterator
iterator(PointContainer& c, PointHandle ph) const;
typename PointContainer::const_iterator
iterator(const PointContainer& c, PointHandle ph) const;
Real internal_p;
private:
unsigned dim_;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int version) { ar & dim_; }
};
} // dnn
template<class Real>
struct dnn::DynamicPointVector<Real>::iterator:
public boost::iterator_facade<iterator,
PointType,
std::random_access_iterator_tag,
PointType,
std::ptrdiff_t>
{
typedef boost::iterator_facade<iterator,
PointType,
std::random_access_iterator_tag,
PointType,
std::ptrdiff_t> Parent;
public:
typedef typename Parent::value_type value_type;
typedef typename Parent::difference_type difference_type;
typedef typename Parent::reference reference;
iterator(size_t point_capacity = 0):
point_capacity_(point_capacity) {}
iterator(void* p, size_t point_capacity):
p_(p), point_capacity_(point_capacity) {}
private:
void increment() { p_ = ((char*) p_) + point_capacity_; }
void decrement() { p_ = ((char*) p_) - point_capacity_; }
void advance(difference_type n) { p_ = ((char*) p_) + n*point_capacity_; }
difference_type
distance_to(iterator other) const { return (((char*) other.p_) - ((char*) p_))/(int) point_capacity_; }
bool equal(const iterator& other) const { return p_ == other.p_; }
reference dereference() const { return {p_}; }
friend class ::boost::iterator_core_access;
private:
void* p_;
size_t point_capacity_;
};
template<class Real>
void dnn::DynamicPointVector<Real>::push_back(PointType p)
{
if (storage_.capacity() < storage_.size() + point_capacity_)
storage_.reserve(1.5*storage_.capacity());
storage_.resize(storage_.size() + point_capacity_);
std::copy((char*) p.p, (char*) p.p + point_capacity_, storage_.end() - point_capacity_);
}
template<class Real>
typename dnn::DynamicPointVector<Real>::iterator dnn::DynamicPointVector<Real>::begin() { return iterator((void*) &*storage_.begin(), point_capacity_); }
template<class Real>
typename dnn::DynamicPointVector<Real>::iterator dnn::DynamicPointVector<Real>::end() { return iterator((void*) &*storage_.end(), point_capacity_); }
template<class Real>
typename dnn::DynamicPointVector<Real>::const_iterator dnn::DynamicPointVector<Real>::begin() const { return const_iterator((void*) &*storage_.begin(), point_capacity_); }
template<class Real>
typename dnn::DynamicPointVector<Real>::const_iterator dnn::DynamicPointVector<Real>::end() const { return const_iterator((void*) &*storage_.end(), point_capacity_); }
template<typename R>
typename dnn::DynamicPointTraits<R>::PointContainer
dnn::DynamicPointTraits<R>::container(size_t n, const PointType& p) const
{
PointContainer c = container(n);
for (auto x : c)
std::copy((char*) p.p, (char*) p.p + capacity(), (char*) x.p);
return c;
}
template<typename R>
typename dnn::DynamicPointTraits<R>::PointContainer::iterator
dnn::DynamicPointTraits<R>::iterator(PointContainer& c, PointHandle ph) const
{ return typename PointContainer::iterator(ph.p, capacity()); }
template<typename R>
typename dnn::DynamicPointTraits<R>::PointContainer::const_iterator
dnn::DynamicPointTraits<R>::iterator(const PointContainer& c, PointHandle ph) const
{ return typename PointContainer::const_iterator(ph.p, capacity()); }
} // ws
} // hera
namespace std {
template<>
struct hash<typename hera::ws::dnn::DynamicPointTraits<double>::PointHandle>
{
using PointHandle = typename hera::ws::dnn::DynamicPointTraits<double>::PointHandle;
size_t operator()(const PointHandle& ph) const
{
return std::hash<void*>()(ph.p);
}
};
template<>
struct hash<typename hera::ws::dnn::DynamicPointTraits<float>::PointHandle>
{
using PointHandle = typename hera::ws::dnn::DynamicPointTraits<float>::PointHandle;
size_t operator()(const PointHandle& ph) const
{
return std::hash<void*>()(ph.p);
}
};
} // std
#endif
|
// Created on: 2000-08-11
// Created by: Andrey BETENEV
// Copyright (c) 2000-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 XCAFPrs_DataMapOfStyleTransient_HeaderFile
#define XCAFPrs_DataMapOfStyleTransient_HeaderFile
#include <XCAFPrs_Style.hxx>
#include <Standard_Transient.hxx>
#include <NCollection_DataMap.hxx>
typedef NCollection_DataMap<XCAFPrs_Style,Handle(Standard_Transient),XCAFPrs_Style> XCAFPrs_DataMapOfStyleTransient;
typedef NCollection_DataMap<XCAFPrs_Style,Handle(Standard_Transient),XCAFPrs_Style>::Iterator XCAFPrs_DataMapIteratorOfDataMapOfStyleTransient;
#endif
|
#ifndef UTILS_PREPROCESS_H
#define UTILS_PREPROCESS_H
#include "string"
bool pick_option(std::vector<std::string>& args, const std::string& option);
std::string pick_option(std::vector<std::string>& args, const std::string& option, const std::string& default_value);
Parameters init_params(const std::string& file_params, int step_alg);
#endif // UTILS_PREPROCESS_H
|
#include <bits/stdc++.h>
#define loop(i,s,e) for(int i = s;i<=e;i++) //including end point
#define pb(a) push_back(a)
#define sqr(x) ((x)*(x))
#define CIN ios_base::sync_with_stdio(0); cin.tie(0);
#define ll long long
#define ull unsigned long long
#define SZ(a) int(a.size())
#define read() freopen("input.txt", "r", stdin)
#define write() freopen("output.txt", "w", stdout)
#define ms(a,b) memset(a, b, sizeof(a))
#define all(v) v.begin(), v.end()
#define PI acos(-1.0)
#define pf printf
#define sfi(a) scanf("%d",&a);
#define sfii(a,b) scanf("%d %d",&a,&b);
#define sfl(a) scanf("%lld",&a);
#define sfll(a,b) scanf("%lld %lld",&a,&b);
#define sful(a) scanf("%llu",&a);
#define sfulul(a,b) scanf("%llu %llu",&a,&b);
#define sful2(a,b) scanf("%llu %llu",&a,&b); // A little different
#define sfc(a) scanf("%c",&a);
#define sfs(a) scanf("%s",a);
#define getl(s) getline(cin,s);
#define mp make_pair
#define paii pair<int, int>
#define padd pair<dd, dd>
#define pall pair<ll, ll>
#define vi vector<int>
#define vll vector<ll>
#define mii map<int,int>
#define mlli map<ll,int>
#define mib map<int,bool>
#define fs first
#define sc second
#define CASE(t) printf("Case %d: ",++t) // t initialized 0
#define cCASE(t) cout<<"Case "<<++t<<": ";
#define D(v,status) cout<<status<<" "<<v<<endl;
#define INF 1000000000 //10e9
#define EPS 1e-9
#define flc fflush(stdout); //For interactive programs , flush while using pf (that's why __c )
#define CONTEST 1
using namespace std;
//Bit Manipulation
bool Check_ON(int mask,int pos) //Check if pos th bit (from right) of mask is ON
{
if( (mask & (1<<pos) ) == 0 )return false;
return true;
}
int SET(int mask,int pos) //Save the returned mask into some var //Turn on pos th bit in mask
{
return (mask | (1<<pos));
}
int RESET(int mask,int pos) //Save the returned mask into some var //Turn off pos th bit in mask
{
return (mask & ~(1<<pos));
}
int FLIP(int mask,int pos) //Save the returned mask into some var //Toggle/Flip pos th bit in mask
{
return (mask ^ (1<<pos));
}
int LSB(int mask) // The actual LSB mask
{
return (mask & (-mask));
}
int LSB_pos(int mask) // 0 based position
{
int mask_2 = (mask & (-mask));
for(int pos = 0; pos<=15; pos++)
{
if(Check_ON(mask_2,pos))
return pos;
}
return -1;//
}
int ON_Bits(int mask)
{
return __builtin_popcount(mask);
}
inline int clz(int N) // O(1) way to calculate log2(X) (int s only)
{
return N ? 32 - __builtin_clz(N) : -INF;
}
ll ai[100005];
struct node
{
int freq[105];
};
node tree[5*100005];
void build(int root,int b,int e)
{
if(b==e)
{
for(int vv=0; vv<=100; vv++)
{
tree[root].freq[vv] = 0;
}
int vl = ai[b];
tree[root].freq[vl]++;
return;
}
int mid = (b+e)/2;
int lc = root*2;
int rc = lc+1;
build(lc,b,mid);
build(rc,mid+1,e);
for(int fv=0; fv<=100; fv++)
{
tree[root].freq[fv]
= tree[lc].freq[fv]
+ tree[rc].freq[fv];
}
}
void update(int root,int b,int e,int i,int v)
{
if(b>i || e<i)
return;
if(b==e && b==i)
{
for(int vv=0; vv<=100; vv++)
{
tree[root].freq[vv] = 0;
}
int vl = v;
tree[root].freq[v]++;
return;
}
int mid = (b+e)/2;
int lc = root*2;
int rc = lc+1;
update(lc,b,mid,i,v);
update(rc,mid+1,e,i,v);
for(int fv=0; fv<=100; fv++)
{
tree[root].freq[fv]
= tree[lc].freq[fv]
+ tree[rc].freq[fv];
}
}
int query(int root,int b,int e,int l,int r,int v)
{
if(b>r || e<l)
{
return 0;
}
if(b>=l && e<=r)
{
return tree[root].freq[v];
}
int mid = (b+e)/2;
int lc = root*2;
int rc = lc+1;
int p1 = query(lc,b,mid,l,r,v);
int p2 = query(rc,mid+1,e,l,r,v);
return p1+p2;
}
int main()
{
int tc;
sfi(tc);
while(tc--)
{
int n,q;
sfii(n,q);
for(int i=1; i<=n; i++)
{
sfl(ai[i]);
}
if(n<=5000)
{
while(q--)
{
int cmd;
sfi(cmd);
if(cmd==1)
{
int L,R;
sfii(L,R);
ll mxans = 0;
for(int xi=L; xi<=R; xi++)
{
mxans = max(mxans,
(ai[xi]-ai[L])*(ai[R]-ai[xi]));
}
pf("%lld\n",mxans);
}
else
{
int xx,yy;
sfii(xx,yy);
ai[xx] = yy;
}
}
}
else
{
build(1,1,n);
while(q--)
{
int cmd;
sfi(cmd);
if(cmd==1)
{
int L,R;
sfii(L,R);
ll mxans = 0;
for(int xi=0; xi<=100; xi++)
{
if(query(1,1,n,L,R,xi)>0)
{
mxans = max(mxans,
(xi-ai[L])*(ai[R]-xi));
}
}
pf("%lld\n",mxans);
}
else
{
int xx;
int yy;
sfii(xx,yy);
update(1,1,n,xx,yy);
}
}
}
}
return 0;
}
|
#ifndef _RAY_HH_
#define _RAY_HH_
#include "Vector3F.hh"
class Ray{
Vector3F orig;
Vector3F dir;
public:
Ray(const Vector3F &orig, const Vector3F &dir, bool normalize = true);
Vector3F get_orig(void) const;
Vector3F get_dir(void) const;
Vector3F getPointAtT(float t) const;
};
#endif /* _RAY_HH_ */
|
#pragma once
#include <QVariant>
#include <QString>
class NamedValue {
public:
// :: Lifecycle ::
NamedValue(const QString &name = QString(),
const QVariant &value = QVariant());
// :: Accessors ::
const QString &getName() const;
void setName(const QString &name);
const QVariant &getValue() const;
void setValue(const QVariant &value);
private:
QString m_name;
QVariant m_value;
};
bool operator ==(const NamedValue &lhs, const NamedValue &rhs);
|
#ifndef MENU_H
#define MENU_H
#include <string>
#include <vector>
#include <cstdlib>
#include "base_menu.h"
using namespace std;
class Menu : public BaseMenu
{
public:
class MenuIterator : public Iterator<BaseMenu*>
{
public:
MenuIterator(Menu *m)
{
_menu=m;
}
void first()
{
_current=_menu->_vMenu.begin();
}
void next()
{
++_current;
}
bool isDone()const
{
return (_current == _menu->_vMenu.end());
}
BaseMenu *currentItem()
{
return *_current;
}
private:
Menu *_menu;
vector<BaseMenu *>::iterator _current;
};
Menu(std::string newName, std::string newDescr = "no description available")
:BaseMenu(newName, newDescr)
{
_totalPrice = 0;
}
Iterator<BaseMenu *>*createIterator()
{
return new MenuIterator(this);
}
void addItem(BaseMenu* item)
{
_vMenu.push_back(item);
}
// void delItem(string name)
// {
// Iterator<BaseMenu *> *it = createIterator();
// for (it->first();!it->isDone();it->next())
// {
// if(it->currentItem()->getName()==name)
// {
// _vMenu.erase(*it->currentItem());
// break;
// }
// }
// }
BaseMenu* getItem(std::string name)
{
Iterator<BaseMenu *> *it = createIterator();
for (it->first();!it->isDone();it->next()) {
if(it->currentItem()->getName()==name) return it->currentItem();
}
//throw std::invalid_argument("Not Found");
return nullptr;
}
bool isVegetarian()
{
Iterator<BaseMenu *> *it = createIterator();
for (it->first();!it->isDone();it->next())
if(!it->currentItem()->isVegetarian())return false;
return true;
}
bool isVegetarian(BaseMenu *m)
{
return m->isVegetarian();
}
void setTotalPrice(double)
{
Iterator<BaseMenu *> *it = createIterator();
for (it->first();!it->isDone();it->next())_totalPrice+=it->currentItem()->getPrice();
}
double getTotalPrice()
{
return _totalPrice;
}
double getPrice()
{
return _totalPrice;
}
void printMenu()
{
cout<<"\t+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<endl
<<"\t+ +"<<endl
<<"\t+\t\t\t"<<getName()<<"\t\t\t\t+"<<endl;
Iterator<BaseMenu *> *it = createIterator();
int number = 1;
for (it->first();!it->isDone();it->next())
{
cout<<"\t+"<<"\t"<<number<<". "<<it->currentItem()->getName()<<"\t"<<it->currentItem()->getDescription()<<"\t";
if (it->currentItem()->isVegetarian()) cout<<"T\t";
else cout<<"F\t";
cout<<it->currentItem()->getPrice()<<"\t+"<<endl;
number++;
}
cout <<"\t+ +"<<endl
<<"\t+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<endl;
}
private:
double _totalPrice;
vector<BaseMenu *> _vMenu;
};
#endif
|
#include "femb.h"
#include <unistd.h>
#include <cstdio>
constexpr size_t CD_I2C_ADDR[] = { 0xA0010000, 0xA0040000, 0xA0050000, 0xA0060000, 0xA0070000, 0xA0080000, 0xA0090000, 0xA00A0000 };
// for all coldata chips
constexpr size_t CD_FASTCMD_ADDR = 0xA0030000;
io_reg_t FEMB::coldata_fast_cmd;
FEMB::FEMB(int _index) : index(_index) {
for (uint8_t i = 0; i < 2; i++) {
io_reg_init(&this->coldata_i2c[i],CD_I2C_ADDR[i+index*2],2);
last_coldata_i2c_chip[i] = -1;
}
}
FEMB::~FEMB() {
for (uint8_t i = 0; i < 2; i++) {
io_reg_free(&this->coldata_i2c[i]);
}
}
bool FEMB::configure_coldata(bool cold, FrameType frame) {
bool res = true;
//See COLDATA datasheet
for (uint8_t i = 0; i < 2; i++) { // For each COLDATA on FEMB
if (cold) {
res &= i2c_write_verify(i, 2, 5, 0x40, 0x3); //CONFIG_PLL_ICP
res &= i2c_write_verify(i, 2, 5, 0x41, 0x10); //CONFIG_PLL_BAND
res &= i2c_write_verify(i, 2, 5, 0x42, 0x2); //CONFIG_PLL_LPFR
res &= i2c_write_verify(i, 2, 5, 0x43, 0x2); //CONFIG_PLL_ATO
res &= i2c_write_verify(i, 2, 5, 0x44, 0x0); //CONFIG_PLL_PDCP
res &= i2c_write_verify(i, 2, 5, 0x45, 0x0); //CONFIG_PLL_OPEN
} else {
res &= i2c_write_verify(i, 2, 5, 0x40, 0x3); //CONFIG_PLL_ICP
res &= i2c_write_verify(i, 2, 5, 0x41, 0x4); //CONFIG_PLL_BAND
res &= i2c_write_verify(i, 2, 5, 0x42, 0x2); //CONFIG_PLL_LPFR
res &= i2c_write_verify(i, 2, 5, 0x43, 0x2); //CONFIG_PLL_ATO
res &= i2c_write_verify(i, 2, 5, 0x44, 0x0); //CONFIG_PLL_PDCP
res &= i2c_write_verify(i, 2, 5, 0x45, 0x0); //CONFIG_PLL_OPEN
}
res &= i2c_write_verify(i, 2, 5, 0x46, 0x1); //CONFIG_SER_MODE
res &= i2c_write_verify(i, 2, 5, 0x47, 0x0); //CONFIG_SER_INV_SER_CLK
res &= i2c_write_verify(i, 2, 5, 0x48, 0x0); //CONFIG_DRV_VMBOOST
res &= i2c_write_verify(i, 2, 5, 0x49, 0x0); //CONFIG_DRV_VMDRIVER
res &= i2c_write_verify(i, 2, 5, 0x4a, 0x0); //CONFIG_DRV_SELPRE
res &= i2c_write_verify(i, 2, 5, 0x4b, 0x0); //CONFIG_DRV_SELPST1
res &= i2c_write_verify(i, 2, 5, 0x4c, 0x0); //CONFIG_DRV_SELPST2
res &= i2c_write_verify(i, 2, 5, 0x4d, 0x0F); //CONFIG_DRV_SELCM_MAIN
res &= i2c_write_verify(i, 2, 5, 0x4e, 0x1); //CONFIG_DRV_ENABLE_CM
res &= i2c_write_verify(i, 2, 5, 0x4f, 0x0); //CONFIG_DRV_INVERSE_CLK
res &= i2c_write_verify(i, 2, 5, 0x50, 0x0); //CONFIG_DRV_DELAYSEL
res &= i2c_write_verify(i, 2, 5, 0x51, 0x0F); //CONFIG_DRV_DELAY_CS
res &= i2c_write_verify(i, 2, 5, 0x52, 0x1); //CONFIG_DRV_CML
res &= i2c_write_verify(i, 2, 5, 0x53, 0x1); //CONGIF_DRV_BIAS_CML_INTERNAL
res &= i2c_write_verify(i, 2, 5, 0x54, 0x1); //CONGIF_DRV_BIAS_CS_INTERNAL
switch (frame) {
case FRAME_DD:
res &= i2c_write_verify(i, 2, 0, 1, 3);
break;
case FRAME_12:
res &= i2c_write_verify(i, 2, 0, 1, 0);
break;
case FRAME_14:
res &= i2c_write_verify(i, 2, 0, 1, 1);
break;
}
//i2c_write (i, 2, 0, 3, 0xc3); // PRBS7, no 8b10b
res &= i2c_write_verify(i, 2, 0, 3, 0x3c); // normal operation
res &= i2c_write_verify(i, 2, 0, 0x20, ACT_RESET_COLDADC); // ACT = COLDADC reset
}
if (!res) fprintf(stderr,"COLDATA configuration failed for FEMB:%i!\n",index);
return res;
}
bool FEMB::configure_coldadc() {
bool res = true;
//See COLDADC datasheet
//FIXME do these options need to be configurable?
for (uint8_t i = 0; i < 2; i++) { // For each COLDATA on FEMB
for (uint8_t j = 4; j <= 7; j++) { // For each COLADC attached to COLDATA
res &= i2c_write_verify(i, j, 2, 0x01, 0x0c); //start_data
res &= i2c_write_verify(i, j, 1, 0x96, 0xff); //bjt_powerdown
res &= i2c_write_verify(i, j, 1, 0x97, 0x2f); //ref_bias
res &= i2c_write_verify(i, j, 1, 0x93, 0x04); //internal_ref
res &= i2c_write_verify(i, j, 1, 0x9C, 0x15); //vt45uA
res &= i2c_write_verify(i, j, 1, 0x98, 0xFF); //vrefp
res &= i2c_write_verify(i, j, 1, 0x99, 0x00); //vrefn
res &= i2c_write_verify(i, j, 1, 0x9a, 0x80); //vcmo
res &= i2c_write_verify(i, j, 1, 0x9b, 0x60); //vcmi
res &= i2c_write_verify(i, j, 1, 0x9d, 0x27); //ref-bias
res &= i2c_write_verify(i, j, 1, 0x9e, 0x27); //ref-bias
res &= i2c_write_verify(i, j, 1, 0x80, 0x63); //sdc_bypassed
res &= i2c_write_verify(i, j, 1, 0x84, 0x3b); //single-ened_input_mode
res &= i2c_write_verify(i, j, 1, 0x88, 0x0b); //ADC-bias-current-50uA
res &= i2c_write_verify(i, j, 1, 0x89, 0x08); //offset_binary_output_data_format
res &= i2c_write_verify(i, j, 1, 0x89, 0x08); //offset_binary_output_data_format
}
}
if (!res) fprintf(stderr,"COLADC configuration failed for FEMB:%i!\n",index);
return res;
}
bool FEMB::configure_larasic(const larasic_conf &c) {
bool res = true;
// See LArASIC datasheet
uint8_t global_reg_1 = ((c.sdd ? 1 : 0) << 1) // 1 = "SEDC" buffer enabled
| ((c.sdc ? 1 : 0) << 2) // 0 = dc; 1 = ac
| ((c.slkh ? 1 : 0) << 3) // 1 = "RQI" * 10 enable
| ((c.s16 ? 1 : 0) << 4) // 1 = ch15 high filter enable
| ((c.stb ? 1 : 0) << 5) // 0 = mon analog channel; 1 = use stb1
| ((c.stb1 ? 1 : 0) << 6) // 0 = mon temp; 1 = mon bandgap
| ((c.slk ? 1 : 0) << 7); // 0 = 500 pA RQI; 1 = 100 pA RQI
uint8_t global_reg_2 = ((c.sdac & 0x3F) << 0) // 6 bit current scaling daq
| ((c.sdacsw1 ? 1 : 0) << 6) // 1 = connected to external test pin
| ((c.sdacsw2 ? 1 : 0) << 7); // 1 = connected to DAC output
uint8_t channel_reg = ((c.sts ? 1 : 0) << 0) // 1 = test capacitor enabled
| ((c.snc ? 1 : 0) << 1) // 0 = 900 mV baseline;1 = 200 mV baseline
| ((c.gain & 0x3) << 2) // 14, 25, 7.8, 4.7 mV/fC (0 - 3)
| ((c.peak_time & 0x3) << 4) // 1.0, 0.5, 3, 2 us (0 - 3)
| ((c.smn ? 1 : 0) << 6) // 1 = monitor enable
| ((c.sdf ? 1 : 0) << 7); // 1 = "SE" buffer enable
// See COLDATA datasheet
// MSB goes first
// [MSB] Ch15 .. Ch0 global_reg_1 global_reg_2 [LSB]
// COLDATA registers 0x80 .. 0x91
for (uint8_t i = 0; i < 2; i++) { // For each COLDATA on FEMB
for (uint8_t page = 1; page <= 4; page++) { // For each LArASIC page in COLDATA
for (uint8_t addr = 0x80; addr < 0x90; addr++) { // set channel registers
res &= i2c_write_verify(i, 2, page, addr, channel_reg);
}
res &= i2c_write_verify(i, 2, page, 0x90, global_reg_1);
res &= i2c_write_verify(i, 2, page, 0x91, global_reg_2);
}
res &= i2c_write_verify(i, 2, 0, 0x20, ACT_PROGRAM_LARASIC); // ACT = Program LArASIC SPI
}
if (!res) printf("Failed to store LArASIC configuration for FEMB:%i!\n",index);
return res;
}
bool FEMB::set_fast_act(uint8_t act_cmd) {
bool res = true;
for (uint8_t i = 0; i < 2; i++) {
res &= i2c_write_verify(i, 2, 0, 0x20, act_cmd);
}
if (!res) printf("Failed to set fast act for FEMB:%i!\n",index);
return res;
}
bool FEMB::read_spi_status() {
bool res = true;
for (uint8_t i = 0; i < 2; i++) {
uint8_t status = i2c_read(i,2,0,0x23);
res &= (status == 0xFF); // all bits 1 for success
}
return res;
}
void FEMB::fast_cmd(uint8_t cmd_code) {
static bool fast_cmd_init = false;
if (!fast_cmd_init) {
io_reg_init(&FEMB::coldata_fast_cmd,CD_FASTCMD_ADDR,2); //never free'd
io_reg_write(&FEMB::coldata_fast_cmd,REG_FAST_CMD_ACT_DELAY,19);
fast_cmd_init = true;
}
io_reg_write(&FEMB::coldata_fast_cmd,REG_FAST_CMD_CODE,cmd_code);
}
void FEMB::i2c_bugfix(uint8_t bus_idx, uint8_t chip_addr, uint8_t reg_page, uint8_t reg_addr) {
if (last_coldata_i2c_chip[bus_idx] != chip_addr) { // Coldata i2c bug latching chip_addr
last_coldata_i2c_chip[bus_idx] = chip_addr;
i2c_read(bus_idx,chip_addr,reg_page,reg_addr);
i2c_read(bus_idx,chip_addr,reg_page,reg_addr);
}
}
void FEMB::i2c_write(uint8_t bus_idx, uint8_t chip_addr, uint8_t reg_page, uint8_t reg_addr, uint8_t data) {
i2c_bugfix(bus_idx,chip_addr,reg_page,reg_addr);
uint32_t ctrl = ((chip_addr & 0xF) << COLD_I2C_CHIP_ADDR)
| ((reg_page & 0x7) << COLD_I2C_REG_PAGE)
| (0x0 << COLD_I2C_RW)
| ((reg_addr & 0xFF) << COLD_I2C_REG_ADDR)
| ((data & 0xFF) << COLD_I2C_DATA);
io_reg_write(&this->coldata_i2c[bus_idx],REG_COLD_I2C_CTRL,ctrl);
io_reg_write(&this->coldata_i2c[bus_idx],REG_COLD_I2C_START,1);
io_reg_write(&this->coldata_i2c[bus_idx],REG_COLD_I2C_START,0);
usleep(COLD_I2C_DELAY);
}
uint8_t FEMB::i2c_read(uint8_t bus_idx, uint8_t chip_addr, uint8_t reg_page, uint8_t reg_addr) {
i2c_bugfix(bus_idx,chip_addr,reg_page,reg_addr);
uint32_t ctrl = ((chip_addr & 0xF) << COLD_I2C_CHIP_ADDR)
| ((reg_page & 0x7) << COLD_I2C_REG_PAGE)
| (0x1 << COLD_I2C_RW)
| ((reg_addr & 0xFF) << COLD_I2C_REG_ADDR);
io_reg_write(&this->coldata_i2c[bus_idx],REG_COLD_I2C_CTRL,ctrl);
io_reg_write(&this->coldata_i2c[bus_idx],REG_COLD_I2C_START,1);
io_reg_write(&this->coldata_i2c[bus_idx],REG_COLD_I2C_START,0);
usleep(COLD_I2C_DELAY);
ctrl = io_reg_read(&this->coldata_i2c[bus_idx],REG_COLD_I2C_CTRL);
// fix for C2W signal inversion in COLDATA chip #0
if (bus_idx == 0) ctrl = ~ctrl;
return (ctrl >> COLD_I2C_DATA) & 0xFF;
}
bool FEMB::i2c_write_verify(uint8_t bus_idx, uint8_t chip_addr, uint8_t reg_page, uint8_t reg_addr, uint8_t data) {
i2c_write(bus_idx,chip_addr,reg_page,reg_addr,data);
uint8_t read = i2c_read(bus_idx,chip_addr,reg_page,reg_addr);
if (read != data) {
fprintf(stderr,"i2c_write_verify failed FEMB:%i COLDATA:%i chip:0x%X page:0x%X reg:0x%X :: 0x%X != 0x%X\n",index,bus_idx,chip_addr,reg_page,reg_addr,data,read);
return false;
}
return true;
}
|
#include "CombinedWorkspace.h"
int main( int arc, char* argv[] ) {
CombinedWorkspace combWS;
// combWS.SetModel( CombinedWorkspace::Model::Couplings12Cat );
// combWS.SetModel( CombinedWorkspace::Model::CouplingsInclusive );
combWS.CombineChannels();
return 0;
}
|
//programm polinom elder.cpp
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
#include <cstdlib>
//#include <conio.h>
#include <stdio.h>
char pp;
void stop ()
{
cout << "Press any key & Enter to continue...";
cin >> pp;
// system("PAUSE");
return;
}
void error ()
{
cout << "You have typed an illigal value! Try again by initiating a desired, numarical value. \n";
cout << "Example: number '4' or '5' ";
cout << "Press any key & Enter to continue...";
cin >> pp;
system("PAUSE"); //poneje ne priema vuvejdaneto na char pp;
return;
}
int main ()
{
cout << "1) For initialization of an equation, please type '1' \n";
cout << "2) For initialization of a derived function, please type '2' \n" << "\n" << "Type here: ";
int choice;
cin >> choice;
if (!cin)
{ error();
return 1;
}
cout << "\n";
if (choice==1)
{
cout << "You have chosen the calculation of an equation \n";
double x[19];
cout << "Enter the equation's grade: ";
int z;
cin >> z;
if (!cin)
{ error ();
return 1;
}
if ((z<1) || (z>20))
{
cout << "Incorrenct grade value. Try againt by typing values between 1 and 20. \n";
// getch();
stop ();
return 1;
}
int bar=z;
cout << "Enter the coefficients for every single grade: \n";
for ( int i=z; i>=0; i--)
{
cout << "x" << bar << " = ";
cin >> x[i];
if (!cin)
{ error();
return 1;
}
bar--;
}
i=1;
int kl=0;
int p,q;
int grade = z-1;
if (x[0]==0)
{
cout << "The equation has been downgraded to " << grade;
switch (grade)
{
case 1 : cout << "st"; break;
case 2 : cout << "nd"; break;
default : cout << "th"; break;
}
cout << " grade \n";
for ( int yy = 0; yy <= z-1 ; yy++)
{
x[yy] = x[i];
i++;
kl++;
}
z--;
}
p=fabs(x[0]);
q=fabs(x[z]);
double del2[30];
int br2=0;
for (int a=1; a<=p; a++)
{
if ((p % a)==0)
{ br2++;
del2[br2]=a;
// cout << a << "\n";
// br2++;
// del2[br2]=-a;
}
}
int br1=0;
int del1[30];
for (a=1; a<=q; a++)
{ if ((q % a)==0)
{ br1++;
del1[br1]=a;
// cout << a << "\n";
// br1++;
// del1[br1]=-a;
}
}
int d2=br2;
int d1=br1;
double del[100];
int br=0;
br2=1;
while (br2<=d2)
{
br1=1;
while (br1<=d1)
{
del[br] = del2[br2] / del1[br1];
br++;
br1++;
del[br] = -del[br-1];
br++;
}
br2++;
}
cout << "The possible answers are: ";
int aa=0;
while (aa<br)
{
cout << del[aa] << ", ";
aa++;
}
cout << "\n";
br--;
int d=br;
br=0;
int pr = 0;
double y;
double r;
cout << "The roots are: \n" ;
if (kl!=0)
cout << "x = 0, \n" ;
while (br<=d)
{
y=0;
r=0;
i=z;
while (i>=0)
{
y = pow(del[br],i)*x[i];
r=r+y;
i--;
}
if (r==0)
{
cout << "x = " << del[br] << "," << "\n";
pr = pr++;
}
br++;
}
if (pr==0)
{
cout << "There are no real roots!!! The equation has no resolving. \n";
stop ();
return 1;
}
stop ();
return 0;
}
if (choice==2)
{
cout << "You have chosen the calculation of a derived function \n";
double x[19];
cout << "Enter the main equation's grade: ";
int z;
cin >> z;
if (!cin)
{ error();
return 1;
}
if ((z<1) || (z>20))
{
cout << "Incorrenct grade value. Try againt by typing values between 1 and 20. \n";
// getch();
if (!cin)
error();
return 1;
}
int bar=z;
cout << "Enter the coefficients for every single grade: \n";
for ( int i=z; i>=0; i--)
{
cout << "x" << bar << " = ";
cin >> x[i];
if (!cin)
{ error();
return 1;
}
bar--;
}
i=1;
int yy = 0;
int kl=0;
int p,q;
int grade = z-1;
if (x[0]==0)
{
cout << "The equation has been downgraded to " << grade;
switch (grade)
{
case 1 : cout << "st"; break;
case 2 : cout << "nd"; break;
default : cout << "th"; break;
}
cout << " grade \n";
grade --;
for ( yy = 0; yy <= z-1 ; yy++)
{
x[yy] = x[i];
i++;
}
z--;
}
i=1;
cout << "The equation has been downgraded to " << grade;
switch (grade)
{
case 1 : cout << "st"; break;
case 2 : cout << "nd"; break;
default : cout << "th"; break;
}
cout << " grade for the derived function to be calculated \n";
for ( yy = 0; yy <= z-1 ; yy++)
{
x[yy] = x[i] * i;
i++;
}
z--;
p=fabs(x[0]);
q=fabs(x[z]);
double del2[30];
int br2=0;
for (int a=1; a<=p; a++)
{
if ((p % a)==0)
{ br2++;
del2[br2]=a;
// cout << a << "\n";
// br2++;
// del2[br2]=-a;
}
}
int br1=0;
int del1[30];
for (a=1; a<=q; a++)
{ if ((q % a)==0)
{ br1++;
del1[br1]=a;
// cout << a << "\n";
// br1++;
// del1[br1]=-a;
}
}
int d2=br2;
int d1=br1;
double del[100];
int br=0;
br2=1;
while (br2<=d2)
{
br1=1;
while (br1<=d1)
{
del[br] = del2[br2] / del1[br1];
br++;
br1++;
del[br] = -del[br-1];
br++;
}
br2++;
}
cout << "The possible answers are: ";
int aa=0;
while (aa<br)
{
cout << del[aa] << ", ";
aa++;
}
cout << "\n";
br--;
int d=br;
br=0;
int pr = 0;
double y;
double r;
cout << "The roots are: \n" ;
while (br<=d)
{
y=0;
r=0;
i=z;
while (i>=0)
{
y = pow(del[br],i)*x[i];
r=r+y;
i--;
}
if (r==0)
{
cout << "x = " << del[br] << "," << "\n";
pr = pr++;
}
br++;
}
if (pr==0)
{
cout << "There are no real roots!!! The derived function has no resolving. \n";
stop ();
return 1;
}
if (x[z]>0)
cout << "In the right the derived function is rising and it changes alternative between the roots. \n";
else
cout << "In the right the derived function is lowering and it changes alternative between the roots. \n";
}
stop ();
return 0;
}
|
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> weekDays;
weekDays.push_back("Sund1ay");
weekDays.push_back("Monday");
weekDays.push_back("Tue58sday");
weekDays.push_back("Wed&nesday");
weekDays.push_back("Turs*day");
weekDays.push_back("Fr##iday");
weekDays.push_back("Sa<turday");
for(auto item : weekDays) {
std::cout << item << std::endl;
}
for(auto &item : weekDays) {
for(int i = 0; item[i] != '\0'; i++) {
if( 'A'> item[i] || 'z' < item[i]) {
item.erase (item.begin() + i);
i--;
}
}
}
for(auto item : weekDays) {
std::cout << item << std::endl;
}
return 0;
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <quic/common/BufAccessor.h>
namespace quic {
SimpleBufAccessor::SimpleBufAccessor(size_t capacity)
: buf_(folly::IOBuf::createCombined(capacity)),
capacity_(buf_->capacity()) {}
Buf SimpleBufAccessor::obtain() {
Buf ret;
buf_.swap(ret);
return ret;
}
void SimpleBufAccessor::release(Buf buf) {
CHECK(!buf_) << "Can't override existing buf";
CHECK(buf) << "Invalid Buf being released";
CHECK_EQ(buf->capacity(), capacity_)
<< "Buf has wrong capacity, capacit_=" << capacity_
<< ", buf capacity=" << buf->capacity();
CHECK(!buf->isChained()) << "Reject chained buf";
buf_ = std::move(buf);
}
bool SimpleBufAccessor::ownsBuffer() const {
return (buf_ != nullptr);
}
} // namespace quic
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef VEGA_H
#define VEGA_H
#ifdef VEGA_SUPPORT
#include "modules/libvega/vegaconfig.h"
#ifdef VEGA_USE_FLOATS
typedef float VEGA_FIX;
typedef double VEGA_DBLFIX;
#define VEGA_FIXTOFLT(x) (x)
#define VEGA_FLTTOFIX(x) ((VEGA_FIX) (x))
#define VEGA_DBLFIXTOFIX(v) ((VEGA_FIX)(v))
#define VEGA_FIXTODBLFIX(v) ((VEGA_DBLFIX)(v))
#define VEGA_DBLFIXADD(a,b) ((a)+(b))
#define VEGA_DBLFIXSUB(a,b) ((a)-(b))
#define VEGA_DBLFIXDIV(a,b) ((VEGA_DBLFIX)(a)/(b))
#define VEGA_DBLFIXNEG(a) (-(a))
static inline int VEGA_DBLFIXSIGN(VEGA_DBLFIX a)
{
return (a < 0) ? -1 : (a > 0);
}
#define VEGA_DBLFIXEQ(a,b) ((a) == (b))
#define VEGA_DBLFIXLT(a,b) ((a) < (b))
#define VEGA_DBLFIXGT(a,b) ((a) > (b))
#define VEGA_DBLFIXLTEQ(a,b) ((a) <= (b))
#define VEGA_DBLFIXGTEQ(a,b) ((a) >= (b))
#define VEGA_DBLFIXSQRT(a) (op_sqrt(a))
#define VEGA_INTTODBLFIX(a) ((double)(a))
static const VEGA_FIX VEGA_INFINITY = 10000.0f;
static const VEGA_FIX VEGA_EPSILON = 1.19209e-07f; // std::numeric_limits<float>::epsilon()
#define VEGA_FLOOR(x) ((float)op_floor((double)(x)))
#define VEGA_CEIL(x) ((float)op_ceil((double)(x)))
#define VEGA_FIXTOINT(x) ((int)((x)+0.5f))
#define VEGA_INTTOFIX(x) ((float)(x))
#define VEGA_TRUNCFIX(x) ((float)((int)(x)))
#define VEGA_TRUNCFIXTOINT(x) ((int)(x))
// Scale with (1 << ss)
#define VEGA_FIXTOSCALEDINT(x,ss) ((int)(((x)*(1 << (ss)))+0.5f))
#define VEGA_FIXTOSCALEDINT_T(x,ss) ((int)((x)*(1 << (ss))))
#define VEGA_FIXMUL(x,y) ((x)*(y))
#define VEGA_FIXMUL_DBL(x,y) ((VEGA_DBLFIX)(x)*(VEGA_DBLFIX)(y))
#define VEGA_FIXDIV(x,y) ((x)/(y))
#define VEGA_FIXMULDIV(x,y,z) ((x)*(y)/(z))
#define VEGA_FIXMUL2(x) ((x)*2)
#define VEGA_FIXDIV2(x) ((x)*0.5f)
#define VEGA_FIX_PI 3.14159265f
#define VEGA_FIX_2PI 6.28318531f
#define VEGA_FIXSIN(x) ((float)op_sin((double)((x)*(VEGA_FIX_PI/180.f))))
#define VEGA_FIXCOS(x) ((float)op_cos((double)((x)*(VEGA_FIX_PI/180.f))))
#define VEGA_FIXACOS(x) (180.f*(float)op_acos((double)(x))/VEGA_FIX_PI)
#define VEGA_FIXSQR(x) ((x)*(x))
#define VEGA_FIXSQRT(x) ((float)op_sqrt((double)(x)))
#define VEGA_FIXPOW(x,y) ((float)op_pow((double)(x),(double)(y)))
#define VEGA_FIXLOG(x) ((float)op_log((double)(x)))
#define VEGA_FIXEXP(x) ((float)op_exp((double)(x)))
#define VEGA_ABS(x) ((float)op_fabs((double)(x)))
#define VEGA_VECLENGTH(x, y) VEGA_FIXSQRT(VEGA_FIXSQR((x))+VEGA_FIXSQR((y)))
#define VEGA_VECDOTSIGN(vx1,vy1,vx2,vy2) (VEGA_FIXMUL((vx1),(vx2))+VEGA_FIXMUL((vy1),(vy2)))
#else // VEGA_USE_FLOATS
#include "modules/libvega/src/vegainteger.h"
#define VEGA_FIX_DECBITS 12
#define VEGA_FIX_DECMASK 0xfff
typedef INT32 VEGA_FIX;
typedef VG_INT64 VEGA_DBLFIX;
#define VEGA_FIXTOFLT(x) ((float)(x) / (float)(1<<VEGA_FIX_DECBITS))
#define VEGA_FLTTOFIX(x) ((VEGA_FIX)(((x)*(1 << VEGA_FIX_DECBITS))+.5f))
static inline VEGA_FIX VEGA_DBLFIXTOFIX(VEGA_DBLFIX v)
{
return (VEGA_FIX)int64_shr32(v, VEGA_FIX_DECBITS);
}
static inline VEGA_DBLFIX VEGA_FIXTODBLFIX(VEGA_FIX v)
{
return int64_shl(int64_load32(v), VEGA_FIX_DECBITS);
}
static const VEGA_FIX VEGA_INFINITY = ~(1<<31);
static const VEGA_FIX VEGA_EPSILON = 1;
#define VEGA_FLOOR(x) ((x)&(~VEGA_FIX_DECMASK))
#define VEGA_CEIL(x) (((x)+VEGA_FIX_DECMASK)&(~VEGA_FIX_DECMASK))
// fix to int will round correctly
#define VEGA_FIXTOINT(x) (((x)+(1<<(VEGA_FIX_DECBITS-1)))>>VEGA_FIX_DECBITS)
#define VEGA_INTTOFIX(x) (VEGA_FIX)((x)<<VEGA_FIX_DECBITS)
#define VEGA_TRUNCFIX(x) ((x)&(~VEGA_FIX_DECMASK))
#define VEGA_TRUNCFIXTOINT(x) ((x)>>VEGA_FIX_DECBITS)
// Scale with (1 << ss)
#define VEGA_FIXTOSCALEDINT(x,ss) \
((ss)<VEGA_FIX_DECBITS ? (x) >> (VEGA_FIX_DECBITS-(ss)) :\
((ss)>VEGA_FIX_DECBITS ? (x) << ((ss)-VEGA_FIX_DECBITS) : (x)))
#define VEGA_FIXTOSCALEDINT_T(x,ss) VEGA_FIXTOSCALEDINT(x,ss)
static inline VEGA_DBLFIX VEGA_INTTODBLFIX(INT32 v)
{
return int64_shl(int64_load32(v), 2*VEGA_FIX_DECBITS);
}
static inline VEGA_DBLFIX VEGA_DBLFIXADD(VEGA_DBLFIX a, VEGA_DBLFIX b)
{
return int64_add(a, b);
}
static inline VEGA_DBLFIX VEGA_DBLFIXSUB(VEGA_DBLFIX a, VEGA_DBLFIX b)
{
return int64_sub(a, b);
}
static inline VEGA_DBLFIX VEGA_DBLFIXNEG(VEGA_DBLFIX a)
{
return int64_neg(a);
}
static inline int VEGA_DBLFIXSIGN(VEGA_DBLFIX a)
{
return int64_sign(a);
}
static inline BOOL VEGA_DBLFIXEQ(VEGA_DBLFIX a, VEGA_DBLFIX b)
{
return int64_eq(a, b);
}
static inline BOOL VEGA_DBLFIXLT(VEGA_DBLFIX a, VEGA_DBLFIX b)
{
return int64_lt(a, b);
}
static inline BOOL VEGA_DBLFIXGT(VEGA_DBLFIX a, VEGA_DBLFIX b)
{
return int64_gt(a, b);
}
static inline BOOL VEGA_DBLFIXLTEQ(VEGA_DBLFIX a, VEGA_DBLFIX b)
{
return int64_lteq(a, b);
}
static inline BOOL VEGA_DBLFIXGTEQ(VEGA_DBLFIX a, VEGA_DBLFIX b)
{
return int64_gteq(a, b);
}
static inline VEGA_FIX VEGA_FIXMUL(VEGA_FIX x, VEGA_FIX y)
{
return (VEGA_FIX)int64_shr32(int64_muls(x, y), VEGA_FIX_DECBITS);
}
static inline VEGA_DBLFIX VEGA_FIXMUL_DBL(VEGA_FIX x, VEGA_FIX y)
{
return int64_muls(x, y);
}
VEGA_FIX VEGA_FIXDIV(VEGA_FIX x, VEGA_FIX y);
VEGA_DBLFIX VEGA_DBLFIXDIV(VEGA_DBLFIX a, VEGA_DBLFIX b);
static inline VEGA_FIX VEGA_FIXMULDIV(VEGA_FIX x, VEGA_FIX y, VEGA_FIX z)
{
return (VEGA_FIX)int64_muldiv(x, y, z);
}
#define VEGA_FIXMUL2(x) ((x)<<1)
#define VEGA_FIXDIV2(x) ((x)>>1)
VEGA_FIX VEGA_FIXSQR(VEGA_FIX x);
VEGA_FIX VEGA_FIXSQRT(VEGA_FIX x);
VEGA_DBLFIX VEGA_DBLFIXSQRT(VEGA_DBLFIX x);
/* 3.14159265f * (1 << DECBITS) => 12868 */
#define VEGA_FIX_PI 12868
#define VEGA_FIX_2PI 25736
/* 2,718281828 * (1 << DECBITS) => 11134 */
#define VEGA_FIX_E 11134
#define VEGA_FIX_PI_OVER_180 (37480660 >> (31-VEGA_FIX_DECBITS))
#define VEGA_FIX_PI_HALF (3373259426 >> (31-VEGA_FIX_DECBITS))
#define VEGA_FIXSIN(x) VEGA_FIXCOS(x-VEGA_INTTOFIX(90))
VEGA_FIX VEGA_FIXCOS(VEGA_FIX x);
VEGA_FIX VEGA_FIXACOS(VEGA_FIX x);
VEGA_FIX VEGA_FIXLOG(VEGA_FIX x);
VEGA_FIX VEGA_FIXEXP(VEGA_FIX x);
VEGA_FIX VEGA_FIXPOW(VEGA_FIX x, VEGA_FIX y);
#define VEGA_ABS(x) op_abs(x)
VEGA_FIX VEGA_VECLENGTH(VEGA_FIX vx, VEGA_FIX vy);
VEGA_FIX VEGA_VECDOTSIGN(VEGA_FIX vx1, VEGA_FIX vy1, VEGA_FIX vx2, VEGA_FIX vy2);
#endif // VEGA_USE_FLOATS
#define VEGA_EQ(x,y) (VEGA_ABS(x-y) <= VEGA_EPSILON)
#define VEGA_FIXCOMP(x,y) (((x) < (y)) ? -1 : (((x) > (y)) ? 1 : 0))
#endif // VEGA_SUPPORT
#endif // VEGA_H
|
#include<iostream>
#include<vector>
#include<algorithm>
#include<iterator>
#include<deque>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
#define inf 9999
void Init_TreeNode(TreeNode** T, vector<int>& vec, int& pos)
{
if (vec[pos] == inf || vec.size() == 0)
{
*T = NULL;
return;
}
else
{
(*T) = new TreeNode(0);
(*T)->val = vec[pos];
Init_TreeNode(&(*T)->left, vec, ++pos);
Init_TreeNode(&(*T)->right, vec, ++pos);
}
}
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
//ๅบๆฌๆๆณ๏ผ้ๅ๏ผๅฐๆฏไธๅฑ็่็นๆ็
งๅ
่ฟๅ
ๅบ้กบๅบไฟๅญๅฐqueue้ๅ
vector<vector<int>> res;
if (root == NULL)
return res;
deque<TreeNode*> queue;
TreeNode* cur;
vector<int> vec;
queue.push_back(root);
while (!queue.empty())
{
//ๅฐไฟๅญๅจqueueไธญ็ๅฝๅๅฑ่็นไป้ๅฐพๅผนๅบไฟๅญ่ณvec๏ผๅผนๅบ็ๅๆถๅฐไธไธๅฑ็่็นไป้้ฆๅ
ฅ้ๅ
int len = queue.size();
for (int i = 0; i < len; i++)
{
cur = queue.back();
queue.pop_back();
vec.push_back(cur->val);
if (cur->left != NULL)
queue.push_front(cur->left);
if (cur->right != NULL)
queue.push_front(cur->right);
}
res.push_back(vec);
vec.clear();
}
return res;
}
};
int main()
{
Solution solute;
TreeNode* root = NULL;
vector<int> vec = { 1,2,inf,inf,2,inf,inf };
int pos = 0;
Init_TreeNode(&root, vec, pos);
vector<vector<int>> res = solute.levelOrder(root);
for (int i = 0; i < res.size(); i++)
{
copy(res[i].begin(), res[i].end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
return 0;
}
|
#include "BattleManager.h"
#include "MPLogger.h"
MP_SINGLETON_IMPLEMENT(BattleManager)
BattleManager::BattleManager() : meplay::MPThread("BattleThread")
{
}
BattleManager::~BattleManager()
{
}
void BattleManager::Run()
{
while (!IsThreadFinal())
{
m_tLastTime.Now();
UpdateBattle();
auto millisec = m_tLastTime.MTimeOut(100);
if (millisec < 0)
{
MP_WARN("BattleLoop TimeOut %d", -millisec);
millisec = 0;
}
std::this_thread::sleep_for(std::chrono::milliseconds(millisec));
}
}
void BattleManager::UpdateBattle()
{
addBattle();
delBattle();
updateBattle();
}
BATTLE_ID_TYPE BattleManager::AddBattle(const BattleInfo& bi)
{
auto pBattle = m_BattleFactory.CreateBattle((BATTLE_TYPE)bi.nBattleType);
if (pBattle == nullptr)
{
MP_INFO("AddBattle Failed!");
return INVALID_BATTLE_ID;
}
auto lBattleId = createBattleId();
if (!pBattle->BattleInit(lBattleId, bi))
{
MP_INFO("AddBattle Failed!");
return INVALID_BATTLE_ID;
}
std::lock_guard<std::mutex> lck(mtx);
m_vAddCache.emplace_back(std::make_pair(lBattleId,pBattle));
MP_INFO("AddBattle Success!");
return lBattleId;
}
void BattleManager::DelBattle(BATTLE_ID_TYPE id)
{
std::lock_guard<std::mutex> lck(mtx);
m_vDelCache.emplace_back(id);
}
BATTLE_ID_TYPE BattleManager::createBattleId()
{
return 1;
}
void BattleManager::addBattle()
{
for (auto& add : m_vAddCache)
{
m_mBattleMap.emplace(add);
}
mtx.try_lock();
m_vAddCache.clear();
mtx.unlock();
}
void BattleManager::delBattle()
{
for (auto& del : m_vDelCache)
{
m_mBattleMap.erase(del);
}
mtx.try_lock();
m_vDelCache.clear();
mtx.unlock();
auto it = m_mBattleMap.begin();
while (it != m_mBattleMap.end())
{
auto pBattle = it->second;
if (pBattle->GetStatus() == eBattleStatus_End
|| pBattle->GetStatus() == eBattleStatus_ErrorEnd)
{
it = m_mBattleMap.erase(it);
}
else
{
++it;
}
}
}
void BattleManager::updateBattle()
{
for (auto& bi : m_mBattleMap)
{
auto& pBattle = bi.second;
switch (pBattle->GetStatus())
{
case eBattleStatus_Start:
{
if (!pBattle->BattleStart())
{
//error
pBattle->SetStatus(eBattleStatus_ErrorEnd);
}
else
{
pBattle->SetStatus(eBattleStatus_Run);
}
}
break;
case eBattleStatus_Run:
{
if (!pBattle->BattleRun())
{
//error
pBattle->SetStatus(eBattleStatus_ErrorEnd);
}
else
{
pBattle->SetStatus(eBattleStatus_Run);
}
}
break;
case eBattleStatus_End:
{
if (!pBattle->BattleEnd())
{
//error
pBattle->SetStatus(eBattleStatus_ErrorEnd);
}
else
{
pBattle->SetStatus(eBattleStatus_Run);
}
}
break;
case eBattleStatus_ErrorEnd:
{
pBattle->BattleErrorEnd();
}
case eBattleStatus_Unknown:
case eBattleStatus_Init:
default:
break;
}
}
}
|
#include <catch2/catch.hpp>
#include <replay/vector_math.hpp>
TEST_CASE("Non-colinear lines intersect")
{
replay::line2 lhs({ 0.f, 1.f }, { 1.f, -1.f });
replay::line2 rhs({ 1.f, -2.f }, { -1.f, 0.f });
auto intersection = intersect_planar_lines(lhs, rhs);
SECTION("And the intersection is valid")
{
REQUIRE(intersection);
}
SECTION("And the intersection is correct")
{
auto p = *intersection;
REQUIRE(p[0] == Approx(3.f));
REQUIRE(p[1] == Approx(-2.f));
}
}
TEST_CASE("Nearly colinear lines depend on the epsilon")
{
replay::line2 lhs{ {917.986694f, 150.000000f} , replay::normalized({-20.0000000f, -34.6408691f}) };
replay::line2 rhs{ {913.656494f, 152.499954f} , replay::normalized({-34.6408691f, -59.9999924f}) };
SECTION("They intersect with the default epsilon")
{
auto point = intersect_planar_lines(lhs, rhs);
REQUIRE(point != std::nullopt);
}
SECTION("But they do not intersect with a greater epsilon")
{
auto no_point = intersect_planar_lines(lhs, rhs, 0.0001f);
REQUIRE(no_point == std::nullopt);
}
}
|
#include "creator.h"
Creator::Creator(int productType)
: productType(productType)
{
}
Creator::~Creator(void)
{
}
int Creator::getProductType(void)
{
return productType;
}
|
// ่ฟๆฎตไปฃ็ ๅ่ชpojๆ้ข็ฎ๏ผไบๅ็ญๆกๅ๏ผ้ช่ฏๆฏๅฆๅญๅจ่ดๆ็ฏ
// ่พนๆ็่ฎก็ฎๆฏๅฝๅไปทๆ ผๅๅป่ดง็ฉ็ไปทๆ ผ๏ผๅไนไธไธชไปไนใ
bool negloop(int beg,int wealth)
{
qtail = 1;
q[++qhead] = beg;
dist[beg] = wealth;
while(qhead >= qtail)
{
int now = q[qtail++];
inq[now] = 0;
for(node * p =head[now];p;p=p->next)
{
double len = (dist[now] - p->c) * p->r;
if(len > dist[p->to])
{
dist[p->to] = len;
if(!inq[p->to])
{
q[++qhead] = p->to,inq[p->to] = 1,incnt[p->to]++;
if(incnt[p->to] > N/4)
return 1;
}
}
}
}
return 0;
}
|
#include "jpeg_persister.h"
#include "../include/jpgd.h"
#include "../include/jpge.h"
namespace persistence {
model::Image *JpegPersister::load(const std::string &fileName) {
int width, height, composition;
core::byte *pixels = jpgd::decompress_jpeg_image_from_file(
fileName.c_str(), &width, &height, &composition, 4);
model::Image *image = new model::Image(width, height);
for (unsigned y = 0; y < height; ++y) {
for (unsigned x = 0; x < width; ++x) {
unsigned pixelIndex = (y * width + x) * 4;
image->setRed(x, y, pixels[pixelIndex]);
image->setGreen(x, y, pixels[pixelIndex + 1]);
image->setBlue(x, y, pixels[pixelIndex + 2]);
image->setAlpha(x, y, pixels[pixelIndex + 3]);
}
}
delete[] pixels;
return image;
}
void JpegPersister::save(model::Image *image, const std::string &fileName) {
core::byte *pixels = new core::byte[image->height() * image->width() * 4];
for (unsigned y = 0; y < image->height(); y++) {
for (unsigned x = 0; x < image->width(); x++) {
unsigned pixelIndex = (y * image->width() + x) * 4;
pixels[pixelIndex] = image->red(x, y);
pixels[pixelIndex + 1] = image->green(x, y);
pixels[pixelIndex + 2] = image->blue(x, y);
pixels[pixelIndex + 3] = image->alpha(x, y);
}
}
jpge::compress_image_to_jpeg_file(fileName.c_str(), image->width(),
image->height(), 4, pixels);
delete[] pixels;
}
}
|
/**
* @file responderbluetooth.cpp
*
* @brief Bluetooth responder system
* @version 0.1
* @date 2021-08-27
*
* @copyright Copyright (c) 2021
*
*/
#include "responderbase.h"
class BluetoothResponder : public ResponderBase {
public:
private:
};
|
int _index=0;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print(_index++);
Serial.print("\n");
delay(500);
}
|
#ifndef _FMT_FORMAT_HPP_
#define _FMT_FORMAT_HPP_
#include <climits>
#include <stdexcept>
#include <string.h>
#include <fmt/flag.hpp>
#include <fmt/itoa.hpp>
namespace fmt {
class InvalidFormatString : public std::invalid_argument {
public:
InvalidFormatString(const std::string& msg = "") : std::invalid_argument(msg) {}
};
struct StringRef {
const char *begin;
size_t size;
};
struct Arg {
union {
#if __WORDSIZE == 32
uint32_t u32;
int32_t i32;
#endif
uint64_t u64;
int64_t i64;
double d;
StringRef s;
void *p;
} value;
enum class Type {
S,
#if __WORDSIZE == 32
U32,
I32,
#endif
U64,
I64,
D,
P
} type;
};
#if __WORDSIZE == 32
inline Arg to_arg(uint8_t o) {
return { .value = { .u32 = o }, .type = Arg::Type::U32 };
}
inline Arg to_arg(int8_t o) {
return { .value = { .i32 = o }, .type = Arg::Type::I32 };
}
inline Arg to_arg(uint16_t o) {
return { .value = { .u32 = o }, .type = Arg::Type::U32 };
}
inline Arg to_arg(int16_t o) {
return { .value = { .i32 = o }, .type = Arg::Type::I32 };
}
inline Arg to_arg(uint32_t o) {
return { .value = { .u32 = o }, .type = Arg::Type::U32 };
}
inline Arg to_arg(int32_t o) {
return { .value = { .i32 = o }, .type = Arg::Type::I32 };
}
#else
inline Arg to_arg(uint8_t o) {
return { .value = { .u64 = o }, .type = Arg::Type::U64 };
}
inline Arg to_arg(int8_t o) {
return { .value = { .i64 = o }, .type = Arg::Type::I64 };
}
inline Arg to_arg(uint16_t o) {
return { .value = { .u64 = o }, .type = Arg::Type::U64 };
}
inline Arg to_arg(int16_t o) {
return { .value = { .i64 = o }, .type = Arg::Type::I64 };
}
inline Arg to_arg(uint32_t o) {
return { .value = { .u64 = o }, .type = Arg::Type::U64 };
}
inline Arg to_arg(int32_t o) {
return { .value = { .i64 = o }, .type = Arg::Type::I64 };
}
#endif
inline Arg to_arg(uint64_t o) {
return { .value = { .u64 = o }, .type = Arg::Type::U64 };
}
inline Arg to_arg(int64_t o) {
return { .value = { .i64 = o }, .type = Arg::Type::I64 };
}
inline Arg to_arg(float o) {
return { .value = { .d = o }, .type = Arg::Type::D };
}
inline Arg to_arg(double o) {
return { .value = { .d = o }, .type = Arg::Type::D };
}
template<std::size_t size>
inline Arg to_arg(const char (&str)[size]) {
Arg a;
a.value.s = { static_cast<const char*>(str), size };
a.type = Arg::Type::S;
return std::move(a);
}
inline Arg to_arg(const char *str, uint32_t size) {
Arg a;
a.value.s = { str, size };
a.type = Arg::Type::S;
return std::move(a);
}
uint32_t vformat(char *buf, const char *fstr, uint32_t fstr_size, Arg *args, uint32_t args_size);
template<typename ...Args>
uint32_t format(char *buf, const char *format_str, Args&& ... args) {
Arg arglist[] = { to_arg(std::forward<Args>(args))... };
return vformat(buf, format_str, strlen(format_str), arglist, sizeof...(args));
}
};
#endif
|
#pragma once
#include <mutex>
#include <list>
namespace iberbar
{
// ๆถๆฏ้ๅ
// ็บฟ็จๅฎๅ
จ
template < typename TMsg, typename TAllocator = std::allocator<TMsg> >
class TMsgQueue
{
public:
TMsgQueue();
TMsgQueue( const TAllocator& Al );
TMsgQueue( const TMsgQueue& Queue ) = delete;
~TMsgQueue();
public:
// ๆทปๅ ๆถๆฏ๏ผ่ฟ่ก้ป่ฎคๆท่ด
void AddMsg( const TMsg& Msg );
// ็ปๆ้้
bool PopMsg( TMsg& Msg );
// ไธ้
void Lock();
// ไธ้
bool TryLock();
// ่งฃ้
void Unlock();
// ๅคๆญๆฏๅฆ็ฉบ
bool IsEmpty() const;
private:
std::list<TMsg, TAllocator> m_MsgList;
std::mutex m_Mutex;
};
}
template < typename TMsg, typename TAllocator >
iberbar::TMsgQueue<TMsg, TAllocator>::TMsgQueue()
: m_MsgList()
, m_Mutex()
{
}
template < typename TMsg, typename TAllocator >
iberbar::TMsgQueue<TMsg, TAllocator>::TMsgQueue( const TAllocator& Al )
: m_MsgList( Al )
, m_Mutex()
{
}
template < typename TMsg, typename TAllocator >
iberbar::TMsgQueue<TMsg, TAllocator>::~TMsgQueue()
{
}
template < typename TMsg, typename TAllocator >
inline void iberbar::TMsgQueue<TMsg, TAllocator>::AddMsg( const TMsg& Msg )
{
m_MsgList.push_back( Msg );
}
template < typename TMsg, typename TAllocator >
inline bool iberbar::TMsgQueue<TMsg, TAllocator>::PopMsg( TMsg& Msg )
{
if ( m_MsgList.empty() == true )
return false;
Msg = m_MsgList.front();
m_MsgList.pop_front();
return true;
}
template < typename TMsg, typename TAllocator >
inline void iberbar::TMsgQueue<TMsg, TAllocator>::Lock()
{
m_Mutex.lock();
}
template < typename TMsg, typename TAllocator >
inline bool iberbar::TMsgQueue<TMsg, TAllocator>::TryLock()
{
return m_Mutex.try_lock();
}
template < typename TMsg, typename TAllocator >
inline void iberbar::TMsgQueue<TMsg, TAllocator>::Unlock()
{
m_Mutex.unlock();
}
template < typename TMsg, typename TAllocator >
inline bool iberbar::TMsgQueue<TMsg, TAllocator>::IsEmpty() const
{
return m_MsgList.empty();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.