text
stringlengths 8
6.88M
|
|---|
#ifndef CVML_LINE_H
#define CVML_LINE_H
class CVMLLine {
private:
CVMLLabel *label_;
CVMLData *data_;
CVMLOp *op_;
public:
CVMLLine(CVMLLabel *label, CVMLData *data) :
label_(label), data_(data), op_(NULL) {
}
CVMLLine(CVMLLabel *label, CVMLOp *op) :
label_(label), data_(NULL), op_(op) {
}
CVMLLabel *getLabel() const { return label_; }
CVMLData *getData () const { return data_ ; }
CVMLOp *getOp () const { return op_ ; }
bool isData() {
return (data_ != NULL);
}
bool isOp() {
return (op_ != NULL);
}
uint getPC();
uint getAddressLen();
friend std::ostream &operator<<(std::ostream &os, CVMLLine &line) {
line.print(os);
return os;
}
void print(std::ostream &os);
void encodeData(CVML &vml, CFile *file);
void writeInstruction(CVML &vml, CFile *file);
};
#endif
|
#include "vr_system.h"
#include "helpers.h"
#include <gtc/type_ptr.hpp>
#include <SDL.h>
#include <iostream>
#include "point_cloud.h"
// Static member delcarations
VRSystem* VRSystem::self_ = nullptr;
// Constructor
VRSystem::VRSystem() :
vr_system_(nullptr),
render_target_width_(0),
render_target_height_(0),
near_clip_plane_(0.1f),
far_clip_plane_(100.0f),
point_cloud_(nullptr)
{
}
// Destructor
VRSystem::~VRSystem()
{
glDeleteFramebuffers( 1, &eye_buffers_[0].render_frame_buffer );
glDeleteFramebuffers( 1, &eye_buffers_[0].resolve_frame_buffer );
glDeleteFramebuffers( 1, &eye_buffers_[1].render_frame_buffer );
glDeleteFramebuffers( 1, &eye_buffers_[1].resolve_frame_buffer );
left_controller_.shutdown();
right_controller_.shutdown();
vr::VR_Shutdown();
// TODO: should i manually delete the vr_system ptr?
vr_system_ = nullptr;
self_ = nullptr;
}
VRSystem* VRSystem::get()
{
// Check if the window exists yet
if( self_ == nullptr )
{
// If the window does not yet exist, create it
self_ = new VRSystem();
bool success = self_->init();
// Check everything went OK
if( success == false )
{
delete self_;
}
}
return self_;
}
bool VRSystem::init()
{
bool success = true;
/* PRELIMINARY CHECKS */
{
bool is_hmd_present = vr::VR_IsHmdPresent();
std::cout << "Found HMD: " << (is_hmd_present ? "yes" : "no") << std::endl;
if( !is_hmd_present ) success = false;
bool is_runtime_installed = vr::VR_IsRuntimeInstalled();
std::cout << "Found OpenVR runtime: " << (is_runtime_installed ? "yes" : "no") << std::endl;
if( !is_runtime_installed ) success = false;
if( !success )
{
SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "error", "Something is missing...", NULL );
return success;
}
}
/* INIT THE VR SYSTEM */
vr::EVRInitError error = vr::VRInitError_None;
vr_system_ = vr::VR_Init( &error, vr::VRApplication_Scene );
if( error != vr::VRInitError_None )
{
vr_system_ = nullptr;
char buf[1024];
sprintf_s( buf, sizeof( buf ), "Unable to init VR runtime: %s", vr::VR_GetVRInitErrorAsEnglishDescription( error ) );
SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "VR_Init Failed", buf, NULL );
success = false;
return success;
}
/* PRINT SYSTEM INFO */
std::cout << "Tracking System: " << getDeviceString( vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_TrackingSystemName_String, NULL ) << std::endl;
std::cout << "Serial Number: " << getDeviceString( vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_SerialNumber_String, NULL ) << std::endl;
vr_system_->GetRecommendedRenderTargetSize( &render_target_width_, &render_target_height_ );
std::cout << "HMD requested resolution: " << render_target_width_ << " by " << render_target_height_ << std::endl;
/* SETUP FRAME BUFFERS */
for( int i = 0; i < 2; i++ )
{
// Create render frame buffer
glGenFramebuffers( 1, &eye_buffers_[i].render_frame_buffer ); // Create a FBO
glBindFramebuffer( GL_FRAMEBUFFER, eye_buffers_[i].render_frame_buffer ); // Bind the FBO
// Attach colour component
glGenTextures( 1, &eye_buffers_[i].render_texture ); // Generate a colour texture
//glBindTexture( GL_TEXTURE_2D, eye_buffers_[i].render_texture ); // Bind the texture
//glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, render_target_width_, render_target_height_, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0 ); // Create texture data
//glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, eye_buffers_[i].render_texture, 0 ); // Attach the texture to the bound FBO
glBindTexture( GL_TEXTURE_2D_MULTISAMPLE, eye_buffers_[i].render_texture ); // Bind the multisampled texture
glTexImage2DMultisample( GL_TEXTURE_2D_MULTISAMPLE, 4, GL_RGBA8, render_target_width_, render_target_height_, true ); // Create multisampled data
glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, eye_buffers_[i].render_texture, 0 ); // Attach the multisampled texture to the bound FBO
// Attach depth component
glGenRenderbuffers( 1, &eye_buffers_[i].render_depth ); // Generate a render buffer
glBindRenderbuffer( GL_RENDERBUFFER, eye_buffers_[i].render_depth ); // Bind the render buffer
glRenderbufferStorageMultisample( GL_RENDERBUFFER, 4, GL_DEPTH_COMPONENT, render_target_width_, render_target_height_ ); // Enable multisampling
//glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH_COMPONENT, render_target_width_, render_target_height_ );
glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, eye_buffers_[i].render_depth ); // Attach the the render buffer as a depth buffer
// Check everything went OK
if( glCheckFramebufferStatus( GL_FRAMEBUFFER ) != GL_FRAMEBUFFER_COMPLETE ) {
std::cout << "ERROR: incomplete render frame buffer!" << std::endl;
success = false;
}
// Create resolve frame buffer
glGenFramebuffers( 1, &eye_buffers_[i].resolve_frame_buffer );
glBindFramebuffer( GL_FRAMEBUFFER, eye_buffers_[i].resolve_frame_buffer );
// Attach colour component
glGenTextures( 1, &eye_buffers_[i].resolve_texture );
glBindTexture( GL_TEXTURE_2D, eye_buffers_[i].resolve_texture );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, GL_LINEAR );
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, render_target_width_, render_target_height_, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr );
glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, eye_buffers_[i].resolve_texture, 0 );
// TODO: this is only needed because i'm rendering directly to the resolve texture
// I should fix it so i render to the multisampled the blit to this, then i can remove this depth component
// Attach depth component
glGenRenderbuffers( 1, &eye_buffers_[i].render_depth ); // Generate a render buffer
glBindRenderbuffer( GL_RENDERBUFFER, eye_buffers_[i].render_depth ); // Bind the render buffer
glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH_COMPONENT, render_target_width_, render_target_height_ );
glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, eye_buffers_[i].render_depth ); // Attach the the render buffer as a depth buffer
// Check everything went OK
if( glCheckFramebufferStatus( GL_FRAMEBUFFER ) != GL_FRAMEBUFFER_COMPLETE ) {
std::cout << "ERROR: incomplete resolve frame buffer!" << std::endl;
success = false;
}
// Unbind any bound frame buffer
glBindFramebuffer( GL_FRAMEBUFFER, 0 );
}
/* INIT SHADERS */
{
controller_shader_.loadVertexSourceFile("render_model_shader_vs.glsl");
controller_shader_.loadFragmentSourceFile("render_model_shader_fs.glsl");
if( !controller_shader_.init() )
{
success = false;
return success;
}
else
{
controller_shader_modl_mat_locaton_ = controller_shader_.getUniformLocation( "model" );
controller_shader_view_mat_locaton_ = controller_shader_.getUniformLocation( "view" );
controller_shader_proj_mat_locaton_ = controller_shader_.getUniformLocation( "projection" );
}
}
return success;
}
void VRSystem::processVREvents()
{
vr::VREvent_t event;
// Poll the event queue
while( vr_system_->PollNextEvent( &event, sizeof( event ) ) )
{
if( event.eventType == vr::VREvent_TrackedDeviceRoleChanged )
{
if( event.trackedDeviceIndex == left_controller_.index() )
{
left_controller_.shutdown();
std::cout << "Left controller changed role" << std::endl;
}
else if( event.trackedDeviceIndex == right_controller_.index() )
{
right_controller_.shutdown();
std::cout << "Right controller changed role" << std::endl;
}
}
else if( event.eventType == vr::VREvent_TrackedDeviceDeactivated )
{
if( event.trackedDeviceIndex == left_controller_.index() )
{
left_controller_.shutdown();
std::cout << "Left controller disconncted" << std::endl;
}
else if( event.trackedDeviceIndex == right_controller_.index() )
{
right_controller_.shutdown();
std::cout << "Right controller disconncted" << std::endl;
}
}
}
}
void VRSystem::manageDevices()
{
// Init the left controller if it hasn't been initialised already
if( !left_controller_.isInitialised() )
{
vr::TrackedDeviceIndex_t left_index = vr_system_->GetTrackedDeviceIndexForControllerRole( vr::ETrackedControllerRole::TrackedControllerRole_LeftHand );
if( left_index != -1 )
{
left_controller_.init( left_index, this, controller_shader_ );
left_controller_.setActiveTool( &move_tool_ );
std::cout << "Left controller initialised!" << std::endl;
}
}
// Init the right controller if it hasn't been initialised already
if( !right_controller_.isInitialised() )
{
vr::TrackedDeviceIndex_t right_index = vr_system_->GetTrackedDeviceIndexForControllerRole( vr::ETrackedControllerRole::TrackedControllerRole_RightHand );
if( right_index != -1 )
{
right_controller_.init( right_index, this, controller_shader_ );
right_controller_.setActiveTool( &pointer_tool_ );
//right_controller_.setActiveTool( &point_light_tool_ );
std::cout << "Right controller initialised!" << std::endl;
}
}
}
void VRSystem::updatePoses()
{
// Update the pose list
vr::VRCompositor()->WaitGetPoses( poses_, vr::k_unMaxTrackedDeviceCount, NULL, 0 );
for( int device_index = 0; device_index < vr::k_unMaxTrackedDeviceCount; device_index++ )
{
if( poses_[device_index].bPoseIsValid )
{
// Translate the pose matrix to a glm::mat4 for ease of use
// The stored matrix is from device to absolute tracking position, we will probably want that inverted
transforms_[device_index] = glm::inverse( convertHMDmat3ToGLMMat4( poses_[device_index].mDeviceToAbsoluteTracking ) );
// Pass controller poses to the controllers
if( left_controller_.index() == device_index ) left_controller_.setPose( poses_[device_index] );
if( right_controller_.index() == device_index ) right_controller_.setPose( poses_[device_index] );
}
}
}
void VRSystem::updateDevices( float dt )
{
if( left_controller_.isInitialised() )
{
left_controller_.update( dt );
if( left_controller_.isButtonPressed( vr::k_EButton_Grip ) )
{
std::cout << "Reset point cloud location" << std::endl;
point_cloud_->resetPosition();
move_tool_.resetTransform();
}
}
if( right_controller_.isInitialised() )
{
right_controller_.update( dt );
// While the pointer tool is not 'active' it is always accissible
// This reveals a desing flaw in the way my controllers + tools were designed but i'll ignore it for now...
pointer_tool_.update( dt );
}
}
void VRSystem::render( const glm::mat4& view, const glm::mat4& projection )
{
drawControllers( view, projection );
if( move_tool_.isInitialised() ) move_tool_.render( view, projection );
if( pointer_tool_.isInitialised() ) pointer_tool_.render( view, projection );
if( point_light_tool_.isInitialised() ) point_light_tool_.render( view, projection );
}
void VRSystem::drawControllers( glm::mat4 view, glm::mat4 projection )
{
controller_shader_.bind();
glUniformMatrix4fv( controller_shader_view_mat_locaton_, 1, GL_FALSE, glm::value_ptr( view ) );
glUniformMatrix4fv( controller_shader_proj_mat_locaton_, 1, GL_FALSE, glm::value_ptr( projection ) );
if( left_controller_.isInitialised() )
{
glUniformMatrix4fv( controller_shader_modl_mat_locaton_, 1, GL_FALSE, glm::value_ptr( left_controller_.deviceToAbsoluteTracking() ) );
left_controller_.draw();
}
if( right_controller_.isInitialised() )
{
glUniformMatrix4fv( controller_shader_modl_mat_locaton_, 1, GL_FALSE, glm::value_ptr( right_controller_.deviceToAbsoluteTracking() ) );
right_controller_.draw();
}
}
void VRSystem::bindEyeTexture( vr::EVREye eye )
{
glEnable( GL_MULTISAMPLE );
glEnable( GL_DEPTH_TEST );
// TODO: this should be binding the renderEyeTexture instead
glBindFramebuffer( GL_FRAMEBUFFER, resolveEyeTexture(eye) );
glViewport( 0, 0, render_target_width_, render_target_height_ );
}
void VRSystem::blitEyeTextures()
{
for( int i = 0; i < 2; i++ )
{
// Blit from the render frame buffer to the resolve
glViewport( 0, 0, render_target_width_, render_target_height_ );
glBindFramebuffer( GL_READ_BUFFER, eye_buffers_[i].render_frame_buffer );
glBindFramebuffer( GL_DRAW_BUFFER, eye_buffers_[i].resolve_frame_buffer );
glBlitFramebuffer(
0, 0, render_target_width_, render_target_height_,
0, 0, render_target_width_, render_target_height_,
GL_COLOR_BUFFER_BIT, GL_LINEAR );
}
}
void VRSystem::submitEyeTextures()
{
if( hasInputFocus() )
{
// NOTE: to find out what the error codes mean Ctal+F 'enum EVRCompositorError' in 'openvr.h'
vr::EVRCompositorError error = vr::VRCompositorError_None;
vr::Texture_t left = { (void*)eye_buffers_[0].resolve_texture, vr::TextureType_OpenGL, vr::ColorSpace_Gamma };
error = vr::VRCompositor()->Submit( vr::Eye_Left, &left, NULL );
if( error != vr::VRCompositorError_None ) std::cout << "ERROR: left eye " << error << std::endl;
vr::Texture_t right = { (void*)eye_buffers_[1].resolve_texture, vr::TextureType_OpenGL, vr::ColorSpace_Gamma };
error = vr::VRCompositor()->Submit( vr::Eye_Right, &right, NULL );
if( error != vr::VRCompositorError_None ) std::cout << "ERROR: right eye " << error << std::endl;
// Added on advice from comments in IVRCompositor::submit in openvr.h
glFlush();
}
}
glm::mat4 VRSystem::projectionMartix( vr::Hmd_Eye eye )
{
vr::HmdMatrix44_t matrix = vr_system_->GetProjectionMatrix( eye, near_clip_plane_, far_clip_plane_ );
return convertHMDmat4ToGLMmat4( matrix );
}
glm::mat4 VRSystem::eyePoseMatrix( vr::Hmd_Eye eye )
{
vr::HmdMatrix34_t matrix = vr_system_->GetEyeToHeadTransform( eye );
return glm::inverse( convertHMDmat3ToGLMMat4( matrix ) );
}
std::string VRSystem::getDeviceString(
vr::TrackedDeviceIndex_t device,
vr::TrackedDeviceProperty prop,
vr::TrackedPropertyError* error )
{
uint32_t buffer_length = vr_system_->GetStringTrackedDeviceProperty( device, prop, NULL, 0, error );
if( buffer_length == 0 ) return "";
char* buffer = new char[buffer_length];
vr_system_->GetStringTrackedDeviceProperty( device, prop, buffer, buffer_length, error );
std::string result = buffer;
delete[] buffer;
return result;
}
|
#include <iostream>
using namespace std;
string s;
int res = 1;
void nhap(){
cin >> s;
}
void solve(){
int i, j;
for(i = 1; i < s.length()-1; i++){
j = 0;
while(i - j >= 0 && i + j < s.length() && s[i-j] == s[i+j]) j++;
if(i - j < 0 || i + j >= s.length() || s[i-j] != s[i+j]) j--;
if(res < 2*j+1) res = 2*j+1;
}
for(i = 0; i < s.length()-1; i++) if(s[i] == s[i+1]){
j = 0;
while(i-j >= 0 && i+1+j < s.length() && s[i-j] == s[i+1+j]) j++;
if(i - j < 0 || i + 1 + j >= s.length() || s[i-j] != s[i+1+j]) j--;
if(res < 2*j+2) res = 2*j+2;
}
cout << res;
}
int main(){
nhap();
solve();
}
|
/*
========================================================================
DEVise Data Visualization Software
(c) Copyright 1992-1995
By the DEVise Development Group
Madison, Wisconsin
All Rights Reserved.
========================================================================
Under no circumstances is this software to be copied, distributed,
or altered in any way without prior permission from the DEVise
Development Group.
*/
/*
$Id: Time.c,v 1.6 1996/10/01 14:00:26 wenger Exp $
$Log: Time.c,v $
Revision 1.6 1996/10/01 14:00:26 wenger
Removed extra path info from includes.
Revision 1.5 1996/07/17 00:47:03 jussi
Switched the order of header file inclusions to get around
some problems.
Revision 1.4 1996/03/26 15:34:36 wenger
Fixed various compile warnings and errors; added 'clean' and
'mostlyclean' targets to makefiles; changed makefiles so that
object lists are derived from source lists.
Revision 1.3 1995/12/02 20:55:53 jussi
Substituted DeviseTime for Time and added copyright notice.
Revision 1.2 1995/09/05 21:13:05 jussi
Added/updated CVS header.
*/
#include <time.h>
#include "machdep.h"
#include "Time.h"
struct timeval DeviseTime::_beginning;
/***********************************************************/
void DeviseTime::Init()
{
struct timezone zone;
gettimeofday(&_beginning, &zone);
}
/***********************************************************/
long DeviseTime::Now()
{
struct timezone zone;
struct timeval now;
gettimeofday(&now,&zone);
return (now.tv_sec - _beginning.tv_sec) * 1000+
(now.tv_usec - _beginning.tv_usec) / 1000;
}
|
// 2017-11-25 thewinds
// [题目] PAT A-1003
// 消防员经过最短的路径到达指定城市,问有多少条最短的路径
// 和(最短路径)最大召集的人数
// [考点] 图的遍历(dfs)
// [心得]
// 因为没有仔细审题,导致TimeOut....
// 题目中说 `Each input file contains one test case.`
// 这时候最外层就不需要用while()来不断读取了.
#include <cstdio>
#include <cstring>
#define MIN -1
#define MAX 1e9
struct Log
{
char id[20];
int hour;
int minute;
int second;
};
int logTimeCmp(Log a, Log b)
{
if (a.hour == b.hour)
{
if (a.minute == b.minute)
{
if (a.second == b.second)
{
return 0;
}
return a.second > b.second ? 1 : -1;
}
return a.minute > b.minute ? 1 : -1;
}
return a.hour > b.hour ? 1 : -1;
}
int main()
{
Log first, last, currentIn, currentOut;
first.hour = first.minute = first.second = MAX;
last.hour = last.minute = last.second = MIN;
int n;
scanf("%d", &n);
while (n--)
{
scanf("%s", ¤tIn.id);
strcpy(currentOut.id, currentIn.id);
scanf("%d:%d:%d", ¤tIn.hour, ¤tIn.minute, ¤tIn.second);
scanf("%d:%d:%d", ¤tOut.hour, ¤tOut.minute, ¤tOut.second);
if (logTimeCmp(currentIn, first) == -1)
{
first = currentIn;
}
if (logTimeCmp(currentOut, last) == 1)
{
last = currentOut;
}
}
printf("%s %s", first.id, last.id);
return 0;
}
|
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
int speed;
cin >> speed;
printf("%d minutos\n",2*speed);
return 0;
}
|
#pragma once
#include<string>
using namespace std;
class Pralka
{
private:
string nazwa;
string typ;
string cena;
string ilosc;
public:
Pralka(string nazwa, string typ, string cena, string ilosc);
string wezNazwe() const;
string wezTyp() const;
string wezCene() const;
string wezIlosc() const;
Pralka & nowaCena(string cena);
Pralka & nowaIlosc(string ilosc);
void napisz() const;
};
|
#include <SFML/Graphics.hpp>
#include <iostream>
#include "Enemy.h"
#include "Bala.h"
#include "Personaje.h"
#define ventanax 640
#define ventanay 640
#define tamper 30.0
#define velperso 5
//g++ main.cpp -o test -lsfml-graphics -lsfml-window -lsfml-system Enemy.cpp Bala.cpp
void Boton(sf::Keyboard X){
}
int main()
{
sf::RenderWindow window(sf::VideoMode(ventanax, ventanay), "Game");
sf::RectangleShape fondo(sf::Vector2f(ventanax,ventanay));
window.setVerticalSyncEnabled(1);
window.setFramerateLimit(60);
fondo.setFillColor(sf::Color(40,55,71,255));
int colorg,aux3=1;
int aux=0;
bool aux2=1;
char dir='W';
static int numb,nume=4;
Enemy *enemy=new Enemy[nume]; //Inicializamos las clases enemy y Bala
Bala *bala=new Bala[5]; // lo de arriba 7u7
Personaje personaje(0,0,tamper,tamper);
while (window.isOpen()){
window.clear();
window.draw(fondo);
colorg=colorg+aux3;std::cout<<colorg; //estetica , darle color al fondo nomas xd
if(colorg>254 || colorg<1)aux3=-1*aux3; //
fondo.setFillColor(sf::Color(0,153,colorg,255)); //lo de arriba
personaje.Movimiento();
window.draw(personaje.Per);
sf::Event event;
while (window.pollEvent(event)){
if (event.type == sf::Event::Closed)
window.close();
}
//Activar enemigos
if(sf::Keyboard::isKeyPressed(sf::Keyboard::L))aux=1;
if(aux){
for(int i=0;i<nume;i++){
enemy[i].PosicionPer(personaje.Per.getPosition().x,personaje.Per.getPosition().y);
enemy[i].Movimiento();
window.draw((enemy[i].entidad));
}
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::E)) return 0;
//Bala
aux2=0;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::F)||aux2==1){
if(!sf::Keyboard::isKeyPressed(sf::Keyboard::F) || aux2==0){
bala[0].PosicionPer(personaje.Per.getPosition().x , personaje.Per.getPosition().y,tamper,dir);
window.draw((bala[0].bala));
}
else {
aux2=0;
}
aux2=1;
}
else {
bala[0].Movimiento();
window.draw((bala[0].bala));
}
std::cout<<personaje.Per.getPosition().y<<" :: "<<personaje.Per.getPosition().x<<" :: "<<dir<<std::endl;
window.display();
}
return 0;
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int INF = 2e9 + 7;
struct edge{
int to,dist;
};
vector<edge> G[1010];
int dis[1010],ans[1010];
bool vis[1010];
void spfa()
{
queue<int> Q;
Q.push(2);
while (!Q.empty())
{
int s = Q.front();Q.pop();
for (int i = 0;i < G[s].size(); i++)
{
edge e = G[s][i];
if (dis[s] + e.dist < dis[e.to])
{
dis[e.to] = dis[s] + e.dist;
if (!vis[e.to])
{
Q.push(e.to);
vis[e.to] = true;
}
}
}
vis[s] = false;
}
}
int cou(int p)
{
if (p == 2) return (ans[2] = 1);
ans[p] = 0;
for (int i = 0;i < G[p].size(); i++)
{
edge e = G[p][i];
if (dis[p] > dis[e.to])
if (ans[e.to] >= 0)
ans[p] += ans[e.to];
else
ans[p] += cou(e.to);
}
return ans[p];
}
int main()
{
int n,m;
while (scanf("%d%d",&n,&m) != EOF && n)
{
int from,to,dist;
for (int i = 1;i <= n; i++)
{
G[i].clear();
dis[i] = INF;
ans[i] = -1;
vis[i] = false;
}
dis[2] = 0;
for (int i = 1;i <= m; i++)
{
scanf("%d%d%d",&from,&to,&dist);
G[from].push_back((edge){to,dist});
G[to].push_back((edge){from,dist});
}
spfa();
printf("%d\n",cou(1));
//for (int i = 1;i <= n; i++) cout << dis[i] << " ";cout << endl;
//for (int i = 1;i <= n; i++) cout << ans[i] << " ";cout << endl;
}
return 0;
}
|
#include<stdlib.h>
#include<iostream>
#include<stdio.h>
#include<conio.h>
using namespace std;
int main()
{
vuongmin:
char mang[100];
int phantu=0;
int demsophay=0;
int demsokitu=0;
int money;
cout<<"\n Nhap Tien:\t";
cin>>money;
while(money!=0)
{
int digit=money%10;
money/=10;
if(demsokitu%3==0&&demsokitu!=0)
{
//ki tu phay
mang[phantu++]=44;
demsophay++;
}
//lay code cong 48 de ra so do
mang[phantu++]=digit+48;
demsokitu++;
}
for(int i=demsokitu+demsophay-1;i>=0;i--)
{
cout<<mang[i];
}
return 0;
}
|
void setup_SDcard() {
Serial.print(F("Initializing SD card..."));
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println(F("Card failed, or not present"));
// don't do anything more:
return;
}
Serial.println(F("card initialized."));
}
void log_data() {
String dataString = "";
if (millis() - lastLoggedTime > LOGINTERVAL) {
dataString += get_gps_reading();
Serial.print("datastring: ");
Serial.println(dataString);
File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
Serial.print(F("Writing to file: "));
Serial.println(dataString);
} else {
Serial.println(F("error opening datalog.txt"));
}
lastLoggedTime = millis();
}
}
|
//
// Created by Tanguy on 28/11/2017.
//
#include "MediatorPacket.hpp"
std::ostream& operator<<(std::ostream& os, const MediatorPacket& mediatorPacket)
{
os << mediatorPacket.packet;
return os;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** This file describe a class used to asynchronously export a cache storage
**
** Luca Venturi
**
*/
#include "core/pch.h"
#ifdef PI_ASYNC_FILE_OP
#include "modules/cache/cache_exporter.h"
#include "modules/util/opfile/opfile.h"
#include "modules/url/url_ds.h"
#include "modules/cache/url_cs.h"
#include "modules/pi/OpSystemInfo.h"
CacheAsyncExporter::CacheAsyncExporter(AsyncExporterListener *progress_listener, URL_Rep *rep, BOOL safe_mode, BOOL delete_if_error, UINT32 param):
url_rep(rep), pos(FILE_LENGTH_NONE), len(0), safe(safe_mode), user_param(param), delete_on_error(delete_if_error),
listener(progress_listener), input(NULL), output(NULL), buf(NULL)
{
OP_ASSERT(listener && url_rep);
OP_ASSERT(url_rep->GetDataStorage() && url_rep->GetDataStorage()->GetCacheStorage());
url_rep->IncUsed(1);
}
OP_STATUS CacheAsyncExporter::StartExport(const OpStringC &file_name)
{
RETURN_IF_ERROR(name.Set(file_name));
if(name.IsEmpty())
return OpStatus::ERR;
OP_ASSERT(pos==FILE_LENGTH_NONE);
if(!listener || !url_rep)
return OpStatus::ERR_NULL_POINTER;
if(pos!=FILE_LENGTH_NONE)
return OpStatus::ERR_OUT_OF_RANGE;
buf = OP_NEWA(UINT8, STREAM_BUF_SIZE);
RETURN_OOM_IF_NULL(buf);
RETURN_IF_ERROR(g_main_message_handler->SetCallBack(this, MSG_CACHE_EXPORT, (MH_PARAM_1)this));
if(!g_main_message_handler->PostMessage(MSG_CACHE_EXPORT, (MH_PARAM_1)this, 0))
return OpStatus::ERR;
return OpStatus::OK;
}
void CacheAsyncExporter::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
OP_ASSERT((CacheAsyncExporter *)par1 == this);
OP_STATUS ops=OpStatus::OK;
if(pos==FILE_LENGTH_NONE) // First message
{
OP_ASSERT(!input && !output);
Cache_Storage *cs=url_rep->GetDataStorage()->GetCacheStorage();
pos=0;
len=0;
// Try to open the input file
if(!safe)
input=cs->OpenCacheFileForExportAsReadOnly(ops);
if(input)
input->GetFileLength(len);
if(!len)
url_rep->GetAttribute(URL::KContentSize, &len);
// First notification, to be able to show something to the user before starting synchronous operations
if(listener)
listener->NotifyStart(len, url_rep, name, user_param);
// First progress notification
if(listener)
listener->NotifyProgress(0, len, url_rep, name, user_param);
// If the problem is that the file is still in memory because it has not been saved, save it synchronously then continue asynchronously
if(!input && !safe && !cs->IsEmbedded() && !cs->IsEmbeddable() && !cs->GetContainerID())
{
OpFileFolder folder;
OpStringC cache_file=url_rep->GetDataStorage()->GetCacheStorage()->FileName(folder);
if(cache_file.IsEmpty())
{
url_rep->GetDataStorage()->GetCacheStorage()->Flush(); // Save the file
url_rep->GetDataStorage()->GetCacheStorage()->CloseFile();
}
// The problem is that files become embedded or containers after Flush... so it needs to be checked again (strictly speaking, the first check is useless)
if(!cs->IsEmbedded() && !cs->GetContainerID())
{
input=url_rep->GetDataStorage()->GetCacheStorage()->OpenCacheFileForExportAsReadOnly(ops);
if(input) // Fast operations are now possible
{
input->GetFileLength(len);
// Repeat first progress notification
if(listener)
listener->NotifyProgress(0, len, url_rep, name, user_param);
}
}
}
//// If it was impossible to open the second file, switch to synchronous
// "Safe", synchronous export (there are cases where OpenCacheFileForExportAsReadOnly() can still refuse to open the file)
if(safe || !input)
{
ops=(OP_STATUS)url_rep->SaveAsFile(name);
if(OpStatus::IsSuccess(ops))
pos=len;
}
else
{
if(OpStatus::IsError(ops) || !input ||
!(output=OP_NEW(OpFile, ())) ||
OpStatus::IsError(ops=output->Construct(name)) ||
OpStatus::IsError(ops=output->Open(OPFILE_WRITE)))
{
NotifyEndAndDeleteThis(OpStatus::ERR_NO_MEMORY); // The destructor will delete the pointers
return;
}
}
}
if(!safe)
{
// Not "safe", asynchronous export
double start=g_op_time_info->GetTimeUTC();
double cur_time=start;
OpFileLength bytes_read=1;
while(OpStatus::IsSuccess(ops) && pos<len && cur_time<start+100 && bytes_read>0)
{
if(OpStatus::IsSuccess(ops=input->Read(buf, STREAM_BUF_SIZE, &bytes_read)) &&
bytes_read>0)
{
ops=output->Write(buf, bytes_read);
}
if(bytes_read>0 && bytes_read!=FILE_LENGTH_NONE)
pos+=bytes_read;
cur_time=g_op_time_info->GetTimeUTC();
//cur_time=start+100; // Simulation for selftests
}
if(bytes_read==0 || bytes_read==FILE_LENGTH_NONE)
ops=OpStatus::ERR;
}
OP_ASSERT(pos<=len);
if(listener)
listener->NotifyProgress(pos, len, url_rep, name, user_param);
if(pos>=len) // File exported
{
OP_ASSERT(ops==OpStatus::OK);
NotifyEndAndDeleteThis(OpStatus::OK);
}
else if(OpStatus::IsError(ops)) // Error
NotifyEndAndDeleteThis(ops);
else
{
OP_ASSERT(!safe);
// Post a message, the export will continue
if(!g_main_message_handler->PostMessage(MSG_CACHE_EXPORT, (MH_PARAM_1)this, 0))
NotifyEndAndDeleteThis(OpStatus::ERR); // Message not posted ==> Stop everything or we will leak memory and file handles
}
}
void CacheAsyncExporter::NotifyEndAndDeleteThis(OP_STATUS ops)
{
OP_ASSERT(listener);
// Close the files, to reduce a bit the resource usage before notifying that the export is finished
if(input)
OpStatus::Ignore(input->Close());
if(output)
{
OpStatus::Ignore(output->Close());
if(delete_on_error && OpStatus::IsError(ops))
OpStatus::Ignore(output->Delete());
}
if(listener)
listener->NotifyEnd(ops, pos, len, url_rep, name, user_param);
OP_DELETE(this);
}
CacheAsyncExporter::~CacheAsyncExporter()
{
g_main_message_handler->UnsetCallBacks(this);
if(input)
input->Close();
if(output)
output->Close();
OP_DELETE(input);
OP_DELETE(output);
url_rep->DecUsed(1);
OP_DELETEA(buf);
}
#endif // CACHE_EXPORTER_H
|
#pragma once
#include "abstractValue.h"
namespace json {
class NullValue : public AbstractValue {
public:
virtual ValueType type() const override { return null; }
virtual bool equal(const IValue *other) const override;
static const IValue *getNull();
};
class BoolValue : public AbstractValue {
public:
virtual ValueType type() const override { return boolean; }
virtual bool getBool() const override = 0;
virtual double getNumber() const override {return getBool()?1.0:0;}
virtual Int getInt() const override {return getBool()?1:0;}
virtual UInt getUInt() const override {return getBool()?1:0;}
virtual LongInt getIntLong() const override {return getBool()?1:0;}
virtual ULongInt getUIntLong() const override {return getBool()?1:0;}
static const IValue *getBool(bool v);
virtual bool equal(const IValue *other) const override;
};
class AbstractNumberValue : public AbstractValue {
public:
virtual ValueType type() const override { return number; }
virtual double getNumber() const override = 0;
virtual Int getInt() const override = 0;
virtual UInt getUInt() const override = 0;
virtual LongInt getIntLong() const override = 0;
virtual ULongInt getUIntLong() const override = 0;
static const IValue *getZero();
virtual bool equal(const IValue *other) const override;
};
class AbstractStringValue : public AbstractValue {
public:
virtual ValueType type() const override { return string; }
virtual StringView<char> getString() const override = 0;
virtual Int getInt() const override;
virtual UInt getUInt() const override;
virtual LongInt getIntLong() const override;
virtual ULongInt getUIntLong() const override;
virtual double getNumber() const override;
static const IValue *getEmptyString();
virtual bool equal(const IValue *other) const override;
};
class AbstractArrayValue : public AbstractValue {
public:
virtual ValueType type() const override { return array; }
virtual std::size_t size() const override = 0;
virtual const IValue *itemAtIndex(std::size_t index) const override = 0;
virtual bool enumItems(const IEnumFn &) const override = 0;
static const IValue *getEmptyArray();
virtual bool equal(const IValue *other) const override;
};
class AbstractObjectValue : public AbstractValue {
public:
virtual ValueType type() const override { return object; }
virtual std::size_t size() const override = 0;
virtual const IValue *itemAtIndex(std::size_t index) const override = 0;
virtual const IValue *member(const StringView<char> &name) const override = 0;
virtual bool enumItems(const IEnumFn &) const override = 0;
virtual bool equal(const IValue *other) const override;
static const IValue *getEmptyObject();
};
template<typename T, ValueTypeFlags f >
class NumberValueT : public AbstractNumberValue {
public:
NumberValueT(const T &v) :v(v) {}
virtual double getNumber() const override { return double(v); }
virtual Int getInt() const override { return Int(v); }
virtual UInt getUInt() const override { return UInt(v); }
virtual LongInt getIntLong() const override {return LongInt(v);}
virtual ULongInt getUIntLong() const override {return ULongInt(v);}
virtual ValueTypeFlags flags() const override { return f; }
virtual bool equal(const IValue *other) const override {
if (other->type() == number) {
const NumberValueT *k = dynamic_cast<const NumberValueT *>(other->unproxy());
if (k) return k->v == v;
else return AbstractNumberValue::equal(other);
} else {
return false;
}
}
virtual bool getBool() const override {return true;}
protected:
T v;
};
using UnsignedIntegerValue = NumberValueT<UInt, numberUnsignedInteger>;
using IntegerValue = NumberValueT<Int, numberInteger>;
using UnsignedLongValue = NumberValueT<ULongInt, numberUnsignedInteger|longInt>;
using LongValue = NumberValueT<LongInt, numberInteger|longInt>;
using NumberValue = NumberValueT<double,0>;
/*
class StringValue : public AbstractStringValue {
public:
StringValue(const StringView<char> &str) :v(str) {}
StringValue(std::string &&str) :v(std::move(str)) {}
virtual StringView<char> getString() const override {
return v;
}
virtual bool getBool() const override {return true;}
virtual Int getInt() const override;
virtual UInt getUInt() const override;
virtual double getNumber() const override;
protected:
std::string v;
};
*/
}
|
#ifndef VECTOR
#define VECTOR
#include "Matrix.h"
class Vector :
public Matrix
{
public:
Vector(int);
double& operator()(int);
double operator() (int) const;
int getLength() const;
Vector(const Matrix&);
};
#endif
|
#include <bits/stdc++.h>
using namespace std;
int main(){
ifstream fi("DEMSO.inp");
ofstream fo("DEMSO.out");
int a[10];
int n = 0;
memset(a, 0, sizeof(a));
while(!fi.eof()){
int x;
fi >> x;
a[x]++;
}
for (int i = 0; i < 9; ++i) {
if(a[i] == 1)
n++;
}
fo << n;
return 0;
}
|
/*************************************************************************
References - description
-------------------
début : 10 nov. 2011
copyright : (C) 2011 par Robin Gicquel et Arnaud Mery de Montigny
*************************************************************************/
//------- Réalisation de la classe <References> (fichier References.cpp) -----
//---------------------------------------------------------------- INCLUDE
//-------------------------------------------------------- Include système
using namespace std;
#include <fstream>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
#include <utility>
#include <cstring>
#include <cstdlib>
//------------------------------------------------------ Include personnel
#include "References.h"
#include "AssocRefFichier.h"
//------------------------------------------------------------- Constantes
static const char DELIM[] = {
' ', '\t', '\r', '\n', ';', ':', ',', '.', '<', '>', '=', '{', '}', '(',
')', '!', '-', '+', '/', '*', '&', '|', '%', '$', '#', '[', ']' };
static const char TAILLE_DELIM = 27;
static const string MOTS_CLES_C[] = {
"asm", "auto", "bool", "break", "case", "catch", "char", "class",
"const", "const_char", "continue", "default", "delete", "do", "double",
"dynamic_cast", "else", "enum", "explicit", "export", "extern", "false",
"float", "for", "friend", "goto", "if", "inline", "int", "long",
"mutable", "namespace", "new", "operator", "private", "protected",
"public", "register", "reinterpret_cast", "return", "short", "signed",
"sizeof", "static", "static_cast", "struct", "switch", "template",
"this", "throw", "true", "try", "typedef", "typeid", "typename",
"union", "unsigned", "using", "virtual", "void", "volatile", "wchar_t",
"while" };
static const int TAILLE_MOTS_CLES_C = 63;
//----------------------------------------------------------------- PUBLIC
//----------------------------------------------------- Méthodes publiques
void References::TraiterFichiers ( char * nomFichierMotsCles,
set<string> &nomsFichiers )
// Algorithme : Trivial
{
if ( nomFichierMotsCles != NULL )
{
lireFichierMotsCles ( nomFichierMotsCles );
}
else
{
// remplissage du vector à partir du tableau constant de mots-clés
motsCles = new vector<string> ( MOTS_CLES_C,
MOTS_CLES_C + TAILLE_MOTS_CLES_C );
}
for ( set<string>::iterator it = nomsFichiers.begin ( );
it != nomsFichiers.end ( ); it++ )
{
const char * truc = it->c_str ( );
lireFichier ( truc );
}
} //----- Fin de TraiterFichiers
string References::AfficherResultat ( )
// Algorithme : Trivial
{
string str = "";
for ( map<string, AssocRefFichier>::iterator it = references.begin ( );
it != references.end ( ); it++ )
{
str += it->first + it->second.AfficherFichiers ( ) + '\n';
}
return str;
} //----- Fin de AfficherResultat
//-------------------------------------------- Constructeurs - destructeur
References::References ( const References & unReferences )
// Algorithme : Trivial
{
#ifdef MAP
cout << "Appel au constructeur de copie de <References>" << endl;
#endif
} //----- Fin de References (constructeur de copie)
References::References ( )
// Algorithme : Trivial
{
#ifdef MAP
cout << "Appel au constructeur par défaut de <References>" << endl;
#endif
} //----- Fin de References (contructeur par défaut)
References::References ( bool optExclureMotsCles ) :
exclureMotsCles ( optExclureMotsCles )
// Algorithme : Trivial
{
#ifdef MAP
cout << "Appel au constructeur de <References>" << endl;
#endif
} //----- Fin de References
References::~References ( )
// Algorithme : Trivial
{
#ifdef MAP
cout << "Appel au destructeur de <References>" << endl;
#endif
delete motsCles;
} //----- Fin de ~References
//------------------------------------------------------------------ PRIVE
//----------------------------------------------------- Méthodes protégées
vector<string> * References::lireFichierMotsCles ( char * nomFichier )
// Algorithme : Lecture ligne par ligne d'un fichier
{
string str;
char c;
motsCles = new vector<string>;
ifstream lecture;
lecture.open ( nomFichier );
if ( lecture.fail ( ) )
{
throw ERREUR_OUVERTURE_MOTS_CLES;
}
while (!lecture.eof ( ))
{
str = "";
// Ajoute les caractères en provenance du flux jusqu'à trouver une
// fin de ligne
while ((c = lecture.get ( )) != '\n' && c != '\r' && c != -1)
{
str.push_back ( c );
}
// Vide le "buffer" des éventuels '\n' et '\r' restants
while ((c = lecture.peek ( )) == '\n' || c == '\r')
{
lecture.get ( );
}
// La fonction find() renvoie la constante npos si la chaîne n'est pas
// trouvée
if ( str.find ( ' ' ) == string::npos
|| str.find ( ',' ) == string::npos
|| str.find ( ';' ) == string::npos
|| str.find ( '\t' ) == string::npos )
{
throw ERREUR_LECTURE_MOTS_CLES;
}
motsCles->push_back ( str );
}
lecture.close ( );
return motsCles;
} //----- Fin de lireFichierMotsCles
void References::lireFichier ( const char * nomFichier )
// Algorithme :
// Lecture caractère par caratère d'un fichier avec détection des
// commentaires. Dès qu'un mot est isolé, il est recherché dans la liste des
// mots clés et ajouté aux références en fonction des options fournies.
{
ifstream lecture;
string mot = "";
int numLigne = 1;
int c;
int c2;
char carAttendu1 = -1;
char carAttendu2 = -1;
lecture.open ( nomFichier );
if ( lecture.fail ( ) )
{
throw ERREUR_OUVERTURE;
}
while (!lecture.eof ( ))
{
c = lecture.get ( );
if ( carAttendu1 == -1 )
{
if ( c == '/' )
{
c2 = lecture.peek ( );
if ( c2 == '/' )
{
carAttendu1 = '\n';
lecture.get ( );
}
else if ( c2 == '*' )
{
carAttendu1 = '*';
carAttendu2 = '/';
lecture.get ( );
}
}
else if ( c == '"' )
{
carAttendu1 = '"';
}
else if ( c == '\'' )
{
carAttendu1 = '\'';
}
else if ( find ( DELIM, DELIM + TAILLE_DELIM, c )
== DELIM + TAILLE_DELIM ) // Recherche du mot lu dans les mots-clés
{
mot.push_back ( c );
}
else
{
if ( mot != "" )
{
traiterMot ( mot, nomFichier, numLigne );
mot.clear ( );
}
}
}
else
{
if ( c == carAttendu1 )
{
if ( carAttendu2 == -1 )
{
carAttendu1 = -1;
}
else
{
if ( lecture.peek ( ) == carAttendu2 )
{
carAttendu1 = -1;
carAttendu2 = -1;
if ( lecture.get ( ) == '\n' )
{
numLigne++;
}
}
}
}
}
if ( lecture.peek ( ) == '\n' )
{
numLigne++;
}
}
} //----- Fin de lireFichier
void References::traiterMot ( string &mot, const char * nomFichier,
int numLigne )
// Algorithme : Trivial, point délicat détaillé dans le corps
{
const char * motC = mot.c_str ( );
char ** retourStrtod = new char*;
// Pour vérifier si motC n'est pas un nombre, on teste s'il s'agit d'un
// réel. Pour cela, on utilise la fonction C strtod qui renvoie 0.0 si la
// chaîne passée en paramètre ne correspond pas à un nombre réel. Pour
// différencier la lecture de la chaîne "0" et celle d'une chaîne quelconque
// ne correspondant pas à un nombre réel, la fonction affecte l'adresse du
// premier paramètre passé à la valeur du second paramètre passé. Ainsi, en
// vérifiant que *retourStrtod est égal à motC, on est assuré que le mot est
// ou n'est un nombre.
if ( strtod ( motC, retourStrtod ) == 0.0 && *retourStrtod == motC )
{
if ( find ( motsCles->begin ( ), motsCles->end ( ), mot )
!= motsCles->end ( ) )
{
if ( !exclureMotsCles )
{
ajouterReference ( mot, nomFichier, numLigne );
}
}
else if ( exclureMotsCles )
{
ajouterReference ( mot, nomFichier, numLigne );
}
}
delete retourStrtod;
} //----- Fin de traiterMot
void References::ajouterReference ( string &mot, const char * nomFichier,
int numLigne )
// Algorithme : Trivial
{
AssocRefFichier * assoc = new AssocRefFichier ( );
pair<map<string, AssocRefFichier>::iterator, bool> paire;
paire = references.insert (
pair<string, AssocRefFichier> ( mot, *(assoc) ) );
map<string, AssocRefFichier>::iterator it = paire.first;
it->second.AjouterReference ( nomFichier, numLigne );
delete assoc;
} //----- Fin de ajouterReference
|
#include <iostream>
int preDecrease(int &i) {
std::cout << "Enter a number:\t";
std::cin >> i;
i -= 1;
return i;
}
int postDecrease(int &i) {
std::cout << "Enter a number:\t";
std::cin >> i;
i -= 1;
return i + 1;
}
int main() {
int k;
std::cout << "Call of PreDec:\t" << preDecrease(k) << std::endl;
std::cout << "Number:\t" << k << std::endl;
std::cout << "Call of postDec:\t" << postDecrease(k) << std::endl;
std::cout << "Number:\t" << k << std::endl;
return 0;
}
|
#include <iostream>
#include <unistd.h>
int main()
{
fork(); fork(); fork();
std::cout << "hi!\n";
return 0;
}
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
#include <complex>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
#define N 11111
int t, m, n, d, h, cc;
int super[N], p[N], reg[N], net[N], z;
char regcode[222][2222];
char buf[11111];
int b[555555][10], bn = 0;
int town[555555];
int cost[4][4];
int type1(int t) {
if (reg[t] == h) return 0;
if (net[reg[t]] && super[reg[t]] == super[h]) return 1;
if (net[reg[t]]) return 2;
return 3;
}
int type2(int from, int to) {
if (from == to) return 0;
if (reg[from] == reg[to]) return 1;
if (net[reg[to]]) return 2;
return 3;
}
void add(const char * s, int t) {
int cur = 0;
while (*s) {
char ch = *s - '0';
++s;
if (!b[cur][ch]) b[cur][ch] = ++bn;
cur = b[cur][ch];
}
town[cur] = t;
}
int gettown(const char * s) {
int cur = 0;
while (*s) {
char ch = *s - '0';
++s;
if (!b[cur][ch]) return -1;
cur = b[cur][ch];
if (town[cur]) {
return town[cur];
}
}
return -1;
}
int main() {
freopen("called.in", "r", stdin);
freopen("called.out", "w", stdout);
scanf("%d%d%d%d", &t, &m, &n, &d);
for (int i = 1; i <= m; ++i) {
scanf("%d%s", &super[i], regcode[i]);
// addr(buf, i);
}
for (int i = 1; i <= t; ++i) {
scanf("%d%d", ®[i], &p[i]);
if (p[i] == 0) {
add(regcode[reg[i]], i);
} else {
strcpy(buf, regcode[reg[i]]);
int ll = strlen(regcode[reg[i]]);
for (int j = 0; j < p[i]; ++j) {
scanf("%s", buf + ll);
add(buf, i);
}
}
}
scanf("%d%d", &h, &z);
for (int i = 0; i < z; ++i) {
int x;
scanf("%d", &x);
net[x] = 1;
}
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
scanf("%d", &cost[i][j]);
}
}
LL ans = 0;
scanf("%d", &cc);
for (int i = 0; i < cc; ++i) {
int from, l;
scanf("%d%s%d", &from, buf, &l);
int to = gettown(buf);
if (to == -1) continue;
ans += LL(l) * cost[type1(from)][type2(from, to)];
}
cout << ans << endl;
return 0;
}
|
#include "wrapper.h"
#include "facedetectcnn.h"
#ifdef _WIN32
# define EXPORTED __declspec(dllexport)
#else
# define EXPORTED
#endif
#define DETECT_BUFFER_SIZE 0x20000
extern "C"
{
EXPORTED Wrapper* Ctor()
{
return new Wrapper();
}
EXPORTED void Dtor(Wrapper* wrapper)
{
if (wrapper)
{
delete wrapper;
}
}
EXPORTED int Detect(Wrapper* wrapper, unsigned char* data, bool rgb2bgr, int width, int height, int step, DetectCallback callback)
{
return wrapper->Detect(data, rgb2bgr, width, height, step, callback);
}
}
Wrapper::Wrapper()
{
pBuffer = (unsigned char*)malloc(DETECT_BUFFER_SIZE);
}
Wrapper::~Wrapper()
{
free(pBuffer);
}
int Wrapper::Detect(unsigned char* data, bool rgb2bgr, int width, int height, int step, DetectCallback callback)
{
int* pResults = NULL;
if (rgb2bgr) {
// Only 24bit is supported
const int bytesPerPixel = 3;
for (int y = 0; y < height; y++)
{
unsigned char* row = data + (y * step);
for (int x = 0; x < width; x += bytesPerPixel)
{
unsigned char* pixel = row + x;
unsigned char r = pixel[0];
pixel[0] = pixel[2];
pixel[2] = r;
}
}
}
pResults = facedetect_cnn(pBuffer, data, width, height, step);
int count = (pResults ? *pResults : 0);
if (callback)
{
for (int i = 0; i < count; i++)
{
short* p = ((short*)(pResults + 1)) + 142 * i;
int confidence = p[0];
int x = p[1];
int y = p[2];
int w = p[3];
int h = p[4];
FaceDetected fd = { x, y, w, h, confidence / 100.f };
callback(&fd);
}
}
return count;
}
|
#include <iostream>
#include <map>
template <typename T>
struct console_context
{
T & Item;
};
template <typename T>
console_context<T> as_console(T & item)
{
return {item};
}
template <template <typename> typename T1, typename T2>
std::ostream & operator << (std::ostream& out, T1<T2> item)
{
out << item.Item;
return out;
}
namespace game
{
class hex
{
public:
hex(int populationId, int populationQtd)
{
population[populationId] = populationQtd;
}
void passTurn()
{
population[0] *= 2;
}
private:
std::map<int,int> population;
std::map<int,float> demands;
std::map<int,float> supplies;
friend std::ostream & operator << (std::ostream&, console_context<game::hex>);
};
std::ostream & operator << (std::ostream& out, console_context<game::hex> ctx)
{
auto hex = ctx.Item;
out << "hex" << std::endl;
out << "-----------------------" << std::endl;
for(auto x : hex.population)
{
out << x.first << ":" << x.second << std::endl;
}
out << "-----------------------" << std::endl;
return out;
}
hex make_hex()
{
return {0,2};
}
}
int main(int argc, char ** argv)
{
auto hex1 = game::make_hex();
std::cout << as_console(hex1) << std::endl;
hex1.passTurn();
std::cout << as_console(hex1) << std::endl;
return 0;
}
|
#include <cstring>
#include <iostream>
#include <cmath>
using namespace std;
class Solution {
public:
int titleToNumber(string s) {
int result = 0;
for(int index = 0; index < s.size(); index++){
result += s[index]-'A'+1;
if(index == s.size()-1){
break;
}
result *=26;
}
return result;
}
};
int main(){
string test1 = "B";
Solution *ins = new Solution();
cout<< ins->titleToNumber(test1) << endl;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2011 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "modules/opdata/src/SegmentCollector.h"
#include "modules/opdata/UniString.h" // Need UniString(const OpData& d) and IsUniCharAligned()
/* virtual */
OP_STATUS ReplaceConcatenator::AddSegment(const OpData& segment)
{
if (m_data.IsEmpty())
return AddData(segment);
else
{
RETURN_IF_ERROR(AddData(m_replacement));
m_count++;
return AddData(segment);
}
}
void ReplaceConcatenator::Done()
{
if (m_remaining_length)
{
OP_ASSERT(m_data.Length() >= m_remaining_length);
m_data.Trunc(m_data.Length() - m_remaining_length);
}
}
OP_STATUS ReplaceConcatenator::AddData(const OpData& data)
{
if (m_data.IsEmpty() && m_remaining_length)
{
OP_ASSERT(m_current_ptr == NULL);
m_current_ptr = m_data.GetAppendPtr(m_remaining_length);
RETURN_OOM_IF_NULL(m_current_ptr);
}
if (m_remaining_length)
{
OP_ASSERT(m_current_ptr);
size_t copied = data.CopyInto(m_current_ptr, m_remaining_length);
OP_ASSERT(copied <= m_remaining_length);
m_remaining_length -= copied;
if (m_remaining_length == 0)
m_current_ptr = NULL;
else
m_current_ptr += copied;
if (data.Length() > copied)
return m_data.Append(OpData(data, copied));
else
return OpStatus::OK;
}
else
return m_data.Append(data);
}
/* virtual */ OP_STATUS
CountedUniStringCollector::AddSegment(const OpData& segment)
{
OP_ASSERT(UniString::IsUniCharAligned(segment.Length()));
return m_list->Append(UniString(segment));
}
|
#pragma once
#include "GlutHeader.h"
#include "Point3.h"
class Cylinder
{
public:
Point3 tilt;
double theta; //tilt an theta is used to descripe the infomation of the cylinder's direction
Point3 center;
Point3 shape; //shape.axis[0] means the length, shape.axis[1] means the radius of the top, shape.axis[2] means the radius of base
float* colour;
Cylinder();
Cylinder(Point3, Point3, Point3, float);
~Cylinder();
void Draw();
};
|
// HumanModel.h: interface for the CHumanModel class.
//
//////////////////////////////////////////////////////////////////////
// changed
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// by gaecha
// chai3d¸¦ ¾µ¶ó°í
#include "CVector3d.h"
#include "CMatrix3d.h"
#include "CMesh.h"
#include "CWorld.h"
///////////////////////////////////////////////////////
#include "TactileArray.h"
#include "ART.h"
#if !defined(AFX_HUMANMODEL_H__E7A7CD4C_BA89_4B7C_9286_4BAECD7A7605__INCLUDED_)
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define PI 3.141592
typedef enum tagHumanPart {
CHEST = 0,
RIGHT_UPPER_ARM,
RIGHT_LOWER_ARM,
TOTAL_NUM_PART
} HumanPart;
typedef struct tagContactInfo {
// Is the proxy is collided with the human model?
bool isContacted;
// Tag for contacted part
HumanPart tagConPart;
// contact position on human model.
cVector3d contactPosH;
// contact position on tactile device. 0.0 - 1.0
// Imagine that the tactile array is flat.
cVector3d contactPosT;
} ContactInfo;
typedef struct tagHumanPartPose {
cVector3d m_pos[TOTAL_NUM_PART];
cMatrix3d m_rot[TOTAL_NUM_PART];
} HumanPartPose;
class CHumanModel
{
public:
TactileArray * m_pTactileArray;
// geometrical parameters for each part of human model
// 0 : x, 1 : y, 2 : z.
// For example, in chest 0->width, 1->height, 2-> depth
double m_partPara[TOTAL_NUM_PART][3];
double m_zTranslateErr;
ART m_ar;
char m_pattName[TOTAL_NUM_PART][100];
HumanPartPose m_partPose;
cMesh * m_pPart[TOTAL_NUM_PART];
CHumanModel();
virtual ~CHumanModel();
void SetPartPose(int a_partNum, cVector3d a_pos, cMatrix3d a_rot);
void SetPartPose(HumanPartPose a_partPose);
// proximity check
double distance[TOTAL_NUM_PART];
ContactInfo m_contactInfo;
ContactInfo proxymityCheck(cVector3d proxyPos);
void UpdatePose(unsigned char * a_pImage);
cWorld * m_pParentWorld;
void SetParentWorld(cWorld * a_pParentWorld);
void ShowAvatar(bool a_show);
};
#endif // !defined(AFX_HUMANMODEL_H__E7A7CD4C_BA89_4B7C_9286_4BAECD7A7605__INCLUDED_)
|
#include <vector>
#include <forward_list>
template <typename Key, typename Value, typename Hash = std::hash<Key>>
class HashTable {
private:
std::vector<std::forward_list<std::pair<Key, Value>>> vec;
Hash hash_function {};
public:
HashTable(const int size);
void insert(const Key&, Value&&);
Value& find(const Key&);
};
#include "HashTable.cpp"
|
#ifndef VECTOR_UTILS_H
#define VECTOR_UTILS_H
// Declaration of a name space in which several useful std::vector related functions are defined
// R. Sheehan 7 - 12 - 2018
namespace vecut {
std::vector<double> get_row(std::vector<std::vector<double>> &data, int r_num);
std::vector<double> get_col(std::vector<std::vector<double>> &data, int c_num);
void read_into_vector(std::string &filename, std::vector<double> &data, int &n_pts, bool loud = false);
void write_into_file(std::string &filename, std::vector<double> &data, bool loud = false);
void read_into_matrix(std::string &filename, std::vector<std::vector<double>> &data, int &n_rows, int &n_cols, bool loud = false);
}
#endif
|
// Spring 2018
//
// Description: This file implements a function 'run_custom_tests' that should be able to use
// the configuration information to drive tests that evaluate the correctness
// and performance of the map_t object.
#include <iostream>
#include <ctime>
#include <stdlib.h>
#include <thread>
#include "config_t.h"
#include "tests.h"
#include <mutex>
#include <chrono>
#include "simplemapFG.h"
//#include "simplemap.h"
void printer(int k, float v) {
std::cout<<"<"<<k<<","<<v<<">"<< std::endl;
}
std::mutex locks[ACCNTS]; //FG
std::mutex mtx; //CG
// Step 1
// Define a simplemap_t of types <int,float>
// this map represents a collection of bank accounts:
// each account has a unique ID of type int;
// each account has an amount of fund of type float.
simplemap_t<int,float> map = simplemap_t<int,float>(); // map for bank accounts
void release2Locks(int index1, int index2) {
locks[index1].unlock();
locks[index2].unlock();
}
void acquire2Locks(int index1, int index2){
while(true){
while(!locks[index1].try_lock());
//lock acquired
//std::cout << "LOCK 1 ACQUIRED" << std::endl;
if(locks[index2].try_lock()) {
//lock 2 acquired
break;
}else{
locks[index1].unlock();
//lock 1 released
continue;
}
}
}
void releaseHelper(int i){
for(i;i>=0;i--){
locks[i].unlock();
}
}
void acquireAll(){
int i = 0;
while(i < ACCNTS && i >=0) {
if(locks[i].try_lock()){
//lock acquired
i++;
if(locks[i].try_lock()){
//next lock acquired
}else{
releaseHelper(i);
}
}else{
releaseHelper(i);
}
}
}
void releaseAll(){
for(int i = 0; i < ACCNTS; i++){
locks[i].unlock();
}
}
//void releaseLocks(std::vector<m_lock> locks, int index) {}
// Step 3
// Define a function "deposit" that selects two random bank accounts
// and an amount. This amount is subtracted from the amount
// of the first account and summed to the amount of the second
// account. In practice, give two accounts B1 and B2, and a value V,
// the function performs B1-=V and B2+=V.
void deposit(float val) {
//CG Lock
//mtx.lock();
int rando = (int) ACCNTS;
int r1 = rand() % rando;
int r2 = rand() % rando;
while(r1 == r2){
r2 = rand() % rando; //ensure bank accounts are not the same
}
//std::cout << "acquiring" << std::endl;
//FG LOCK
acquire2Locks(r1, r2);
std::pair<float, bool> B1 = map.lookup(r1);
std::pair<float, bool> B2 = map.lookup(r2);
float newVal1 = B1.first;
float newVal2 = B2.first;
newVal1 -= val;
newVal2 += val;
map.update(r1, newVal1);
map.update(r2, newVal2);
//FG LOCK
release2Locks(r1, r2);
//CG Lock
//mtx.unlock();
}
// Step 4
// Define a function "balance" that sums the amount of all the
// bank accounts in the map.
float balance() {
//CG Lock
//mtx.lock();
//FG LOCK
acquireAll();
float total = 0;
for(int i = 0; i < ACCNTS; i++) {
std::pair<float, bool> foo = map.lookup(i);
total += std::get<0>(foo);
}
//FG LOCK
releaseAll();
//std::cout << "total is " << total << "\n" << std::endl;
//CG Lock
//mtx.unlock();
return total;
}
// Step 5
// Define a function 'do_work', which has a for-loop that
// iterates for config_t.iters times. Each iteration, the function should
// call the function 'deposit' with 80% of the probability;
// otherwise (the rest 20%) the function 'balance' should be called.
// The function 'do_work' should measure 'exec_time_i', which is the
// time needed to perform the entire for-loop.
// The main thread should be able to access this amount of time once the
// thread executing the 'do_work' joins its execution with the main thread.
void do_work(int x) {
float val = 0;
int doBal = (int)(x*(0.2));
for(int i = 0; i < x; i++) {
val = 20;
if(i % doBal == 0) {
balance();
}else{
deposit(val);
}
}
}
void run_custom_tests(config_t& cfg) {
// Step 2
// Populate the entire map with the 'insert' function
// Initialize the map in a way the sum of the amounts of
// all the accounts in the map is 1000
float cash = (float)TOTAL/ACCNTS;
for(int i = 0; i < ACCNTS; i++) {
map.insert(i, cash);
}
// Step 6
// The evaluation should be performed in the following way:
// - the main thread creates one thread
// << use std:threds >>
// - the spawned thread executes the function 'do_work' until completion
// - the (main) thread waits for the spawned thread to be executed
// << use std::thread::join() >>
// and collects the 'exec_time_i' from the spawned thread
// - once the spawned thread has joined, the function "balance" must be called
auto start = std::chrono::high_resolution_clock::now();
std::thread t[MAXTHREADS];
for (int i = 0; i < MAXTHREADS; i++) {
t[i] = std::thread(do_work, cfg.iters);
}
std::cout << "Launched from the main\n";
//Join the threads with the main thread
for (int i = 0; i < MAXTHREADS; ++i) {
t[i].join();
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = end-start;
std::cout << diff.count() << " s\n";
std::cout << "total is " << balance() << std::endl;
// Step 7
// Remove all the items in the map by leveraging the 'remove' function of the map
// Execution terminates.
// If you reach this stage happy, then you did a good job!
for(int i = 0; i < ACCNTS; i++) {
map.remove(i);
}
// You might need the following function to print the entire map.
// Attention if you use it while multiple threads are operating
map.apply(printer);
}
void test_driver(config_t &cfg) {
run_custom_tests(cfg);
}
|
#include "game.h"
#include "QLayout"
Game::Game(QWidget* parent, int total_processes, int priority_low, int priority_high, QString username, int gamemode, int lv): QGraphicsView()
{
//set parameters for the game
Q_UNUSED(parent)
GAMEMODE = gamemode;
LV = lv;
user_name = username;
if(GAMEMODE==0)
totalProcesses = 999;
else
totalProcesses = total_processes;
prior_low = priority_low;
prior_high = priority_high;
//set scene;
scene = new QGraphicsScene(this);
scene->setSceneRect(0,0,1400,700);
setScene(scene);
//set cursor;
cursor = new QGraphicsRectItem();
cursor->setRect(0,0,100,100);
cursor->setBrush(Qt::blue);
scene->addItem(cursor);
cursor->hide();
setMouseTracking(true);
dragging = false;
dragging_process = nullptr;
slot_the_process_is_going_to = nullptr;
slot_the_process_is_coming_from = nullptr;
//set window
setFixedSize(1400,700);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
//making the core(player)
p1 = new CpuCore(this,1);
p1->blocker->setZValue(10);
p1->setZValue(1);
scene->addItem(p1);
scene->addItem(p1->slot1);
scene->addItem(p1->slot2);
scene->addItem(p1->slot3);
scene->addItem(p1->slot4);
p1->slot1->setPos(605,345);
p1->slot2->setPos(710,345);
p1->slot3->setPos(605,450);
p1->slot4->setPos(710,450);
p1->setPos(600,340);
//monitor
monitor = new displayScreen();
monitor->setPos(QPointF(150,350));
scene->addItem(monitor);
//create queues
InterruptedQueue = new ProcessQueue(this);
InterruptedQueue->label->setPlainText("Interrupted processes");
scene->addItem(InterruptedQueue);
InterruptedQueue->setPos(QPointF(x()+95,y()+75));
waitingQueue = new ProcessQueue(this);
connect(waitingQueue, &ProcessQueue::populate_queue, this, &Game::fill_waiting_queue);
waitingQueue->label->setPlainText("Waiting");
scene->addItem(waitingQueue);
waitingQueue->setPos(QPointF(95,235));
fill_waiting_queue();
//add the pause button
pause = new PauseButton(this);
scene->addItem(pause);
pause->setZValue(10);
//add area for interruptProcess
interruptArea = new InterruptProcess(this);
interruptArea->setPos(850,350);
scene->addItem(interruptArea);
//add area for finishProcess
finishArea = new FinishProcess(this);
finishArea->setPos(850,450);
scene->addItem(finishArea);
//add the HP bar
hp_count=200;
hp_bar = new QGraphicsRectItem();
hp_bar->setRect(0,0,hp_count,20);
hp_bar->setBrush(Qt::green);
hp_bar->setPos(450,30);
scene->addItem(hp_bar);
hp_bar_border = new QGraphicsRectItem(0,0,204,24);
hp_bar_border->setPos(448,28);
hp_bar->setPen(Qt::PenStyle::SolidLine);
scene->addItem(hp_bar_border);
//set data for scoreBoard
gameTime = new QTimer(this);
gameTime->setInterval(1000);
connect(gameTime, &QTimer::timeout, this, &Game::set_time);
gameTime->start();
}
void Game::mouseMoveEvent(QMouseEvent *event){
//makes the cursor moves
if (cursor)
cursor->setPos(event->pos());
}
void Game::interruptProcess(Process *p, ProcessSlot* slot_the_process_is_coming_from)
{
p->is_running = false;
p->is_waiting = false;
p->is_interrupted = true;
p->change_status_txt();
p->run_timer->stop();
disconnect(p->execute_actions, &QTimer::timeout, p, &Process::action);
p->setBrush(Qt::yellow);
p->neccessary_actions->setDefaultTextColor(Qt::blue);
p->process_id->setDefaultTextColor(Qt::blue);
p->process_state->setDefaultTextColor(Qt::blue);
if(slot_the_process_is_coming_from == p1->slot1)
p->emit slotIsFree(1);
else if(slot_the_process_is_coming_from == p1->slot2)
p->emit slotIsFree(2);
else if(slot_the_process_is_coming_from == p1->slot3)
p->emit slotIsFree(3);
else if(slot_the_process_is_coming_from == p1->slot4)
p->emit slotIsFree(4);
p->emit notify_process_interrupted(p->ID);
InterruptedQueue->Add(p);
}
int Game::countProcesses()
{
int count=0;
count+=waitingQueue->size;
count+=InterruptedQueue->size;
if(p1->slot1Occupied)
count++;
if(p1->slot2Occupied)
count++;
if(p1->slot3Occupied)
count++;
if(p1->slot4Occupied)
count++;
if(count==0)
{
game_over();
}
return count;
}
void Game::set_time()
{
time_count++;
}
void Game::fill_waiting_queue()
{
for(int i=waitingQueue->Size() ;i<13; i++)
{
int priority = QRandomGenerator::global()->bounded(prior_low,prior_high);
int actions = QRandomGenerator::global()->bounded(15,30);
int id = QRandomGenerator::global()->bounded(0,99);
Process* p = new Process(waitingQueue, priority, id, actions);
scene->addItem(p);
p->setZValue(2);
connect(p, &Process::gameOver, this, &Game::game_over);
connect(p, &Process::starved, waitingQueue, &ProcessQueue::remove_process);
connect(p, &Process::slotIsOccupied, p1, &CpuCore::slotIsOccupied);
connect(p, &Process::slotIsFree, p1, &CpuCore::slotIsFree);
connect(p, &Process::process_was_terminated, p1, &CpuCore::process_was_terminated);
connect(p, &Process::process_starved, p1, &CpuCore::process_starved);
connect(p, &Process::notify_process_interrupted, monitor, &displayScreen::notify_process_interrupted);
connect(p, &Process::notify_process_execution, monitor, &displayScreen::notify_process_execution);
connect(p, &Process::notify_process_needs_io, monitor, &displayScreen::notify_process_needs_io);
connect(p, &Process::notify_io_ready, monitor, &displayScreen::notify_io_ready);
connect(p->execute_actions, &QTimer::timeout, p, &Process::action);
p->wait_timer->start();
waitingQueue->Add(p);
}
}
void Game::game_over()
{
qInfo() << "losed: " << losed;
qInfo() << time_count;
score_board = nullptr;
score_board = new ScoreBoard(this,finished_processes,starved_processes,hp_count,time_count,p1->scoreCount, LV);
score_board->setZValue(10);
pause->stop_start_allTimers();
qInfo() << "GAME FINISHED!";
gameTime->stop();
scene->addItem(score_board);
scene->addWidget(score_board->back_to_menu);
score_board->setPos(420,200);
score_board->back_to_menu->move(420,600);
int totalScore = score_board->getScore();
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL","conn");
db.setHostName("localhost");
db.setDatabaseName("ProjetoIntegrador");
db.setUserName("root");
db.setPassword("M4a10121");
bool ok = db.open();
if(!ok)
{
QMessageBox::warning(this, "connection", "can not open connection!");
}
else
{
QSqlQuery q(db);
QString update;
if(GAMEMODE==1)
{
switch (LV) {
case 1: update = QString("UPDATE users set played_campaign = played_campaign+1 WHERE login = '%1';"
"UPDATE max_score SET maxScore_Lv1 = CASE WHEN maxScore_Lv1 < %2 THEN %2 ELSE maxScore_Lv1 END WHERE username = '%1';").arg(user_name).arg(totalScore);break;
case 2: update = QString("UPDATE users set played_campaign = played_campaign+1 WHERE login = '%1';"
"UPDATE max_score SET maxScore_Lv2 = CASE WHEN maxScore_Lv2 < %2 THEN %2 ELSE maxScore_Lv2 END WHERE username = '%1';").arg(user_name).arg(totalScore); break;
case 3: update = QString("UPDATE users set played_campaign = played_campaign+1 WHERE login = '%1';"
"UPDATE max_score SET maxScore_Lv3 = CASE WHEN maxScore_Lv3 < %2 THEN %2 ELSE maxScore_Lv3 END WHERE username = '%1';").arg(user_name).arg(totalScore); break;
case 4: update = QString("UPDATE users set played_campaign = played_campaign+1 WHERE login = '%1';"
"UPDATE max_score SET maxScore_Lv4 = CASE WHEN maxScore_Lv4 < %2 THEN %2 ELSE maxScore_Lv4 END WHERE username = '%1';").arg(user_name).arg(totalScore); break;
case 5: update = QString("UPDATE users set played_campaign = played_campaign+1 WHERE login = '%1';"
"UPDATE max_score SET maxScore_Lv5 = CASE WHEN maxScore_Lv5 < %2 THEN %2 ELSE maxScore_Lv5 END WHERE username = '%1';").arg(user_name).arg(totalScore); break;
case 6: update = QString("UPDATE users set played_campaign = played_campaign+1 WHERE login = '%1';"
"UPDATE max_score SET maxScore_Lv6 = CASE WHEN maxScore_Lv6 < %2 THEN %2 ELSE maxScore_Lv6 END WHERE username = '%1';").arg(user_name).arg(totalScore); break;
case 7: update = QString("UPDATE users set played_campaign = played_campaign+1 WHERE login = '%1';"
"UPDATE max_score SET maxScore_Lv7 = CASE WHEN maxScore_Lv7 < %2 THEN %2 ELSE maxScore_Lv7 END WHERE username = '%1';").arg(user_name).arg(totalScore); break;
case 8: update = QString("UPDATE users set played_campaign = played_campaign+1 WHERE login = '%1';"
"UPDATE max_score SET maxScore_Lv8 = CASE WHEN maxScore_Lv8 < %2 THEN %2 ELSE maxScore_Lv8 END WHERE username = '%1';").arg(user_name).arg(totalScore); break;
}
}
else
update = QString("UPDATE users SET played_survival = played_survival+1 WHERE login = '%1';"
"UPDATE max_score SET maxScore_survival = CASE WHEN maxScore_survival < %2 THEN %2 ELSE maxScore_survival END WHERE username = '%1';").arg(user_name).arg(totalScore);
q.prepare(update);
if(q.exec())
{
if(losed==true)
{
switch (LV) {
case 1: update = QString("UPDATE losed SET loseLv1 = loseLv1+1 WHERE username = '%1';").arg(user_name); break;
case 2: update = QString("UPDATE losed SET loseLv2 = loseLv2+1 WHERE username = '%1';").arg(user_name); break;
case 3: update = QString("UPDATE losed SET loseLv3 = loseLv3+1 WHERE username = '%1';").arg(user_name); break;
case 4: update = QString("UPDATE losed SET loseLv4 = loseLv4+1 WHERE username = '%1';").arg(user_name); break;
case 5: update = QString("UPDATE losed SET loseLv5 = loseLv5+1 WHERE username = '%1';").arg(user_name); break;
case 6: update = QString("UPDATE losed SET loseLv6 = loseLv6+1 WHERE username = '%1';").arg(user_name); break;
case 7: update = QString("UPDATE losed SET loseLv7 = loseLv7+1 WHERE username = '%1';").arg(user_name); break;
case 8: update = QString("UPDATE losed SET loseLv8 = loseLv8+1 WHERE username = '%1';").arg(user_name); break;
}
}
else
{
switch (LV) {
case 1: update = QString("UPDATE users SET Lv1_Clear = '1' WHERE login = '%1';").arg(user_name); break;
case 2: update = QString("UPDATE users SET Lv2_Clear = '1' WHERE login = '%1';").arg(user_name); break;
case 3: update = QString("UPDATE users SET Lv3_Clear = '1' WHERE login = '%1';").arg(user_name); break;
case 4: update = QString("UPDATE users SET Lv4_Clear = '1' WHERE login = '%1';").arg(user_name); break;
case 5: update = QString("UPDATE users SET Lv5_Clear = '1' WHERE login = '%1';").arg(user_name); break;
case 6: update = QString("UPDATE users SET Lv6_Clear = '1' WHERE login = '%1';").arg(user_name); break;
case 7: update = QString("UPDATE users SET Lv7_Clear = '1' WHERE login = '%1';").arg(user_name); break;
case 8: update = QString("UPDATE users SET Lv8_Clear = '1' WHERE login = '%1';").arg(user_name); break;
}
}
if(q.exec(update))
db.commit();
else
{
QMessageBox warning;
warning.setText("queue failed!" "could not update data");
warning.exec();
}
db.commit();
emit update_userData();
}
else
{
QMessageBox warning;
warning.setText("queue failed!" "could not update data");
warning.exec();
}
}
db.close();
}
void Game::mousePressEvent(QMouseEvent *event){
/*select a process from somewhere and place it in somewhere else following the cases:
*
* 1* if process is inside the waiting queue , the process must go to a slot in the second click and start execute
*
* 2* if process is inside a slot:
* * process can be interrupted during execution
* * process can be placed back in the waiting queue
* * process can be finished(but player only gets score if it's finished)
*
* 3* if process is inside the ready queue and is INTERRUPTED, it can go back to a slot and continue be execued
*
*/
if(dragging)// 2nd click (RELEASE AND RESET)
{
if(found_in_waiting||found_in_interrupted) // go to a slot
{
if(p1->slot1->contains(p1->slot1->mapFromScene(event->pos())))
{
if(!p1->slot1Occupied)
{
p1->slot1->process = dragging_process;
slot_the_process_is_going_to = p1->slot1;
dragging_process->emit slotIsOccupied(1);
qInfo() << " you placed the process in the slot 1";
}
else
{
pause->stop_start_allTimers();
QMessageBox warning;
warning.setText("this slot is occupied!");
warning.exec();
if(warning.Close)
pause->stop_start_allTimers();
dragging=false;
dragging_process->show();
cursor->hide();
dragging_process=nullptr;
}
}
if(p1->slot2->contains(p1->slot2->mapFromScene(event->pos())))
{
if(!p1->slot2Occupied)
{
p1->slot2->process = dragging_process;
slot_the_process_is_going_to = p1->slot2;
dragging_process->emit slotIsOccupied(2);
qInfo() << " you placed the process in the slot 2";
}
else
{
pause->stop_start_allTimers();
QMessageBox warning;
warning.setText("this slot is occupied!");
warning.exec();
if(warning.Close)
pause->stop_start_allTimers();
dragging=false;
dragging_process->show();
cursor->hide();
dragging_process=nullptr;
}
}
if(p1->slot3->contains(p1->slot3->mapFromScene(event->pos())))
{
if(!p1->slot3Occupied)
{
p1->slot3->process = dragging_process;
slot_the_process_is_going_to = p1->slot3;
dragging_process->emit slotIsOccupied(3);
qInfo() << " you placed the process in the slot 3";
}
else
{
pause->stop_start_allTimers();
QMessageBox warning;
warning.setText("this slot is occupied!");
warning.exec();
if(warning.Close)
pause->stop_start_allTimers();
dragging=false;
dragging_process->show();
cursor->hide();
dragging_process=nullptr;
}
}
if(p1->slot4->contains(p1->slot4->mapFromScene(event->pos())))
{
if(!p1->slot4Occupied)
{
p1->slot4->process = dragging_process;
slot_the_process_is_going_to = p1->slot4;
dragging_process->emit slotIsOccupied(4);
qInfo() << " you placed the process in the slot 4";
}
else
{
pause->stop_start_allTimers();
QMessageBox warning;
warning.setText("this slot is occupied!");
warning.exec();
if(warning.Close)
pause->stop_start_allTimers();
dragging=false;
dragging_process->show();
cursor->hide();
dragging_process=nullptr;
}
}
//if process is going to a slot, then start execution
if(slot_the_process_is_going_to)
{
//run process
dragging_process->is_waiting = false;
dragging_process->is_running = true;
dragging_process->change_status_txt();
dragging_process->setPos(slot_the_process_is_going_to->x()+100, slot_the_process_is_going_to->y()+5);///
if(found_in_waiting)
{
waitingQueue->Remov(dragging_process);
slot_the_process_is_going_to = nullptr;
}
else if(found_in_interrupted)// if this process is interrupted, then run it again from where it stopped!
{
dragging_process->is_interrupted=false;
dragging_process->is_running = true;
dragging_process->is_waiting=false;
dragging_process->change_status_txt();
dragging_process->setBrush(Qt::blue);
dragging_process->neccessary_actions->setDefaultTextColor(Qt::yellow);
dragging_process->process_id->setDefaultTextColor(Qt::yellow);
dragging_process->process_state->setDefaultTextColor(Qt::yellow);
dragging_process->run_timer->start();
connect(dragging_process->execute_actions, &QTimer::timeout, dragging_process, &Process::action);
Process *p = InterruptedQueue->Remov(dragging_process);
}
}
else
{
QGraphicsView::mousePressEvent(event);
}
if(dragging_process)
{
dragging_process->show();
dragging_process = nullptr;
}
}
else if(foundInSlot)
{
//player clicked waiting queue
if(waitingQueue->bounding_rect->contains(waitingQueue->bounding_rect->mapFromScene(event->pos())))
{
//add to waiting queue
dragging_process->is_waiting = true;
dragging_process->is_running = false;
dragging_process->change_status_txt();
waitingQueue->Add(dragging_process);
//free slot
if(slot_the_process_is_coming_from == p1->slot1)
dragging_process->emit slotIsFree(1);
else if(slot_the_process_is_coming_from == p1->slot2)
dragging_process->emit slotIsFree(2);
else if(slot_the_process_is_coming_from == p1->slot3)
dragging_process->emit slotIsFree(3);
else if(slot_the_process_is_coming_from == p1->slot4)
dragging_process->emit slotIsFree(4);
slot_the_process_is_coming_from->process = nullptr;
dragging_process->show();
//reset
dragging_process = nullptr;
}
else if(interruptArea->contains(interruptArea->mapFromScene(event->pos())))// interrupt process
{
//interrupt this process
interruptProcess(dragging_process , slot_the_process_is_coming_from);
slot_the_process_is_coming_from->process = nullptr;
dragging_process->show();
dragging_process = nullptr;
}
else if(finishArea->contains(finishArea->mapFromScene(event->pos())))// finish process
{
if(dragging_process->finished)
{
//finish this process
if(slot_the_process_is_coming_from == p1->slot1)
dragging_process->emit slotIsFree(1);
else if(slot_the_process_is_coming_from == p1->slot2)
dragging_process->emit slotIsFree(2);
else if(slot_the_process_is_coming_from == p1->slot3)
dragging_process->emit slotIsFree(3);
else if(slot_the_process_is_coming_from == p1->slot4)
dragging_process->emit slotIsFree(4);
slot_the_process_is_coming_from->process = nullptr;
scene->removeItem(dragging_process);
dragging_process = nullptr;
p1->scoreCount+=5;
qInfo() << "SCORE: " << p1->scoreCount;
p1->Pscore->setPlainText(QString("Score: %1").arg(p1->scoreCount));
totalProcesses--;
finished_processes++;
countProcesses();
}
else
{
pause->stop_start_allTimers();
QMessageBox warning;
warning.setText("this process have not finished yet!");
warning.exec();
if(warning.Close)
pause->stop_start_allTimers();
dragging=false;
dragging_process->show();
cursor->hide();
dragging_process=nullptr;
}
}
else
{
QGraphicsView::mousePressEvent(event);
dragging_process->show();
dragging_process = nullptr;
}
}
dragging = false;
foundInSlot=false;
found_in_waiting=false;
found_in_interrupted=false;
cursor->hide();
}
else// 1st click (SELECT AND DRAG)
{
//look for the clicked process in the waiting queue
Node* n;
for(n = waitingQueue->front; n!= NULL; n=n->next)
{
if(n->process->contains(n->process->mapFromScene(event->pos())))
{
//found
dragging_process = n->process;
found_in_waiting = true;
}
}//<-is not waiting
//look for the clicked process in the interrupted queue
if(!found_in_waiting)
{
Node* n;
for(n=InterruptedQueue->front; n != NULL; n=n->next)
{
if(n->process->contains(n->process->mapFromScene(event->pos())))
{
if(!n->process->needs_io)
{
dragging_process = n->process;
found_in_interrupted=true;
}
else
{
QMessageBox warning;
warning.setText("this process is waiting for a i/o event!");
pause->stop_start_allTimers();
warning.exec();
if(warning.close())
pause->stop_start_allTimers();
}
}
}
}//is not interrupted
//look in the slots
if(!found_in_interrupted && !found_in_waiting)
{
if(p1->slot1Occupied)
{
if(p1->slot1->process->contains(p1->slot1->process->mapFromScene(event->pos())))
{
//found
qInfo() << "you selected the process from the slot 1";
dragging_process = p1->slot1->process;
foundInSlot = true;
slot_the_process_is_coming_from = p1->slot1;
}//is not in the slot1
}
if(p1->slot2Occupied)
{
if(p1->slot2->process->contains(p1->slot2->process->mapFromScene(event->pos())))
{
//found
qInfo() << "you selected the process from the slot 2";
dragging_process = p1->slot2->process;
foundInSlot = true;
slot_the_process_is_coming_from = p1->slot2;
}//is not in the slot2
}
if(p1->slot3Occupied)
{
if(p1->slot3->process->contains(p1->slot3->process->mapFromScene(event->pos())))
{
//found
qInfo() << "you selected the process from the slot 3";
dragging_process = p1->slot3->process;
foundInSlot = true;
slot_the_process_is_coming_from = p1->slot3;
}//is not in the slot 3
}
if(p1->slot4Occupied)
{
if(p1->slot4->process->contains(p1->slot4->process->mapFromScene(event->pos())))
{
//found
qInfo() << "you selected the process from the slot 4";
dragging_process = p1->slot4->process;
foundInSlot = true;
slot_the_process_is_coming_from = p1->slot4;
}//is not in slot 4
}
}//player have not clicked in a process.
//if player selected a process
if(foundInSlot||found_in_waiting||found_in_interrupted)
{
dragging = true;
cursor->show();
dragging_process->hide();
}
else//pass the event down if no process was clicked
{
QGraphicsView::mousePressEvent(event);
}
}
}
|
#pragma once
#include "../../structs/Transform.h"
#include "PhysicsTransform.h"
#include "../CollisionShapes.h"
#include "../../structs/MeshTransform.h"
namespace Game
{
class PhysicsObject
{
public:
// virtual void setTransform(PhysicsTransform& transform) = 0;
virtual void setShape(CollisionShapes shape) = 0;
virtual void setMass(float mass) = 0;
virtual void setMesh(MeshTransform* meshTransform) = 0;
virtual PhysicsTransform& transform() = 0;
};
}
|
#include "articulocontroller.h"
#include "articuloviewer.h"
#include "articulodao.h"
ArticuloController::ArticuloController()
{
//ctor
}
ArticuloController::~ArticuloController()
{
//dtor
}
void ArticuloController::abm()
{
ArticuloViewer* av = new ArticuloViewer();
bool salir = false;
while (!salir)
{
switch (av->menu())
{
case 1:
listar();
break;
case 2:
buscar();
break;
case 3:
agregar();
break;
case 4:
modificar();
break;
case 5:
eliminar();
break;
case 6:
salir = true;
break;
}
}
}
void ArticuloController::listar()
{
(new ArticuloViewer())->listar((new ArticuloDAO())->collection());
}
void ArticuloController::buscar()
{
ArticuloViewer* av = new ArticuloViewer();
av->mostrar((new ArticuloDAO())->find(av->buscar()));
}
void ArticuloController::agregar()
{
Articulo* ar = new Articulo();
(new ArticuloViewer())->cargar(ar, "Agregar ARTICULO");
(new ArticuloDAO())->add(ar);
}
void ArticuloController::modificar()
{
Articulo* ar = new Articulo();
ArticuloViewer* av = new ArticuloViewer();
av->mostrar(ar = (new ArticuloDAO())->find(av->buscar()));
(new ArticuloViewer())->cargar(ar, "Modificar ARTICULO");
(new ArticuloDAO())->update(ar);
}
void ArticuloController::eliminar()
{
Articulo* ar = new Articulo();
ArticuloViewer* av = new ArticuloViewer();
av->mensaje("Eliminar ARTICULO");
av->mostrar(ar = (new ArticuloDAO())->find(av->buscar()));
(new ArticuloDAO())->del(ar);
}
|
#include "../src/graphic/window.h"
#include "../src/graphic/renderer/batch2Drenderer.h"
#include "../src/graphic/layers/group.h"
#include "../src/graphic/layers/layer.h"
#include "../src/graphic/renderable/sprite.h"
#include "../src/gui/label.h"
#include "../src/font/fontmanager.h"
#include "../src/audio/soundmanager.h"
#include "../src/math/maths.h"
#include "../src/utils/colors.h"
#include <time.h>
#include <thread>
int main() {
using namespace sge;
using namespace graphics;
using namespace audio;
using namespace math;
Window window("SGE", 960, 540);
glClearColor(0.0f,0.0f,0.0f,1.0f);
Shader *shader = new Shader("src/shaders/basic.vert", "src/shaders/basic.frag");
Layer layer(new Batch2DRenderer(), shader , math::mat4::orthographic(0.0f, 16.0f, 0.0f, 9.0f, -1.0f, 1.0f));
Texture *textures[] = {
new Texture("resources/images/teste3.jpeg"),
new Texture("resources/images/teste3.jpeg"),
new Texture("resources/images/teste3.jpeg")
};
for(float y=0.0f; y<9.0f; y+=0.5f){
for(float x=0.0f; x<16.0f; x+=0.5f){
layer.add(new Sprite(x,y,0.48f,0.48f,BLUE_70));
}
}
FontManager::add(new Font("SourceSansPro", "resources/fonts/SourceSansPro-Light.ttf", 32));
FontManager::add(new Font("LuckiestGuy", "resources/fonts/LuckiestGuy.ttf", 48));
FontManager::get("SourceSansPro")->setScale(window.getWidth()/16.0f, window.getHeight()/9.0f);
FontManager::get("LuckiestGuy")->setScale(window.getWidth()/16.0f, window.getHeight()/9.0f);
SoundManager::add(new Sound("test","resources/audios/test.ogg"));
float gain = 0.5f;
//SoundManager::get("test")->setGain(gain);
Group *g = new Group(math::mat4::translate(math::vec3(0.0f, 7.5f, 0.0f)));
Label *fps = new Label("fps", 0.5f, 0.5f, FontManager::get("SourceSansPro"), WHITE);
g->add(new Sprite(0.2f, 0.2f, 2.2f, 0.95f, BLUE_GREY_40));
g->add(fps);
Group *g2 = new Group(math::mat4::translate(math::vec3(5, 4.5, 0.0f)));
g2->add(new Sprite(0, 0, 5.5f, 0.95f, BLUE_GREY_80));
g2->add(new Label("Hello World!", 0.2f, 0.2f, FontManager::get("LuckiestGuy"), AMBER));
layer.add(g);
layer.add(g2);
while(!window.closed()){
window.clear();
double x, y;
window.getMousePosition(x,y);
shader->enable();
shader->setUniform2f("light_pos", math::vec2((float)(x*16.0f/window.getWidth()), (float)(9.0f-y*9.0f/window.getHeight())));
fps->text = "fps";
layer.render();
if(window.isKeyTyped(GLFW_KEY_P)){
SoundManager::get("test")->play(false);
}else if(window.isKeyTyped(GLFW_KEY_S)){
SoundManager::get("test")->stop();
}else if(window.isKeyTyped(GLFW_KEY_U)){
SoundManager::get("test")->pause();
}else if(window.isKeyTyped(GLFW_KEY_W)){
gain += 0.1f;
SoundManager::get("test")->setGain(gain);
std::cout << "Volume: " << gain << std::endl;
}else if(window.isKeyTyped(GLFW_KEY_Q)){
gain -= 0.1f;
SoundManager::get("test")->setGain(gain);
std::cout << "Volume: " << gain << std::endl;
}
window.update();
}
return 0;
}
|
//: C03:Global.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
//{L} Global2
// Demonstracja zmiennych globalnych
#include <iostream>
using namespace std;
int globe;
void func();
int main() {
globe = 12;
cout << globe << endl;
func(); // Modyfikuje zmienna globe
cout << globe << endl;
} ///:~
|
#ifndef PATHFINDRULE_JPS_PLUS_DYNAMIC_H
#define PATHFINDRULE_JPS_PLUS_DYNAMIC_H
namespace JPS
{
namespace Rule
{
// 길찾기 룰 (JPS+ 다이나믹 맵=변경 될수 있는 맵)
// grid 의 정보가 변경될수 있을때 사용한다.
// 기본적으로 4방향 직선 포인트만 전처리를 사용하고 대각선 방향을 전처리를 하지 않는다.
// - 맵이 변경될 경우 너무 많은 대각선 방향의 포인트를 전처리 해야하므로 부하가 생긴다.
// - 대각선 포인트 Jump 시에 직선 전처리를 사용해서 jump를 하도록 해야한다.
// - 맵이 변경된 경우 전처리된 정보를 변경된 grid point +3,+3 만큼 충돌체가 없는 범위까지 테이블은 초기화 해야한다.
template <typename GRID, bool PRECOMPUTE>
class PathFindRule_JPSPlusDynamic : public PathFindRule_JPS<GRID>
{
const int JUMP_DIR = 4;
const int m_Height; // 맵의 높이
const int m_Width; // 맵의 넓이
Position* m_PreComputeTable; // 전처리 맵
public:
PathFindRule_JPSPlusDynamic(const GRID& g);
~PathFindRule_JPSPlusDynamic();
void ChangedGrid(Position Start, Position End);
protected:
void InitMap();
void PrecomputeMap();
virtual Position JumpD(Position p, int dx, int dy, const Position& EndPos);
virtual Position JumpX(Position p, int dx, const Position& EndPos);
virtual Position JumpY(Position p, int dy, const Position& EndPos);
bool HasPreComputeJumpPoint(const Position& p, int dx, int dy) const;
Position GetPreComputeJumpPoint(const Position& p, int dx, int dy) const;
void SetPreComputeJumpPoint(const Position& p, int dx, int dy, const Position& JumpPos);
void ClearPreComputeJumpPoint(const Position& p);
};
///////////////////////////////////////////////////////////////////////////////
// ctor
///////////////////////////////////////////////////////////////////////////////
template <typename GRID, bool PRECOMPUTE>
PathFindRule_JPSPlusDynamic<GRID, PRECOMPUTE>::PathFindRule_JPSPlusDynamic(const GRID& g)
: PathFindRule_JPS(g), m_Height(g.GetHeight()), m_Width(g.GetWidth())
{
InitMap();
if (PRECOMPUTE)
{
PrecomputeMap();
}
}
///////////////////////////////////////////////////////////////////////////////
// dtor
///////////////////////////////////////////////////////////////////////////////
template <typename GRID, bool PRECOMPUTE>
PathFindRule_JPSPlusDynamic<GRID, PRECOMPUTE>::~PathFindRule_JPSPlusDynamic()
{
delete[] m_PreComputeTable;
}
///////////////////////////////////////////////////////////////////////////////
// 초기화(맵)
///////////////////////////////////////////////////////////////////////////////
template <typename GRID, bool PRECOMPUTE>
void PathFindRule_JPSPlusDynamic<GRID, PRECOMPUTE>::InitMap()
{
m_PreComputeTable = new Position[m_Height*m_Width*JUMP_DIR];
for (int h = 0; h < m_Height; ++h) {
for (int w = 0; w < m_Width; ++w) {
for (int k = 0; k < JUMP_DIR; ++k) {
m_PreComputeTable[h*m_Width*JUMP_DIR + w * JUMP_DIR + k].x = 0;
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
// 전처리(맵)
///////////////////////////////////////////////////////////////////////////////
template <typename GRID, bool PRECOMPUTE>
void PathFindRule_JPSPlusDynamic<GRID, PRECOMPUTE>::PrecomputeMap()
{
bool End = false;
// 직선 먼저 테이블을 만든다.
for (int y = 0; y < m_Height; ++y) {
for (int x = 0; x < m_Width; ++x) {
if (m_Grid(x, y))
{
m_PreComputeTable[y * m_Width * JUMP_DIR + x * JUMP_DIR + 0] = ComputeJumpX(Position(x, y), 1, JPS::npos, End);
m_PreComputeTable[y * m_Width * JUMP_DIR + x * JUMP_DIR + 1] = ComputeJumpX(Position(x, y), -1, JPS::npos, End);
m_PreComputeTable[y * m_Width * JUMP_DIR + x * JUMP_DIR + 2] = ComputeJumpY(Position(x, y), 1, JPS::npos, End);
m_PreComputeTable[y * m_Width * JUMP_DIR + x * JUMP_DIR + 3] = ComputeJumpY(Position(x, y), -1, JPS::npos, End);
}
else
{
// 못가면 그냥 -1
for (int k = 0; k < JUMP_DIR; ++k) {
m_PreComputeTable[y * m_Width * JUMP_DIR + x * JUMP_DIR + 0].x = -1;
}
}
}
}
}
template <typename GRID, bool PRECOMPUTE>
void PathFindRule_JPSPlusDynamic<GRID, PRECOMPUTE>::ChangedGrid(Position Start, Position End)
{
if (Start.x <= End.x && Start.y <= End.y)
{
// ###
// # => ###
// ###
if (Start.x > 0) {
Start.x = Start.x - 1;
}
if (Start.y > 0) {
Start.y = Start.y - 1;
}
if (End.x + 1 < m_Width) {
End.x = End.x + 1;
}
if (End.y + 1 < m_Height) {
End.y = End.y + 1;
}
// 가운데
//
// #
//
for (short y = Start.y + 1; y <= End.y - 1; ++y)
{
for (short x = Start.x + 1; x <= End.x - 1; ++x)
{
ClearPreComputeJumpPoint(Position(x, y));
}
}
for (short y = Start.y; y <= End.y; ++y)
{
// 왼쪽
// <
// <--#
// <
for (short x = Start.x; x >= 0; --x)
{
if (m_Grid(x, y) == false)
break;
ClearPreComputeJumpPoint(Position(x, y));
}
// 오른쪽
// >
// #-->
// >
for (short x = End.x; x <= m_Width; ++x)
{
if (m_Grid(x, y) == false)
break;
ClearPreComputeJumpPoint(Position(x, y));
}
}
for (short x = Start.x; x <= End.x; ++x)
{
// 위쪽
// ^^^
// |
// #
for (short y = Start.y; y >= 0; --y)
{
if (m_Grid(x, y) == false)
break;
ClearPreComputeJumpPoint(Position(x, y));
}
// 아랫쪽
// #
// |
// VVV
for (short y = End.y; y <= m_Height; ++y)
{
if (m_Grid(x, y) == false)
break;
ClearPreComputeJumpPoint(Position(x, y));
}
}
return;
}
ASSERT(false);
}
///////////////////////////////////////////////////////////////////////////////
// Jump (대각선)
///////////////////////////////////////////////////////////////////////////////
template <typename GRID, bool PRECOMPUTE>
Position PathFindRule_JPSPlusDynamic<GRID, PRECOMPUTE>::JumpD(Position p, int dx, int dy, const Position& EndPos)
{
bool ReachEndPos = false;
p = ComputeJumpD(p, dx, dy, EndPos, ReachEndPos);
return p;
}
///////////////////////////////////////////////////////////////////////////////
// Jump X축
///////////////////////////////////////////////////////////////////////////////
template <typename GRID, bool PRECOMPUTE>
Position PathFindRule_JPSPlusDynamic<GRID, PRECOMPUTE>::JumpX(Position p, int dx, const Position& EndPos)
{
//ASSERT(dx);
//ASSERT(m_Grid(p.x, p.y));
if (p.y != EndPos.y && HasPreComputeJumpPoint(p, dx, 0))
return GetPreComputeJumpPoint(p, dx, 0);
const auto Start = p;
bool ReachEndPos = false;
p = ComputeJumpX(p, dx, EndPos, ReachEndPos);
if (ReachEndPos == false)
SetPreComputeJumpPoint(Start, dx, 0, p);
return p;
}
///////////////////////////////////////////////////////////////////////////////
// Jump Y축
///////////////////////////////////////////////////////////////////////////////
template <typename GRID, bool PRECOMPUTE>
Position PathFindRule_JPSPlusDynamic<GRID, PRECOMPUTE>::JumpY(Position p, int dy, const Position& EndPos)
{
//ASSERT(dy);
//ASSERT(m_Grid(p.x, p.y));
if (p.x != EndPos.x && HasPreComputeJumpPoint(p, 0, dy))
return GetPreComputeJumpPoint(p, 0, dy);
const auto Start = p;
bool ReachEndPos = false;
p = ComputeJumpY(p, dy, EndPos, ReachEndPos);
if (ReachEndPos == false) {
SetPreComputeJumpPoint(Start, 0, dy, p);
}
return p;
}
template <typename GRID, bool PRECOMPUTE>
bool PathFindRule_JPSPlusDynamic<GRID, PRECOMPUTE>::HasPreComputeJumpPoint(const Position& p, int dx, int dy) const
{
ASSERT(!( dx == 0 && dy == 0 ));
if (dy == 0)
{
if( dx > 0)
return m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 0].x != 0;
else
return m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 1].x != 0;
}
else
{
if (dy > 0)
return m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 2].x != 0;
else
return m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 3].x != 0;
}
}
template <typename GRID, bool PRECOMPUTE>
Position PathFindRule_JPSPlusDynamic<GRID, PRECOMPUTE>::GetPreComputeJumpPoint(const Position& p, int dx, int dy) const
{
ASSERT(!(dx == 0 && dy == 0));
if (dy == 0)
{
if (dx > 0)
return m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 0];
else
return m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 1];
}
else
{
if (dy > 0)
return m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 2];
else
return m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 3];
}
}
template <typename GRID, bool PRECOMPUTE>
void PathFindRule_JPSPlusDynamic<GRID, PRECOMPUTE>::SetPreComputeJumpPoint(const Position& p, int dx, int dy, const Position& JumpPos)
{
ASSERT(!(dx == 0 && dy == 0));
if (dy == 0)
{
if (dx > 0)
m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 0] = JumpPos;
else
m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 1] = JumpPos;
}
else
{
if (dy > 0)
m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 2] = JumpPos;
else
m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 3] = JumpPos;
}
}
template <typename GRID, bool PRECOMPUTE>
void PathFindRule_JPSPlusDynamic<GRID, PRECOMPUTE>::ClearPreComputeJumpPoint(const Position& p)
{
std::cout << "(" << p.x << "," << p.y << ")";
m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 0].x = 0;
m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 1].x = 0;
m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 2].x = 0;
m_PreComputeTable[p.y * m_Width * JUMP_DIR + p.x * JUMP_DIR + 3].x = 0;
}
}
}
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) Opera Software ASA 2002 - 2006
*
* Bytecode compiler for ECMAScript -- overview, common data and functions
*
* @author Jens Lindstrom
*/
#include "core/pch.h"
#include "modules/ecmascript/carakan/src/es_pch.h"
#include "modules/ecmascript/carakan/src/compiler/es_code.h"
#include "modules/ecmascript/carakan/src/object/es_global_object.h"
#include "modules/ecmascript/carakan/src/object/es_regexp_object.h"
#include "modules/ecmascript/carakan/src/object/es_function.h"
#include "modules/ecmascript/carakan/src/compiler/es_native.h"
#include "modules/ecmascript/carakan/src/compiler/es_analyzer.h"
#include "modules/ecmascript/carakan/src/compiler/es_compiler.h"
#include "modules/ecmascript/carakan/src/compiler/es_instruction_data.h"
#include "modules/ecmascript/carakan/src/es_program_cache.h"
#include "modules/regexp/include/regexp_advanced_api.h"
ES_CodeStatic::ConstantArrayLiteral::~ConstantArrayLiteral()
{
OP_DELETEA(indeces);
OP_DELETEA(values);
}
ES_CodeStatic::ES_CodeStatic(Type type)
: codewords(NULL),
instruction_offsets(NULL),
parent_code(NULL),
source_storage_owner(NULL),
source_storage(NULL),
string_storage_owner(NULL),
string_storage(NULL),
strings(NULL),
doubles(NULL),
functions(NULL),
function_declarations(NULL),
object_literal_classes(NULL),
constant_array_literals(NULL),
regexps(NULL),
global_accesses(NULL),
switch_tables(NULL),
#ifdef ES_NATIVE_SUPPORT
loop_data(NULL),
#endif // ES_NATIVE_SUPPORT
exception_handlers(NULL),
inner_scopes(NULL),
compressed_debug_records(NULL),
debug_records(NULL),
#ifdef ES_NATIVE_SUPPORT
first_variable_range_limit_span(NULL),
optimization_data(NULL),
profile_data(NULL),
#endif // ES_NATIVE_SUPPORT
ref_count(0),
cache_ref_count(0),
type(type),
privilege_level(ES_Runtime::PRIV_LVL_UNSPEC),
prepared_for_sharing(FALSE),
is_external(FALSE),
is_strict_mode(FALSE),
#ifdef ECMASCRIPT_DEBUGGER
has_debug_code(FALSE),
#endif // ECMASCRIPT_DEBUGGER
codewords_count(0),
instruction_count(0),
register_frame_size(0),
first_temporary_register(0),
strings_count(0),
doubles_count(0),
functions_count(0),
function_declarations_count(0),
object_literal_classes_count(0),
constant_array_literals_count(0),
regexps_count(0),
global_accesses_count(0),
property_get_caches_count(0),
property_put_caches_count(0),
#ifdef ES_NATIVE_SUPPORT
loop_data_count(0),
#endif // ES_NATIVE_SUPPORT
format_string_caches_count(0),
eval_caches_count(0),
switch_tables_count(0),
exception_handlers_count(0),
inner_scopes_count(0),
debug_records_count(0)
{
}
ES_CodeStatic::~ES_CodeStatic()
{
OP_ASSERT(ref_count == 0);
unsigned index;
#ifndef _STANDALONE
MemoryManager::DecDocMemoryCount(sizeof(ES_CodeWord) * codewords_count);
#endif // !_STANDALONE
OP_DELETEA(codewords);
OP_DELETEA(instruction_offsets);
if (!parent_code)
{
ES_StaticStringData::DecRef(source_storage_owner);
ES_StaticStringData::DecRef(string_storage_owner);
OP_DELETEA(strings);
OP_DELETEA(doubles);
for (index = 0; index < functions_count; ++index)
DecRef(functions[index]);
OP_DELETEA(functions);
OP_DELETEA(function_declarations);
OP_DELETEA(object_literal_classes);
OP_DELETEA(constant_array_literals);
for (index = 0; index < regexps_count; ++index)
regexps[index].regexp->DecRef();
OP_DELETEA(regexps);
OP_DELETEA(global_accesses);
#ifdef ES_NATIVE_SUPPORT
OP_DELETEA(loop_data);
#endif // ES_NATIVE_SUPPORT
OP_DELETEA(switch_tables);
OP_DELETEA(exception_handlers);
OP_DELETEA(inner_scopes);
}
OP_DELETEA(compressed_debug_records);
OP_DELETEA(debug_records);
#ifdef ES_NATIVE_SUPPORT
VariableRangeLimitSpan *vrls = first_variable_range_limit_span;
while (vrls)
{
VariableRangeLimitSpan *next = vrls->next;
OP_DELETE(vrls);
vrls = next;
}
OP_DELETE(optimization_data);
OP_DELETEA(profile_data);
#endif // ES_NATIVE_SUPPORT
}
void
ES_CodeStatic::SetParentCode(ES_CodeStatic *new_parent_code)
{
parent_code = new_parent_code;
#define COPY(what) what = new_parent_code->what, what##_count = new_parent_code->what##_count
#define COPYN(what) what##_count = new_parent_code->what##_count
COPY(strings);
COPY(doubles);
COPY(object_literal_classes);
COPY(constant_array_literals);
COPY(functions);
COPY(regexps);
COPYN(property_get_caches);
COPYN(property_put_caches);
COPYN(global_accesses);
COPY(inner_scopes);
COPYN(format_string_caches);
COPYN(eval_caches);
COPY(switch_tables);
#undef COPYN
#undef COPY
}
void
ES_Code::DiscardCacheRecord(ES_Execution_Context *context, BOOL get_cache, unsigned index, PropertyCache *record)
{
PropertyCache *discard;
if (record->next)
{
discard = record->next;
*record = *discard;
}
else
{
PropertyCache *first = &(get_cache ? property_get_caches : property_put_caches)[index];
if (record == first)
{
*record = PropertyCache();
return;
}
else
{
while (first->next != record)
first = first->next;
first->next = NULL;
discard = record;
}
}
if (context->IsUsingStandardStack())
OP_DELETE(discard);
else
{
ES_Suspended_DELETE<ES_Code::PropertyCache> suspended(discard);
context->SuspendedCall(&suspended);
}
}
void
ES_Code::RemoveCacheRecord(ES_Execution_Context *context, BOOL get_cache, unsigned index, PropertyCache *record)
{
PropertyCache *discard;
if (record->next)
{
discard = record->next;
*record = *discard;
}
else
{
PropertyCache *first = &(get_cache ? property_get_caches : property_put_caches)[index];
if (record == first)
{
*record = PropertyCache();
return;
}
else
{
while (first->next != record)
first = first->next;
first->next = NULL;
discard = record;
}
}
context->CachePropertyCache(discard);
}
/* static */ BOOL
ES_Code::IsSimplePropertyCache(PropertyCache *cache, BOOL is_get_cache)
{
if (is_get_cache)
return !ES_Class::HasHashTableProperties(cache->class_id) || (!cache->IsNegativeCache() && !cache->data.prototype_object);
else
return !ES_Class::HasHashTableProperties(cache->class_id) || !cache->data.new_class;
}
/* static */ void
ES_Code::Initialize(ES_Code *code, ES_CodeStatic *data, ES_Global_Object *global_object, Type type)
{
op_memset(reinterpret_cast<char *>(code) + sizeof(ES_Header), 0, sizeof(*code) - sizeof(ES_Header));
code->data = ES_CodeStatic::IncRef(data);
code->global_object = global_object;
code->type = type;
}
static void
ES_DeleteCaches(ES_Code::PropertyCache *caches, unsigned count)
{
if (caches)
{
for (unsigned index = 0; index < count; ++index)
if (ES_Code::PropertyCache *cache = caches[index].next)
{
ES_Code::PropertyCache *next;
do
{
next = cache->next;
OP_DELETE(cache);
}
while ((cache = next) != NULL);
}
OP_DELETEA(caches);
}
}
/* static */ void
ES_Code::Destroy(ES_Code *code)
{
if (!code->parent_code)
{
OP_DELETEA(code->strings);
OP_DELETEA(code->regexps);
OP_DELETEA(code->object_literal_classes);
/* The GC releases the object_literal_prototype_classes object. */
code->object_literal_prototype_classes = NULL;
OP_DELETEA(code->constant_array_literals);
OP_DELETEA(code->functions);
ES_DeleteCaches(code->property_get_caches, code->data->property_get_caches_count);
ES_DeleteCaches(code->property_put_caches, code->data->property_put_caches_count);
OP_DELETEA(code->global_caches);
code->global_caches = NULL;
#ifdef ES_NATIVE_SUPPORT
if (code->loop_dispatcher_codes)
{
for (unsigned index = 0; index < code->data->loop_data_count; ++index)
if (code->loop_dispatcher_codes[index])
OP_DELETE(code->loop_dispatcher_codes[index]->native_code_block);
OP_DELETEA(code->loop_dispatcher_codes);
}
OP_DELETEA(code->loop_counters);
#endif // ES_NATIVE_SUPPORT
OP_DELETEA(code->format_string_caches);
OP_DELETEA(code->eval_caches);
#ifdef ES_NATIVE_SUPPORT
OP_DELETEA(code->switch_tables);
#endif // ES_NATIVE_SUPPORT
OP_DELETEA(code->scope_chain);
}
#ifdef ES_NATIVE_SUPPORT
if (code->native_code_block)
OP_DELETE(code->native_code_block);
OP_DELETEA(code->codeword_from_return_address);
while (LoopIO *loop_io = code->first_loop_io)
{
code->first_loop_io = loop_io->next;
OP_DELETE(loop_io);
}
#endif // ES_NATIVE_SUPPORT
ES_CodeStatic::DecRef(code->data);
}
BOOL
ES_Code::CanHaveVariableObject()
{
if (type == TYPE_FUNCTION)
return static_cast<ES_FunctionCode *>(this)->GetData()->CanHaveVariableObject();
else if (type == TYPE_EVAL_PLAIN)
return TRUE;
else
return FALSE;
}
void
ES_Code::PrepareForExecution(ES_Context *context)
{
OptimizeGlobalAccessors(context);
}
/*static */ BOOL
ES_CodeStatic::DecRef(ES_CodeStatic *data)
{
if (data)
{
--data->ref_count;
if (data->ref_count + data->cache_ref_count == 0)
{
if (data->type == TYPE_PROGRAM)
{
ES_ProgramCodeStatic* program = static_cast<ES_ProgramCodeStatic*>(data);
if (program->program_cache)
{
program->program_cache->TouchProgram(program);
if (data->cache_ref_count != 0)
return TRUE;
}
}
OP_DELETE(data);
return FALSE;
}
}
return TRUE;
}
/* static */ BOOL
ES_CodeStatic::DecCacheRef(ES_CodeStatic *data)
{
OP_ASSERT(data->cache_ref_count == 1);
--data->cache_ref_count;
if (data->cache_ref_count + data->ref_count == 0)
{
OP_DELETE(data);
return FALSE;
}
return TRUE;
}
void
ES_CodeStatic::SetIsExternal(BOOL value)
{
is_external = value;
for (unsigned index = 0; index < functions_count; ++index)
functions[index]->SetIsExternal(value);
}
void
ES_CodeStatic::SetPrivilegeLevel(ES_Runtime::PrivilegeLevel value)
{
privilege_level = value;
for (unsigned index = 0; index < functions_count; ++index)
functions[index]->SetPrivilegeLevel(value);
}
void
ES_CodeStatic::FindInstructionOffsets(ES_Execution_Context *context)
{
if (!instruction_offsets)
{
ES_CodeWord *iter;
unsigned count = 1, index = 0;
for (iter = codewords; ES_Analyzer::NextInstruction(this, iter); ++count)
;
if (context)
{
if ((instruction_offsets = Suspended_NEWA<unsigned>(context, count + 1)) == NULL)
context->AbortOutOfMemory();
}
else if ((instruction_offsets = OP_NEWA(unsigned, count + 1)) == NULL)
LEAVE(OpStatus::ERR_NO_MEMORY);
instruction_count = count;
iter = codewords;
do
instruction_offsets[index++] = iter - codewords;
while (ES_Analyzer::NextInstruction(this, iter));
instruction_offsets[count] = codewords_count;
}
}
void
ES_Code::SetParentCode(ES_Code *new_parent_code)
{
data->SetParentCode(new_parent_code->data);
global_object = new_parent_code->global_object;
parent_code = new_parent_code;
#define COPY(what) what = new_parent_code->what
COPY(strings);
COPY(regexps);
COPY(object_literal_classes);
COPY(object_literal_prototype_classes);
COPY(constant_array_literals);
COPY(functions);
COPY(property_get_caches);
COPY(property_put_caches);
COPY(global_caches);
COPY(format_string_caches);
COPY(eval_caches);
scope_chain = new_parent_code->scope_chain;
scope_chain_length = new_parent_code->scope_chain_length;
#undef COPY
}
void
ES_Code::SetIsExternal(BOOL value)
{
data->SetIsExternal(value);
}
void
ES_Code::SetPrivilegeLevel(ES_Runtime::PrivilegeLevel value)
{
data->SetPrivilegeLevel(value);
}
void
ES_Code::OptimizeGlobalAccessors(ES_Context *context)
{
BOOL with_eval_type = type == TYPE_EVAL_PLAIN || type == TYPE_EVAL_ODD;
if (type == TYPE_PROGRAM || with_eval_type)
{
ES_ProgramCode *program = static_cast<ES_ProgramCode *>(this);
ES_ProgramCodeStatic *data = program->GetData();
global_object->PrepareForOptimizeGlobalAccessors(context, data->variable_declarations_count);
for (unsigned variable_declaration_index = 0; variable_declaration_index < data->variable_declarations_count; ++variable_declaration_index)
{
unsigned index = data->variable_declarations[variable_declaration_index];
BOOL is_function = FALSE;
#ifdef ES_NATIVE_SUPPORT
if ((0x80000000u & index) != 0)
{
index &= 0x7fffffffu;
is_function = TRUE;
}
#endif
JString *name = GetString(index);
if (!global_object->HasOwnNativeProperty(name) && global_object->GetHostObject()->AllowOperationOnProperty(StorageZ(context, name), EcmaScript_Object::ALLOW_NATIVE_DECLARED_OVERRIDE))
global_object->AddVariable(context, name, is_function, with_eval_type);
}
}
for (unsigned cache_index = 0; cache_index < data->global_accesses_count; ++cache_index)
{
unsigned val = data->global_accesses[cache_index];
JString *name = GetString((val & 0xc0000000u) | ((val & ~0xc0000000u) >> 3));
unsigned global_index;
if (global_object->GetVariableIndex(global_index, name) && (val & ES_CodeStatic::GetScope) == 0
#ifdef ES_NATIVE_SUPPORT
&& ((val & (ES_CodeStatic::PutGlobal | ES_CodeStatic::GetGlobal)) == ES_CodeStatic::GetGlobal || !global_object->GetVariableIsFunction(global_index))
#endif // ES_NATIVE_SUPPORT
)
{
global_caches[cache_index].class_id = ES_Class::GLOBAL_IMMEDIATE_CLASS_ID;
global_caches[cache_index].cached_index = global_index;
}
}
for (unsigned function_index = 0; function_index < data->functions_count; ++function_index)
functions[function_index]->OptimizeGlobalAccessors(context);
}
BOOL
ES_CodeStatic::FindExceptionHandler(unsigned current_ip, unsigned &handler_ip, ES_CodeStatic::ExceptionHandler::Type &handler_type)
{
BOOL found = FALSE;
ExceptionHandler *handlers = exception_handlers;
unsigned count = exception_handlers_count;
while (handlers)
{
int low = 0, high = count - 1;
while (high >= low)
{
unsigned index = (low + high) / 2;
if (handlers[index].start < current_ip && current_ip <= handlers[index].end)
{
found = TRUE;
handler_ip = handlers[index].handler_ip;
handler_type = handlers[index].type;
count = handlers[index].nested_handlers_count;
handlers = handlers[index].nested_handlers;
break;
}
else if (current_ip <= handlers[index].start)
high = index - 1;
else
low = index + 1;
}
if (high < low)
break;
}
return found;
}
BOOL
ES_CodeStatic::FindFinallyHandler(unsigned current_ip, unsigned target, unsigned &handler_ip)
{
BOOL found = FALSE;
ExceptionHandler *handlers = exception_handlers;
unsigned count = exception_handlers_count;
while (handlers)
{
int low = 0, high = count - 1;
while (high >= low)
{
unsigned index = (low + high) / 2;
if (handlers[index].start < current_ip &&
current_ip <= handlers[index].end &&
(target > handlers[index].end || target < handlers[index].start) &&
handlers[index].type == ExceptionHandler::TYPE_FINALLY)
{
found = TRUE;
handler_ip = handlers[index].handler_ip;
count = handlers[index].nested_handlers_count;
handlers = handlers[index].nested_handlers;
break;
}
else if (current_ip <= handlers[index].start)
high = index - 1;
else
low = index + 1;
}
if (high < low)
break;
}
return found;
}
ES_Class *
ES_Code::GetObjectLiteralClass(ES_Context *context, unsigned index, ES_CodeWord *values, ES_Value_Internal *reg)
{
ES_Class *klass = object_literal_classes[index];
if (klass)
return klass;
else
{
BOOL unique;
ES_CodeStatic::ObjectLiteralClass &olc = data->object_literal_classes[index];
if (type == TYPE_FUNCTION && data->object_literal_classes_count < ES_Code_ClassTable::MAX_OBJECT_LITERAL_COMPACT_CLASSES)
{
klass = ES_Class::MakeCompactRoot(context, global_object->GetObjectPrototype(), "Object", context->rt_data->idents[ESID_Object], TRUE, olc.properties_count);
unique = TRUE;
}
else
{
klass = global_object->GetObjectClass();
unique = FALSE;
}
ES_CollectorLock gclock(context);
for (unsigned property_index = 0; property_index < olc.properties_count; ++property_index)
{
ES_Property_Info info;
ES_StorageType type = values ? reg[values[property_index].index].GetStorageType() : ES_STORAGE_WHATEVER;
unsigned string_index = olc.properties[property_index];
if ((string_index & 0x80000000u) != 0)
{
info.SetIsFunction();
string_index &= 0x7fffffffu;
}
klass = ES_Class::ExtendWithL(context, klass, GetString(string_index), info, type, ES_LayoutIndex(property_index));
}
if (unique)
{
if (!object_literal_prototype_classes)
{
if (ES_Execution_Context *exec_context = context->GetExecutionContext())
{
ES_Suspended_NEW<ES_Code_ClassTable> allocate;
exec_context->SuspendedCall(&allocate);
object_literal_prototype_classes = allocate.storage;
}
else
object_literal_prototype_classes = OP_NEW(ES_Code_ClassTable, ());
if (!object_literal_prototype_classes)
context->AbortOutOfMemory();
context->heap->AddClassTable(object_literal_prototype_classes);
}
for (unsigned i = 0; i < ES_Code_ClassTable::MAX_OBJECT_LITERAL_COMPACT_CLASSES; i++)
if (object_literal_prototype_classes->table[i] == NULL)
{
object_literal_prototype_classes->table[i] = klass;
break;
}
}
if (olc.properties_count > 0)
klass = ES_Class::Branch(context, klass, ES_LayoutIndex(klass->GetPropertyInfoAtIndex(ES_PropertyIndex(olc.properties_count - 1)).Index() + 1));
return object_literal_classes[index] = klass;
}
}
void
ES_Code::SetObjectLiteralClass(ES_Context *context, unsigned index, ES_Class *klass)
{
ES_CodeStatic::ObjectLiteralClass &olc = data->object_literal_classes[index];
object_literal_classes[index] = klass;
if (olc.properties_count > 0)
object_literal_classes[index] = ES_Class::Branch(context, klass, ES_LayoutIndex(klass->GetPropertyInfoAtIndex(ES_PropertyIndex(olc.properties_count - 1)).Index() + 1));
}
unsigned
ES_Code::GetObjectLiteralClassCount(unsigned index)
{
return data->object_literal_classes[index].properties_count;
}
OP_STATUS
ES_Code::SetScopeChain(ES_Object **objects, unsigned length)
{
scope_chain = OP_NEWA(ES_Object *, length);
if (!scope_chain)
return OpStatus::ERR_NO_MEMORY;
op_memcpy(scope_chain, objects, length * sizeof scope_chain[0]);
scope_chain_length = length;
for (unsigned i = 0; i < data->functions_count; i++)
functions[i]->SetScopeChain(objects, length);
return OpStatus::OK;
}
ES_Code_ClassTable::ES_Code_ClassTable()
: next(NULL)
{
op_memset(table, 0, MAX_OBJECT_LITERAL_COMPACT_CLASSES * sizeof(ES_Class *));
}
static unsigned
CompressedDelta(unsigned previous, unsigned next)
{
if (previous <= next)
return (next - previous) << 1;
else
return ((previous - next) << 1) | 1;
}
static unsigned
CompressedLength(unsigned value)
{
if (value < (1 << 7))
return 1;
else if (value < (1 << 14))
return 2;
else if (value < (1 << 21))
return 3;
else if (value < (1 << 28))
return 4;
else
return 5;
}
static unsigned char *
CompressedWrite(unsigned char *write, unsigned value)
{
if (value & (((1 << 4) - 1) << 28))
*write++ = static_cast<unsigned char>(0x80 | (value >> 28) & 0x7f);
if (value & (((1 << 7) - 1) << 21))
*write++ = static_cast<unsigned char>(0x80 | (value >> 21) & 0x7f);
if (value & (((1 << 14) - 1) << 14))
*write++ = static_cast<unsigned char>(0x80 | (value >> 14) & 0x7f);
if (value & (((1 << 21) - 1) << 7))
*write++ = static_cast<unsigned char>(0x80 | (value >> 7) & 0x7f);
*write++ = static_cast<unsigned char>(value & 0x7f);
return write;
}
static unsigned
CompressedRead(const unsigned char *&read)
{
unsigned value = 0;
while (*read & 0x80)
value = (value << 7) | *read++ & 0x7f;
return (value << 7) | *read++;
}
static unsigned
DecompressDelta(unsigned previous, unsigned value)
{
if (value & 1)
return previous - (value >> 1);
else
return previous + (value >> 1);
}
/* static */ const unsigned char *
ES_CodeStatic::DebugRecord::Compress(DebugRecord *records, unsigned count)
{
OP_ASSERT(count > 0);
unsigned length = 0;
unsigned previous_cw_index = 0;
unsigned previous_index = 0;
unsigned previous_line = 0;
ES_CodeStatic::DebugRecord *iter = records, *stop = iter + count;
while (iter != stop)
{
unsigned cw_index = (iter->codeword_index << 1) | iter->type;
unsigned index = iter->location.Index();
unsigned line = iter->location.Line();
length += (CompressedLength(CompressedDelta(previous_cw_index, cw_index)) +
CompressedLength(CompressedDelta(previous_index, index)) +
CompressedLength(CompressedDelta(previous_line, line)) +
CompressedLength(iter->location.Length()));
previous_cw_index = cw_index;
previous_index = index;
previous_line = line;
++iter;
}
unsigned char *compressed = OP_NEWA_L(unsigned char, length), *write = compressed;
previous_cw_index = 0;
previous_index = 0;
previous_line = 0;
iter = records;
stop = iter + count;
while (iter != stop)
{
unsigned cw_index = (iter->codeword_index << 1) | iter->type;
unsigned index = iter->location.Index();
unsigned line = iter->location.Line();
write = CompressedWrite(write, CompressedDelta(previous_cw_index, cw_index));
write = CompressedWrite(write, CompressedDelta(previous_index, index));
write = CompressedWrite(write, CompressedDelta(previous_line, line));
write = CompressedWrite(write, iter->location.Length());
previous_cw_index = cw_index;
previous_index = index;
previous_line = line;
++iter;
}
OP_ASSERT(write == compressed + length);
#if defined _DEBUG && defined DEBUG_ENABLE_OPASSERT
ANCHOR_ARRAY(unsigned char, compressed);
ES_CodeStatic::DebugRecord *reverse = Decompress(compressed, count);
OP_ASSERT(op_memcmp(reverse, records, sizeof *records * count) == 0);
OP_DELETEA(reverse);
ANCHOR_ARRAY_RELEASE(compressed);
#endif // _DEBUG && DEBUG_ENABLE_OPASSERT
return compressed;
}
/* static */ ES_CodeStatic::DebugRecord *
ES_CodeStatic::DebugRecord::Decompress(const unsigned char *data, unsigned count, ES_Execution_Context *context)
{
OP_ASSERT(count > 0);
DebugRecord *records;
if (context)
{
ES_Suspended_NEWA<ES_CodeStatic::DebugRecord> allocate(count);
context->SuspendedCall(&allocate);
if (!allocate.storage)
context->AbortOutOfMemory();
records = allocate.storage;
}
else
records = OP_NEWA_L(ES_CodeStatic::DebugRecord, count);
ES_CodeStatic::DebugRecord *write = records, *stop = write + count;
const unsigned char *read = data;
unsigned previous_cw_index = 0;
unsigned previous_index = 0;
unsigned previous_line = 0;
while (write != stop)
{
unsigned cw_index = DecompressDelta(previous_cw_index, CompressedRead(read));
write->codeword_index = cw_index >> 1;
write->type = static_cast<ES_CodeStatic::DebugRecord::Type>(cw_index & 1);
unsigned index = DecompressDelta(previous_index, CompressedRead(read));
unsigned line = DecompressDelta(previous_line, CompressedRead(read));
unsigned length = CompressedRead(read);
write->location.Set(index, line, length);
previous_cw_index = cw_index;
previous_index = index;
previous_line = line;
++write;
}
return records;
}
ES_CodeStatic::DebugRecord *
ES_CodeStatic::FindDebugRecord(ES_Execution_Context *context, DebugRecord::Type type, ES_CodeWord *codeword)
{
if (compressed_debug_records && !debug_records)
{
debug_records = DebugRecord::Decompress(compressed_debug_records, debug_records_count, context);
ES_Suspended_DELETEA<unsigned char> delete_compressed_records(const_cast<unsigned char*>(compressed_debug_records));
context->SuspendedCall(&delete_compressed_records);
compressed_debug_records = NULL;
}
if (debug_records)
{
unsigned codeword_index = codeword - codewords;
unsigned stop = debug_records_count - 1;
unsigned index = 0;
int low, high;
if (codeword_index < debug_records[0].codeword_index)
return NULL;
else if (codeword_index >= debug_records[stop].codeword_index)
{
index = stop;
goto found;
}
else
{
low = 0;
high = stop;
while (high >= low)
{
index = (low + high) / 2;
if (debug_records[index].codeword_index <= codeword_index && (index == stop || debug_records[index + 1].codeword_index > codeword_index))
{
found:
if (type == DebugRecord::TYPE_EXTENT_INFORMATION)
{
while (type != static_cast<DebugRecord::Type>(debug_records[index].type))
if (index-- == 0)
return NULL;
return &debug_records[index];
}
else
{
while (index < stop && debug_records[index + 1].codeword_index <= codeword_index)
++index;
do
if (type == static_cast<DebugRecord::Type>(debug_records[index].type))
return &debug_records[index];
while (index != 0 && debug_records[--index].codeword_index <= codeword_index);
}
return NULL;
}
else if (codeword_index < debug_records[index].codeword_index)
high = index - 1;
else
low = index + 1;
}
}
}
return NULL;
}
/* virtual */
ES_ProgramCodeStatic::~ES_ProgramCodeStatic()
{
OP_DELETEA(variable_declarations);
if (program_cache)
program_cache->RemoveProgram(this);
}
static ES_FunctionCode *
AllocateFunctionCode(ES_Context *context, ES_FunctionCodeStatic *data, ES_Global_Object *global_object, ES_ProgramCodeStaticReaper *program_reaper)
{
ES_FunctionCode *function_code;
GC_ALLOCATE(context, function_code, ES_FunctionCode, (function_code, data, global_object, program_reaper));
return function_code;
}
/* static */ void
ES_Code::InitializeFromStatic(ES_Context *context, ES_Global_Object *global_object, ES_Code *code, ES_Identifier_List *strings_table, ES_ProgramCodeStaticReaper *program_reaper, JString *url_str)
{
JStringStorage *source_storage = code->data->source_storage;
JStringStorage *string_storage = code->data->string_storage;
ES_CodeStatic::String *strings = code->data->strings;
unsigned index, source_storage_length = source_storage ? source_storage->length : 0;
code->url = url_str;
code->strings = OP_NEWA_L(JString *, code->data->strings_count);
for (index = 0; index < code->data->strings_count; ++index)
{
JStringStorage *storage;
unsigned offset;
if (strings[index].offset < source_storage_length)
storage = source_storage, offset = strings[index].offset;
else if ((strings[index].offset & 0x80000000u) != 0)
{
code->strings[index] = ES_Lexer::ProcessStringLiteral(context, source_storage->storage + (strings[index].offset & 0x7fffffffu), strings[index].length, code->data->is_strict_mode);
continue;
}
else
storage = string_storage, offset = strings[index].offset - source_storage_length;
JString *string;
JTemporaryString temporary(storage->storage + offset, strings[index].length);
unsigned string_index;
if (strings_table->IndexOf(temporary, string_index))
strings_table->Lookup(string_index, string);
else
{
string = temporary.Allocate(context, storage);
string->hash = static_cast<JString *>(temporary)->hash;
strings_table->AppendAtIndexL(context, string, string_index, string_index);
}
code->strings[index] = string;
}
if (code->data->regexps_count)
{
code->regexps = OP_NEWA_L(ES_RegExp_Object *, code->data->regexps_count);
op_memset(code->regexps, 0, code->data->regexps_count * sizeof(ES_RegExp_Object *));
}
if (code->data->object_literal_classes_count)
{
code->object_literal_classes = OP_NEWA_L(ES_Class *, code->data->object_literal_classes_count);
op_memset(code->object_literal_classes, 0, code->data->object_literal_classes_count * sizeof(ES_Class *));
}
if (code->data->constant_array_literals_count)
{
code->constant_array_literals = OP_NEWA_L(ES_Compact_Indexed_Properties *, code->data->constant_array_literals_count);
op_memset(code->constant_array_literals, 0, code->data->constant_array_literals_count * sizeof(ES_Compact_Indexed_Properties *));
}
code->functions = OP_NEWA_L(ES_FunctionCode *, code->data->functions_count);
for (index = 0; index < code->data->functions_count; ++index)
{
ES_FunctionCode *function_code = AllocateFunctionCode(context, code->data->functions[index], global_object, program_reaper);
InitializeFromStatic(context, global_object, code->functions[index] = function_code, strings_table, program_reaper, url_str);
}
code->property_get_caches = OP_NEWA_L(ES_Code::PropertyCache, code->data->property_get_caches_count);
code->property_put_caches = OP_NEWA_L(ES_Code::PropertyCache, code->data->property_put_caches_count);
code->global_caches = OP_NEWA_L(ES_Code::GlobalCache, code->data->global_accesses_count);
#ifdef ES_PROPERTY_CACHE_PROFILING
context->rt_data->pcache_allocated_property += 8 + sizeof(ES_Code::PropertyCache) * (code->data->property_get_caches_count + code->data->property_put_caches_count);
context->rt_data->pcache_allocated_global += 8 + sizeof(ES_Code::GlobalCache) * code->data->global_accesses_count;
#endif // ES_PROPERTY_CACHE_PROFILING
#ifdef ES_NATIVE_SUPPORT
code->loop_counters = OP_NEWA_L(unsigned, code->data->loop_data_count);
op_memset(code->loop_counters, 0, code->data->loop_data_count * sizeof(unsigned));
code->loop_dispatcher_codes = OP_NEWA_L(ES_Code *, code->data->loop_data_count);
op_memset(code->loop_dispatcher_codes, 0, code->data->loop_data_count * sizeof(ES_Code *));
#endif // ES_NATIVE_SUPPORT
code->format_string_caches = OP_NEWA_L(ES_Code::FormatStringCache, code->data->format_string_caches_count);
code->eval_caches = OP_NEWA_L(ES_Code::EvalCache, code->data->eval_caches_count);
#ifdef ES_NATIVE_SUPPORT
code->switch_tables = OP_NEWA_L(ES_Code::SwitchTable, code->data->switch_tables_count);
#endif // ES_NATIVE_SUPPORT
}
/* static */ ES_ProgramCode *
ES_ProgramCode::Make(ES_Context *context, ES_Global_Object *global_object, ES_ProgramCodeStatic *data, BOOL initialize_from_static, JString *url_str)
{
OpStackAutoPtr<ES_ProgramCodeStatic> data_anchor;
if (!data->IsShared())
data_anchor.reset(data);
ES_ProgramCode *program;
GC_ALLOCATE(context, program, ES_ProgramCode, (program, data, global_object));
data_anchor.release();
if (initialize_from_static)
{
if (data->string_storage_owner && !context->heap->AddStaticStringData(context, data->string_storage_owner))
LEAVE(OpStatus::ERR_NO_MEMORY);
if (data->source_storage_owner && !context->heap->AddStaticStringData(context, data->source_storage_owner))
LEAVE(OpStatus::ERR_NO_MEMORY);
ES_Identifier_List *strings_table = ES_Identifier_List::Make(context, 256);
ES_ProgramCodeStaticReaper *program_reaper = ES_ProgramCodeStaticReaper::IncRef(OP_NEW_L(ES_ProgramCodeStaticReaper, ()));
program_reaper->Initialize(data);
TRAPD(status, InitializeFromStatic(context, global_object, program, strings_table, program_reaper, url_str));
ES_ProgramCodeStaticReaper::DecRef(program_reaper);
if (OpStatus::IsMemoryError(status))
LEAVE(status);
}
return program;
}
static unsigned
CountStrings(ES_Code *code)
{
unsigned count = code->data->strings_count;
for (unsigned index = 0; index < code->data->functions_count; ++index)
count += CountStrings(code->functions[index]);
return count;
}
/* static */ void
ES_Code::CalculateStringOffsets(ES_Context *context, ES_Code *code, ES_Identifier_Hash_Table *long_string_literal_table, ES_Identifier_List *strings_table, unsigned *offsets, unsigned ¤t_offset)
{
ES_CodeStatic::String *strings = code->data->strings = OP_NEWA_L(ES_CodeStatic::String, code->data->strings_count);
unsigned index;
for (index = 0; index < code->data->strings_count; ++index)
{
JString *string = code->strings[index];
if (string->value == code->data->source_storage)
strings->offset = string->offset;
else
{
if (long_string_literal_table && Length(string) > 1024)
{
unsigned string_literal_index;
if (long_string_literal_table->Find(string, string_literal_index))
{
OP_ASSERT(code->data->source_storage && (code->data->source_storage->storage[string_literal_index] == '\'' || code->data->source_storage->storage[string_literal_index] == '"'));
strings->offset = string_literal_index | 0x80000000u;
goto next_string;
}
}
unsigned position;
if (strings_table->IndexOf(string, position))
strings->offset = offsets[position];
else
{
strings_table->AppendAtIndexL(context, string, position, position);
strings->offset = offsets[position] = current_offset;
current_offset += Length(string) + 1;
}
}
next_string:
strings++->length = Length(string);
}
for (index = 0; index < code->data->functions_count; ++index)
CalculateStringOffsets(context, code->functions[index], long_string_literal_table, strings_table, offsets, current_offset);
}
/* static */ unsigned
ES_Code::CopyStrings(ES_Context *context, ES_Code *code, ES_StaticStringData *data, unsigned write_offset)
{
code->data->string_storage_owner = ES_StaticStringData::IncRef(data);
code->data->string_storage = data->storage;
uni_char *storage = data->storage->storage;
ES_CodeStatic::String *strings = code->data->strings;
unsigned index, write_offset_adjust = code->data->source_storage ? code->data->source_storage->length : 0;
for (index = 0; index < code->data->strings_count; ++index)
{
JString *string = code->strings[index];
if (string->value != code->data->source_storage && (strings[index].offset & 0x80000000u) == 0)
{
OP_ASSERT(Length(string) == strings[index].length);
OP_ASSERT(strings[index].offset <= write_offset);
if (strings[index].offset == write_offset)
{
unsigned length = Length(string), local_write_offset = write_offset - write_offset_adjust;
op_memmove(storage + local_write_offset, Storage(context, string), length * sizeof(uni_char));
storage[local_write_offset + length] = 0;
write_offset += length + 1;
}
else
{
OP_ASSERT(op_memcmp(storage + strings[index].offset - write_offset_adjust, Storage(context, string), Length(string) * sizeof(uni_char)) == 0);
OP_ASSERT(storage[strings[index].offset - write_offset_adjust + strings[index].length] == 0);
}
}
}
for (index = 0; index < code->data->functions_count; ++index)
write_offset = CopyStrings(context, code->functions[index], data, write_offset);
return write_offset;
}
void
ES_ProgramCode::PrepareStaticForSharing(ES_Context *context)
{
if (data->prepared_for_sharing)
return;
OP_ASSERT(!data->string_storage);
OP_ASSERT(!data->strings);
unsigned count = CountStrings(this);
if (count != 0)
{
unsigned *offsets = OP_NEWA_L(unsigned, count);
ANCHOR_ARRAY(unsigned, offsets);
ES_Identifier_List *strings_table = ES_Identifier_List::Make(context, 2 * count);
unsigned current_offset = 0;
if (data->source_storage)
current_offset += data->source_storage->length;
CalculateStringOffsets(context, this, long_string_literal_table, strings_table, offsets, current_offset);
if (data->source_storage)
current_offset -= data->source_storage->length;
ES_StaticStringData *string_data = OP_NEW_L(ES_StaticStringData, ());
TRAPD(status, string_data->storage = JStringStorage::MakeStatic(context, current_offset));
if (OpStatus::IsSuccess(status))
{
unsigned write_offset = 0;
if (data->source_storage)
write_offset += data->source_storage->length;
CopyStrings(context, this, string_data, write_offset);
}
ES_StaticStringData::DecRef(string_data);
context->heap->Free(strings_table);
LEAVE_IF_ERROR(status);
}
data->prepared_for_sharing = TRUE;
}
void
ES_ProgramCode::StartExecution(ES_Runtime *runtime, ES_Context *context)
{
PrepareForExecution(context);
}
/* virtual */
ES_FunctionCodeStatic::~ES_FunctionCodeStatic()
{
OP_DELETEA(formals_and_locals);
}
static ES_Class *
PruneConstructorPropertyCache(ES_Execution_Context *context, ES_FunctionCode *code, ES_CodeWord *word, ES_Class *klass, BOOL first)
{
ES_Code::PropertyCache *cache = &code->property_put_caches[word[4].index];
ES_Class *next_klass = NULL;
unsigned class_id = klass->Id();
if (first && (cache->next != NULL || cache->data.new_class == NULL))
return NULL;
while (cache != NULL)
{
if (cache->class_id == class_id)
{
if (next_klass != NULL)
return NULL;
else
next_klass = cache->data.new_class;
cache = cache->next;
}
else
{
BOOL is_last = cache->next == NULL;
code->RemoveCacheRecord(context, FALSE, word[4].index, cache);
if (is_last)
break;
}
}
return next_klass;
}
ES_Class *
ES_FunctionCode::OptimizeConstructorPropertyCaches(ES_Execution_Context *context, ES_Class *root_class, unsigned &property_count)
{
ES_Class *final_class = root_class;
OP_ASSERT(context->GetExecutionContext() != NULL);
property_count = 0;
for (unsigned index = 0, count = data->instruction_count; final_class && index < count; ++index)
{
unsigned cw_index = data->instruction_offsets[index];
ES_CodeWord *word = &data->codewords[cw_index];
switch (word->instruction)
{
case ESI_PUTN_IMM:
case ESI_INIT_PROPERTY:
if (word[1].index == 0)
final_class = PruneConstructorPropertyCache(context->GetExecutionContext(), this, word, final_class, property_count++ == 0);
break;
case ESI_JUMP:
case ESI_JUMP_IF_TRUE:
case ESI_JUMP_IF_FALSE:
case ESI_TABLE_SWITCH:
case ESI_CONSTRUCT:
final_class = NULL;
break;
#ifdef ES_COMBINED_ADD_SUPPORT
case ESI_ADDN:
{
unsigned index = cw_index + 2, stop = cw_index + 2 + word[2].index;
while (index != stop)
if (word[index++].index == 0)
{
final_class = NULL;
break;
}
}
break;
#endif // ES_COMBINED_ADD_SUPPORT
case ESI_CONSTRUCT_OBJECT:
{
unsigned index = 3, stop = 3 + data->object_literal_classes[word[2].index].properties_count;
while (index != stop)
if (word[index++].index == 0)
{
final_class = NULL;
break;
}
}
break;
default:
unsigned operand_count = g_instruction_operand_count[word->instruction];
unsigned short register_i = g_instruction_operand_register_io[word->instruction] >> 8;
for (unsigned index = 0; index < operand_count; ++index)
if ((register_i & (1 << index)) != 0)
if (word[1 + index].index == 0)
{
final_class = NULL;
break;
}
}
}
if (final_class && final_class != root_class)
final_class = ES_Class::Branch(context, final_class, ES_LayoutIndex(final_class->GetPropertyInfoAtIndex(ES_PropertyIndex(property_count - 1)).Index() + 1));
return final_class;
}
void
ES_FunctionCode::ConstructClass(ES_Context *context)
{
if (!klass)
{
ES_FunctionCodeStatic *data = GetData();
klass = ES_Class::MakeCompactRoot(context, NULL, "Variable", context->rt_data->idents[ESID_Variable]);
klass->SetIsCompact();
ES_Property_Info info(DD);
unsigned index, locals_count = data->LocalsCount();
if (data->formals_count + locals_count != 0)
{
unsigned count = 0;
for (index = 0; index < data->formals_count; ++index)
klass = klass->ExtendWithL(context, GetString(data->formals_and_locals[index]), info, ES_STORAGE_WHATEVER, ES_LayoutIndex(count++), TRUE);
for (index = 0; index < locals_count; ++index)
klass = klass->ExtendWithL(context, GetString(data->formals_and_locals[data->formals_count + index]), info, ES_STORAGE_WHATEVER, ES_LayoutIndex(count++), FALSE);
klass = klass->Branch(context, ES_LayoutIndex(count));
}
}
}
BOOL
ES_FunctionCodeStatic::CanHaveVariableObject()
{
return uses_get_scope_ref || uses_eval || functions_count != 0 && functions_count != static_functions_count;
}
BOOL
ES_FunctionCodeStatic::CanInline()
{
#define INLINE_CODEWORDS_LIMIT 64
return !exception_handlers && !CanHaveVariableObject() && codewords_count < INLINE_CODEWORDS_LIMIT && !uses_arguments;
}
ES_ProgramCodeStaticReaper::ES_ProgramCodeStaticReaper()
: ref_count(0),
data(NULL),
functions_count(0),
deleted_functions(0)
{
}
ES_ProgramCodeStaticReaper::~ES_ProgramCodeStaticReaper()
{
if (data)
ES_ProgramCodeStatic::DecRef(data);
}
void
ES_ProgramCodeStaticReaper::Initialize(ES_ProgramCodeStatic *data)
{
OP_ASSERT(this->data == NULL);
this->data = data;
if (data)
ES_ProgramCodeStatic::IncRef(data);
}
void
ES_ProgramCodeStaticReaper::FunctionCreatedInternal()
{
functions_count++;
}
void
ES_ProgramCodeStaticReaper::FunctionDeletedInternal()
{
deleted_functions++;
if (data)
if (functions_count > 16 && deleted_functions * 4 > functions_count || deleted_functions == functions_count)
{
ES_ProgramCodeStatic::DecRef(data);
data = NULL;
}
}
/* static */ void
ES_ProgramCodeStaticReaper::FunctionCreated(ES_ProgramCodeStaticReaper *reaper)
{
if (reaper)
reaper->FunctionCreatedInternal();
}
/* static */ void
ES_ProgramCodeStaticReaper::FunctionDeleted(ES_ProgramCodeStaticReaper *reaper)
{
if (reaper)
reaper->FunctionDeletedInternal();
}
/* static */ ES_ProgramCodeStaticReaper *
ES_ProgramCodeStaticReaper::IncRef(ES_ProgramCodeStaticReaper *reaper)
{
if (reaper)
++reaper->ref_count;
return reaper;
}
/* static */ void
ES_ProgramCodeStaticReaper::DecRef(ES_ProgramCodeStaticReaper *reaper)
{
if (reaper)
if (--reaper->ref_count == 0)
OP_DELETE(reaper);
}
/* virtual */ void
ES_Program::GCTrace()
{
if (program)
heap->Mark(program);
}
/* virtual */ void
ES_Program::NewHeap(ES_Heap *heap)
{
this->heap = heap;
}
ES_CodeOptimizationData::~ES_CodeOptimizationData()
{
if (register_accesses)
{
for (unsigned index = 0; index < code->register_frame_size; ++index)
OP_DELETEA(register_accesses[index]);
OP_DELETEA(register_accesses);
}
OP_DELETEA(register_access_counts);
JumpTarget *jt = first_jump_target;
while (jt)
{
JumpTarget *next = jt->next;
OP_DELETE(jt);
jt = next;
}
}
BOOL
ES_CodeOptimizationData::RegisterAccess::GetValue(ES_Code *code, ES_Value_Internal &value) const
{
if (IsValueKnown())
{
ES_CodeWord *ip = &code->data->codewords[data >> SHIFT_WRITE_CW_INDEX];
switch (ip->instruction)
{
case ESI_LOAD_INT32:
value.SetInt32(ip[2].immediate);
return TRUE;
case ESI_LOAD_DOUBLE:
value.SetDouble(code->data->doubles[ip[2].index]);
return TRUE;
case ESI_LOAD_STRING:
value.SetString(code->GetString(ip[2].index));
return TRUE;
case ESI_LOAD_NULL:
value.SetNull();
return TRUE;
case ESI_LOAD_UNDEFINED:
value.SetUndefined();
return TRUE;
case ESI_LOAD_TRUE:
value.SetTrue();
return TRUE;
case ESI_LOAD_FALSE:
value.SetFalse();
return TRUE;
case ESI_LOAD_GLOBAL_OBJECT:
value.SetObject(code->global_object);
return TRUE;
}
OP_ASSERT(FALSE);
}
return FALSE;
}
unsigned
ES_CodeOptimizationData::RegisterAccess::GetLastReadIndex(BOOL ignore_implicit_writes) const
{
OP_ASSERT(IsWrite());
const RegisterAccess *access = GetNextRead(ignore_implicit_writes), *next;
if (access)
while (TRUE)
if ((next = access->GetNextRead(ignore_implicit_writes)) != NULL)
access = next;
else
return access->cw_index;
else
return UINT_MAX;
}
unsigned
ES_CodeOptimizationData::RegisterAccess::GetNumberOfReads(BOOL ignore_implicit_writes) const
{
OP_ASSERT(IsWrite());
const RegisterAccess *access = GetNextRead(ignore_implicit_writes);
unsigned count = 0;
while (access)
{
++count;
access = access->GetNextRead(ignore_implicit_writes);
}
return count;
}
const ES_CodeOptimizationData::RegisterAccess *
ES_CodeOptimizationData::RegisterAccess::GetNextRead(BOOL ignore_implicit_writes) const
{
const RegisterAccess *access = this + 1;
while (!access->IsTerminator())
if (access->IsRead())
return access;
else if (ignore_implicit_writes && access->IsImplicit())
++access;
else
break;
return NULL;
}
const ES_CodeOptimizationData::RegisterAccess *
ES_CodeOptimizationData::RegisterAccess::GetNextWrite() const
{
const RegisterAccess *access = this + 1;
while (access->IsRead())
++access;
return access;
}
BOOL
ES_CodeOptimizationData::RegisterAccess::IsWrittenValueRead() const
{
OP_ASSERT(IsWrite());
return GetNextRead(TRUE) != NULL;
}
static unsigned
FindRegisterAccessIndex(unsigned cw_index, const ES_CodeOptimizationData::RegisterAccess *accesses, unsigned count)
{
int low = 0, high = count - 1;
OP_ASSERT(count != 0 && cw_index <= accesses[high].cw_index);
while (TRUE)
{
unsigned index = (low + high) / 2;
if (cw_index <= accesses[index].cw_index)
{
if (index == 0 || cw_index > accesses[index - 1].cw_index)
{
while (index + 1 < count && cw_index == accesses[index + 1].cw_index)
++index;
return index;
}
high = index - 1;
}
else
low = index + 1;
}
}
const ES_CodeOptimizationData::RegisterAccess *
ES_CodeOptimizationData::FindWriteAt(unsigned cw_index, unsigned register_index)
{
const ES_CodeOptimizationData::RegisterAccess *accesses = register_accesses[register_index];
unsigned count = register_access_counts[register_index];
unsigned index = FindRegisterAccessIndex(cw_index, accesses, count);
OP_ASSERT(accesses[index].cw_index == cw_index);
if (accesses[index].IsImplicitRead())
--index;
OP_ASSERT(accesses[index].cw_index == cw_index && accesses[index].IsWrite());
return &accesses[index];
}
const ES_CodeOptimizationData::RegisterAccess *
ES_CodeOptimizationData::FindCorrespondingImplicitWrite(unsigned register_index, const RegisterAccess *implicit_read)
{
ES_CodeWord *word = &code->codewords[implicit_read->cw_index];
switch (word->instruction)
{
default:
return NULL;
case ESI_JUMP:
case ESI_JUMP_IF_TRUE:
case ESI_JUMP_IF_FALSE:
const ES_CodeOptimizationData::RegisterAccess *accesses = register_accesses[register_index];
unsigned count = register_access_counts[register_index];
unsigned cw_index = implicit_read->cw_index + 1 + word[1].offset;
unsigned index = FindRegisterAccessIndex(cw_index, accesses, count);
OP_ASSERT(accesses[index].cw_index == cw_index);
if (accesses[index].IsImplicitRead())
--index;
if (accesses[index].IsExplicitWrite())
--index;
if (accesses[index].IsExplicitRead())
--index;
OP_ASSERT(accesses[index].cw_index == cw_index && accesses[index].IsImplicitWrite());
return &accesses[index];
}
}
const ES_CodeOptimizationData::RegisterAccess *
ES_CodeOptimizationData::FindReadAt(unsigned cw_index, unsigned register_index)
{
const ES_CodeOptimizationData::RegisterAccess *accesses = register_accesses[register_index];
unsigned count = register_access_counts[register_index];
unsigned index = FindRegisterAccessIndex(cw_index, accesses, count);
OP_ASSERT(accesses[index].cw_index == cw_index);
if (accesses[index].IsImplicitRead())
--index;
if (accesses[index].IsExplicitWrite())
--index;
OP_ASSERT(accesses[index].cw_index == cw_index && accesses[index].IsExplicitRead());
return &accesses[index];
}
const ES_CodeOptimizationData::RegisterAccess *
ES_CodeOptimizationData::FindWriteReadAt(unsigned cw_index, unsigned register_index)
{
const ES_CodeOptimizationData::RegisterAccess *accesses = register_accesses[register_index];
unsigned count = register_access_counts[register_index];
unsigned index = FindRegisterAccessIndex(cw_index, accesses, count);
/* We don't care about things happening after 'cw_index'. */
while (index != 0 && cw_index < accesses[index].cw_index)
--index;
/* We also don't care about things happening at 'cw_index' unless it happens
to be an implicit write. */
while (index != 0 && cw_index == accesses[index].cw_index && !accesses[index].IsImplicitWrite())
--index;
/* And we don't care about reads at all. */
if (accesses[index].IsRead() && index != 0)
if (accesses[--index].IsRead() && index != 0)
if (accesses[--index].IsRead())
{
/* We seem to be looking at a possibly long list of reads. Find
the write with a binary search using the write index recorded
in each read access. */
unsigned write_cw_index = accesses[index].GetWriteIndex();
index = FindRegisterAccessIndex(write_cw_index, accesses, count);
OP_ASSERT(accesses[index].cw_index == write_cw_index || write_cw_index == 0);
while (index != 0 && accesses[index].IsRead())
--index;
OP_ASSERT(accesses[index].cw_index == write_cw_index || write_cw_index == 0);
}
/* Now, if we've found a write occur before 'cw_index' or an implicit write
occuring at 'cw_index', return it, otherwise return NULL. */
if (accesses[index].IsWrite() && (accesses[index].cw_index < cw_index || accesses[index].IsImplicit()))
return &accesses[index];
else
return NULL;
}
|
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int> > ret;
if(candidates.empty()) return ret;
sort(candidates.begin(),candidates.end());
vector<int> temp;
dfs(candidates,ret,target,temp,candidates.size()-1);
return ret;
}
void dfs(vector<int>& candidates,vector<vector<int> > &ret,int target,vector<int> &temp,int index){
if(target < 0) return;
if(target == 0){
ret.push_back(temp);
return;
}
if(index < 0) return;
for(int i=0; i<=index; ++i){
if(candidates[index-i] <= target){
temp.push_back(candidates[index-i]);
dfs(candidates,ret,target-candidates[index-i],temp,index-i);
temp.pop_back();
}
}
}
};
|
#pragma once
#include<iostream>
using namespace std;
//extern int a;
//void put();
template <typename T,int size,int e>
class A
{
public:
void print();
private:
T x;
};
template <typename T, int size, int e>
void A< T, size , e >::print()
{
T a[size];
for (int i = 0; i < size; i++)
{
cin >> a[i];
}
cout << "e:" << e << endl;
for (T x : a)
{
cout << x << endl;
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
/**
* @file OpOCSPResponseVerifier_impl.cpp
*
* OpenSSL-based OCSP response verifier implementation.
*
* @author Alexei Khlebnikov <alexeik@opera.com>
*
*/
#include "core/pch.h"
#if defined(CRYPTO_OCSP_SUPPORT) && defined(CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION)
#include "modules/libcrypto/src/openssl_impl/OCSPResponseVerifier_impl.h"
#include "modules/libcrypto/src/openssl_impl/CryptoCertificate_impl.h"
#include "modules/libcrypto/src/openssl_impl/CryptoCertificateChain_impl.h"
#include "modules/libcrypto/src/openssl_impl/CryptoCertificateStorage_impl.h"
#include "modules/libcrypto/src/openssl_impl/OCSPRequest_impl.h"
#include "modules/libcrypto/src/openssl_impl/openssl_util.h"
#include "modules/libopeay/openssl/cryptlib.h"
#include "modules/libopeay/openssl/ocsp.h"
OpOCSPResponseVerifier* OpOCSPResponseVerifier::Create()
{
return OP_NEW(OCSPResponseVerifier_impl, ());
}
OCSPResponseVerifier_impl::OCSPResponseVerifier_impl()
: m_request(0)
, m_response_der(0)
, m_response_length(0)
, m_certificate_chain(0)
, m_ca_storage(0)
, m_verify_status(CryptoCertificateChain::VERIFY_STATUS_UNKNOWN)
{}
OCSPResponseVerifier_impl::~OCSPResponseVerifier_impl()
{}
void OCSPResponseVerifier_impl::SetOCSPResponseDER(
const unsigned char* response_der, unsigned int response_length)
{
m_response_der = response_der;
m_response_length = response_length;
}
void OCSPResponseVerifier_impl::SetOCSPRequest(const OpOCSPRequest* request)
{
m_request = request;
}
void OCSPResponseVerifier_impl::SetCertificateChain(const CryptoCertificateChain* certificate_chain)
{
m_certificate_chain = certificate_chain;
}
void OCSPResponseVerifier_impl::SetCAStorage(const CryptoCertificateStorage* ca_storage)
{
m_ca_storage = ca_storage;
}
void OCSPResponseVerifier_impl::ProcessL()
{
if (!m_request || !m_response_der || m_response_length == 0 ||
!m_certificate_chain || !m_ca_storage)
LEAVE(OpStatus::ERR_OUT_OF_RANGE);
// Default value. Will be checked in the end of the function.
OP_STATUS status = OpStatus::ERR;
// Default verify status.
m_verify_status = CryptoCertificateChain::VERIFY_STATUS_UNKNOWN;
OCSP_RESPONSE* ocsp_response = 0;
OCSP_BASICRESP* ocsp_basicresp = 0;
do
{
const OCSPRequest_impl* request_impl =
static_cast <const OCSPRequest_impl*> (m_request);
const CryptoCertificateChain_impl* chain_impl =
static_cast <const CryptoCertificateChain_impl*> (m_certificate_chain);
const CryptoCertificateStorage_impl* storage_impl =
static_cast <const CryptoCertificateStorage_impl*> (m_ca_storage);
if (!request_impl || !chain_impl || !storage_impl)
{
status = OpStatus::ERR_OUT_OF_RANGE;
break;
}
OCSP_REQUEST* ocsp_request = request_impl->GetOCSP_REQUEST();
STACK_OF(X509)* x509_chain = chain_impl->GetStackOfX509();
X509_STORE* x509_store = storage_impl->GetX509Store();
OP_ASSERT(ocsp_request && x509_chain && x509_store);
// Both ocsp_request, x509_chain and x509_store are owned
// by their container objects.
// Temporary variable, according to the documentation.
const unsigned char* response_tmp = m_response_der;
ocsp_response = d2i_OCSP_RESPONSE(0, &response_tmp, m_response_length);
OPENSSL_VERIFY_OR_BREAK2(ocsp_response, status);
// Check that the OCSP responder was able to respond correctly.
int ocsp_response_status = OCSP_response_status(ocsp_response);
OPENSSL_BREAK2_IF(ocsp_response_status != OCSP_RESPONSE_STATUS_SUCCESSFUL, status);
ocsp_basicresp = OCSP_response_get1_basic(ocsp_response);
OPENSSL_VERIFY_OR_BREAK2(ocsp_basicresp, status);
// Verify that the response is correctly signed.
int response_valid_status =
OCSP_basic_verify(ocsp_basicresp, x509_chain, x509_store, /* flags = */ 0);
OPENSSL_BREAK2_IF(response_valid_status != 1, status);
OP_ASSERT(ocsp_request->tbsRequest && ocsp_request->tbsRequest->requestList);
OCSP_ONEREQ* ocsp_onereq =
sk_OCSP_ONEREQ_value(ocsp_request->tbsRequest->requestList, 0);
OPENSSL_VERIFY_OR_BREAK(ocsp_onereq);
// ocsp_request owns ocsp_onereq.
OCSP_CERTID* ocsp_certid = ocsp_onereq->reqCert;
OPENSSL_VERIFY_OR_BREAK(ocsp_certid);
// ocsp_request owns ocsp_certid.
int revocation_code = -1, response_code = -1;
ASN1_GENERALIZEDTIME* thisupd = 0;
ASN1_GENERALIZEDTIME* nextupd = 0;
int err = OCSP_resp_find_status(
ocsp_basicresp, ocsp_certid, &response_code, &revocation_code,
0, &thisupd, &nextupd);
OPENSSL_BREAK2_IF(err != 1 || response_code < 0, status);
// Allow some difference in client and server clocks.
const long int CLOCK_SHARPNESS = 3600;
// Default age limit for responses without nextUpdate field.
const long int DEFAULT_MAXAGE = 100 * 24 * 3600;
err = OCSP_check_validity(thisupd, nextupd, CLOCK_SHARPNESS, DEFAULT_MAXAGE);
OPENSSL_BREAK2_IF(err != 1, status);
switch (response_code)
{
case V_OCSP_CERTSTATUS_GOOD:
m_verify_status = CryptoCertificateChain::OK_CHECKED_WITH_OCSP;
status = OpStatus::OK;
break;
case V_OCSP_CERTSTATUS_REVOKED:
m_verify_status = CryptoCertificateChain::CERTIFICATE_REVOKED;
status = OpStatus::OK;
break;
default:
OP_ASSERT(!"Unexpected OCSP response code!");
// fall-through
case V_OCSP_CERTSTATUS_UNKNOWN:
OP_ASSERT(m_verify_status == CryptoCertificateChain::VERIFY_STATUS_UNKNOWN);
break;
}
} while(0);
if(ocsp_basicresp)
OCSP_BASICRESP_free(ocsp_basicresp);
if(ocsp_response)
OCSP_RESPONSE_free(ocsp_response);
// There shouldn't be any errors.
OP_ASSERT(ERR_peek_error() == 0);
LEAVE_IF_ERROR(status);
}
CryptoCertificateChain::VerifyStatus
OCSPResponseVerifier_impl::GetVerifyStatus() const
{
return m_verify_status;
}
#endif // defined(CRYPTO_OCSP_SUPPORT) && defined(CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION)
|
//MilesEstimator.h
class MilesEstimator
{
public:
virtual int getMilesLeft() {
return (getMilesPerGallon()*getGallonsLeft());
}
virtual void setGallonsLeft(int inValue) {mGallonsLeft=inValue;}
virtual int getGallonsLeft() {return mGallonsLeft;}
private:
int mGallonsLeft;
virtual int getMilesPerGallon() {return 20;}
};
MilesEstimator myMilesEstimator;
myMilesEstimator.setGallonsLeft(2);
cout<<"I can go "<<myMilesEstimator.getMilesLeft()<<" more miles. "<<endl;
class EfficientCarMilesEstimator : public MilesEstimator
{
private:
virtual int getMilesPerGallon() {return 35;}
};
EfficientCarMilesEstimator myEstimator;
myEstimator.setGallonsLeft(2);
cout<<"I can go "<<myEstimator.getMilesLeft()<<" more miles. "<<endl;
|
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <map>
typedef long long LL;
typedef unsigned long long ULL;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
char word[2222];
int n;
pair<LL, LL> words[2222];
LL p29[2222], p31[2222], st1[2222], st2[2222], fin1[2222], fin2[2222];
char s[2222][2222];
int h, w, stdot[2222], findot[2222];
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
scanf("%d\n", &n);
for (int i = 0; i < n; i++) {
gets(word);
LL h1 = 0, h2 = 0;
for (int j = 0; word[j]; j++) {
h1 = h1 * 29 + word[j] - 'a' + 1;
h2 = (h2 * 31 + word[j] - 'a' + 1) % 1000000007;
}
words[i] = make_pair(h1, h2);
}
sort(words, words + n);
p29[0] = 1;
p31[0] = 1;
for (int i = 1; i <= 2000; i++) {
p29[i] = p29[i - 1] * 29;
p31[i] = (p31[i - 1] * 31) % 1000000007;
}
scanf("%d\n", &h);
for (int i = 0; i < h; i++) {
gets(s[i]);
w = strlen(s[0]);
char * ss = s[i];
if (ss[0] == '.') stdot[i] = true; else {
st1[i] = st2[i] = 0;
for (int j = 0; ss[j] != '.'; j++) {
st1[i] = st1[i] * 29 + ss[j] - 'a' + 1;
st2[i] = (st2[i] * 31 + ss[j] - 'a' + 1) % 1000000007;
}
}
if (ss[w - 1] == '.') findot[i] = true; else {
fin1[i] = fin2[i] = 0;
for (int j = w - 1, p = 0; ss[j] != '.'; j--, p++) {
fin1[i] += (ss[j] - 'a' + 1) * p29[p];
fin2[i] = (fin2[i] + (ss[j] - 'a' + 1) * p31[p]) % 1000000007;
}
}
}
for (int dw = 0; dw < w; dw++) {
if ( !Good(st1[0], st2[0]) ) continue;
bool good = true;
for (int i = 1; i < h; i++) {
LL h1 = fin1[i - 1] * p29[]
}
}
return 0;
}
|
//
// Created by JACK on 11/9/2015.
//
#include "Institution.h"
Institution::Institution(const string& size):
size(size) { }
Institution& Institution::operator=(const Institution& obj) {
if(this == &obj) {
return *this;
}
size = obj.size;
return *this;
}
Institution::~Institution() {
size = "";
}
|
#include<iostream>
#include<string>
#include"person.h"
using namespace std;
#ifndef CHILD_H
#define CHILD_H
class Employee;
class Child : public Person {
private:
string favoriteToy;
Employee *emp;
public:
Child();
Child(string pname, string pssnum, int page, string favToy);
~Child();
string getFavoriteToy();
Employee * getEmployee();
void setFavoriteToy(string favToy);
void setEmployee(Employee * e);
};
Child :: Child(){
favoriteToy = " ";
}
Child :: Child(string pname, string pssnum, int page, string favToy)
: Person(pname, pssnum, page){
favoriteToy = favToy;
}
Child :: ~Child(){
}
string Child :: getFavoriteToy(){
return favoriteToy;
}
Employee * Child :: getEmployee(){
return emp;
}
void Child :: setFavoriteToy (string favToy){
favoriteToy = favToy;
}
void Child :: setEmployee(Employee * e){
emp = e;
}
#endif
|
//Copyright 2021 by Winter Solider
#include "Student.hpp"
#include <iomanip>
#include <utility>
auto get_name(const json& j) -> std::string;
auto get_debt(const json& j) -> std::any;
auto get_avg(const json& j) -> std::any;
auto get_group(const json& j) -> std::any;
Student::Student(std::string _name, std::any _group,
std::any _avg, std::any _debt) {
name = std::move(_name);
group = std::move(_group);
avg = std::move(_avg);
debt = std::move(_debt);
}
bool anyDate(std::any a1, std::any a2)
{
if (a1.type() != a2.type())
return false;
if (a1.type() == typeid(std::string))
return std::any_cast<std::string>(a1)== std::any_cast<std::string>(a2);
if (a1.type() == typeid(nullptr))
return true;
if (a1.type() == typeid(double))
return std::any_cast<double>(a1) == std::any_cast<double>(a2);
if (a1.type() == typeid(size_t))
return std::any_cast<size_t>(a1) == std::any_cast<size_t>(a2);
if (a1.type() == typeid(std::vector<std::string>))
return
std::any_cast<std::vector<std::string>>(a1)
== std::any_cast<std::vector<std::string>>(a2);
return false;
}
bool Student::operator==(const Student& student) const
{
bool n = name == student.name;
bool g = anyDate(group, student.group);
bool a = anyDate(avg, student.avg);
bool d = anyDate(debt, student.debt);
return n && g && a && d;
}
void parse_JSON(const json& j, Student& s) {
s.name = get_name(j.at("name"));
s.group = get_group(j.at("group"));
s.avg = get_avg(j.at("avg"));
s.debt = get_debt(j.at("debt"));
}
|
// Copyright 2017 Google Inc. All rights reserved.
//
// 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 "FirebaseDatabaseScene.h"
#include <stdarg.h>
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <android/log.h>
#include <jni.h>
#include "platform/android/jni/JniHelper.h"
#endif
#include "FirebaseCocos.h"
#include "firebase/auth.h"
#include "firebase/database.h"
#include "firebase/future.h"
USING_NS_CC;
/// Padding for the UI elements.
static const float kUIElementPadding = 10.0;
/// Placeholder labels for the text fields.
static const char* kKeyPlaceholderText = "Key";
static const char* kValuePlaceholderText = "Value";
static const char* kTestAppData = "test_app_data";
static void logDataSnapshot(FirebaseDatabaseScene* scene,
const firebase::database::DataSnapshot& snapshot) {
const firebase::Variant& value_variant = snapshot.value();
const char* key = snapshot.key();
switch (value_variant.type()) {
case firebase::Variant::kTypeNull: {
scene->logMessage("key: `%s`, value: null", key);
break;
}
case firebase::Variant::kTypeInt64: {
int64_t value = value_variant.int64_value();
scene->logMessage("key: \"%s\", value: %lli", key, value);
break;
}
case firebase::Variant::kTypeDouble: {
double value = value_variant.double_value();
scene->logMessage("key: \"%s\", value: %f", key, value);
break;
}
case firebase::Variant::kTypeBool: {
bool value = value_variant.bool_value();
scene->logMessage("key: \"%s\", value: %s", key,
value ? "true" : "false");
break;
}
case firebase::Variant::kTypeMutableString:
case firebase::Variant::kTypeStaticString: {
const char* value = value_variant.string_value();
scene->logMessage("key: \"%s\", value: \"%s\"", key,
value ? value : "<null>");
break;
}
default: {
scene->logMessage("ERROR: This sample only supports scalar variants.");
}
}
}
// An example of a ValueListener object. This specific version will
// simply log every value it sees, and store them in a list so we can
// confirm that all values were received.
class SampleValueListener : public firebase::database::ValueListener {
public:
SampleValueListener(FirebaseDatabaseScene* scene) : scene_(scene) {};
void OnValueChanged(
const firebase::database::DataSnapshot& snapshot) override {
scene_->logMessage("ValueListener::OnValueChanged");
logDataSnapshot(scene_, snapshot);
}
void OnCancelled(const firebase::database::Error& error_code,
const char* error_message) override {
scene_->logMessage("ERROR: SampleValueListener canceled: %d: %s",
error_code, error_message);
}
private:
FirebaseDatabaseScene* scene_;
};
/// Creates the Firebase scene.
Scene* CreateFirebaseScene() {
return FirebaseDatabaseScene::createScene();
}
/// Creates the FirebaseDatabaseScene.
Scene* FirebaseDatabaseScene::createScene() {
// Create the scene.
auto scene = Scene::create();
// Create the layer.
auto layer = FirebaseDatabaseScene::create();
// Add the layer to the scene.
scene->addChild(layer);
return scene;
}
/// Initializes the FirebaseScene.
bool FirebaseDatabaseScene::init() {
if (!Layer::init()) {
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
cocos2d::Vec2 origin = Director::getInstance()->getVisibleOrigin();
// Create the Firebase label.
auto firebaseLabel =
Label::createWithTTF("Firebase Database", "fonts/Marker Felt.ttf", 20);
nextYPosition =
origin.y + visibleSize.height - firebaseLabel->getContentSize().height;
firebaseLabel->setPosition(
cocos2d::Vec2(origin.x + visibleSize.width / 2, nextYPosition));
this->addChild(firebaseLabel, 1);
const float scrollViewYPosition = nextYPosition -
firebaseLabel->getContentSize().height -
kUIElementPadding * 2;
// Create the ScrollView on the Cocos2d thread.
cocos2d::Director::getInstance()
->getScheduler()
->performFunctionInCocosThread(
[=]() { this->createScrollView(scrollViewYPosition); });
// Use ModuleInitializer to initialize both Auth and Database, ensuring no
// dependencies are missing.
void* initialize_targets[] = {&auth_, &database_};
CCLOG("Initializing the Database with Firebase API.");
const firebase::ModuleInitializer::InitializerFn initializers[] = {
[](firebase::App* app, void* data) {
// this->logMessage("Attempt to initialize Firebase Auth.");
void** targets = reinterpret_cast<void**>(data);
firebase::InitResult result;
*reinterpret_cast<firebase::auth::Auth**>(targets[0]) =
firebase::auth::Auth::GetAuth(app, &result);
return result;
},
[](firebase::App* app, void* data) {
// this->logMessage("Attempt to initialize Firebase Database.");
void** targets = reinterpret_cast<void**>(data);
firebase::InitResult result;
*reinterpret_cast<firebase::database::Database**>(targets[1]) =
firebase::database::Database::GetInstance(app, &result);
return result;
}};
// There are two ways to track long running operations: (1) retrieve the
// future using a LastResult function or (2) Cache the future manually.
//
// Here we use method 1: the future is not cached but will be later retrieved
// using SetValueLastResult. Which method is best for your app depends on
// your use case.
initializer_.Initialize(
firebase::App::GetInstance(), initialize_targets, initializers,
sizeof(initializers) / sizeof(initializers[0]));
logMessage("Created the Database %x class for the Firebase app.",
static_cast<int>(reinterpret_cast<intptr_t>(database_)));
key_text_field_ = createTextField(kKeyPlaceholderText);
this->addChild(key_text_field_);
value_text_field_ = createTextField(kValuePlaceholderText);
this->addChild(value_text_field_);
add_listener_button_ = createButton(false, "Add Listener");
add_listener_button_->addTouchEventListener(
[this](Ref* /*sender*/, cocos2d::ui::Widget::TouchEventType type) {
switch (type) {
case cocos2d::ui::Widget::TouchEventType::ENDED: {
const char* key = key_text_field_->getString().c_str();
firebase::database::DatabaseReference reference =
this->database_->GetReference(kTestAppData).Child(key);
this->logMessage("Adding ValueListener to key `%s`.", key);
// The SampleValueListener will respond to changes in this entry's
// value. Changes can be made by other instances of this sample app
// or in the Firebase Console.
reference.AddValueListener(new SampleValueListener(this));
break;
}
default: {
break;
}
}
});
this->addChild(add_listener_button_);
query_button_ = createButton(false, "Query");
query_button_->addTouchEventListener(
[this](Ref* /*sender*/, cocos2d::ui::Widget::TouchEventType type) {
switch (type) {
case cocos2d::ui::Widget::TouchEventType::ENDED: {
const char* key = key_text_field_->getString().c_str();
firebase::database::DatabaseReference reference =
this->database_->GetReference(kTestAppData).Child(key);
this->logMessage("Querying key `%s`.", key);
// There are two ways to track long running operations:
// (1) retrieve the future using a LastResult function or (2) Cache
// the future manually.
//
// Here (and below in the set_button_) we use method 2: caching the
// future. Which method is best for your app depends on your use
// case.
query_future_ = reference.GetValue();
this->query_button_->setEnabled(false);
this->set_button_->setEnabled(false);
break;
}
default: {
break;
}
}
});
this->addChild(query_button_);
set_button_ = createButton(false, "Set");
set_button_->addTouchEventListener(
[this](Ref* /*sender*/, cocos2d::ui::Widget::TouchEventType type) {
switch (type) {
case cocos2d::ui::Widget::TouchEventType::ENDED: {
const char* key = key_text_field_->getString().c_str();
const char* value = value_text_field_->getString().c_str();
firebase::database::DatabaseReference reference =
this->database_->GetReference(kTestAppData).Child(key);
this->logMessage("Setting key `%s` to `%s`.", key, value);
this->set_future_ = reference.SetValue(value);
this->query_button_->setEnabled(false);
this->set_button_->setEnabled(false);
break;
}
default: {
break;
}
}
});
this->addChild(set_button_);
// Create the close app menu item.
auto closeAppItem = MenuItemImage::create(
"CloseNormal.png", "CloseSelected.png",
CC_CALLBACK_1(FirebaseScene::menuCloseAppCallback, this));
closeAppItem->setContentSize(cocos2d::Size(25, 25));
// Position the close app menu item on the top-right corner of the screen.
closeAppItem->setPosition(cocos2d::Vec2(
origin.x + visibleSize.width - closeAppItem->getContentSize().width / 2,
origin.y + visibleSize.height -
closeAppItem->getContentSize().height / 2));
// Create the Menu for touch handling.
auto menu = Menu::create(closeAppItem, NULL);
menu->setPosition(cocos2d::Vec2::ZERO);
this->addChild(menu, 1);
state_ = kStateInitialize;
// Schedule the update method for this scene.
this->scheduleUpdate();
return true;
}
FirebaseDatabaseScene::State FirebaseDatabaseScene::updateInitialize() {
firebase::Future<void> initialize_future =
initializer_.InitializeLastResult();
if (initialize_future.status() != firebase::kFutureStatusComplete) {
return kStateInitialize;
}
if (initialize_future.error() != 0) {
logMessage("Failed to initialize Firebase libraries: %s",
initialize_future.error_message());
return kStateRun;
}
logMessage("Successfully initialized Firebase Auth and Firebase Database.");
auth_->SignInAnonymously();
return kStateLogin;
}
FirebaseDatabaseScene::State FirebaseDatabaseScene::updateLogin() {
// Sign in using Auth before accessing the database.
//
// The default Database permissions allow anonymous user access. However,
// Firebase Auth does not allow anonymous user login by default. This setting
// can be changed in the Auth settings page for your project in the Firebase
// Console under the "Sign-In Method" tab.
firebase::Future<firebase::auth::User*> sign_in_future =
auth_->SignInAnonymouslyLastResult();
if (sign_in_future.status() != firebase::kFutureStatusComplete) {
return kStateLogin;
}
if (sign_in_future.error() != firebase::auth::kAuthErrorNone) {
logMessage("ERROR: Could not sign in anonymously. Error %d: %s",
sign_in_future.error(), sign_in_future.error_message());
logMessage(
"Ensure your application has the Anonymous sign-in provider enabled in "
"the Firebase Console.");
return kStateRun;
}
logMessage("Auth: Signed in anonymously.");
add_listener_button_->setEnabled(true);
query_button_->setEnabled(true);
set_button_->setEnabled(true);
return kStateRun;
}
FirebaseDatabaseScene::State FirebaseDatabaseScene::updateRun() {
if (query_future_.status() == firebase::kFutureStatusComplete) {
if (query_future_.error() == firebase::database::kErrorNone) {
logMessage("Query complete");
const firebase::database::DataSnapshot* snapshot = query_future_.result();
logDataSnapshot(this, *snapshot);
} else {
logMessage("ERROR: Could not query value. Error %d: %s",
query_future_.error(), query_future_.error_message());
}
query_button_->setEnabled(true);
set_button_->setEnabled(true);
query_future_.Release();
}
if (set_future_.status() == firebase::kFutureStatusComplete) {
if (set_future_.error() == firebase::database::kErrorNone) {
logMessage("Database updated.");
} else {
logMessage("ERROR: Could not set value. Error %d: %s",
set_future_.error(), set_future_.error_message());
}
query_button_->setEnabled(true);
set_button_->setEnabled(true);
set_future_.Release();
}
return kStateRun;
}
// Called automatically every frame. The update is scheduled in `init()`.
void FirebaseDatabaseScene::update(float /*delta*/) {
switch (state_) {
case kStateInitialize: state_ = updateInitialize(); break;
case kStateLogin: state_ = updateLogin(); break;
case kStateRun: state_ = updateRun(); break;
default: assert(0);
}
}
/// Handles the user tapping on the close app menu item.
void FirebaseDatabaseScene::menuCloseAppCallback(Ref* pSender) {
CCLOG("Cleaning up Database C++ resources.");
// Close the cocos2d-x game scene and quit the application.
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
|
#include <iostream>
#include <string>
class bad_range {};
class some_other {
public:
explicit some_other(int x) {}
};
class tiny {
private:
char v;
void assign(int i) { if (i & ~077) throw bad_range(); v=i; }
public:
tiny(int i) { assign(i); }
tiny& operator=(int i) { assign(i); return *this; }
explicit operator int() const { return v; }
};
class X {
public:
X(int x) : x{x} {}
int x;
};
class Y {
private:
int x;
public:
explicit Y(int x) : x{x} {}
operator X() const { return X(x); }
};
void test_conversion(X const& x) { std::cout << "x = " << x.x << std::endl; }
int main() {
tiny t1{1};
tiny t2{63};
tiny t3{10};
//std::cout << "i = " << i << std::endl;
some_other o1{1};
some_other o2{static_cast<int>(t1)};
int x{t1};
Y y{5};
test_conversion(y);
}
|
#include <iostream>
#include <set>
#include <map>
void test_set() {
std::set<int> values;
for(unsigned int i=0; i<10; i++)
values.insert(i*10);
auto [it, was_inserted] = values.insert(20);
if (was_inserted)
std::cout << "element 20 has been inserted\n";
else {
std::cout << "element 20 already exists\n";
}
}
void test_map() {
std::map<std::string, int> values;
for (unsigned int i=0; i<10; i++)
values.insert({std::to_string(i), i});
auto [it, was_inserted] = values.insert({std::to_string(5), 5});
if (was_inserted)
std::cout << "new element 5 has been inserted\n";
else
std::cout << "element 5 already exists\n";
}
int main() {
test_set();
test_map();
return 0;
}
|
// Copyright Sascha Ochsenknecht 2009.
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/program_options/config.hpp>
#include <pika/program_options/parsers.hpp>
#include <boost/tokenizer.hpp>
#include <string>
#include <vector>
namespace pika::program_options::detail {
template <class Char>
std::vector<std::basic_string<Char>>
split_unix(const std::basic_string<Char>& cmdline, const std::basic_string<Char>& separator,
const std::basic_string<Char>& quote, const std::basic_string<Char>& escape)
{
using tokenizerT = boost::tokenizer<boost::escaped_list_separator<Char>,
typename std::basic_string<Char>::const_iterator, std::basic_string<Char>>;
tokenizerT tok(cmdline.begin(), cmdline.end(),
boost::escaped_list_separator<Char>(escape, separator, quote));
std::vector<std::basic_string<Char>> result;
for (typename tokenizerT::iterator cur_token(tok.begin()), end_token(tok.end());
cur_token != end_token; ++cur_token)
{
if (!cur_token->empty()) result.push_back(*cur_token);
}
return result;
}
} // namespace pika::program_options::detail
namespace pika::program_options {
// Take a command line string and splits in into tokens, according
// to the given collection of separators chars.
std::vector<std::string> split_unix(const std::string& cmdline, const std::string& separator,
const std::string& quote, const std::string& escape)
{
return detail::split_unix<char>(cmdline, separator, quote, escape);
}
std::vector<std::wstring> split_unix(const std::wstring& cmdline, const std::wstring& separator,
const std::wstring& quote, const std::wstring& escape)
{
return detail::split_unix<wchar_t>(cmdline, separator, quote, escape);
}
} // namespace pika::program_options
|
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define NUM_MAX_LEN 20
using namespace std;
bool check_init_input(int args, char ** argv){
if(args != 2){
printf("Wrong number of arguments!\n");
return false;
}
return true;
}
FILE * read_file(FILE * fp, char * file_name){
if(!(fp = fopen(file_name, "r")))
printf("Failed to open or file doesn't exit!\n");
return fp;
}
double get_average(FILE * fp){
int num = 0;
double sum = 0.0, temp = 0.0;
char in[NUM_MAX_LEN+1] = {0}, *pEnd = nullptr;
while(!feof(fp)){
memset(in, 0, sizeof(in));
fgets(in, sizeof(in)-1,fp);
if (in[0]<48 || in[0]>57){
printf("Ignore one line!\n");
continue;
}
temp = strtod(in,&pEnd);
if (pEnd[0] == '\0'||pEnd[0] == '\n'){
sum += temp;
num++;
} else {
printf("Special character in one line, ignore.\n");
}
}
pEnd = nullptr;
return num?sum/num:0;
}
int main(int args, char ** argv){
if(!check_init_input(args, argv)) return 1;
double * array = nullptr;
char * file_name = argv[1];
FILE * fp;
file_name = argv[1];
if(!(fp = read_file(fp, file_name))) return 1;
printf("The average in file '%s' is %lf\n",argv[1], get_average(fp));
fclose(fp);
return 0;
}
|
#pragma once
#include "imgui/imgui.h"
#include "rttr/type.h"
struct GLFWwindow;
namespace studio
{
class ImGuiView
{
public:
ImGuiView(GLFWwindow *window);
virtual ~ImGuiView() = default;
virtual void onInit() {}
virtual void onRender() {}
GLFWwindow *getWindow() const { return m_window; }
private:
void beginFrame();
void endFrame();
GLFWwindow *m_window;
friend class ImGuiHelper;
};
class ImGuiHelper
{
public:
static void render(ImGuiView *view);
static int run(ImGuiView *view);
static void enableRender(bool b);
};
class ImGuiWidget
{
public:
static void showPropertyEditor(rttr::variant obj, bool *open = nullptr);
};
}
|
#ifndef SHADERLOADER_H
#define SHADERLOADER_H
#include <string>
#include <GL/glew.h>
GLuint loadShader(const std::string &vertexShader, const std::string &fragmentShader);
#endif // SHADERLOADER_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
* psmaas - Patricia Aas
*/
#ifndef LEX_SPLAY_KEY_H
#define LEX_SPLAY_KEY_H
//#define HISTORY_DEBUG
#ifdef HISTORY_SUPPORT
class LexSplayKey
{
public :
/**
@return pointer to start of key buffer
*/
virtual const uni_char * GetKey() const = 0;
/**
*/
LexSplayKey();
/**
*/
virtual ~LexSplayKey() {}
/**
Decrements the reference counter
*/
void Decrement();
/**
Increments the reference counter
*/
void Increment();
/**
@return TRUE if the address is still in use
*/
BOOL InUse();
#ifdef HISTORY_DEBUG
INT NumberOfReferences() { return m_ref_counter; }
#endif //HISTORY_DEBUG
private:
INT m_ref_counter;
};
#endif // HISTORY_SUPPORT
#endif // LEX_SPLAY_KEY_H
|
#pragma once
#include <string>
class DResource
{
protected:
std::string m_name;
public:
DResource(std::string name);
virtual ~DResource();
virtual void Load(std::string file);
virtual void Release();
virtual void Draw() {}
};
#define SAFE_DELETE(p) { if(p) delete (p); (p) = NULL; }
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2009 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef BTStartDownloadDialog_H
#define BTStartDownloadDialog_H
#include "adjunct/quick_toolkit/widgets/Dialog.h"
#include "adjunct/quick/dialogs/SimpleDialog.h"
class BTInfo;
class BTDownloadInfo
{
public:
BTDownloadInfo() :
btinfo(NULL)
{}
OpString savepath;
OpString loadpath;
BTInfo* btinfo;
URL url;
};
class BTStartDownloadDialog : public Dialog
{
public:
BTStartDownloadDialog();
virtual ~BTStartDownloadDialog();
OP_STATUS Init(DesktopWindow* parent_window, BTDownloadInfo *info, INT32 start_page = 0);
Type GetType() {return DIALOG_TYPE_BITTORRENT_STARTDOWNLOAD;}
DialogType GetDialogType() {return TYPE_YES_NO;}
const char* GetWindowName() {return "BitTorrent Start Download Dialog";}
const char* GetHelpAnchor() {return "bittorrent.html";}
DialogImage GetDialogImageByEnum() {return IMAGE_WARNING;}
void OnInit();
void OnCancel();
UINT32 OnOk();
BOOL OnInputAction(OpInputAction *action);
private:
BTDownloadInfo *m_info;
};
#endif // BTStartDownloadDialog_H
|
#ifndef _SYLVESTER_MATRIX_
#define _SYLVESTER_MATRIX_
#include "BivariatePolynomial.h"
#include "Polynomial.h"
#include "Matrix.h"
#include "ChangeOfVariableCoefficients.h"
class SylvesterMatrix
{
unsigned int RowDimension, ColDimension;
unsigned int d0,d1;
int hiddenDeg;
Polynomial *** matrix;
char hiddenVariable;
void assignXCol(BivariatePolynomial * Bp, int power, double * & resultM);
void assignYRow(BivariatePolynomial * Bp, int row, double * & resultM);
void initMatrixWithHiddenX(BivariatePolynomial * Bp1, BivariatePolynomial * Bp2);
void initMatrixWithHiddenY(BivariatePolynomial * Bp1, BivariatePolynomial * Bp2);
void cleanPowerUps(Polynomial **&, int);
public:
ChangeOfVariableCoefficients * coefs;
static bool initPowerUps(Polynomial **& , double * , int, int);
ChangeOfVariableCoefficients * getCoefs()
{
return this->coefs;
}
int getHiddenDeg()
{
return hiddenDeg;
}
unsigned int getRowDimension()
{
return RowDimension;
}
unsigned int getColDimension()
{
return ColDimension;
}
char getHiddenVariable()
{
return hiddenVariable;
}
Polynomial *** getMatrix()
{
return this->matrix;
}
int max(int, int);
SylvesterMatrix(BivariatePolynomial * Bp1, BivariatePolynomial * Bp2);
SylvesterMatrix(Polynomial ***, unsigned int, unsigned int);
SylvesterMatrix(SylvesterMatrix & SM);
bool changeOfVariableBody();
void allocMatrix();
bool changeOfVariable();
void Print();
void multiply(MyMatrix * m, SylvesterMatrix*& result);
int getMatrixRowMaxDegree(int Row);
void assignZero(int deg, double *& temp);
void getRandom(int &);
~SylvesterMatrix();
};
#endif
|
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& nums) {
int even =0;
for(int i=0; i<nums.size(); i++){
if(nums[i]%2==0){
swap(nums[i], nums[even]);
even++;
}
}
return nums;
}
};
|
#include "function.h"
int makeProcess(Process_data *pArr)
{
int fds[2];
for (int i = 0; i < PROCESSNUM; i++)
{
int ret = socketpair(AF_LOCAL, SOCK_STREAM, 0, fds);
ERROR_CHECK(ret, -1, "socketpair");
pid_t pid = fork();
if (pid == 0)
{
close(fds[0]);
doingTask(fds[1]);
}
else
{
close(fds[1]);
Process_data child;
child.pid = pid;
child.fd = fds[0];
child.busy = false;
pArr[i] = child;
}
}
return 0;
}
void doingTask(int fd)
{
while (1)
{
int newfd;
recvFd(fd, &newfd);
tranFile(newfd);
bool busy = false;
send(fd, &busy, 1, 0);//发送一个标识消息,告诉主进程,自己不忙了
}
}
|
#ifndef BOARD_H
#define BOARD_H
#include "board.h"
#include "board_normal.h"
#include "board_torus.h"
#include "board_mirror.h"
#endif
#include<iostream>
using namespace std;
namespace hw2{
class game{
public:
void initializeGame();
void handleUpdateBoard();
void handlePrintBoard();
void runGame1();
void runGame2();
void runGame3();
void runGame();
bool fromInput;
int output_mode, board_type;
int rows, columns;
int inputi;
float inputf;
float newDensity;
char inputc;
board default_board;
board_normal board1;
board_mirror board2;
board_torus board3;
};
}
|
#include<bits/stdc++.h>
using namespace std;
main()
{
char s[500];
while(cin>>s)
{
int i, count=0;
for(i=0; s[i]!='\0'; i++)
{
if(s[i]=='4'||s[i]=='7')
count++;
}
if(count==4 ||count==7)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}
|
#pragma once
#include <memory>
#include <utility>
#include <glad\glad.h>
#include "GLFW\glfw3.h"
#include "glm\glm.hpp"
#include "glm\gtc\matrix_transform.hpp"
#include "Test.h"
#include "VertexArray.h"
#include "VertexBuffer.h"
#include "Shader.h"
#include "Texture.h"
#include "CubeMap.h"
#include "Camera.h"
#include "FrameBuffer.h"
#include "Model.h"
namespace test {
class TestCubeMap : public Test
{
public:
TestCubeMap();
virtual ~TestCubeMap();
void OnUpdate(float deltaTime) override;
void OnRender() override;
void OnImGuiRender() override;
private:
std::unique_ptr<VertexArray> m_SkyboxVAO;
std::unique_ptr<VertexBuffer> m_SkyboxVBO;
std::unique_ptr<Shader> m_SkyboxShader;
std::unique_ptr<Shader> m_ModelShader;
std::unique_ptr<CubeMap> m_SkyboxTexture;
obj::Model* loadModel;
glm::mat4 m_Model;
glm::mat4 m_View;
glm::mat4 m_Proj/* = glm::perspective(glm::radians(45.0f), 1024.0f / 768.0f, 0.1f, 100.0f)*/;
glm::vec3 objPosition = glm::vec3(1.0f, 1.0f, 1.0f);
Camera camera;
std::unique_ptr<VertexArray> m_CubeVAO;
std::unique_ptr<VertexBuffer> m_CubeVBO;
};
}
|
/*********************************************************\
* Copyright (c) 2012-2018 The Unrimp Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\*********************************************************/
//[-------------------------------------------------------]
//[ Header guard ]
//[-------------------------------------------------------]
#pragma once
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "Renderer/RenderTarget/IRenderTarget.h"
//[-------------------------------------------------------]
//[ Forward declarations ]
//[-------------------------------------------------------]
namespace Renderer
{
class ITexture;
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace Renderer
{
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
struct FramebufferAttachment final
{
ITexture* texture;
uint32_t mipmapIndex;
uint32_t layerIndex; ///< "slice" in Direct3D terminology, depending on the texture type it's a 2D texture array layer, 3D texture slice or cube map face
inline FramebufferAttachment() :
texture(nullptr),
mipmapIndex(0),
layerIndex(0)
{
// Nothing here
}
inline FramebufferAttachment(ITexture* _texture, uint32_t _mipmapIndex = 0, uint32_t _layerIndex = 0) :
texture(_texture),
mipmapIndex(_mipmapIndex),
layerIndex(_layerIndex)
{
// Nothing here
}
};
/**
* @brief
* Abstract framebuffer (FBO) interface
*/
class IFramebuffer : public IRenderTarget
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Destructor
*/
inline virtual ~IFramebuffer() override;
//[-------------------------------------------------------]
//[ Protected methods ]
//[-------------------------------------------------------]
protected:
/**
* @brief
* Constructor
*
* @param[in] renderPass
* Render pass to use, the framebuffer a reference to the render pass
*/
inline explicit IFramebuffer(IRenderPass& renderPass);
explicit IFramebuffer(const IFramebuffer& source) = delete;
IFramebuffer& operator =(const IFramebuffer& source) = delete;
};
//[-------------------------------------------------------]
//[ Type definitions ]
//[-------------------------------------------------------]
typedef SmartRefCount<IFramebuffer> IFramebufferPtr;
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // Renderer
//[-------------------------------------------------------]
//[ Implementation ]
//[-------------------------------------------------------]
#include "Renderer/RenderTarget/IFramebuffer.inl"
|
#ifndef SHOEMANAGERDATACENTER_HPP
#define SHOEMANAGERDATACENTER_HPP
#include "shoemanagermodel_global.h"
//! 数据中心
class SHOEMANAGERMODELSHARED_EXPORT ShoeManagerDataCenter
{
public:
ShoeManagerDataCenter();
};
#endif // SHOEMANAGERDATACENTER_HPP
|
// $Id$
//
// Copyright (C) 2003-2008 Greg Landrum and Rational Discovery LLC
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#define NO_IMPORT_ARRAY
#define PY_ARRAY_UNIQUE_SYMBOL rdpicker_array_API
#include <boost/python.hpp>
#include <RDBoost/Wrap.h>
#include <boost/python/numeric.hpp>
#include "numpy/oldnumeric.h"
#include <map>
#include <DataStructs/BitVects.h>
#include <DataStructs/BitOps.h>
#include <SimDivPickers/DistPicker.h>
#include <SimDivPickers/MaxMinPicker.h>
#include <SimDivPickers/HierarchicalClusterPicker.h>
#include <iostream>
namespace python = boost::python;
namespace RDPickers {
// REVIEW: the poolSize can be pulled from the numeric array
RDKit::INT_VECT MaxMinPicks(MaxMinPicker *picker,
python::object distMat,
int poolSize,
int pickSize,
python::object firstPicks,
int seed) {
if(pickSize>=poolSize){
throw ValueErrorException("pickSize must be less than poolSize");
}
if (!PyArray_Check(distMat.ptr())){
throw ValueErrorException("distance mat argument must be a numpy matrix");
}
PyArrayObject *copy;
copy = (PyArrayObject *)PyArray_ContiguousFromObject(distMat.ptr(),
PyArray_DOUBLE, 1,1);
double *dMat = (double *)copy->data;
RDKit::INT_VECT firstPickVect;
for(unsigned int i=0;i<python::extract<unsigned int>(firstPicks.attr("__len__")());++i){
firstPickVect.push_back(python::extract<int>(firstPicks[i]));
}
RDKit::INT_VECT res=picker->pick(dMat, poolSize, pickSize,firstPickVect,seed);
Py_DECREF(copy);
return res;
}
class pyobjFunctor {
public:
pyobjFunctor(python::object obj,bool useCache) : dp_obj(obj), dp_cache(NULL) {
if(useCache) dp_cache= new std::map<std::pair<unsigned int,unsigned int>,double>();
}
~pyobjFunctor() {
delete dp_cache;
}
double operator()(unsigned int i,unsigned int j) {
double res;
std::pair<unsigned int ,unsigned int> idxPair(i,j);
if(dp_cache && dp_cache->count(idxPair)>0){
res = (*dp_cache)[idxPair];
} else {
res=python::extract<double>(dp_obj(i,j));
if(dp_cache)
(*dp_cache)[idxPair]=res;
}
return res;
}
private:
python::object dp_obj;
std::map<std::pair<unsigned int,unsigned int>,double> *dp_cache;
};
RDKit::INT_VECT LazyMaxMinPicks(MaxMinPicker *picker,
python::object distFunc,
int poolSize,
int pickSize,
python::object firstPicks,
int seed,
bool useCache) {
RDKit::INT_VECT firstPickVect;
for(unsigned int i=0;i<python::extract<unsigned int>(firstPicks.attr("__len__")());++i){
firstPickVect.push_back(python::extract<int>(firstPicks[i]));
}
RDKit::INT_VECT res;
pyobjFunctor functor(distFunc,useCache);
res=picker->lazyPick(functor, poolSize, pickSize,firstPickVect,seed);
return res;
}
// NOTE: TANIMOTO and DICE provably return the same results for the diversity picking
// this is still here just in case we ever later want to support other methods.
typedef enum {
TANIMOTO=1,
DICE
} DistanceMethod;
template <typename BV>
class pyBVFunctor {
public:
pyBVFunctor(const std::vector<const BV *> &obj,DistanceMethod method,bool useCache) : d_obj(obj), d_method(method), dp_cache(NULL) {
if(useCache) dp_cache = new std::map<std::pair<unsigned int,unsigned int>,double>();
}
~pyBVFunctor() {
delete dp_cache;
}
double operator()(unsigned int i,unsigned int j) {
double res=0.0;
std::pair<unsigned int ,unsigned int> idxPair(i,j);
if(dp_cache && dp_cache->count(idxPair)>0){
res = (*dp_cache)[idxPair];
} else {
switch(d_method){
case TANIMOTO:
res = 1.-TanimotoSimilarity(*d_obj[i],*d_obj[j]);
break;
case DICE:
res = 1.-DiceSimilarity(*d_obj[i],*d_obj[j]);
break;
default:
throw_value_error("unsupported similarity value");
}
if(dp_cache){
(*dp_cache)[idxPair]=res;
}
}
return res;
}
private:
const std::vector<const BV *> &d_obj;
DistanceMethod d_method;
std::map<std::pair<unsigned int,unsigned int>,double> *dp_cache;
};
RDKit::INT_VECT LazyVectorMaxMinPicks(MaxMinPicker *picker,
python::object objs,
int poolSize,
int pickSize,
python::object firstPicks,
int seed,
bool useCache
) {
std::vector<const ExplicitBitVect *> bvs(poolSize);
for(unsigned int i=0;i<poolSize;++i){
bvs[i]=python::extract<const ExplicitBitVect *>(objs[i]);
}
pyBVFunctor<ExplicitBitVect> functor(bvs,TANIMOTO,useCache);
RDKit::INT_VECT firstPickVect;
for(unsigned int i=0;i<python::extract<unsigned int>(firstPicks.attr("__len__")());++i){
firstPickVect.push_back(python::extract<int>(firstPicks[i]));
}
RDKit::INT_VECT res=picker->lazyPick(functor, poolSize, pickSize,firstPickVect,seed);
return res;
}
} // end of namespace RDPickers
struct MaxMin_wrap {
static void wrap() {
python::class_<RDPickers::MaxMinPicker>("MaxMinPicker",
"A class for diversity picking of items using the MaxMin Algorithm\n")
.def("Pick", RDPickers::MaxMinPicks,
(python::arg("self"),python::arg("distMat"),python::arg("poolSize"),
python::arg("pickSize"),python::arg("firstPicks")=python::tuple(),
python::arg("seed")=-1),
"Pick a subset of items from a pool of items using the MaxMin Algorithm\n"
"Ashton, M. et. al., Quant. Struct.-Act. Relat., 21 (2002), 598-604 \n\n"
"ARGUMENTS:\n"
" - distMat: 1D distance matrix (only the lower triangle elements)\n"
" - poolSize: number of items in the pool\n"
" - pickSize: number of items to pick from the pool\n"
" - firstPicks: (optional) the first items to be picked (seeds the list)\n"
" - seed: (optional) seed for the random number generator\n"
)
.def("LazyPick", RDPickers::LazyMaxMinPicks,
(python::arg("self"),python::arg("distFunc"),python::arg("poolSize"),
python::arg("pickSize"),python::arg("firstPicks")=python::tuple(),
python::arg("seed")=-1,python::arg("useCache")=true),
"Pick a subset of items from a pool of items using the MaxMin Algorithm\n"
"Ashton, M. et. al., Quant. Struct.-Act. Relat., 21 (2002), 598-604 \n"
"ARGUMENTS:\n\n"
" - distFunc: a function that should take two indices and return the\n"
" distance between those two points.\n"
" NOTE: the implementation caches distance values, so the\n"
" client code does not need to do so; indeed, it should not.\n"
" - poolSize: number of items in the pool\n"
" - pickSize: number of items to pick from the pool\n"
" - firstPicks: (optional) the first items to be picked (seeds the list)\n"
" - seed: (optional) seed for the random number generator\n"
" - useCache: (optional) toggles use of a cache for the distance calculation\n"
" This trades memory usage for speed.\n"
)
.def("LazyBitVectorPick", RDPickers::LazyVectorMaxMinPicks,
(python::arg("self"),python::arg("objects"),python::arg("poolSize"),
python::arg("pickSize"),python::arg("firstPicks")=python::tuple(),
python::arg("seed")=-1,
python::arg("useCache")=true),
"Pick a subset of items from a pool of bit vectors using the MaxMin Algorithm\n"
"Ashton, M. et. al., Quant. Struct.-Act. Relat., 21 (2002), 598-604 \n"
"ARGUMENTS:\n\n"
" - vectors: a sequence of the bit vectors that should be picked from.\n"
" - poolSize: number of items in the pool\n"
" - pickSize: number of items to pick from the pool\n"
" - firstPicks: (optional) the first items to be picked (seeds the list)\n"
" - seed: (optional) seed for the random number generator\n"
" - useCache: (optional) toggles use of a cache for the distance calculation\n"
" This trades memory usage for speed.\n"
)
;
};
};
void wrap_maxminpick() {
MaxMin_wrap::wrap();
}
|
#include "Stub.h"
#include <Arduino.h>
using namespace Codingfield::Brew::Sensors::Temperature;
Stub::Stub() {
}
Stub::~Stub() {
}
float Stub::Value() const {
return value;
}
void Stub::Update() {
//value = 20.0f + (random(-200,200) / 100.0f);
}
void Stub::SetValue(float v) {
value = v;
}
int32_t Stub::ErrorCounter() {
return 0;
}
int32_t Stub::RetryCounter() {
return 0;
}
bool Stub::IsReady() {
return true;
}
void Stub::Reset() {
}
void Stub::ResetCounters() {
}
|
/*
* GroupSession.h
*
* Created on: Jun 11, 2017
* Author: root
*/
#ifndef NETWORK_GROUPSESSION_H_
#define NETWORK_GROUPSESSION_H_
#include "Context.h"
#include <vector>
#include <map>
#include "../define.h"
#include "../Common.h"
#include "../Memory/MemAllocator.h"
using namespace std;
namespace CommBaseOut
{
/*
* 组连接
* 为解决单通道缓冲区满的问题
* 可以通过key来定制通道,如果没有定制,会按照默认的通道发送
*/
class GroupSession
#ifdef USE_MEMORY_POOL
: public MemoryBase
#endif
{
struct GroupSessionInfo
{
vector<int> channel; //组的channel
BYTE count; //组的成员数目
WORD slot; //轮
GroupSessionInfo():count(0),slot(0)
{
}
int GetChannel(int key)
{
int tSlot = key % channel.size();// % key;
// printf("\n++++++++++++++++++++slot=%d, channel=%d++++++++++++++\n", tSlot, channel[tSlot]);
return channel[tSlot];
}
bool DeleteChannel(int channelID)
{
vector<int>::iterator it = channel.begin();
for(; it!=channel.end(); ++it)
{
if(channelID == *it)
{
channel.erase(it);
break;
}
}
if(channel.size() <= 0)
return false;
return true;
}
};
public:
GroupSession(Context * c);
~GroupSession();
void DeleteGroupSession(int group, int channel);
int AddGroupSession(int type, int id, int channel, int count, bool &isSuccess);
int BindSession(int64 key, int group);
void UnBindSession(int64 key, int group);
private:
map<WORD, int> m_group;
map<int, GroupSessionInfo> m_groupChannel;
CRWLock m_groupLock;
Context * m_c;
};
}
#endif /* NETWORK_GROUPSESSION_H_ */
|
#include <iostream>
using namespace std;
char matrix[3][3] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
char symbol;
bool playerDidWin = false;
char symbols[2];
char winner;
//function to draw the grid for tic-tac-toe
void drawMatrix();
//function that prompts a user for their turn to enter a number on the grid
void playerPrompt();
//checks for any horizontal line wins
bool checkHorizontals();
//checks for any vertical column wins
bool checkVerticals();
//checks diagonal wins
bool checkDiagonals();
//loops through the grid to see if any three-in-a-row pattern is present
bool checkForWin();
//function to renew the grid with new values as and when entered by user
void updateGrid(int num);
//function to change the symbol between user turns
void changeSymbol();
//function to print out the winner at the end of the game
void announceWinner();
void drawMatrix(){
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
cout << matrix[i][j] << " ";
if(j<2){
cout << "| ";
}
}
cout << endl;
if(i<2){
cout << "--|---|--" << endl;
}
}
}
//how to add Player specificity?
void playerPrompt(){
int number;
cout << "Enter number on grid: " << endl;
cin >> number;
updateGrid(number);
//didWin(number);
}
bool checkHorizontals(){
//check the three rows;
for(int i = 0; i < 3; i++){
if((matrix[i][0] == matrix[i][1]) && (matrix[i][0] == matrix[i][2])){
winner = matrix[i][0];
return true;
}
}
return false;
}
bool checkVerticals(){
//check the three columns
for(int j= 0; j < 3; j++){
if((matrix[0][j] == matrix[1][j]) && (matrix[0][j] == matrix[2][j])){
winner = matrix[0][j];
return true;
}
}
return false;
}
bool checkDiagonals(){
//check first diagonal
if((matrix[0][0] == matrix[1][1]) && (matrix[0][0] == matrix[2][2])){
winner = matrix[0][0];
return true;
//check second diagonal
}else if((matrix[0][2] == matrix[1][1]) && (matrix[0][2] == matrix[2][0])){
winner = matrix[0][2];
return true;
}else{
return false;
}
}
//room for improvement in terms of more efficient code
bool checkForWin(){
bool horizontalCheck = checkHorizontals();
bool verticalCheck = checkVerticals();
bool diagCheck = checkDiagonals();
if(horizontalCheck == true){
return true;
}else if(verticalCheck == true){
return true;
}else if(diagCheck == true){
return true;
}//add another condition for exiting game?
else{
return false;
}
}
void updateGrid(int num){
//printf("\033c"); //command to clear screen
switch(num) {
case 1: if (matrix[0][0] == symbols[0] || matrix[0][0] == symbols[1]){
cout << "Can't overwrite a number, enter a new one" << endl;
changeSymbol();
}
else{
matrix[0][0] = symbol;
}
break;
case 2: if (matrix[0][1] == symbols[0] || matrix[0][1] == symbols[1]){
cout << "Can't overwrite a number, enter a new one" << endl;
changeSymbol();
}else{
matrix[0][1] = symbol;
}
break;
case 3: if (matrix[0][2] == symbols[0] || matrix[0][2] == symbols[1]){
cout << "Can't overwrite a number, enter a new one" << endl;
changeSymbol();
}else{
matrix[0][2] = symbol;
}
break;
case 4: if (matrix[1][0] == symbols[0] || matrix[1][0] == symbols[1]){
cout << "Can't overwrite a number, enter a new one" << endl;
changeSymbol();
}else{
matrix[1][0] = symbol;
}
break;
case 5: if (matrix[1][1] == symbols[0] || matrix[1][1] == symbols[1]){
cout << "Can't overwrite a number, enter a new one" << endl;
changeSymbol();
}else{
matrix[1][1] = symbol;
}
break;
case 6: if (matrix[1][2] == symbols[0] || matrix[1][2] == symbols[1]){
cout << "Can't overwrite a number, enter a new one" << endl;
changeSymbol();
}else{
matrix[1][2] = symbol;
}
break;
case 7: if (matrix[2][0] == symbols[0] || matrix[2][0] == symbols[1]){
cout << "Can't overwrite a number, enter a new one" << endl;
changeSymbol();
}else{
matrix[2][0] = symbol;
}
break;
case 8: if (matrix[2][1] == symbols[0] || matrix[2][1] == symbols[1]){
cout << "Can't overwrite a number, enter a new one" << endl;
changeSymbol();
}else {
matrix[2][1] = symbol;
}
break;
case 9: if (matrix[2][2] == symbols[0] || matrix[2][2] == symbols[1]){
cout << "Can't overwrite a number, enter a new one" << endl;
changeSymbol();
}else{
matrix[2][2] = symbol;
}
break;
default: cout << "Ending game..." << endl;
playerDidWin = true;
break;
}
system("clear");//clear the screen before re-drawing
drawMatrix();
}
void changeSymbol(){
if(symbol == symbols[0]){
symbol = symbols[1];
}else{
symbol = symbols[0];
}
}
void announceWinner(){
if(winner == symbols[0]){
cout << "Player 1 wins!" << endl;
}else if(winner == symbols[1]){
cout << "Player 2 wins!" << endl;
}else{
cout << "No winner. It's a tie!" << endl;
}
}
int main(){
drawMatrix();
cout << "Player 1, choose symbol: " << endl;
cin >> symbols[0];
cout << "Player 2, choose symbol: "<< endl;
cin >> symbols[1];
symbol = symbols[0];
int counter = 0;
while(!(playerDidWin == true) && (counter < 9)){
// printf("\033c"); //command to clear screen
playerPrompt();
changeSymbol();
playerDidWin = checkForWin();//prevents from exiting the game before
counter++;
}
announceWinner();
return 0;
}
/*
TODO:
1. Add specifics (Player 1 and Player 2) to each number prompt
2. Need to update exit code. Not working with checkForWin function
3. Back button for history of grid?
4. opengl?
5. Overwriting message not showing because screen keeps clearing after showing message
6. counter can increase to more than 9 in cases where player has
//entered numerous turns trying to overwrite an existing symbol
*/
|
/*
#pragma once
#include "Engine.h"
namespace engine{
Scene loadSceneFile(const char* file);
}
*/
|
#include <iostream>
#include <string>
#include <cassert>
#include <vector>
#include "Side.h"
#include "Board.h"
#include "Player.h"
#include "Game.h"
using namespace std;
//int main()
//{
// HumanPlayer hp("Marge");
// BadPlayer bp("Homer");
// Board b(3, 2);
// Game g(b, &hp, &bp);
// g.play();
// return 0;
//}
//int main()
//{
// BadPlayer bp1("Bart");
// BadPlayer bp2("Homer");
// Board b(3, 2);
// Game g(b, &bp1, &bp2);
// g.play();
// return 0;
//}
void doBoardTests()
{
// Test the constructor:
Board a(-1, -1);
assert(a.holes() == 1 && a.totalBeans() == 0 && a.beansInPlay(SOUTH) == 0);
// Test const functions:
Board b(3, 2);
assert(b.beans(SOUTH, 5) == -1); // test beans: special case
assert(b.holes() == 3 && b.totalBeans() == 12
&& b.beans(SOUTH, POT) == 0 && b.beansInPlay(SOUTH) == 6);
// Test move and set:
assert(!b.moveToPot(SOUTH, 4, SOUTH) && !b.setBeans(SOUTH, 4, 0) && !b.setBeans(SOUTH, 2, -1)); // invalid
assert(b.holes() == 3 && b.totalBeans() == 12 && b.beans(SOUTH, POT) == 0 && b.beansInPlay(SOUTH) == 6); // unchanged
b.setBeans(SOUTH, 1, 1);
b.moveToPot(SOUTH, 2, SOUTH);
assert(b.totalBeans() == 11 && b.beans(SOUTH, 1) == 1 && b.beans(SOUTH, 2) == 0 && b.beans(SOUTH, POT) == 2
&& b.beansInPlay(SOUTH) == 3);
// Test sow:
Side es;
int eh;
b.sow(SOUTH, 3, es, eh);
assert(es == NORTH && eh == 3 && b.beans(SOUTH, 3) == 0
&& b.beans(NORTH, 3) == 3 && b.beans(SOUTH, POT) == 3
&& b.beansInPlay(SOUTH) == 1 && b.beansInPlay(NORTH) == 7);
// A more complex case for sow:
Board c(6, 15);
c.sow(SOUTH, 5, es, eh); // test south
assert(es == SOUTH && eh == 0);
assert(c.beans(NORTH, POT) == 0 && c.beans(SOUTH, 1) == 16
&& c.beans(SOUTH, 3) == 16 && c.beans(SOUTH, 4) == 16 && c.beans(SOUTH, 5) == 1
&& c.beans(SOUTH, 6) == 17 && c.beans(SOUTH, POT) == 2 && c.beans(NORTH, 1) == 16
&& c.beans(NORTH, 2) == 16 && c.beans(NORTH, 3) == 16 && c.beans(NORTH, 4) == 16
&& c.beans(NORTH, 5) == 16 && c.beans(NORTH, 6) == 16);
c.sow(NORTH, 1, es, eh); // test north
assert(es == SOUTH && eh == 2);
assert(c.beans(NORTH, POT) == 2 && c.beans(SOUTH, 1) == 18
&& c.beans(SOUTH, 3) == 17 && c.beans(SOUTH, 4) == 17 && c.beans(SOUTH, 5) == 2
&& c.beans(SOUTH, 6) == 18 && c.beans(SOUTH, POT) == 2 && c.beans(NORTH, 1) == 1
&& c.beans(NORTH, 2) == 17 && c.beans(NORTH, 3) == 17 && c.beans(NORTH, 4) == 17
&& c.beans(NORTH, 5) == 17 && c.beans(NORTH, 6) == 17);
}
void doPlayerTests()
{
// Test virtual function:
HumanPlayer hp("Marge");
assert(hp.name() == "Marge" && hp.isInteractive());
BadPlayer bp("Homer");
assert(bp.name() == "Homer" && !bp.isInteractive());
SmartPlayer sp("Lisa");
assert(sp.name() == "Lisa" && !sp.isInteractive());
// Test special cases for all players:
Board b(3, 2);
b.setBeans(SOUTH, 2, 0);
b.setBeans(SOUTH, 1, 0);
b.setBeans(SOUTH, 3, 0);
int n = bp.chooseMove(b, SOUTH);
assert(n == -1);
n = hp.chooseMove(b, SOUTH);
assert(n == -1);
n = sp.chooseMove(b, SOUTH);
assert(n == -1);
// Test normal cases:
b.setBeans(SOUTH, 1, 2);
b.setBeans(SOUTH, 3, 2);
cout << "=========" << endl;
n = hp.chooseMove(b, SOUTH);
cout << "=========" << endl;
assert(n == 1 || n == 3);
n = bp.chooseMove(b, SOUTH);
assert(n == 1 || n == 3);
n = sp.chooseMove(b, SOUTH);
assert(n == 1 || n == 3);
}
void doPlayerTest2()
{
HumanPlayer hp("Marge");
SmartPlayer sp("Lisa");
Board b(6, 0);
b.setBeans(NORTH, 2, 1);
b.setBeans(NORTH, 5, 2);
b.setBeans(NORTH, POT, 22);
b.setBeans(SOUTH, POT, 20);
b.setBeans(SOUTH, 3, 2);
b.setBeans(SOUTH, 5, 1);
int n = sp.chooseMove(b, SOUTH);
cerr << n;
}
void doGameTests()
{
BadPlayer bp1("Bart");
BadPlayer bp2("Homer");
HumanPlayer hp("aa");
Board b(3, 0);
bool over;
bool hasWinner;
Side winner;
// Test move and status (game over cases):
Game a(b, &bp1, &bp2);
a.status(over, hasWinner, winner);
assert(!a.move() && over && !hasWinner);
// Test another turn & capture:
Board anotherb(3, 0);
anotherb.setBeans(SOUTH, 1, 2);
anotherb.setBeans(SOUTH, 2, 1);
anotherb.setBeans(SOUTH, 3, 1);
anotherb.setBeans(NORTH, 3, 2);
Game another(anotherb, &hp, &bp2);
// Homer
// 0 0 2
// 0 0
// 2 1 1
// Bart
another.move(); // choose 3 then choose 2
another.status(over, hasWinner, winner);
assert(over && winner == SOUTH);
// Simulate a game:
b.setBeans(SOUTH, 1, 2);
b.setBeans(NORTH, 2, 1);
b.setBeans(NORTH, 3, 2);
Game g(b, &bp1, &bp2);
// Homer
// 0 1 2
// 0 0
// 2 0 0
// Bart
g.status(over, hasWinner, winner);
assert(!over && g.beans(NORTH, POT) == 0 && g.beans(SOUTH, POT) == 0 &&
g.beans(NORTH, 1) == 0 && g.beans(NORTH, 2) == 1 && g.beans(NORTH, 3) == 2 &&
g.beans(SOUTH, 1) == 2 && g.beans(SOUTH, 2) == 0 && g.beans(SOUTH, 3) == 0);
g.move();
// 0 1 0
// 0 3
// 0 1 0
g.status(over, hasWinner, winner);
assert(!over && g.beans(NORTH, POT) == 0 && g.beans(SOUTH, POT) == 3 &&
g.beans(NORTH, 1) == 0 && g.beans(NORTH, 2) == 1 && g.beans(NORTH, 3) == 0 &&
g.beans(SOUTH, 1) == 0 && g.beans(SOUTH, 2) == 1 && g.beans(SOUTH, 3) == 0);
g.move();
// 1 0 0
// 0 3
// 0 1 0
g.status(over, hasWinner, winner);
assert(!over && g.beans(NORTH, POT) == 0 && g.beans(SOUTH, POT) == 3 &&
g.beans(NORTH, 1) == 1 && g.beans(NORTH, 2) == 0 && g.beans(NORTH, 3) == 0 &&
g.beans(SOUTH, 1) == 0 && g.beans(SOUTH, 2) == 1 && g.beans(SOUTH, 3) == 0);
g.move();
// 1 0 0
// 0 3
// 0 0 1
g.status(over, hasWinner, winner);
assert(!over && g.beans(NORTH, POT) == 0 && g.beans(SOUTH, POT) == 3 &&
g.beans(NORTH, 1) == 1 && g.beans(NORTH, 2) == 0 && g.beans(NORTH, 3) == 0 &&
g.beans(SOUTH, 1) == 0 && g.beans(SOUTH, 2) == 0 && g.beans(SOUTH, 3) == 1);
g.move();
// 0 0 0
// 1 4
// 0 0 0
g.status(over, hasWinner, winner);
assert(over && g.beans(NORTH, POT) == 1 && g.beans(SOUTH, POT) == 4 &&
g.beans(NORTH, 1) == 0 && g.beans(NORTH, 2) == 0 && g.beans(NORTH, 3) == 0 &&
g.beans(SOUTH, 1) == 0 && g.beans(SOUTH, 2) == 0 && g.beans(SOUTH, 3) == 0);
assert(hasWinner && winner == SOUTH);
}
int main()
{
//doBoardTests();
//doPlayerTests();
//doGameTests();
doPlayerTest2();
return 0;
}
|
/*The structure of the class is
class SortedStack{
public:
stack<int> s;
void sort();
};
*/
// Sort a stack
/* The below method sorts the stack s
you are required to complete the below method */
void SortedStack :: sort()
{
//Your code here
stack<int> stk;
while(!s.empty()) {
int x = s.top();
s.pop();
while(!stk.empty() && stk.top()<x) {
s.push(stk.top());
stk.pop();
}
stk.push(x);
}
while(!stk.empty()) {
s.push(stk.top());
stk.pop();
}
}
|
//Static方法
class SuperStatic
{
public:
static void beStatic() {cout<<"SuperStatic being static,yo! "<<endl;}
} ;
class SubStatic
{
public:
static void beStatic() {cout<<"SubStatic keepin' it static! "<<endl;}
};
//Call the Static
SuperStatic.beStatic();
SubStatic.beStatic();
//重载超类
class Foo
{
public:
virtual void overload() {cout<<"Foo's overload(). "<<endl;}
virtual void overload(int i) {cout<<"Foo's overload(int i). "<<endl;}
} ;
class Bar : public Foo
{
public:
virtual void overload() {cout<<"Bar's overload(). "<<endl;}
};
//从Bar访问overload(int)
Bar myBar;
Foo* ptr=&myBar;
ptr->overload(7);
|
#include <iostream>
#include <algorithm>
using namespace std;
int n, minima, opti;
string s;
char combi[6][3] = {{'R', 'G', 'B'}, {'R', 'B', 'G'}, {'B', 'R', 'G'}, {'B', 'G', 'R'}, {'G', 'R', 'B'}, {'G', 'B', 'R'}};
void findMinima(int idx)
{
int cost = 0;
for (int i = 0; i < n; i += 3)
{
if (s[i] != combi[idx][0])
cost++;
if (i + 1 < n && s[i + 1] != combi[idx][1])
cost++;
if (i + 2 < n && s[i + 2] != combi[idx][2])
cost++;
}
if(cost < minima)
{
minima = cost;
opti = idx;
}
}
int main()
{
cin >> n >> s;
minima = 200000;
opti = 0;
findMinima(0); findMinima(1); findMinima(2); findMinima(3); findMinima(4); findMinima(5);
cout << minima << endl;
for(int i = 0; i < n; i += 3)
{
cout << combi[opti][0];
if(i + 1 < n)
cout << combi[opti][1];
if(i + 2 < n)
cout << combi[opti][2];
}
cout << endl;
}
|
/**
* Copyright (c) 2007-2017, 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.
*
* @file log_format_impls.cc
*/
#include <algorithm>
#include <utility>
#include "log_format.hh"
#include <stdio.h>
#include "base/injector.bind.hh"
#include "base/opt_util.hh"
#include "config.h"
#include "formats/logfmt/logfmt.parser.hh"
#include "log_vtab_impl.hh"
#include "scn/scn.h"
#include "sql_util.hh"
#include "yajlpp/yajlpp.hh"
class generic_log_format : public log_format {
static const pcre_format* get_pcre_log_formats()
{
static const pcre_format log_fmt[] = {
pcre_format(
"^(?:\\*\\*\\*\\s+)?(?<timestamp>@[0-9a-zA-Z]{16,24})(.*)"),
pcre_format(
R"(^(?:\*\*\*\s+)?(?<timestamp>(?:\s|\d{4}[\-\/]\d{2}[\-\/]\d{2}|T|\d{1,2}:\d{2}(?::\d{2}(?:[\.,]\d{1,6})?)?|Z|[+\-]\d{2}:?\d{2}|(?!ERR|INFO|WARN)[A-Z]{3,4})+)(?:\s+|[:|])([^:]+))"),
pcre_format(
"^(?:\\*\\*\\*\\s+)?(?<timestamp>[\\w:+/\\.-]+) \\[\\w (.*)"),
pcre_format("^(?:\\*\\*\\*\\s+)?(?<timestamp>[\\w:,/\\.-]+) (.*)"),
pcre_format(
"^(?:\\*\\*\\*\\s+)?(?<timestamp>[\\w:,/\\.-]+) - (.*)"),
pcre_format(
"^(?:\\*\\*\\*\\s+)?(?<timestamp>[\\w: \\.,/-]+) - (.*)"),
pcre_format("^(?:\\*\\*\\*\\s+)?(?<timestamp>[\\w: "
"\\.,/-]+)\\[[^\\]]+\\](.*)"),
pcre_format("^(?:\\*\\*\\*\\s+)?(?<timestamp>[\\w: \\.,/-]+) (.*)"),
pcre_format(
R"(^(?:\*\*\*\s+)?\[(?<timestamp>[\w: \.,+/-]+)\]\s*(\w+):?)"),
pcre_format(
"^(?:\\*\\*\\*\\s+)?\\[(?<timestamp>[\\w: \\.,+/-]+)\\] (.*)"),
pcre_format("^(?:\\*\\*\\*\\s+)?\\[(?<timestamp>[\\w: "
"\\.,+/-]+)\\] \\[(\\w+)\\]"),
pcre_format("^(?:\\*\\*\\*\\s+)?\\[(?<timestamp>[\\w: "
"\\.,+/-]+)\\] \\w+ (.*)"),
pcre_format("^(?:\\*\\*\\*\\s+)?\\[(?<timestamp>[\\w: ,+/-]+)\\] "
"\\(\\d+\\) (.*)"),
pcre_format(),
};
return log_fmt;
}
std::string get_pattern_regex(uint64_t line_number) const override
{
int pat_index = this->pattern_index_for_line(line_number);
return get_pcre_log_formats()[pat_index].name;
}
const intern_string_t get_name() const override
{
static const intern_string_t RETVAL
= intern_string::lookup("generic_log");
return RETVAL;
}
scan_result_t scan(logfile& lf,
std::vector<logline>& dst,
const line_info& li,
shared_buffer_ref& sbr,
scan_batch_context& sbc) override
{
struct exttm log_time;
struct timeval log_tv;
string_fragment ts;
nonstd::optional<string_fragment> level;
const char* last_pos;
if ((last_pos = this->log_scanf(dst.size(),
sbr.to_string_fragment(),
get_pcre_log_formats(),
nullptr,
&log_time,
&log_tv,
&ts,
&level))
!= nullptr)
{
log_level_t level_val = log_level_t::LEVEL_UNKNOWN;
if (level) {
level_val = string2level(level->data(), level->length());
}
if (!((log_time.et_flags & ETF_DAY_SET)
&& (log_time.et_flags & ETF_MONTH_SET)
&& (log_time.et_flags & ETF_YEAR_SET)))
{
this->check_for_new_year(dst, log_time, log_tv);
}
if (!(this->lf_timestamp_flags
& (ETF_MILLIS_SET | ETF_MICROS_SET | ETF_NANOS_SET))
&& !dst.empty() && dst.back().get_time() == log_tv.tv_sec
&& dst.back().get_millis() != 0)
{
auto log_ms
= std::chrono::milliseconds(dst.back().get_millis());
log_time.et_nsec
= std::chrono::duration_cast<std::chrono::nanoseconds>(
log_ms)
.count();
log_tv.tv_usec
= std::chrono::duration_cast<std::chrono::microseconds>(
log_ms)
.count();
}
dst.emplace_back(li.li_file_range.fr_offset, log_tv, level_val);
return scan_match{0};
}
return scan_no_match{"no patterns matched"};
}
void annotate(uint64_t line_number,
string_attrs_t& sa,
logline_value_vector& values,
bool annotate_module) const override
{
auto& line = values.lvv_sbr;
int pat_index = this->pattern_index_for_line(line_number);
const auto& fmt = get_pcre_log_formats()[pat_index];
int prefix_len = 0;
auto md = fmt.pcre->create_match_data();
auto match_res = fmt.pcre->capture_from(line.to_string_fragment())
.into(md)
.matches(PCRE2_NO_UTF_CHECK)
.ignore_error();
if (!match_res) {
return;
}
auto ts_cap = md[fmt.pf_timestamp_index].value();
auto lr = to_line_range(ts_cap.trim());
sa.emplace_back(lr, logline::L_TIMESTAMP.value());
prefix_len = ts_cap.sf_end;
auto level_cap = md[2];
if (level_cap) {
if (string2level(level_cap->data(), level_cap->length(), true)
!= LEVEL_UNKNOWN)
{
prefix_len = level_cap->sf_end;
}
}
lr.lr_start = 0;
lr.lr_end = prefix_len;
sa.emplace_back(lr, logline::L_PREFIX.value());
lr.lr_start = prefix_len;
lr.lr_end = line.length();
sa.emplace_back(lr, SA_BODY.value());
}
std::shared_ptr<log_format> specialized(int fmt_lock) override
{
auto retval = std::make_shared<generic_log_format>(*this);
retval->lf_specialized = true;
return retval;
}
};
std::string
from_escaped_string(const char* str, size_t len)
{
std::string retval;
for (size_t lpc = 0; lpc < len; lpc++) {
switch (str[lpc]) {
case '\\':
if ((lpc + 3) < len && str[lpc + 1] == 'x') {
int ch;
if (sscanf(&str[lpc + 2], "%2x", &ch) == 1) {
retval.append(1, (char) ch & 0xff);
lpc += 3;
}
}
break;
default:
retval.append(1, str[lpc]);
break;
}
}
return retval;
}
nonstd::optional<const char*>
lnav_strnstr(const char* s, const char* find, size_t slen)
{
char c, sc;
size_t len;
if ((c = *find++) != '\0') {
len = strlen(find);
do {
do {
if (slen < 1 || (sc = *s) == '\0') {
return nonstd::nullopt;
}
--slen;
++s;
} while (sc != c);
if (len > slen) {
return nonstd::nullopt;
}
} while (strncmp(s, find, len) != 0);
s--;
}
return s;
}
struct separated_string {
const char* ss_str;
size_t ss_len;
const char* ss_separator;
size_t ss_separator_len;
separated_string(const char* str, size_t len)
: ss_str(str), ss_len(len), ss_separator(","),
ss_separator_len(strlen(this->ss_separator))
{
}
separated_string& with_separator(const char* sep)
{
this->ss_separator = sep;
this->ss_separator_len = strlen(sep);
return *this;
}
struct iterator {
const separated_string& i_parent;
const char* i_pos;
const char* i_next_pos;
size_t i_index;
iterator(const separated_string& ss, const char* pos)
: i_parent(ss), i_pos(pos), i_next_pos(pos), i_index(0)
{
this->update();
}
void update()
{
const separated_string& ss = this->i_parent;
auto next_field
= lnav_strnstr(this->i_pos,
ss.ss_separator,
ss.ss_len - (this->i_pos - ss.ss_str));
if (next_field) {
this->i_next_pos = next_field.value() + ss.ss_separator_len;
} else {
this->i_next_pos = ss.ss_str + ss.ss_len;
}
}
iterator& operator++()
{
this->i_pos = this->i_next_pos;
this->update();
this->i_index += 1;
return *this;
}
string_fragment operator*()
{
const auto& ss = this->i_parent;
int end;
if (this->i_next_pos < (ss.ss_str + ss.ss_len)) {
end = this->i_next_pos - ss.ss_str - ss.ss_separator_len;
} else {
end = this->i_next_pos - ss.ss_str;
}
return string_fragment::from_byte_range(
ss.ss_str, this->i_pos - ss.ss_str, end);
}
bool operator==(const iterator& other) const
{
return (&this->i_parent == &other.i_parent)
&& (this->i_pos == other.i_pos);
}
bool operator!=(const iterator& other) const
{
return !(*this == other);
}
size_t index() const { return this->i_index; }
};
iterator begin() { return {*this, this->ss_str}; }
iterator end() { return {*this, this->ss_str + this->ss_len}; }
};
class bro_log_format : public log_format {
public:
struct field_def {
logline_value_meta fd_meta;
logline_value_meta* fd_root_meta;
std::string fd_collator;
nonstd::optional<size_t> fd_numeric_index;
explicit field_def(const intern_string_t name,
size_t col,
log_format* format)
: fd_meta(name,
value_kind_t::VALUE_TEXT,
logline_value_meta::table_column{col},
format),
fd_root_meta(&FIELD_META.find(name)->second)
{
}
field_def& with_kind(value_kind_t kind,
bool identifier = false,
const std::string& collator = "")
{
this->fd_meta.lvm_kind = kind;
this->fd_meta.lvm_identifier = identifier;
this->fd_collator = collator;
return *this;
}
field_def& with_numeric_index(size_t index)
{
this->fd_numeric_index = index;
return *this;
}
};
static std::unordered_map<const intern_string_t, logline_value_meta>
FIELD_META;
static const intern_string_t get_opid_desc()
{
static const intern_string_t RETVAL = intern_string::lookup("std");
return RETVAL;
}
bro_log_format()
{
this->lf_is_self_describing = true;
this->lf_time_ordered = false;
auto desc_v = std::make_shared<std::vector<opid_descriptor>>();
desc_v->emplace({});
this->lf_opid_description_def->emplace(get_opid_desc(),
opid_descriptors{desc_v});
}
const intern_string_t get_name() const override
{
static const intern_string_t name(intern_string::lookup("bro"));
return this->blf_format_name.empty() ? name : this->blf_format_name;
}
void clear() override
{
this->log_format::clear();
this->blf_format_name.clear();
this->blf_field_defs.clear();
}
scan_result_t scan_int(std::vector<logline>& dst,
const line_info& li,
shared_buffer_ref& sbr,
scan_batch_context& sbc)
{
static const intern_string_t STATUS_CODE
= intern_string::lookup("bro_status_code");
static const intern_string_t TS = intern_string::lookup("bro_ts");
static const intern_string_t UID = intern_string::lookup("bro_uid");
static const intern_string_t ID_ORIG_H
= intern_string::lookup("bro_id_orig_h");
separated_string ss(sbr.get_data(), sbr.length());
struct timeval tv;
struct exttm tm;
bool found_ts = false;
log_level_t level = LEVEL_INFO;
uint8_t opid = 0;
auto opid_cap = string_fragment::invalid();
auto host_cap = string_fragment::invalid();
ss.with_separator(this->blf_separator.get());
for (auto iter = ss.begin(); iter != ss.end(); ++iter) {
if (iter.index() == 0 && *iter == "#close") {
return scan_match{0};
}
if (iter.index() >= this->blf_field_defs.size()) {
break;
}
const auto& fd = this->blf_field_defs[iter.index()];
if (TS == fd.fd_meta.lvm_name) {
string_fragment sf = *iter;
if (this->lf_date_time.scan(
sf.data(), sf.length(), nullptr, &tm, tv))
{
this->lf_timestamp_flags = tm.et_flags;
found_ts = true;
}
} else if (STATUS_CODE == fd.fd_meta.lvm_name) {
const auto sf = *iter;
if (!sf.empty() && sf[0] >= '4') {
level = LEVEL_ERROR;
}
} else if (UID == fd.fd_meta.lvm_name) {
opid_cap = *iter;
opid = hash_str(opid_cap.data(), opid_cap.length());
} else if (ID_ORIG_H == fd.fd_meta.lvm_name) {
host_cap = *iter;
}
if (fd.fd_numeric_index) {
switch (fd.fd_meta.lvm_kind) {
case value_kind_t::VALUE_INTEGER:
case value_kind_t::VALUE_FLOAT: {
const auto sv = (*iter).to_string_view();
auto scan_float_res = scn::scan_value<double>(sv);
if (scan_float_res) {
this->lf_value_stats[fd.fd_numeric_index.value()]
.add_value(scan_float_res.value());
}
break;
}
default:
break;
}
}
}
if (found_ts) {
if (!this->lf_specialized) {
for (auto& ll : dst) {
ll.set_ignore(true);
}
}
if (opid_cap.is_valid()) {
auto opid_iter = sbc.sbc_opids.los_opid_ranges.find(opid_cap);
if (opid_iter == sbc.sbc_opids.los_opid_ranges.end()) {
auto opid_copy = opid_cap.to_owned(sbc.sbc_allocator);
auto otr = opid_time_range{time_range{tv, tv}};
auto emplace_res
= sbc.sbc_opids.los_opid_ranges.emplace(opid_copy, otr);
opid_iter = emplace_res.first;
} else {
opid_iter->second.otr_range.extend_to(tv);
}
opid_iter->second.otr_level_stats.update_msg_count(level);
auto& otr = opid_iter->second;
if (!otr.otr_description.lod_id && host_cap.is_valid()
&& otr.otr_description.lod_elements.empty())
{
otr.otr_description.lod_id = get_opid_desc();
otr.otr_description.lod_elements.emplace_back(
0, host_cap.to_string());
}
}
dst.emplace_back(li.li_file_range.fr_offset, tv, level, 0, opid);
return scan_match{0};
}
return scan_no_match{};
}
scan_result_t scan(logfile& lf,
std::vector<logline>& dst,
const line_info& li,
shared_buffer_ref& sbr,
scan_batch_context& sbc) override
{
static const auto SEP_RE
= lnav::pcre2pp::code::from_const(R"(^#separator\s+(.+))");
if (!this->blf_format_name.empty()) {
return this->scan_int(dst, li, sbr, sbc);
}
if (dst.empty() || dst.size() > 20 || sbr.empty()
|| sbr.get_data()[0] == '#')
{
return scan_no_match{};
}
auto line_iter = dst.begin();
auto read_result = lf.read_line(line_iter);
if (read_result.isErr()) {
return scan_no_match{"unable to read first line"};
}
auto line = read_result.unwrap();
auto md = SEP_RE.create_match_data();
auto match_res = SEP_RE.capture_from(line.to_string_fragment())
.into(md)
.matches(PCRE2_NO_UTF_CHECK)
.ignore_error();
if (!match_res) {
return scan_no_match{"cannot read separator header"};
}
this->clear();
auto sep = from_escaped_string(md[1]->data(), md[1]->length());
this->blf_separator = intern_string::lookup(sep);
for (++line_iter; line_iter != dst.end(); ++line_iter) {
auto next_read_result = lf.read_line(line_iter);
if (next_read_result.isErr()) {
return scan_no_match{"unable to read header line"};
}
line = next_read_result.unwrap();
separated_string ss(line.get_data(), line.length());
ss.with_separator(this->blf_separator.get());
auto iter = ss.begin();
string_fragment directive = *iter;
if (directive.empty() || directive[0] != '#') {
continue;
}
++iter;
if (iter == ss.end()) {
continue;
}
if (directive == "#set_separator") {
this->blf_set_separator = intern_string::lookup(*iter);
} else if (directive == "#empty_field") {
this->blf_empty_field = intern_string::lookup(*iter);
} else if (directive == "#unset_field") {
this->blf_unset_field = intern_string::lookup(*iter);
} else if (directive == "#path") {
auto full_name = fmt::format(FMT_STRING("bro_{}_log"), *iter);
this->blf_format_name = intern_string::lookup(full_name);
} else if (directive == "#fields" && this->blf_field_defs.empty()) {
do {
auto field_name
= intern_string::lookup("bro_" + sql_safe_ident(*iter));
auto common_iter = FIELD_META.find(field_name);
if (common_iter == FIELD_META.end()) {
FIELD_META.emplace(field_name,
logline_value_meta{
field_name,
value_kind_t::VALUE_TEXT,
});
}
this->blf_field_defs.emplace_back(
field_name, this->blf_field_defs.size(), this);
++iter;
} while (iter != ss.end());
} else if (directive == "#types") {
static const char* KNOWN_IDS[] = {
"bro_conn_uids",
"bro_fuid",
"bro_host",
"bro_info_code",
"bro_method",
"bro_mime_type",
"bro_orig_fuids",
"bro_parent_fuid",
"bro_proto",
"bro_referrer",
"bro_resp_fuids",
"bro_service",
"bro_status_code",
"bro_uid",
"bro_uri",
"bro_user_agent",
"bro_username",
};
int numeric_count = 0;
do {
string_fragment field_type = *iter;
auto& fd = this->blf_field_defs[iter.index() - 1];
if (field_type == "time") {
fd.with_kind(value_kind_t::VALUE_TIMESTAMP);
} else if (field_type == "string") {
bool ident = std::binary_search(std::begin(KNOWN_IDS),
std::end(KNOWN_IDS),
fd.fd_meta.lvm_name);
fd.with_kind(value_kind_t::VALUE_TEXT, ident);
} else if (field_type == "count") {
bool ident = std::binary_search(std::begin(KNOWN_IDS),
std::end(KNOWN_IDS),
fd.fd_meta.lvm_name);
fd.with_kind(value_kind_t::VALUE_INTEGER, ident)
.with_numeric_index(numeric_count);
numeric_count += 1;
} else if (field_type == "bool") {
fd.with_kind(value_kind_t::VALUE_BOOLEAN);
} else if (field_type == "addr") {
fd.with_kind(
value_kind_t::VALUE_TEXT, true, "ipaddress");
} else if (field_type == "port") {
fd.with_kind(value_kind_t::VALUE_INTEGER, true);
} else if (field_type == "interval") {
fd.with_kind(value_kind_t::VALUE_FLOAT)
.with_numeric_index(numeric_count);
numeric_count += 1;
}
++iter;
} while (iter != ss.end());
this->lf_value_stats.resize(numeric_count);
}
}
if (!this->blf_format_name.empty() && !this->blf_separator.empty()
&& !this->blf_field_defs.empty())
{
dst.clear();
return this->scan_int(dst, li, sbr, sbc);
}
this->blf_format_name.clear();
this->lf_value_stats.clear();
return scan_no_match{};
}
void annotate(uint64_t line_number,
string_attrs_t& sa,
logline_value_vector& values,
bool annotate_module) const override
{
static const intern_string_t TS = intern_string::lookup("bro_ts");
static const intern_string_t UID = intern_string::lookup("bro_uid");
auto& sbr = values.lvv_sbr;
separated_string ss(sbr.get_data(), sbr.length());
ss.with_separator(this->blf_separator.get());
for (auto iter = ss.begin(); iter != ss.end(); ++iter) {
if (iter.index() >= this->blf_field_defs.size()) {
return;
}
const field_def& fd = this->blf_field_defs[iter.index()];
string_fragment sf = *iter;
if (sf == this->blf_empty_field) {
sf.clear();
} else if (sf == this->blf_unset_field) {
sf.invalidate();
}
auto lr = line_range(sf.sf_begin, sf.sf_end);
if (fd.fd_meta.lvm_name == TS) {
sa.emplace_back(lr, logline::L_TIMESTAMP.value());
} else if (fd.fd_meta.lvm_name == UID) {
sa.emplace_back(lr, logline::L_OPID.value());
}
if (lr.is_valid()) {
values.lvv_values.emplace_back(fd.fd_meta, sbr, lr);
} else {
values.lvv_values.emplace_back(fd.fd_meta);
}
values.lvv_values.back().lv_meta.lvm_user_hidden
= fd.fd_root_meta->lvm_user_hidden;
}
}
const logline_value_stats* stats_for_value(
const intern_string_t& name) const override
{
const logline_value_stats* retval = nullptr;
for (const auto& blf_field_def : this->blf_field_defs) {
if (blf_field_def.fd_meta.lvm_name == name) {
if (!blf_field_def.fd_numeric_index) {
break;
}
retval = &this->lf_value_stats[blf_field_def.fd_numeric_index
.value()];
break;
}
}
return retval;
}
bool hide_field(const intern_string_t field_name, bool val) override
{
auto fd_iter = FIELD_META.find(field_name);
if (fd_iter == FIELD_META.end()) {
return false;
}
fd_iter->second.lvm_user_hidden = val;
return true;
}
std::map<intern_string_t, logline_value_meta> get_field_states() override
{
std::map<intern_string_t, logline_value_meta> retval;
for (const auto& fd : FIELD_META) {
retval.emplace(fd.first, fd.second);
}
return retval;
}
std::shared_ptr<log_format> specialized(int fmt_lock = -1) override
{
auto retval = std::make_shared<bro_log_format>(*this);
retval->lf_specialized = true;
return retval;
}
class bro_log_table : public log_format_vtab_impl {
public:
explicit bro_log_table(const bro_log_format& format)
: log_format_vtab_impl(format), blt_format(format)
{
}
void get_columns(std::vector<vtab_column>& cols) const override
{
for (const auto& fd : this->blt_format.blf_field_defs) {
auto type_pair = log_vtab_impl::logline_value_to_sqlite_type(
fd.fd_meta.lvm_kind);
cols.emplace_back(fd.fd_meta.lvm_name.to_string(),
type_pair.first,
fd.fd_collator,
false,
"",
type_pair.second);
}
}
void get_foreign_keys(
std::vector<std::string>& keys_inout) const override
{
this->log_vtab_impl::get_foreign_keys(keys_inout);
for (const auto& fd : this->blt_format.blf_field_defs) {
if (fd.fd_meta.lvm_identifier) {
keys_inout.push_back(fd.fd_meta.lvm_name.to_string());
}
}
}
const bro_log_format& blt_format;
};
static std::map<intern_string_t, std::shared_ptr<bro_log_table>>&
get_tables()
{
static std::map<intern_string_t, std::shared_ptr<bro_log_table>> retval;
return retval;
}
std::shared_ptr<log_vtab_impl> get_vtab_impl() const override
{
if (this->blf_format_name.empty()) {
return nullptr;
}
std::shared_ptr<bro_log_table> retval = nullptr;
auto& tables = get_tables();
auto iter = tables.find(this->blf_format_name);
if (iter == tables.end()) {
retval = std::make_shared<bro_log_table>(*this);
tables[this->blf_format_name] = retval;
}
return retval;
}
void get_subline(const logline& ll,
shared_buffer_ref& sbr,
bool full_message) override
{
}
intern_string_t blf_format_name;
intern_string_t blf_separator;
intern_string_t blf_set_separator;
intern_string_t blf_empty_field;
intern_string_t blf_unset_field;
std::vector<field_def> blf_field_defs;
};
std::unordered_map<const intern_string_t, logline_value_meta>
bro_log_format::FIELD_META;
struct ws_separated_string {
const char* ss_str;
size_t ss_len;
explicit ws_separated_string(const char* str = nullptr, size_t len = -1)
: ss_str(str), ss_len(len)
{
}
struct iterator {
enum class state_t {
NORMAL,
QUOTED,
};
const ws_separated_string& i_parent;
const char* i_pos;
const char* i_next_pos;
size_t i_index{0};
state_t i_state{state_t::NORMAL};
iterator(const ws_separated_string& ss, const char* pos)
: i_parent(ss), i_pos(pos), i_next_pos(pos)
{
this->update();
}
void update()
{
const auto& ss = this->i_parent;
bool done = false;
while (!done && this->i_next_pos < (ss.ss_str + ss.ss_len)) {
switch (this->i_state) {
case state_t::NORMAL:
if (*this->i_next_pos == '"') {
this->i_state = state_t::QUOTED;
} else if (isspace(*this->i_next_pos)) {
done = true;
}
break;
case state_t::QUOTED:
if (*this->i_next_pos == '"') {
this->i_state = state_t::NORMAL;
}
break;
}
if (!done) {
this->i_next_pos += 1;
}
}
}
iterator& operator++()
{
const auto& ss = this->i_parent;
this->i_pos = this->i_next_pos;
while (this->i_pos < (ss.ss_str + ss.ss_len)
&& isspace(*this->i_pos))
{
this->i_pos += 1;
this->i_next_pos += 1;
}
this->update();
this->i_index += 1;
return *this;
}
string_fragment operator*()
{
const auto& ss = this->i_parent;
int end = this->i_next_pos - ss.ss_str;
return string_fragment(ss.ss_str, this->i_pos - ss.ss_str, end);
}
bool operator==(const iterator& other) const
{
return (&this->i_parent == &other.i_parent)
&& (this->i_pos == other.i_pos);
}
bool operator!=(const iterator& other) const
{
return !(*this == other);
}
size_t index() const { return this->i_index; }
};
iterator begin() { return {*this, this->ss_str}; }
iterator end() { return {*this, this->ss_str + this->ss_len}; }
};
class w3c_log_format : public log_format {
public:
struct field_def {
const intern_string_t fd_name;
logline_value_meta fd_meta;
logline_value_meta* fd_root_meta{nullptr};
std::string fd_collator;
nonstd::optional<size_t> fd_numeric_index;
explicit field_def(const intern_string_t name)
: fd_name(name), fd_meta(intern_string::lookup(sql_safe_ident(
name.to_string_fragment())),
value_kind_t::VALUE_TEXT)
{
}
field_def(const intern_string_t name, logline_value_meta meta)
: fd_name(name), fd_meta(meta)
{
}
field_def(size_t col,
const char* name,
value_kind_t kind,
bool ident = false,
std::string coll = "")
: fd_name(intern_string::lookup(name)),
fd_meta(
intern_string::lookup(sql_safe_ident(string_fragment(name))),
kind,
logline_value_meta::table_column{col}),
fd_collator(std::move(coll))
{
this->fd_meta.lvm_identifier = ident;
}
field_def& with_kind(value_kind_t kind,
bool identifier = false,
const std::string& collator = "")
{
this->fd_meta.lvm_kind = kind;
this->fd_meta.lvm_identifier = identifier;
this->fd_collator = collator;
return *this;
}
field_def& with_numeric_index(int index)
{
this->fd_numeric_index = index;
return *this;
}
};
static std::unordered_map<const intern_string_t, logline_value_meta>
FIELD_META;
struct field_to_struct_t {
field_to_struct_t(const char* prefix, const char* struct_name)
: fs_prefix(prefix),
fs_struct_name(intern_string::lookup(struct_name))
{
}
const char* fs_prefix;
intern_string_t fs_struct_name;
};
static const std::vector<field_def> KNOWN_FIELDS;
const static std::vector<field_to_struct_t> KNOWN_STRUCT_FIELDS;
w3c_log_format()
{
this->lf_is_self_describing = true;
this->lf_time_ordered = false;
}
const intern_string_t get_name() const override
{
static const intern_string_t name(intern_string::lookup("w3c"));
return this->wlf_format_name.empty() ? name : this->wlf_format_name;
}
void clear() override
{
this->log_format::clear();
this->wlf_time_scanner.clear();
this->wlf_format_name.clear();
this->wlf_field_defs.clear();
}
scan_result_t scan_int(std::vector<logline>& dst,
const line_info& li,
shared_buffer_ref& sbr)
{
static const intern_string_t F_DATE = intern_string::lookup("date");
static const intern_string_t F_DATE_LOCAL
= intern_string::lookup("date-local");
static const intern_string_t F_DATE_UTC
= intern_string::lookup("date-UTC");
static const intern_string_t F_TIME = intern_string::lookup("time");
static const intern_string_t F_TIME_LOCAL
= intern_string::lookup("time-local");
static const intern_string_t F_TIME_UTC
= intern_string::lookup("time-UTC");
static const intern_string_t F_STATUS_CODE
= intern_string::lookup("sc-status");
ws_separated_string ss(sbr.get_data(), sbr.length());
struct timeval date_tv {
0, 0
}, time_tv{0, 0};
struct exttm date_tm, time_tm;
bool found_date = false, found_time = false;
log_level_t level = LEVEL_INFO;
for (auto iter = ss.begin(); iter != ss.end(); ++iter) {
if (iter.index() >= this->wlf_field_defs.size()) {
level = LEVEL_INVALID;
break;
}
const auto& fd = this->wlf_field_defs[iter.index()];
string_fragment sf = *iter;
if (sf.startswith("#")) {
if (sf == "#Date:") {
auto sbr_sf_opt
= sbr.to_string_fragment().consume_n(sf.length());
if (sbr_sf_opt) {
auto sbr_sf = sbr_sf_opt.value().trim();
date_time_scanner dts;
struct exttm tm;
struct timeval tv;
if (dts.scan(sbr_sf.data(),
sbr_sf.length(),
nullptr,
&tm,
tv))
{
this->lf_date_time.set_base_time(tv.tv_sec,
tm.et_tm);
this->wlf_time_scanner.set_base_time(tv.tv_sec,
tm.et_tm);
}
}
}
dst.emplace_back(
li.li_file_range.fr_offset, 0, 0, LEVEL_IGNORE, 0);
return scan_match{0};
}
sf = sf.trim("\" \t");
if (F_DATE == fd.fd_name || F_DATE_LOCAL == fd.fd_name
|| F_DATE_UTC == fd.fd_name)
{
if (this->lf_date_time.scan(
sf.data(), sf.length(), nullptr, &date_tm, date_tv))
{
this->lf_timestamp_flags |= date_tm.et_flags;
found_date = true;
}
} else if (F_TIME == fd.fd_name || F_TIME_LOCAL == fd.fd_name
|| F_TIME_UTC == fd.fd_name)
{
if (this->wlf_time_scanner.scan(
sf.data(), sf.length(), nullptr, &time_tm, time_tv))
{
this->lf_timestamp_flags |= time_tm.et_flags;
found_time = true;
}
} else if (F_STATUS_CODE == fd.fd_name) {
if (!sf.empty() && sf[0] >= '4') {
level = LEVEL_ERROR;
}
}
if (fd.fd_numeric_index) {
switch (fd.fd_meta.lvm_kind) {
case value_kind_t::VALUE_INTEGER:
case value_kind_t::VALUE_FLOAT: {
auto scan_float_res
= scn::scan_value<double>(sf.to_string_view());
if (scan_float_res) {
this->lf_value_stats[fd.fd_numeric_index.value()]
.add_value(scan_float_res.value());
}
break;
}
default:
break;
}
}
}
if (found_time) {
struct exttm tm = time_tm;
struct timeval tv;
if (found_date) {
tm.et_tm.tm_year = date_tm.et_tm.tm_year;
tm.et_tm.tm_mday = date_tm.et_tm.tm_mday;
tm.et_tm.tm_mon = date_tm.et_tm.tm_mon;
tm.et_tm.tm_wday = date_tm.et_tm.tm_wday;
tm.et_tm.tm_yday = date_tm.et_tm.tm_yday;
}
tv = tm.to_timeval();
if (!this->lf_specialized) {
for (auto& ll : dst) {
ll.set_ignore(true);
}
}
dst.emplace_back(li.li_file_range.fr_offset, tv, level, 0);
return scan_match{0};
}
return scan_no_match{};
}
scan_result_t scan(logfile& lf,
std::vector<logline>& dst,
const line_info& li,
shared_buffer_ref& sbr,
scan_batch_context& sbc) override
{
static const auto* W3C_LOG_NAME = intern_string::lookup("w3c_log");
static const auto* X_FIELDS_NAME = intern_string::lookup("x_fields");
static auto X_FIELDS_IDX = 0;
if (li.li_partial) {
return scan_incomplete{};
}
if (!this->wlf_format_name.empty()) {
return this->scan_int(dst, li, sbr);
}
if (dst.empty() || dst.size() > 20 || sbr.empty()
|| sbr.get_data()[0] == '#')
{
return scan_no_match{};
}
this->clear();
for (auto line_iter = dst.begin(); line_iter != dst.end(); ++line_iter)
{
auto next_read_result = lf.read_line(line_iter);
if (next_read_result.isErr()) {
return scan_no_match{"unable to read first line"};
}
auto line = next_read_result.unwrap();
ws_separated_string ss(line.get_data(), line.length());
auto iter = ss.begin();
const auto directive = *iter;
if (directive.empty() || directive[0] != '#') {
continue;
}
++iter;
if (iter == ss.end()) {
continue;
}
if (directive == "#Date:") {
date_time_scanner dts;
struct exttm tm;
struct timeval tv;
if (dts.scan(line.get_data_at(directive.length() + 1),
line.length() - directive.length() - 1,
nullptr,
&tm,
tv))
{
this->lf_date_time.set_base_time(tv.tv_sec, tm.et_tm);
this->wlf_time_scanner.set_base_time(tv.tv_sec, tm.et_tm);
}
} else if (directive == "#Fields:" && this->wlf_field_defs.empty())
{
int numeric_count = 0;
do {
auto sf = (*iter).trim(")");
auto field_iter = std::find_if(
begin(KNOWN_FIELDS),
end(KNOWN_FIELDS),
[&sf](auto elem) { return sf == elem.fd_name; });
if (field_iter != end(KNOWN_FIELDS)) {
this->wlf_field_defs.emplace_back(*field_iter);
auto& fd = this->wlf_field_defs.back();
auto common_iter = FIELD_META.find(fd.fd_meta.lvm_name);
if (common_iter == FIELD_META.end()) {
auto emp_res = FIELD_META.emplace(
fd.fd_meta.lvm_name, fd.fd_meta);
common_iter = emp_res.first;
}
fd.fd_root_meta = &common_iter->second;
} else if (sf == "date" || sf == "time") {
this->wlf_field_defs.emplace_back(
intern_string::lookup(sf));
auto& fd = this->wlf_field_defs.back();
auto common_iter = FIELD_META.find(fd.fd_meta.lvm_name);
if (common_iter == FIELD_META.end()) {
auto emp_res = FIELD_META.emplace(
fd.fd_meta.lvm_name, fd.fd_meta);
common_iter = emp_res.first;
}
fd.fd_root_meta = &common_iter->second;
} else {
const auto fs_iter = std::find_if(
begin(KNOWN_STRUCT_FIELDS),
end(KNOWN_STRUCT_FIELDS),
[&sf](auto elem) {
return sf.startswith(elem.fs_prefix);
});
if (fs_iter != end(KNOWN_STRUCT_FIELDS)) {
const intern_string_t field_name
= intern_string::lookup(sf.substr(3));
this->wlf_field_defs.emplace_back(
field_name,
logline_value_meta(
field_name,
value_kind_t::VALUE_TEXT,
logline_value_meta::table_column{
KNOWN_FIELDS.size() + 1
+ std::distance(
begin(KNOWN_STRUCT_FIELDS),
fs_iter)},
this)
.with_struct_name(fs_iter->fs_struct_name));
} else {
const intern_string_t field_name
= intern_string::lookup(sf);
this->wlf_field_defs.emplace_back(
field_name,
logline_value_meta(
field_name,
value_kind_t::VALUE_TEXT,
logline_value_meta::table_column{
KNOWN_FIELDS.size() + X_FIELDS_IDX},
this)
.with_struct_name(X_FIELDS_NAME));
}
}
auto& fd = this->wlf_field_defs.back();
fd.fd_meta.lvm_format = nonstd::make_optional(this);
switch (fd.fd_meta.lvm_kind) {
case value_kind_t::VALUE_FLOAT:
case value_kind_t::VALUE_INTEGER:
fd.with_numeric_index(numeric_count);
numeric_count += 1;
break;
default:
break;
}
++iter;
} while (iter != ss.end());
this->wlf_format_name = W3C_LOG_NAME;
this->lf_value_stats.resize(numeric_count);
}
}
if (!this->wlf_format_name.empty() && !this->wlf_field_defs.empty()) {
return this->scan_int(dst, li, sbr);
}
this->wlf_format_name.clear();
this->lf_value_stats.clear();
return scan_no_match{};
}
void annotate(uint64_t line_number,
string_attrs_t& sa,
logline_value_vector& values,
bool annotate_module) const override
{
auto& sbr = values.lvv_sbr;
ws_separated_string ss(sbr.get_data(), sbr.length());
for (auto iter = ss.begin(); iter != ss.end(); ++iter) {
string_fragment sf = *iter;
if (iter.index() >= this->wlf_field_defs.size()) {
sa.emplace_back(line_range{sf.sf_begin, -1},
SA_INVALID.value("extra fields detected"));
return;
}
const auto& fd = this->wlf_field_defs[iter.index()];
if (sf == "-") {
sf.invalidate();
}
auto lr = line_range(sf.sf_begin, sf.sf_end);
if (lr.is_valid()) {
values.lvv_values.emplace_back(fd.fd_meta, sbr, lr);
if (sf.startswith("\"")) {
auto& meta = values.lvv_values.back().lv_meta;
if (meta.lvm_kind == value_kind_t::VALUE_TEXT) {
meta.lvm_kind = value_kind_t::VALUE_W3C_QUOTED;
} else {
meta.lvm_kind = value_kind_t::VALUE_NULL;
}
}
} else {
values.lvv_values.emplace_back(fd.fd_meta);
}
if (fd.fd_root_meta != nullptr) {
values.lvv_values.back().lv_meta.lvm_user_hidden
= fd.fd_root_meta->lvm_user_hidden;
}
}
}
const logline_value_stats* stats_for_value(
const intern_string_t& name) const override
{
const logline_value_stats* retval = nullptr;
for (const auto& wlf_field_def : this->wlf_field_defs) {
if (wlf_field_def.fd_meta.lvm_name == name) {
if (!wlf_field_def.fd_numeric_index) {
break;
}
retval = &this->lf_value_stats[wlf_field_def.fd_numeric_index
.value()];
break;
}
}
return retval;
}
bool hide_field(const intern_string_t field_name, bool val) override
{
auto fd_iter = FIELD_META.find(field_name);
if (fd_iter == FIELD_META.end()) {
return false;
}
fd_iter->second.lvm_user_hidden = val;
return true;
}
std::map<intern_string_t, logline_value_meta> get_field_states() override
{
std::map<intern_string_t, logline_value_meta> retval;
for (const auto& fd : FIELD_META) {
retval.emplace(fd.first, fd.second);
}
return retval;
}
std::shared_ptr<log_format> specialized(int fmt_lock = -1) override
{
auto retval = std::make_shared<w3c_log_format>(*this);
retval->lf_specialized = true;
return retval;
}
class w3c_log_table : public log_format_vtab_impl {
public:
explicit w3c_log_table(const w3c_log_format& format)
: log_format_vtab_impl(format), wlt_format(format)
{
}
void get_columns(std::vector<vtab_column>& cols) const override
{
for (const auto& fd : KNOWN_FIELDS) {
auto type_pair = log_vtab_impl::logline_value_to_sqlite_type(
fd.fd_meta.lvm_kind);
cols.emplace_back(fd.fd_meta.lvm_name.to_string(),
type_pair.first,
fd.fd_collator,
false,
"",
type_pair.second);
}
cols.emplace_back("x_fields");
cols.back().with_comment(
"A JSON-object that contains fields that are not first-class "
"columns");
for (const auto& fs : KNOWN_STRUCT_FIELDS) {
cols.emplace_back(fs.fs_struct_name.to_string());
}
};
void get_foreign_keys(
std::vector<std::string>& keys_inout) const override
{
this->log_vtab_impl::get_foreign_keys(keys_inout);
for (const auto& fd : KNOWN_FIELDS) {
if (fd.fd_meta.lvm_identifier) {
keys_inout.push_back(fd.fd_meta.lvm_name.to_string());
}
}
}
const w3c_log_format& wlt_format;
};
static std::map<intern_string_t, std::shared_ptr<w3c_log_table>>&
get_tables()
{
static std::map<intern_string_t, std::shared_ptr<w3c_log_table>> retval;
return retval;
}
std::shared_ptr<log_vtab_impl> get_vtab_impl() const override
{
if (this->wlf_format_name.empty()) {
return nullptr;
}
std::shared_ptr<w3c_log_table> retval = nullptr;
auto& tables = get_tables();
auto iter = tables.find(this->wlf_format_name);
if (iter == tables.end()) {
retval = std::make_shared<w3c_log_table>(*this);
tables[this->wlf_format_name] = retval;
}
return retval;
}
void get_subline(const logline& ll,
shared_buffer_ref& sbr,
bool full_message) override
{
}
date_time_scanner wlf_time_scanner;
intern_string_t wlf_format_name;
std::vector<field_def> wlf_field_defs;
};
std::unordered_map<const intern_string_t, logline_value_meta>
w3c_log_format::FIELD_META;
static size_t KNOWN_FIELD_INDEX = 0;
const std::vector<w3c_log_format::field_def> w3c_log_format::KNOWN_FIELDS = {
{
KNOWN_FIELD_INDEX++,
"cs-method",
value_kind_t::VALUE_TEXT,
true,
},
{
KNOWN_FIELD_INDEX++,
"c-ip",
value_kind_t::VALUE_TEXT,
true,
"ipaddress",
},
{
KNOWN_FIELD_INDEX++,
"cs-bytes",
value_kind_t::VALUE_INTEGER,
false,
},
{
KNOWN_FIELD_INDEX++,
"cs-host",
value_kind_t::VALUE_TEXT,
true,
},
{
KNOWN_FIELD_INDEX++,
"cs-uri-stem",
value_kind_t::VALUE_TEXT,
true,
"naturalnocase",
},
{
KNOWN_FIELD_INDEX++,
"cs-uri-query",
value_kind_t::VALUE_TEXT,
false,
},
{
KNOWN_FIELD_INDEX++,
"cs-username",
value_kind_t::VALUE_TEXT,
false,
},
{
KNOWN_FIELD_INDEX++,
"cs-version",
value_kind_t::VALUE_TEXT,
true,
},
{
KNOWN_FIELD_INDEX++,
"s-ip",
value_kind_t::VALUE_TEXT,
true,
"ipaddress",
},
{
KNOWN_FIELD_INDEX++,
"s-port",
value_kind_t::VALUE_INTEGER,
true,
},
{
KNOWN_FIELD_INDEX++,
"s-computername",
value_kind_t::VALUE_TEXT,
true,
},
{
KNOWN_FIELD_INDEX++,
"s-sitename",
value_kind_t::VALUE_TEXT,
true,
},
{
KNOWN_FIELD_INDEX++,
"sc-bytes",
value_kind_t::VALUE_INTEGER,
false,
},
{
KNOWN_FIELD_INDEX++,
"sc-status",
value_kind_t::VALUE_INTEGER,
false,
},
{
KNOWN_FIELD_INDEX++,
"sc-substatus",
value_kind_t::VALUE_INTEGER,
false,
},
{
KNOWN_FIELD_INDEX++,
"time-taken",
value_kind_t::VALUE_FLOAT,
false,
},
};
const std::vector<w3c_log_format::field_to_struct_t>
w3c_log_format::KNOWN_STRUCT_FIELDS = {
{"cs(", "cs_headers"},
{"sc(", "sc_headers"},
{"rs(", "rs_headers"},
{"sr(", "sr_headers"},
};
struct logfmt_pair_handler {
explicit logfmt_pair_handler(date_time_scanner& dts) : lph_dt_scanner(dts)
{
}
bool process_value(const string_fragment& value_frag)
{
if (this->lph_key_frag == "time" || this->lph_key_frag == "ts") {
if (!this->lph_dt_scanner.scan(value_frag.data(),
value_frag.length(),
nullptr,
&this->lph_time_tm,
this->lph_tv))
{
return false;
}
this->lph_found_time = true;
} else if (this->lph_key_frag == "level") {
this->lph_level
= string2level(value_frag.data(), value_frag.length());
}
return true;
}
date_time_scanner& lph_dt_scanner;
bool lph_found_time{false};
struct exttm lph_time_tm {};
struct timeval lph_tv {
0, 0
};
log_level_t lph_level{log_level_t::LEVEL_INFO};
string_fragment lph_key_frag{""};
};
class logfmt_format : public log_format {
public:
const intern_string_t get_name() const override
{
const static intern_string_t NAME = intern_string::lookup("logfmt_log");
return NAME;
}
class logfmt_log_table : public log_format_vtab_impl {
public:
logfmt_log_table(const log_format& format)
: log_format_vtab_impl(format)
{
}
void get_columns(std::vector<vtab_column>& cols) const override
{
static const auto FIELDS = std::string("fields");
cols.emplace_back(FIELDS);
}
};
std::shared_ptr<log_vtab_impl> get_vtab_impl() const override
{
static auto retval = std::make_shared<logfmt_log_table>(*this);
return retval;
}
scan_result_t scan(logfile& lf,
std::vector<logline>& dst,
const line_info& li,
shared_buffer_ref& sbr,
scan_batch_context& sbc) override
{
auto p = logfmt::parser(sbr.to_string_fragment());
scan_result_t retval = scan_no_match{};
bool done = false;
logfmt_pair_handler lph(this->lf_date_time);
while (!done) {
auto parse_result = p.step();
done = parse_result.match(
[](const logfmt::parser::end_of_input&) { return true; },
[&lph](const logfmt::parser::kvpair& kvp) {
lph.lph_key_frag = kvp.first;
return kvp.second.match(
[](const logfmt::parser::bool_value& bv) {
return false;
},
[&lph](const logfmt::parser::float_value& fv) {
return lph.process_value(fv.fv_str_value);
},
[&lph](const logfmt::parser::int_value& iv) {
return lph.process_value(iv.iv_str_value);
},
[&lph](const logfmt::parser::quoted_value& qv) {
auto_mem<yajl_handle_t> handle(yajl_free);
yajl_callbacks cb;
memset(&cb, 0, sizeof(cb));
handle = yajl_alloc(&cb, nullptr, &lph);
cb.yajl_string = +[](void* ctx,
const unsigned char* str,
size_t len) -> int {
auto& lph = *((logfmt_pair_handler*) ctx);
string_fragment value_frag{str, 0, (int) len};
return lph.process_value(value_frag);
};
if (yajl_parse(
handle,
(const unsigned char*) qv.qv_value.data(),
qv.qv_value.length())
!= yajl_status_ok
|| yajl_complete_parse(handle)
!= yajl_status_ok)
{
log_debug("json parsing failed");
string_fragment unq_frag{
qv.qv_value.sf_string,
qv.qv_value.sf_begin + 1,
qv.qv_value.sf_end - 1,
};
return lph.process_value(unq_frag);
}
return false;
},
[&lph](const logfmt::parser::unquoted_value& uv) {
return lph.process_value(uv.uv_value);
});
},
[](const logfmt::parser::error& err) {
// log_error("logfmt parse error: %s", err.e_msg.c_str());
return true;
});
}
if (lph.lph_found_time) {
dst.emplace_back(
li.li_file_range.fr_offset, lph.lph_tv, lph.lph_level);
retval = scan_match{0};
}
return retval;
}
void annotate(uint64_t line_number,
string_attrs_t& sa,
logline_value_vector& values,
bool annotate_module) const override
{
static const auto FIELDS_NAME = intern_string::lookup("fields");
auto& sbr = values.lvv_sbr;
auto p = logfmt::parser(sbr.to_string_fragment());
bool done = false;
while (!done) {
auto parse_result = p.step();
done = parse_result.match(
[](const logfmt::parser::end_of_input&) { return true; },
[this, &sa, &values](const logfmt::parser::kvpair& kvp) {
auto value_frag = kvp.second.match(
[this, &kvp, &values](
const logfmt::parser::bool_value& bv) {
auto lvm = logline_value_meta{intern_string::lookup(
kvp.first),
value_kind_t::
VALUE_INTEGER,
logline_value_meta::
table_column{0},
(log_format*) this}
.with_struct_name(FIELDS_NAME);
values.lvv_values.emplace_back(lvm, bv.bv_value);
return bv.bv_str_value;
},
[this, &kvp, &values](
const logfmt::parser::int_value& iv) {
auto lvm = logline_value_meta{intern_string::lookup(
kvp.first),
value_kind_t::
VALUE_INTEGER,
logline_value_meta::
table_column{0},
(log_format*) this}
.with_struct_name(FIELDS_NAME);
values.lvv_values.emplace_back(lvm, iv.iv_value);
return iv.iv_str_value;
},
[this, &kvp, &values](
const logfmt::parser::float_value& fv) {
auto lvm = logline_value_meta{intern_string::lookup(
kvp.first),
value_kind_t::
VALUE_INTEGER,
logline_value_meta::
table_column{0},
(log_format*) this}
.with_struct_name(FIELDS_NAME);
values.lvv_values.emplace_back(lvm, fv.fv_value);
return fv.fv_str_value;
},
[](const logfmt::parser::quoted_value& qv) {
return qv.qv_value;
},
[](const logfmt::parser::unquoted_value& uv) {
return uv.uv_value;
});
auto value_lr
= line_range{value_frag.sf_begin, value_frag.sf_end};
if (kvp.first == "time" || kvp.first == "ts") {
sa.emplace_back(value_lr, logline::L_TIMESTAMP.value());
} else if (kvp.first == "level") {
} else if (kvp.first == "msg") {
sa.emplace_back(value_lr, SA_BODY.value());
} else if (kvp.second.is<logfmt::parser::quoted_value>()
|| kvp.second
.is<logfmt::parser::unquoted_value>())
{
auto lvm
= logline_value_meta{intern_string::lookup(
kvp.first),
value_frag.startswith("\"")
? value_kind_t::VALUE_JSON
: value_kind_t::VALUE_TEXT,
logline_value_meta::
table_column{0},
(log_format*) this}
.with_struct_name(FIELDS_NAME);
values.lvv_values.emplace_back(lvm, value_frag);
}
return false;
},
[line_number, &sbr](const logfmt::parser::error& err) {
log_error("bad line %.*s", sbr.length(), sbr.get_data());
log_error("%lld:logfmt parse error: %s",
line_number,
err.e_msg.c_str());
return true;
});
}
}
std::shared_ptr<log_format> specialized(int fmt_lock) override
{
auto retval = std::make_shared<logfmt_format>(*this);
retval->lf_specialized = true;
return retval;
}
};
static auto format_binder = injector::bind_multiple<log_format>()
.add<logfmt_format>()
.add<bro_log_format>()
.add<w3c_log_format>()
.add<generic_log_format>();
|
// BEGIN CUT HERE
// PROBLEM STATEMENT
// The game of Errant Knights is played on an infinite
// chessboard using two knights, white and black. The players
// alternate turns and the white player starts the game. Each
// player makes a normal chess knight's move with his knight,
// but there is a restriction that each move must make the
// Euclidean distance between the two knights smaller. A
// player can make more than one move in a single turn, but
// then each move must go in the same direction.
//
// For example, if the black knight is at coordinates (0, 0)
// and the white knight is at (9, 5), then the white knight
// can move to (7, 4), (5, 3), (3, 2), (1, 1), (-1, 0).
// Further moving in this direction is not allowed because
// (-3, -1) is further from (0, 0) than (-1, 0). Of course,
// the white knight could also start his turn by moving in
// one of several other directions, and then possibly making
// more moves in that direction.
//
// The game ends when one of the knights wins by capturing
// the other one (by moving to its position), or when it is
// impossible to make another move (because the knights are
// orthogonally next to each other and each move would
// increase the distance). In the second case, the player who
// should make the next move loses.
//
// Several games of Errant Knight will be played. The
// starting position of the white knight in the i-th game is
// (x[i], y[i]). The black knight will start each game at
// (0, 0). Both players play optimally. Return a String
// where the i-th character is 'B' if the black knight wins
// the i-th game or 'W' if the white knight wins.
//
//
// DEFINITION
// Class:ErrantKnight
// Method:whoWins
// Parameters:vector <int>, vector <int>
// Returns:string
// Method signature:string whoWins(vector <int> x, vector
// <int> y)
//
//
// NOTES
// -A chess knight can move in 8 directions. From (0, 0), a
// knight could move to (2, 1), (2, -1), (1, 2), (-1, 2), (1,
// -2), (-1, -2), (-2, 1), (-2, -1).
//
//
// CONSTRAINTS
// -x and y will contain between 1 and 50 elements, inclusive.
// -x and y will contain the same number of elements.
// -Each element of x will be between -4000 and 4000,
// inclusive.
// -Each element of y will be between -4000 and 4000,
// inclusive.
// -For each i, x[i] and y[i] cannot both be equal to 0.
//
//
// EXAMPLES
//
// 0)
// {1,1,2,2,9,3}
// {0,1,0,1,5,3}
//
// Returns: "BWWWWB"
//
// In the first game, there is no possible move for White
// from (1,0), so Black wins.
// In the second game, White moves from (1,1) to (0,-1).
// Black has no legal move from there, so White wins.
// In the third game, White moves from (2,0) to (0,1). Again,
// Black has no legal move, and White wins.
// In the fourth game, White moves from (2,1) to (0,0), and
// captures the Black knight. White wins.
// In the fifth game, White makes five moves from the same
// direction, moving from (9,5) to (-1,0). White wins.
// In the sixth game, White can make a sequence of moves
// which lead to one of the following squares: (2,1), (1,-1),
// (1,2), (-1,1), (4,1), (1,4). After each of these moves
// Black can win.
//
//
// 1)
// {1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,7}
// {0,0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4,4,5,5,5,5,5,5,5,6,6,6,6,6,6,6,7}
//
// Returns:
// "BWBBBBBWWWWWWWWWWWWWWWWBWWWWWWWBWWWWWWWBWWWWWWWWWB"
//
//
//
// 2)
// {-10}
// {0}
//
// Returns: "B"
//
// Note that x[i] and y[i] can be negative.
//
//
// END CUT HERE
#line 107 "ErrantKnight.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;
typedef long long ll;
map<pair<int, pair<int, int> >, bool> memo;
ll getdist(int x, int y) {
return x * x + y * y;
}
bool go(int pl, int x, int y) {
pair<int, pair<int,int> > te(pl, make_pair(x,y));
if (memo.count(te) > 0) return memo[te];
if (x == 0 && y == 0) {
if (pl == 1) return memo[te]=false;
return memo[te]=true;
}
int dx[] = { 2,2,1,-1,1,-1,-2,-2 };
int dy[] = { 1,-1,2,2,-2,-2,1,-1};
fi(8) {
int c = 1;
ll dist = getdist(x,y);
while (true) {
int nx = x + c * pl * dx[i];
int ny = y + c * pl * dy[i];
ll nd = getdist(nx, ny);
if (nd > dist) break;
bool re = go(-pl, nx, ny);
if (pl == 1 && re) return memo[te]=true;
if (pl == -1 && !re) return memo[te]=false;
dist = nd;
++c;
}
}
if (pl == 1) return memo[te]=false;
if (pl == -1) return memo[te]=true;
}
class ErrantKnight
{
public:
string whoWins(vector <int> x, vector <int> y)
{
string ret;
fi(x.size()) {
if (go(1, x[i], y[i])) ret += 'W';
else ret += 'B';
}
return ret;
}
// 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(); }
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 string &Expected, const string &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 Arr0[] = {1,1,2,2,9,3}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0,1,0,1,5,3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "BWWWWB"; verify_case(0, Arg2, whoWins(Arg0, Arg1)); }
void test_case_1() { int Arr0[] = {1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,7}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0,0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4,4,5,5,5,5,5,5,5,6,6,6,6,6,6,6,7}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "BWBBBBBWWWWWWWWWWWWWWWWBWWWWWWWBWWWWWWWBWWWWWWWWWB"; verify_case(1, Arg2, whoWins(Arg0, Arg1)); }
void test_case_2() { int Arr0[] = {-10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "B"; verify_case(2, Arg2, whoWins(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
ErrantKnight ___test;
___test.run_test(-1);
}
// END CUT HERE
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
//
// 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 SEARCHMANAGER_H
#define SEARCHMANAGER_H
#ifdef DESKTOP_UTIL_SEARCH_ENGINES
// Use mapping in translations to map from IDs to GUIDs for searches still using the ID
// Anything without a mapping gets a new generated guid.
#include "modules/util/adt/OpFilteredVector.h"
#include "adjunct/desktop_util/treemodel/optreemodel.h"
#include "adjunct/desktop_util/treemodel/optreemodelitem.h"
#include "adjunct/desktop_util/search/search_types.h"
#ifdef SEARCH_PROVIDER_QUERY_SUPPORT
#include "modules/windowcommander/OpWindowCommanderManager.h"
#endif //SEARCH_PROVIDER_QUERY_SUPPORT
#include "adjunct/quick/data_types/OpenURLSetting.h"
#define SUPPORTS_ADD_SEARCH_TO_HISTORY_LIST
class PrefsFile;
class SearchTemplate;
class SearchEngineItem;
class Window;
class UserSearches;
class DesktopWindow;
class TLDUpdater;
#define SEARCH_USER_ID_START 1000000 // ID at which user defined searches start from
#define DEFAULT_SEARCH_KEY UNI_L("?") // Default search key
#define g_searchEngineManager (SearchEngineManager::GetInstance())
static const struct search_id_map_s
{
int old_id;
const char* new_id;
} g_search_id_mapping[] =
{
#include "data/translations/search-map.inc"
};
static const int num_search_id_mappings = sizeof(g_search_id_mapping) / sizeof(search_id_map_s);
/*********************************************************************************
*
* SearchEngineManager holds a list m_search_engine_list of all search engines,
* the ones from the package, and the user added ones, both visible and deleted
* ('hidden') ones, and a TreeModel UserSearches holding the searches
* visible in the UI.
*
**********************************************************************************/
/***********************************************************************************
** SearchEngineManager
** -------------------
**
** Option entries:
**
** Default Search - The default search used in the address field and search field
** Speed Dial Search - The search used in Speed Dial
**
** Search Engine Entry :
**
** Name - the name of the search engine
** URL - the search url
** Default Tracking Code - string replaces the string {TrackingCode} in the URL field if it is present. This string identifies searches invoked from search or address fields.
** SpeedDial Tracking Code - string replaces the string {TrackingCode} in the URL field if it is present. This string identifies searches invoked from speeddial field.
** Query - should be set to the query if "Is post" is 1
** Key - the key for the search engine (e.g. "g" for google)
** Is post - if the url should be a post (0 == NO and 1 == YES)
** Has endseparator - dropdown and menu : add seperator after
** Encoding - the encoding of the url
** Search Type - the search type (see search_types.h)
** Verbtext - string id for format of the search label
** Position - personal bar position
** Nameid - language title id
** Suggest Protocol - The protocol used for search suggestions, if available. See below.
** Suggest URL - The url used for search suggestions. See below.
**
** Suggest protocols:
**
** BING - The Bing protocol format. Uses JSON.
** WIKIPEDIA - The Wikipedia protocol format. Uses JSON.
** YANDEX - The Yandex protocol format. Uses JSON.
**
** Suggest URL keywords:
**
** {SearchTerm} - The search term to search for.
**
***********************************************************************************/
// Is an OpTreeModel for OpPersonalbar
class SearchEngineManager : public OpTreeModel
#ifdef SEARCH_PROVIDER_QUERY_SUPPORT
, public OpSearchProviderListener
#endif
{
public:
enum
{
FLAG_NONE = 0x0,
FLAG_GUID = 0x00001,
FLAG_KEY = 0x00002, // Set if nick has changed
FLAG_NAME = 0x00004, // Set if name has changed
FLAG_URL = 0x00008, // Set if url has changed
FLAG_ICON = 0x00010,
FLAG_PERSONALBAR = 0x00020,
FLAG_ENCODING = 0x00040,
FLAG_QUERY = 0x00080,
FLAG_ISPOST = 0x00100,
FLAG_DELETED = 0x00200,
FLAG_MOVED_FROM = 0x10000,
FLAG_MOVED_TO = 0x20000,
FLAG_UNKNOWN = 0xFFFFF, // Set if change unknown (sets all of the flags)
};
enum SearchReqIssuer
{
SEARCH_REQ_ISSUER_ADDRESSBAR,
SEARCH_REQ_ISSUER_SPEEDDIAL,
SEARCH_REQ_ISSUER_OTHERS,
};
class SearchSetting : public OpenURLSetting
{
public:
SearchSetting()
: OpenURLSetting()
, m_search_template(0)
, m_search_issuer(SearchEngineManager::SEARCH_REQ_ISSUER_ADDRESSBAR)
{
m_new_window = MAYBE;
m_new_page = MAYBE;
m_in_background = MAYBE;
}
SearchSetting(const OpenURLSetting& src)
: OpenURLSetting(src)
, m_search_template(0)
, m_search_issuer(SearchEngineManager::SEARCH_REQ_ISSUER_ADDRESSBAR)
{
m_new_window = MAYBE;
m_new_page = MAYBE;
m_in_background = MAYBE;
}
OpString m_keyword;
OpString m_key;
SearchTemplate* m_search_template;
SearchReqIssuer m_search_issuer;
};
static SearchEngineManager* GetInstance();
void CleanUp();
#ifdef SUPPORT_SYNC_SEARCHES
/**
* Listener class for listening to notifications about adds, removals or changes
* to items in the set corresponding to search.ini in the user profile.
* This set consists of changed or removed default searches, and user added searches.
*
* This is not a listener meant for UI, as it notifies about changes to the internal
* structure of items, not about what should be shown in the UI.
*/
class Listener
{
public:
virtual void OnSearchEngineItemAdded(SearchTemplate* item) = 0;
virtual void OnSearchEngineItemChanged(SearchTemplate* item, UINT32 flag) = 0;
virtual void OnSearchEngineItemRemoved(SearchTemplate* item) = 0;
// Listeners should rebuild search engines from scratch
virtual void OnSearchEnginesChanged() = 0;
virtual ~Listener() {}
};
#endif
#ifdef SUPPORT_SYNC_SEARCHES
OP_STATUS AddSearchEngineListener(Listener* listener) { if (m_search_engine_listeners.Find(listener) < 0) return m_search_engine_listeners.Add(listener); else return OpStatus::ERR; }
OP_STATUS RemoveSearchEngineListener(Listener* listener) { return m_search_engine_listeners.RemoveByItem(listener);}
#endif
/**
* Will load the searches.
*/
void ConstructL();
/**
* Reads in the search.ini and merges the user and package search.ini
* if that is neccessary.
*/
void LoadSearchesL();
/**
* Writes out to the user search.ini
*
* @return OpStatus::OK if successful
*/
OP_STATUS Write();
/**
*
* Get UserSearches model to be displayed in the UI
* (contains non-deleted and merged entries)
*
*/
UserSearches* GetSearchModel() { return m_usersearches; }
#ifdef SUPPORT_SYNC_SEARCHES
/***
* Broadcast Add, Change and Remove of search engine item
*
* This broadcasts changes to the set of items in the user profile
* search.ini.
*
* When a default search engine is changed or removed for the first time,
* a BroadcastAdded notification is sent.
*
* When a default search engine is changed or removed not for the first
* time, a BroadcastChanged notification is sent.
*
* For custom search engines, the notifications will correspond
* to 'normal' adds, changes and removals of items.
*
*/
void BroadcastSearchEngineAdded(SearchTemplate* search)
{
for ( UINT32 i = 0; i < m_search_engine_listeners.GetCount(); i++ )
{
Listener* listener = m_search_engine_listeners.Get(i);
listener->OnSearchEngineItemAdded(search);
}
}
void BroadcastSearchEngineChanged(SearchTemplate* search, UINT32 changed_flag)
{
for ( UINT32 i = 0; i < m_search_engine_listeners.GetCount(); i++ )
{
Listener* listener = m_search_engine_listeners.Get(i);
listener->OnSearchEngineItemChanged(search, changed_flag);
}
}
void BroadcastSearchEngineRemoved(SearchTemplate* search)
{
for ( UINT32 i = 0; i < m_search_engine_listeners.GetCount(); i++ )
{
Listener* listener = m_search_engine_listeners.Get(i);
listener->OnSearchEngineItemRemoved(search);
}
}
void BroadcastSearchEnginesChanged()
{
for ( UINT32 i = 0; i < m_search_engine_listeners.GetCount(); i++ )
{
Listener* listener = m_search_engine_listeners.Get(i);
listener->OnSearchEnginesChanged();
}
}
#endif // SUPPORT_SYNC_SEARCHES
/**
* Return TRUE if the text is single word and POSSIBLY a intranet page but not known to be one.
* So f.ex "wiki" would return TRUE, but "wiki/" or "wiki.com" would return FALSE.
*/
BOOL IsIntranet(const uni_char *text);
/**
* Returns TRUE if the text looks like a url.
*/
BOOL IsUrl(const uni_char *text);
/** Return TRUE if it's a hostname for a intranet. This checks with the list of
* stored intranet host names in prefs, previosly added with AddSpecialIntranetHost. */
BOOL IsDetectedIntranetHost(const uni_char *text);
/** Add a host name to the list of intranet hosts in prefs. All host names in this list
* should be treaded like urls when f.ex typing them in the addressfield. */
void AddDetectedIntranetHost(const uni_char *text);
/**
* Returns TRUE if the text doesn't look like a url or search, and is a single word.
*/
BOOL IsSingleWordSearch(const uni_char *text);
/**
* Attempt to start a search using the content of 'm_keyword'. The format
* can be "<key> <value>" where <key> is a known search engine key. The default
* search engine will be used if a valid key can not be extracted.
*
* Note that the content of 'settings' can be modified
*
* The 'm_keyword' is tested in such a way that a regular url or a nickname
* will not start a search.
*
* @param settings The 'm_keyword' member must be set
*
* @return TRUE if the search was performed, otherwise FALSE
*/
BOOL CheckAndDoSearch(SearchSetting& settings) { return CheckAndDoSearch(settings, TRUE); }
/**
* Check if a search can be performed. Behavior is the same as for @ref CheckAndDoSearch
*
* Note that the content of 'settings' can be modified
*
* @param settings The 'm_keyword' member must be set
*
* @return TRUE when a search can be made, otherwise FALSE
*/
BOOL CanSearch(SearchSetting& settings) { return CheckAndDoSearch(settings, FALSE); }
/**
* Search for keyword with specifed search engine, or if it fails, attempt a history
* or inline search. Note that the content of 'settings' can be modified
*
* @param settings Search setting. The 'm_keyword' and 'm_search_template' members
* must always be set
*
* @return TRUE on success (search started) otherwise FALSE
*/
BOOL DoSearch(SearchSetting& settings);
/**
* Open the history page and set the quickfind field to the string in search_terms
*
* @param search_terms to search for
*/
BOOL DoHistorySearch(const OpStringC& search_terms);
/**
* Do inline find in the current page
*
* @param search_terms to search for
*/
BOOL DoInlineFind(const OpStringC& search_terms);
/**
* This function is meant to add a search entry at the bottom of the list we
* get when preparing the autocomplete dropdown list. The list is assumed to
* contain three strings per item.
*
* This is ONLY used for OpEdit, the Address dropdown is an OpAddressDropDown
* and uses different functionality which was added for peregrine.
*
* @param search_key - the user typed string
* @param list - an array representing the dropdown strings
* @param num_items - the number of items in the list.
*/
void AddSearchStringToList(const uni_char* search_key,
uni_char**& list,
int& num_items);
/**
* Find the SearchTemplate based on the id and make a search url
* based on that SearchTemplate and place that in url_object.
*
* @param url_object - that should contain the finished url
* @param keyword - that should be searched for
* @param resolve_keyword - whether the key word should be resolved
* (i.e. "www.opera.com" to "http://www.opera.com")
* @param id - of the SearchTemplate requested
* @param search_req_issuer - identifies search issuer
* @param key - key used to init the search
*
*
* @return TRUE if successful - FALSE otherwise
*/
BOOL PrepareSearch(URL& url_object,
const uni_char* keyword,
BOOL resolve_keyword,
int id,
SearchReqIssuer search_req_issuer = SEARCH_REQ_ISSUER_ADDRESSBAR,
const OpStringC& key = UNI_L(""),
URL_CONTEXT_ID context_id = 0);
/**
* Looks up the description of the search based on its index in the search
* engine list and gets the string that represents it.
*
* @param index - the index of the desired search
* @param buf - the string will be set to the search's description
*/
void MakeSearchWithString(int index,
OpString& buf);
void MakeSearchWithString(SearchTemplate* search,
OpString& buf);
/**
* Find the search string and label for a search key. If the key
* is empty the search string and label is made for the default
* search engine.
*
* The search_label will be set to the description for the
* search (i.e. search_label = "Google").
*
* The search_string will be set to the internal search url string
* (i.e. search_string = "g hello world").
*
* @param key - the search key (eg. "g") can be empty
* @param value - the search words
* @param search_label - string that will be set to the name of the searchengine
* @param search_string - string that will be set to the internal search url
*
* @return TRUE if the search found is the default search
*/
BOOL FindSearchByKey(const OpStringC & key,
const OpStringC & value,
OpString & search_label,
OpString & search_string);
/**
* Takes a string that may contain one or more spaces
* and splits it such that the first word (if there is one)
* is placed in key and the rest in value. If there is no space
* input is copied into value and key is left empty.
*
* @param input - the string to be split
* @param key - the word before the space
* @param value - the words after the space
*/
static void SplitKeyValue(const OpStringC& input,
OpString & key,
OpString & value);
/**
* @return TRUE if string is a search string i.e. "g hello world"
*/
BOOL IsSearchString(const OpStringC& input);
// -------------------------
// Conversion methods :
// -------------------------
const char* GetGUIDByOldId(int id);
/**
* Gets the index of the item with the given id
*
* @param id - the requested id
*
* @return the index of the item with this id - default is 0
*/
int SearchIDToIndex(int id);
/**
* Gets the id of the item with the given type
*
* @param type - the requested type
*
* @return the id of the item with this type, if the type is not found, this returns 0
*/
// NOTE: Only one item for each search type??
int SearchTypeToID(SearchType type);
int SearchTypeToIndex(SearchType type);
/**
* Gets the id of the item at the given index
*
* @param index - the requested index
*
* @return the id of the item at the given index - default is 0
*/
int SearchIndexToID(int index);
/**
* Gets the search type of the item with the given id
*
* @param id - the requested id
*
* @return the search type of the item with the given id -
* default is 0 (SEARCH_TYPE_GOOGLE)
*/
SearchType IDToSearchType(int id);
/**
* Gets the search with the given id
*
* @param id - the requested id
*
* @return the item with this id if it exists
*/
SearchTemplate* SearchFromID(int id);
int GetSearchIndex(SearchTemplate* search);
// -------------------------
// Managing the search engine list :
// -------------------------
/**
* Adds a new search template to the search engine manager.
* @param search_engine The search engine to be added. Ownership is taken
* over by this function.
* @param char_set The character set of the new search engine.
* @sa EditSearchEngineDialog
*/
OP_STATUS AddSearch(SearchEngineItem* search_engine, OpStringC char_set);
/**
* Edits an existing search template in the search engine manager
* @param search_engine The item holding all the changes to be made.
* Ownership is taken over by this function.
* @param char_set The character set of the changed item.
* @param item_to_change The item that the above changes will be applied to.
* @param default_search_changed Indicates if the default search engine has
* changed in search_engine.
* @param speeddial_search_changed Indicates if the default SpeedDial search
* engine has changed in search_engine.
* @sa EditSearchEngineDialog
*/
OP_STATUS EditSearch(SearchEngineItem * search_engine, OpStringC char_set, SearchTemplate * item_to_change, BOOL default_search_changed = FALSE, BOOL speeddial_search_changed = FALSE);
/**
* Retrieve number of search engines.
*
* @return the number of search engines
*/
inline unsigned int GetSearchEnginesCount() { return m_search_engines_list.GetCount(); }
/**
* Retrieves the search template at a specific index
*
* @param i - the index of the desired item
*
* @return the item if it exists
*/
SearchTemplate* GetSearchEngine(int i) { return m_search_engines_list.Get(i); };
/**
* Retrieves the search template with a specific user id
*
* @param i - user id the desired item
*
* @return the item if it exists
*/
SearchTemplate* GetDefaultSearch();
SearchTemplate* GetDefaultSpeedDialSearch();
#ifdef SEARCH_PROVIDER_QUERY_SUPPORT
SearchTemplate* GetDefaultErrorPageSearch();
#endif // SEARCH_PROVIDER_QUERY_SUPPORT
OP_STATUS SetDefaultSearch(const OpStringC& search);
OP_STATUS SetDefaultSpeedDialSearch(const OpStringC& search);
#ifdef SEARCH_PROVIDER_QUERY_SUPPORT
//from OpSearchProviderListener
virtual SearchProviderInfo* OnRequestSearchProviderInfo(RequestReason reason);
#endif
/**
* Retrieves the search template with a specific key
*
* @param key for the search engine
*
* @return the item if it exists
*/
SearchTemplate* GetSearchEngineByKey(const OpStringC& key);
/**
* Returns TRUE if key is already in use
*
* @param key for the search engine
* @param exclude_search item to exclude from the search
*
* (Note: There can currently more than one item with the same key,'
* so just doing GetSearchEngineByKey doesn't work here
* because the item returned might be exclude_search, but there
* might still be another item with this key too)
*
* @return TRUE if in use
*/
BOOL KeyInUse(const OpStringC& key,
SearchTemplate* exclude_search);
/**
* Creates search key that is not in use.
*
* @param ref_key optional reference key used to generate new key
* @param ref_name optional reference name used to generate new key
* @param new_key gets new key on success
*
* @return OpStatus::OK or OpStatus::ERR_NO_MEMORY
*/
OP_STATUS FindFreeKey(OpStringC ref_key, OpStringC ref_name, OpString& new_key);
/**
* Adds a search item
*
* @param search - item to be added
*
* @return OpStatus::OK if successful
*/
OP_STATUS AddItem(SearchTemplate* search);
/**
* Removes a search item
*
* @param search - item to be removed
*
* @return OpStatus::OK if successful
*/
OP_STATUS RemoveItem(SearchTemplate* search);
/**
* Gets the index of an item
*
* @param search - the item to be search for
*
* @return the index of the item
*/
INT32 FindItem(SearchTemplate* search) {return m_search_engines_list.Find(search);}
/**
* Force this search to become a user search
*
* @param search - item to be changed
* @param pos - the index of the item in the search engine list
* @param flag - indicates which fields on the item has changed
*/
void ChangeItem(SearchTemplate* search, INT32 pos, UINT32 flag);
SearchTemplate* GetByUniqueGUID(const OpStringC& guid);
// Updates the google top level domain (TLD) i.e get's google.ru, google.no, etc
OP_STATUS UpdateGoogleTLD();
// == OpTreeModel ======================
virtual INT32 GetColumnCount() { return 2; }
virtual OP_STATUS GetColumnData(ColumnData* column_data);
virtual OpTreeModelItem* GetItemByPosition(INT32 position);
virtual INT32 GetItemParent(INT32 position) {return -1;}
virtual INT32 GetItemCount() {return m_search_engines_list.GetCount();}
/**
* Returns true if LoadSearchesL has been called at least once.
*/
bool HasLoadedConfig() const { return m_user_search_engines_file != NULL; }
private:
/**
* Checks if the url the user typed in is a search-command if so, calls DoSearch [all os]
* if the url is not a search command the default search engine will be called if
* the url does not seem to be a url (i.e. it looks like "hello world" or similar)
*
* @param settings Search setting. The 'm_keyword' and 'm_search_template' members
* must always be set
* @param do_search If FALSE, it will only calculate a return value without actually
* do the search.
*
* @return TRUE if the search was performed, otherwise FALSE
*/
BOOL CheckAndDoSearch(SearchSetting& settings, BOOL do_search);
/**
* Copies the searches from a prefs file to the class lists
*
* @param prefsfile -
* @param from_package -
*/
void AddSearchesL(PrefsFile* prefsfile,
BOOL from_package = TRUE);
/**
* Loads default and speed dial search from hardcoded searches.
*/
void AddHardcodedSearchesL();
/**
* Searches the current m_user_search_engines_list for a search
*
* @param original_search -
* @param index -
* @param from_package_only -
*
* @return
*/
SearchTemplate * FindSearchL(const SearchTemplate *original_search,
INT32 *index,
BOOL from_package_only = TRUE);
/**
* Inserts fallback search into the list of search engines and resolves keyword
* conflicts caused by adding fallback search.
*
* @param search fallback search
* @param position position of fallback search
*
* @return OpStatus::OK or OpStatus::ERR_NO_MEMORY
*/
OP_STATUS InsertFallbackSearch(SearchTemplate* search, int position);
/**
* Temporary Exception from search protection for Yandex.
* TODO: remove when enough people have transitioned to the new search protection.
* If the default search has been hijacked, and happens to be set to Yandex, we let it be a Yandex search
* but we make sure it corresponds to our deal with yandex.
* Without this, it would be replaced by google, which our current deals don't permit.
*
* @param search the search that was detected as being hijacked.
*
* @return true if the exception was applied. When false is returned, the normal operation mode for
* hijacked searches should be used instead.
*/
bool TryYandexSearchProtectionException(SearchTemplate *search);
/**
* Checks protected searches. If search is found to be tampered it is replaced with
* package search (if not modified) or copy of package search made before merging
* changes from user's search.ini.
*
* @param copy_of_package_default_search copy of default search from package search.ini
* @param copy_of_package_speeddial_search copy of speed dial search from package search.ini
*
* @return OpStatus::OK or OpStatus::ERR_NO_MEMORY
*/
OP_STATUS CheckProtectedSearches(OpStackAutoPtr<SearchTemplate>& copy_of_pacakge_default_search,
OpStackAutoPtr<SearchTemplate>& copy_of_package_speeddial_search);
// Initialization and destruction
SearchEngineManager();
~SearchEngineManager();
private:
// Version of the package search.ini :
int m_version;
// Complete set of searchengines :
OpFilteredVector<SearchTemplate> m_search_engines_list;
// Used to read both the package search.ini and user search.ini,
// but holds and writes out just the package search.ini
PrefsFile* m_user_search_engines_file;
INT32 m_next_user_id; // Holds the highest user search id currently assigned
UserSearches* m_usersearches;
TLDUpdater* m_tld_update; // Google top level domain (TLD) update object
#ifdef SUPPORT_SYNC_SEARCHES
OpVector<Listener> m_search_engine_listeners;
#endif
OpString m_default_search_guid; // GUID if the default search
OpString m_default_speeddial_search_guid; // GUID if the default Speed Dial search
OpString m_package_default_search_guid; // GUID if the default search
OpString m_package_speeddial_search_guid; // GUID if the default Speed Dial search
OpString m_fallback_default_search_guid; // GUID of search to use instead of tampered default search
OpString m_fallback_speeddial_search_guid; // GUID of search to use instead of tampered Speed Dial search
#ifdef SEARCH_PROVIDER_QUERY_SUPPORT
OpString m_default_error_search_guid; // GUID if the default error search
OpString m_package_error_search_guid; // GUID if the default error search
#endif // SEARCH_PROVIDER_QUERY_SUPPORT
};
/***********************************************************************************
**
** UserSearches
** ------------
**
**
***********************************************************************************/
class UserSearches : public TreeModel<SearchTemplate>
{
public:
friend class SearchEngineManager;
UserSearches() {}
~UserSearches() {}
// == OpTreeModel ======================
virtual INT32 GetColumnCount() {return 3;}
virtual INT32 GetItemParent(INT32 position) {return -1;}
virtual OP_STATUS GetColumnData(ColumnData* column_data);
private:
OP_STATUS AddUserSearch(SearchTemplate*);
OP_STATUS RemoveUserSearch(SearchTemplate*);
void Clear() { RemoveAll(); }
};
#endif // DESKTOP_UTIL_SEARCH_ENGINES
#endif // SEARCHMANAGER_H
|
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <time.h>
#include <memory.h>
#include <cmath>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
#define EPS 1e-10
LD SDist(LD x, LD y, LD z) {
return x * x + y * y + z * z;
}
int n, R;
int x, y, z, vx, vy, vz;
vector< pair<int, int> > all;
vector< pair<int, int> > tt;
int ans[111111], m;
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
scanf("%d%d", &n, &R);
for (int i = 0; i < n; ++i) {
scanf("%d%d%d", &x, &y, &z);
scanf("%d%d%d", &vx, &vy, &vz);
LD left = 0;
LD right = 1e9;
for (int it = 0; it < 150; ++it) {
LD c1 = left + (right - left) / 3;
LD c2 = right - (right - left) / 3;
if (SDist(x + vx * c1, y + vy * c1, z + vz * c1) < SDist(x + vx * c2, y + vy * c2, z + vz * c2)) {
right = c2;
} else
left = c1;
}
LD mp = (left + right) / 2;
if (SDist(x + vx * mp, y + vy * mp, z + vz * mp) - EPS > LD(R) * R) continue;
left = 0;
right = mp;
for (int it = 0; it < 150; ++it) {
LD c = (left + right) / 2;
if (SDist(x + vx * c, y + vy * c, z + vz * c) <= LD(R) * R)
right = c;
else
left = c;
}
for (int dk = max( (left + right) / 2 - 3, LD(0.)); dk <= (left + right) / 2 + 3; ++dk) {
if (SDist(x + vx * dk, y + vy * dk, z + vz * dk) - EPS <= LD(R) * R) {
all.push_back(make_pair(dk, -1));
break;
}
}
left = mp;
right = 1e9;
for (int it = 0; it < 150; ++it) {
LD c = (left + right) / 2;
if (SDist(x + vx * c, y + vy * c, z + vz * c) > LD(R) * R)
right = c;
else
left = c;
}
for (int dk = (left + right) / 2 + 3; dk >= max(LD(0.), (left + right) / 2 - 3); --dk) {
if (SDist(x + vx * dk, y + vy * dk, z + vz * dk) - EPS <= LD(R) * R) {
all.push_back(make_pair(dk + 1, 1));
break;
}
}
}
sort(all.begin(), all.end());
scanf("%d", &m);
for (int i = 0; i < m; ++i) {
int t;
scanf("%d", &t);
tt.push_back(make_pair(t, i));
}
sort(tt.begin(), tt.end());
int bad = 0;
for (int i = 0, j = 0; i < tt.size(); ++i) {
while (j < all.size() && all[j].first <= tt[i].first) {
bad -= all[j].second;
++j;
}
ans[tt[i].second] = bad;
}
for (int i = 0; i < m; ++i) printf("%d\n", ans[i]);
return 0;
}
|
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
/*
ham doPrint dung de in nhieu ki tu lien tiep
param : kitu -> kitu can in
soluong -> so luong ki tu muon in
*/
void doPrint(char kitu,int soluong){
for (int i=0;i<soluong;i++)
printf("%c",kitu);
}
int main()
{
freopen("labiec11.inp","r",stdin);
//freopen("labiec11.out","w",stdout);
int hang,cot;
scanf("%d %d",&cot,&hang);
//in hang dau tien
doPrint('*',cot); // in 1 dong toan sao
printf("\n");
//in cac hang o giua
for (int i=0;i<hang-2;i++){
doPrint('*',1); // in 1 dau sao
doPrint(' ',cot-2); // in ruot hinh chu nhat
doPrint('*',1); // in 1 dau sao
printf("\n");
}
//in hang cuoi cung
doPrint('*',cot); // in 1 dong toan sao
printf("\n");
return 0;
}
|
/*
* EmailRepositoryImpl.cc
*
* Created on: Nov 11, 2017
* Author: cis505
*/
#include "ServerToServerImpl.h"
using namespace std;
Status ServerToServerImpl::AskForLog(ServerContext* context, const LogRequest* request, ServerWriter<WriteCommandRequest>* writer) {
int seqNum = request->sequencenum();
string entry;
string entrySize;
vector<WriteCommandRequest> logEntries = logger->get();
cerr << "End to read logs from primary. Sending " << logEntries.size() << " log entries" << endl;
for (WriteCommandRequest logEntry : logEntries) {
writer->Write(logEntry);
}
return Status::OK;
}
|
#include <stdio.h>
#define _CCRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
int main() {
int no, count;
scanf_s("%d", &no, sizeof(no));
scanf_s("%d", &count, sizeof(count));
printf("%d\n", no + count);
cin >> no;
cin >> count;
cout << no + count;
return 0;
}
|
#pragma GCC optimize("Ofast")
#include <algorithm>
#include <bitset>
#include <deque>
#include <iostream>
#include <iterator>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
struct Node {
int data;
Node* next;
};
Node* head;
void insert(int x, int pos) {
Node *temp = new Node();
temp->data = x;
temp->next = NULL;
if(pos == 1) {
temp->next = head;
head = temp;
return;
}
Node *temp1 = head;
for(int i=1; i<pos-1; i++) {
temp1 = temp1->next;
}
temp->next = temp1->next;
temp1->next = temp;
}
void del(int pos) {
Node *temp3 = head;
if(pos == 1) {
head = temp3->next;
free(temp3);
return;
}
for(int i=1; i<pos-1; i++) {
temp3 = temp3->next;
}
Node *temp4 = temp3->next;
temp3->next = temp4->next;
free(temp4);
// without using extra variable
// temp3->next = temp3->next->next;
}
void print() {
Node *temp2 = head;
while(temp2 != NULL) {
cout << temp2->data << " ";
temp2=temp2->next;
cout << endl;
}
}
int main(int argc, char* argv[]) {
abhisheknaiidu();
head = NULL;
insert(2,1);
insert(4,2);
insert(3,1);
del(2);
print();
return 0;
}
|
#include"Barrier_method.h"
Barrier_method::Barrier_method(string Filename)
{
X0.resize(2);
input(Filename);
}
Barrier_method::Barrier_method(vector_2d X, double R, double c, double e)
{
X0 = X;
r = R;
C = c;
eps = e;
}
void Barrier_method::input(string Filename)
{
ifstream input(Filename);
input >> X0[0] >> X0[1];
input >> r >> C >> eps;
}
double Barrier_method::f(double X, double Y)
{
return (-2 * exp(-pow((X - 1.0) / 2.0, 2) - pow(Y - 1.0, 2)) - 3 * exp(-pow((X - 2.0) / 3.0, 2) - pow((Y - 3.0) / 2.0, 2)));
}
double Barrier_method::F(double X, double Y, double Rk)
{
return f(X, Y) + P(X, Y, Rk);
}
double FB(double X, double Y, double Rk)
{
return Barrier_method::f(X, Y) + Barrier_method::P(X, Y, Rk);
}
double Barrier_method::P(double X, double Y, double Rk)
{
return -Rk *( 1.0 / ((X + Y-1)*(X + Y-1) + (-X)* (-X) + (X - 4)* (X - 4)));
}
vector_2d Barrier_method::Calc()
{
vector_2d Xk = X0;
Method_Of_Gauss MG;
function<double(double, double)> temp_F_2;//указатель на функцию двух переменных
do
{
Xk = X0;
temp_F_2 = bind(FB, _1, _2, r);
Xk = MG.Calc(X0, 1e-6, 1e-6, temp_F_2,true);
r = r/C;
Num_calculation += MG.Num_calcultaion;
Num_iteration++;
} while (abs(P(Xk[0], Xk[1], r/C)) > eps);
return Xk;
}
|
// Created on: 1997-01-24
// Created by: Robert COUBLANC
// Copyright (c) 1997-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 _AIS_GlobalStatus_HeaderFile
#define _AIS_GlobalStatus_HeaderFile
#include <Standard.hxx>
#include <Prs3d_Drawer.hxx>
#include <TColStd_ListOfInteger.hxx>
#include <Standard_Integer.hxx>
#include <Standard_Transient.hxx>
DEFINE_STANDARD_HANDLE(AIS_GlobalStatus, Standard_Transient)
//! Stores information about objects in graphic context:
class AIS_GlobalStatus : public Standard_Transient
{
DEFINE_STANDARD_RTTIEXT(AIS_GlobalStatus, Standard_Transient)
public:
//! Default constructor.
Standard_EXPORT AIS_GlobalStatus();
//! Returns the display mode.
Standard_Integer DisplayMode() const { return myDispMode; }
//! Sets display mode.
void SetDisplayMode (const Standard_Integer theMode) { myDispMode = theMode; }
//! Returns TRUE if object is highlighted
Standard_Boolean IsHilighted() const { return myIsHilit; }
//! Sets highlighted state.
void SetHilightStatus (const Standard_Boolean theStatus) { myIsHilit = theStatus; }
//! Changes applied highlight style for a particular object
void SetHilightStyle (const Handle(Prs3d_Drawer)& theStyle) { myHiStyle = theStyle; }
//! Returns applied highlight style for a particular object
const Handle(Prs3d_Drawer)& HilightStyle() const { return myHiStyle; }
//! Returns active selection modes of the object.
const TColStd_ListOfInteger& SelectionModes() const { return mySelModes; }
//! Return TRUE if selection mode was registered.
Standard_Boolean IsSModeIn (Standard_Integer theMode) const
{
return mySelModes.Contains (theMode);
}
//! Add selection mode.
Standard_Boolean AddSelectionMode (const Standard_Integer theMode)
{
if (!mySelModes.Contains (theMode))
{
mySelModes.Append (theMode);
return Standard_True;
}
return Standard_False;
}
//! Remove selection mode.
Standard_Boolean RemoveSelectionMode (const Standard_Integer theMode)
{
return mySelModes.Remove (theMode);
}
//! Remove all selection modes.
void ClearSelectionModes()
{
mySelModes.Clear();
}
Standard_Boolean IsSubIntensityOn() const { return mySubInt; }
void SetSubIntensity (Standard_Boolean theIsOn) { mySubInt = theIsOn; }
private:
TColStd_ListOfInteger mySelModes;
Handle(Prs3d_Drawer) myHiStyle;
Standard_Integer myDispMode;
Standard_Boolean myIsHilit;
Standard_Boolean mySubInt;
};
#endif // _AIS_GlobalStatus_HeaderFile
|
#include <iostream>
#include "Perro.h"
#include "Gato.h"
int main() {
Animal* pet[3];
Gato g1("Silvestre",1947);
Perro p("Fido",2000);
Gato g2("Tom",1940);
pet[0]=&g1;
pet[1]=&p;
pet[2]=&g2;
for (int i=0;i<3;i++){
pet[i]->muestra();
pet[i]->habla();
cout<<endl;
}
return 0;
}
|
/* Question: Given a 2-Dimensional character array and a string,
we need to find the given string in 2-dimensional
character array such that individual characters
can be present left to right, right to left,
top to down or down to top. */
#include <iostream>
#include <vector>
#include <array>
#include <string>
#include <cstring>
using namespace std;
bool isValid(pair<int, int>& point, string direction, int row, int col, string& pat)
{
if (direction == "UP"){
if (point.first >= pat.size()){
return 1;
}
else{
return 0;
}
}
if (direction == "DOWN")
{
if (row - point.first >= pat.size()){
return 1;
}
else{
return 0;
}
}
if (direction == "LEFT")
{
if (point.second >= pat.size()){
return 1;
}
else{
return 0;
}
}
if (direction == "RIGHT")
{
if (col - point.second >= pat.size()){
return 1;
}
else{
return 0;
}
}
}
void explore(vector<pair<int, int> >& loc, string& pat, int rows, int cols, string arr[]){
int seq = 0;
int travelunits = pat.size();
// Now we have points but we have constraints as well
for(pair<int, int>& num : loc){
int x = num.first;
int y = num.second;
// accessing each pair and explore in parallel (in all 4 dirs)
// explore only if direction is feasible
if (isValid(num, "UP", rows, cols, pat)){
// If up is valid explore the up direction
int match = 0;
for (int i = 0; i < travelunits; i ++){
if (arr[x][y-i] == pat[i]) {
match++;
}
}
if (match == travelunits){
seq++;
}
}
if (isValid(num, "DOWN", rows, cols, pat))
{
// If up is valid explore the up direction
int match = 0;
for (int i = 0; i < travelunits; i++)
{
if (arr[x][y+i] == pat[i])
{
match++;
}
}
if (match == travelunits)
{
seq++;
}
}
if (isValid(num, "LEFT", rows, cols, pat))
{
// If up is valid explore the up direction
int match = 0;
for (int i = 0; i < travelunits; i++)
{
if (arr[x-i][y] == pat[i])
{
match++;
}
}
if (match == travelunits)
{
seq++;
}
}
if (isValid(num, "RIGHT", rows, cols, pat))
{
// If up is valid explore the up direction
int match = 0;
for (int i = 0; i < travelunits; i++)
{
if (arr[x + i][y] == pat[i])
{
match++;
}
}
if (match == travelunits)
{
seq++;
}
}
}
cout << "Matches found: " << seq << endl;
}
int main()
{
// define a string
string needle = "MAGIC";
string input[] = {"BBABBM",
"CBMBBA",
"IBABBG",
"GOZBBI",
"ABBBBC",
"MCIGAM"};
// Preprocessing step, find all locations where we have "M"
// variable definition to store all the locations
vector<pair<int, int> > locations;
int array_size = (sizeof(input) / sizeof(*input));
for (int row; row < array_size; row++){
for (int col; col < input[0].size(); col++ ){
// check if input's specific row and column reads needles first char
if (input[row][col] == needle[0]){
locations.push_back(make_pair(row, col));
}
}
}
// Now we have all the required locations that have "M" of "MAGIC"
// Make a function for exploration
explore(locations, needle, array_size, input[0].size(), input);
return 0;
}
|
#pragma once
#include "ast.hpp"
#include "lexer.hpp"
#include <vector>
class ASTBuilder {
public:
ASTBuilder(std::vector<Token> t) { tokens = t;}
block parseFile();
private:
statp parseStatement();
statp parseStatementAux(std::string id);
statp parseIf();
statp parseWhile();
statp parseFor();
statp parseReturn();
statp parseAssignStatement(std::string id);
std::vector<std::string> parseArgList();
block parseBlock();
exprp parseExpression();
exprp parseTernary();
exprp parseFunction();
exprp parseLogicOr();
exprp parseLogicOrAux(exprp e);
exprp parseLogicAnd();
exprp parseLogicAndAux(exprp e);
exprp parseComp();
exprp parseCompAux(exprp e);
exprp parseRel();
exprp parseRelAux(exprp e);
exprp parseTerm();
exprp parseTermAux(exprp e);
exprp parseFactor();
exprp parseFactorAux(exprp e);
exprp parsePrimary();
exprp parsePrimaryAux(UnOpType t);
exprp parseElement();
Token next();
Token peek();
bool expect(Token::Kind kind);
std::vector<Token> tokens;
size_t index = 0;
};
|
#include <map>
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include "crossplatform.h"
#define LONG_SIDE_WIDTH 0
#define LONG_SIDE_HIGH 1
using namespace std;
using namespace cv;
map<string,string> config;
string getFFmpegCmd();
map<string,string> readConfig();
void adjustPicture(const vector<string>& fileName);
int main(int argc,const char* argv[])
{
config = readConfig();
vector<string> fileName = readFileNameFromDir(config["pictureDir"]);
adjustPicture(fileName);
system(getFFmpegCmd().c_str());
removeDir("tmp");
// for(auto i=fileName.begin();i!=fileName.end();++i){
// cout << *i << endl;
// }
return 0;
}
map<string,string> readConfig()
{
char tmp[128] = {0};
map<string,string> ret;
fstream fin;
fin.open("config.ini",fstream::in);
if(!fin.is_open()){
cout << "open configure error" << endl;
return ret;
}
while(!fin.eof()){
fin.getline(tmp,127);
if(*tmp == 0){
continue;
}
char* head = tmp;
char* tail = tmp;
while(*tail != 0){
if(*tail == ' '){
++tail;
}
else{
*head++ = *tail++;
}
}
if(*tmp == '#'){
continue;
}
*head = 0;
string s(tmp);
size_t t = s.find('=');
string a = s.substr(0,t);
string b = s.substr(t+1,string::npos);
ret.insert(pair<string,string>(a,b));
}
fin.close();
size_t t = ret["resolution"].find('x');
string a = ret["resolution"].substr(0,t);
string b = ret["resolution"].substr(t+1,string::npos);
ret.insert(pair<string,string>("width",a));
ret.insert(pair<string,string>("high",b));
if(ret["pictureDir"].back() != '/'){
ret["pictureDir"].push_back('/');
}
return ret;
}
void adjustPicture(const vector<string>& fileName)
{
int t = 0;
int j = 1;
int high = 0;
int digit = 0;
int width = 0;
int longSide = 0;
double a = 0;
double b = 0;
double scale = 0;
char saveName[256] = {0};
char tmp[10] = {0};
Mat p;
Mat pic;
Mat pROI;
Rect roi;
sscanf(config["high"].c_str(),"%d",&high);
sscanf(config["width"].c_str(),"%d",&width);
pic.create(high,width,CV_8UC3);
system("mkdir tmp");
t = fileName.size();
while(t){
t /= 10;
++digit;
}
sprintf(tmp,"%d",digit);
config.insert(pair<string,string>("digit",string(tmp)));
for(auto i=fileName.begin();i!=fileName.end();++i){
pic.setTo(Scalar(0,0,0));
p = imread(config["pictureDir"]+*i);
longSide = (p.rows<p.cols)?LONG_SIDE_WIDTH:LONG_SIDE_HIGH;
a = (double)high/p.rows;
b = (double)width/p.cols;
scale = (a<b)?(a):(b);
longSide = (a>b)?LONG_SIDE_WIDTH:LONG_SIDE_HIGH;
if(scale < 1){
resize(p,p,Size(),scale,scale);
if (longSide == LONG_SIDE_HIGH) {
roi = Rect((width - p.cols) / 2, 0, p.cols, p.rows);
}
else {
roi = Rect(0, (high - p.rows) / 2, p.cols, p.rows);
}
}
else {
roi = Rect((width - p.cols) / 2, (high - p.rows) / 2, p.cols, p.rows);
}
pROI = pic(roi);
p.copyTo(pROI);
sprintf(saveName,"./tmp/%0*d.jpg",digit,j);
imwrite(String(saveName),pic);
++j;
}
return;
}
string getFFmpegCmd()
{
int digit = 0;
double fps = 0;
char cmd[256] = {0};
sscanf(config["digit"].c_str(),"%d",&digit);
sscanf(config["perPictureSecond"].c_str(),"%lf",&fps);
fps = 1/fps;
#ifdef OS_LINUX
sprintf(cmd,"./linux/ffmpeg -r %.5f -i ./tmp/%%0%dd.jpg -vcodec mpeg4 -r 30 -y video.mp4",fps,digit);
#else
sprintf(cmd,".\\windows\\ffmpeg.exe -r %.5f -i .\\tmp\\%%0%dd.jpg -vcodec mpeg4 -r 30 -b 4000000 -y video.mp4",fps,digit);
#endif
cout << cmd << endl;
return string(cmd);
}
|
#pragma once
#include "../../gl_command.h"
namespace glmock
{
//
// http://www.opengl.org/sdk/docs/man3/xhtml/glUseProgram.xml
class GLUseProgram : public GLCommand
{
public:
GLUseProgram(GLuint program);
virtual ~GLUseProgram();
public:
void Eval(GLuint program);
private:
GLenum mProgram;
};
}
|
// Created on : Sat May 02 12:41:15 2020
// Created by: Irina KRYLOVA
// Generator: Express (EXPRESS -> CASCADE/XSTEP Translator) V3.0
// Copyright (c) Open CASCADE 2020
//
// 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 _StepKinematics_KinematicTopologyNetworkStructure_HeaderFile_
#define _StepKinematics_KinematicTopologyNetworkStructure_HeaderFile_
#include <Standard.hxx>
#include <StepRepr_RepresentationContext.hxx>
#include <StepKinematics_KinematicTopologyStructure.hxx>
DEFINE_STANDARD_HANDLE(StepKinematics_KinematicTopologyNetworkStructure, StepRepr_Representation)
//! Representation of STEP entity KinematicTopologyNetworkStructure
class StepKinematics_KinematicTopologyNetworkStructure : public StepRepr_Representation
{
public :
//! default constructor
Standard_EXPORT StepKinematics_KinematicTopologyNetworkStructure();
//! Initialize all fields (own and inherited)
Standard_EXPORT void Init(const Handle(TCollection_HAsciiString)& theRepresentation_Name,
const Handle(StepRepr_HArray1OfRepresentationItem)& theRepresentation_Items,
const Handle(StepRepr_RepresentationContext)& theRepresentation_ContextOfItems,
const Handle(StepKinematics_KinematicTopologyStructure)& theParent);
//! Returns field Parent
Standard_EXPORT Handle(StepKinematics_KinematicTopologyStructure) Parent() const;
//! Sets field Parent
Standard_EXPORT void SetParent (const Handle(StepKinematics_KinematicTopologyStructure)& theParent);
DEFINE_STANDARD_RTTIEXT(StepKinematics_KinematicTopologyNetworkStructure, StepRepr_Representation)
private:
Handle(StepKinematics_KinematicTopologyStructure) myParent;
};
#endif // _StepKinematics_KinematicTopologyNetworkStructure_HeaderFile_
|
#include <iostream>
using namespace std;
int main()
{
int a,b,n;
float s;
cin>>a>>b;
s=a+0.1*b;
n=(s/1.9)/1;
cout<<n;
return 0;
}
|
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCursesColor.h"
#include "cmCursesStandardIncludes.h"
bool cmCursesColor::HasColors()
{
#ifdef HAVE_CURSES_USE_DEFAULT_COLORS
return has_colors();
#else
return false;
#endif
}
void cmCursesColor::InitColors()
{
#ifdef HAVE_CURSES_USE_DEFAULT_COLORS
if (HasColors()) {
start_color();
use_default_colors();
init_pair(cmCursesColor::BoolOff, COLOR_RED, -1);
init_pair(cmCursesColor::BoolOn, COLOR_GREEN, -1);
init_pair(cmCursesColor::String, COLOR_BLUE, -1);
init_pair(cmCursesColor::Path, COLOR_YELLOW, -1);
init_pair(cmCursesColor::Options, COLOR_MAGENTA, -1);
}
#endif
}
|
bool isSafe(vector<vector<int> > &A, int i, int j, int n, int m)
{
if(i>=0 &&i<n && j>=0 && j<m && A[i][j]==1)
return true;
return false;
}
int find(vector<vector<int> > &A, int x, int y, int n, int m)
{
queue<pair<int, int> > q;
q.push({x,y});
int X[]={0,0,1,-1,1,1,-1,-1};
int Y[]={1,-1,0,0,-1,1,1,-1};
int c=0, newX, newY, i;
A[x][y]=0;
while(!q.empty())
{
pair<int, int> temp = q.front();
q.pop();
c++;
for(i=0;i<8;i++)
{
newX = X[i]+temp.first;
newY = Y[i]+temp.second;
if(isSafe(A,newX,newY,n,m))
{
A[newX][newY]=0;
q.push({newX, newY});
}
}
}
return c;
}
int Solution::solve(vector<vector<int> > &A) {
int ans=0;
if(A.size()==0 || A[0].size()==0)
return 0;
int n=A.size(), m=A[0].size(), i, j;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
if(A[i][j]==1)
{
int x = find(A,i,j,n,m);
ans=max(ans, x);
}
return ans;
}
|
#include "notebook.h"
Notebook::Notebook(const std::weak_ptr<Settings> settings)
{
this->settings = settings.lock();
try
{
loadNotes();
}
catch(...)
{
throw;
}
}
Notebook::~Notebook()
{
deleteAll();
}
void Notebook::addNote(Note * const note)
{
notes.append(note);
}
void Notebook::loadNotes()
{
QFile file(filePath);
if(!file.exists())
return;
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
throw std::runtime_error("Failed to open OrgNotes.xml");
QXmlStreamReader xml(&file);
while (!xml.atEnd() && !xml.hasError())
{
QXmlStreamReader::TokenType token = xml.readNext();
if(token == QXmlStreamReader::StartDocument)
continue;
if(token == QXmlStreamReader::StartElement)
{
if(xml.name() == "notebook")
continue;
if(xml.name() == "note")
{
notes.append(parseNote(xml));
}
}
}
if(xml.hasError())
throw std::runtime_error(xml.errorString().toStdString());
file.close();
}
Note* Notebook::parseNote(QXmlStreamReader &xml) const
{
Note *n = nullptr;
QDate date;
QString text;
nFrequency frequency;
bool notifEnabled;
int daysPrior;
QXmlStreamAttributes attributes = xml.attributes();
if(attributes.hasAttribute("date"))
date = QDate::fromString(attributes.value("date").toString(),"dd/MM/yyyy");
xml.readNext();
while(xml.tokenType() != QXmlStreamReader::EndElement || xml.name() != "note")
{
if(xml.tokenType() == QXmlStreamReader::StartElement)
{
if(xml.name() == "text")
{
xml.readNext();
text = xml.text().toString();
}
else if(xml.name() == "frequency")
{
xml.readNext();
frequency = static_cast<nFrequency>(xml.text().toInt());
}
else if(xml.name() == "notifEnabled")
{
xml.readNext();
notifEnabled = xml.text().toInt();
}
else if(xml.name() == "daysPrior")
{
xml.readNext();
daysPrior = xml.text().toInt();
}
}
xml.readNext();
}
n = new Note(date, text, frequency, notifEnabled, daysPrior);
return n;
}
void Notebook::saveNotes() const
{
QFile file(filePath);
if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
throw std::runtime_error("Failed to open OrgNotes.xml");
QXmlStreamWriter xml(&file);
xml.setAutoFormatting(true);
xml.writeStartDocument();
xml.writeStartElement("notebook");
for (Note *n : notes)
{
xml.writeStartElement("note");
xml.writeAttribute("date",n->date.toString("dd/MM/yyyy"));
xml.writeTextElement("text",n->text);
xml.writeTextElement("frequency",QString::number(static_cast<int>(n->frequency)));
xml.writeTextElement("notifEnabled",QString::number(n->notifEnabled));
xml.writeTextElement("daysPrior",QString::number(n->daysPrior));
xml.writeEndElement();
}
xml.writeEndElement();
xml.writeEndDocument();
file.flush();
file.close();
}
std::unique_ptr<QList<Note*>> Notebook::getNotesFromDate(const QDate & date) const
{
std::unique_ptr<QList<Note*>> list(new QList<Note*>);
for(auto note : notes)
{
if(noteOnDate(note, date))
{
list->append(note);
}
}
return list;
}
std::unique_ptr<QList<Note*>> Notebook::getNotificationsFromDate(const QDate & date) const
{
// Returns notes that are up for notification popup at the date.
std::unique_ptr<QList<Note*>> list(new QList<Note*>);
for(auto note : notes)
{
if(notificationOnDate(note, date))
{
list->append(note);
}
}
return list;
}
int Notebook::contains(const QDate &date) const
{
int count = 0;
for (auto note : notes)
{
if(noteOnDate(note, date))
{
++count;
}
}
return count;
}
bool Notebook::noteOnDate(Note * const note, const QDate & date) const
{
if(
(
(note->date == date) ||
(note->frequency == nFrequency::Week && note->date.daysTo(date) % 7 == 0) ||
(note->frequency == nFrequency::Month && date.day() == note->date.day()) ||
(note->frequency == nFrequency::Year && date.day() == note->date.day() && date.month() == note->date.month())
)
&&
(
(settings->rDisplay == Settings::All) ||
(settings->rDisplay == Settings::Future && (date >= QDate::currentDate() || note->frequency == nFrequency::Once)) ||
(settings->rDisplay == Settings::Closest && date == getClosestDate(note, QDate::currentDate()))
)
)
return true;
return false;
}
bool Notebook::notificationOnDate(Note * const note, const QDate & date) const
{
if(note->notifEnabled)
{
if(note->date == date)
return true;
auto showNotification = [&](QDate ¬eDate)->bool{return noteDate >= date && date >= noteDate.addDays(-note->daysPrior);};
if(note->frequency == nFrequency::Once)
{
return showNotification(note->date);
}
else
{
note->date = getClosestDate(note, date);
return showNotification(note->date);
}
}
return false;
}
QDate Notebook::getClosestDate(Note * const note, const QDate &date) const
{
if(note->frequency == nFrequency::Once)
{
return note->date;
}
else
{
QDate (*next)(QDate&, int&);
if(note->frequency == nFrequency::Week)
next = [](QDate &d, int &sign){return d.addDays(sign * 7);};
else if(note->frequency == nFrequency::Month)
next = [](QDate &d, int &sign){return d.addMonths(sign * 1);};
else
next = [](QDate &d, int &sign){return d.addYears(sign * 1);};
int sign = note->date > date ? -1 : 1;
QDate closestDate = note->date;
if(note->date > date)
{
QDate tempDate = next(closestDate, sign);
while(tempDate >= date)
{
closestDate = tempDate;
tempDate = next(tempDate, sign);
}
}
else
{
while(closestDate < date)
{
closestDate = next(closestDate, sign);
}
}
return closestDate;
}
}
bool Notebook::deleteNote(Note *note)
{
if(notes.contains(note))
{
delete note;
return notes.removeOne(note);
}
return false;
}
int Notebook::deleteAll()
{
int deleted = notes.size();
for(auto note : notes)
{
delete note;
}
notes.clear();
return deleted;
}
int Notebook::deleteOutdated(const QDate &date)
{
int deleted = 0;
for(auto note : notes)
{
if(note->date < date)
{
if(note->frequency == nFrequency::Once)
{
delete note;
notes.removeOne(note);
++deleted;
}
}
else
return deleted;
}
return deleted;
}
Note* Notebook::findClosest(const QDate &date) const
{
Note *cNote = nullptr;
QDate cDate;
for(auto note : notes)
{
QDate cDateOther = getClosestDate(note, date);
if(cDateOther >= date)
{
if(cNote == nullptr)
{
cNote = note;
cDate = cDateOther;
}
else
if(cDate > cDateOther)
{
cNote = note;
cDate = cDateOther;
}
}
}
return cNote;
}
|
// Copyright Low Entry. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "CoreUObject.h"
#include "ELowEntryFileManagerYesNo.h"
#include "LowEntryFileManagerDirectory.generated.h"
class ULowEntryFileManagerDirectory;
class ULowEntryFileManagerFile;
UCLASS(BlueprintType)
class LOWENTRYFILEMANAGER_API ULowEntryFileManagerDirectory : public UObject
{
GENERATED_UCLASS_BODY()
public:
static ULowEntryFileManagerDirectory* CreateRoot();
static ULowEntryFileManagerDirectory* CreateAbsoluteRoot();
static ULowEntryFileManagerDirectory* Create(const FString& Directory, const FString& Name);
static ULowEntryFileManagerDirectory* Create(const FString& Path);
public:
UPROPERTY()
FString Directory;
UPROPERTY()
FString Name;
UPROPERTY()
FString Path;
UPROPERTY()
bool bIsRoot = false;
/**
* Returns the path of this directory.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Get Path (Directory)"))
FString GetPath() const;
/**
* Returns the absolute path of this directory.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Get Absolute Path (Directory)"))
FString GetAbsolutePath() const;
/**
* Returns the name of this directory.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Get Name (Directory)"))
FString GetName() const;
/**
* Returns true if this directory is the root of UE4's file system.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Is Root (Directory) (Boolean)"))
bool IsRootBool();
/**
* Returns true if this directory is the root of UE4's file system.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Is Root (Directory)", ExpandEnumAsExecs = "Branch"))
void IsRoot(ELowEntryFileManagerYesNo& Branch);
/**
* Returns an array of files that exist in this directory.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Get Files"))
TArray<ULowEntryFileManagerFile*> GetFiles();
/**
* Returns an array of directories that exist in this directory.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Get Directories"))
TArray<ULowEntryFileManagerDirectory*> GetDirectories();
/**
* Returns a file in this directory, the file may or may not exist.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Get File"))
ULowEntryFileManagerFile* GetFile(const FString& File);
/**
* Returns a directory in this directory, the directory may or may not exist.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Get Directory"))
ULowEntryFileManagerDirectory* GetDirectory(const FString& Directory_);
/**
* Returns the directory this directory is inside in.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Get Parent Directory (Directory)"))
ULowEntryFileManagerDirectory* GetParentDirectory();
/**
* Returns true if this directory exists.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Exists (Directory) (Boolean)"))
bool ExistsBool();
/**
* Returns true if this directory exists.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Exists (Directory)", ExpandEnumAsExecs = "Branch"))
void Exists(ELowEntryFileManagerYesNo& Branch);
/**
* Creates this directory (and any parent directories) if it doesn't exist yet.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Create (Directory)"))
void Create();
/**
* Deletes this directory if it exists.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Delete (Directory)"))
void Delete();
/**
* Returns true if this directory is empty or if it does not exist.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Is Empty (Directory) (Boolean)"))
bool IsEmptyBool();
/**
* Returns true if this directory is empty or if it does not exist.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Is Empty (Directory)", ExpandEnumAsExecs = "Branch"))
void IsEmpty(ELowEntryFileManagerYesNo& Branch);
/**
* Removes this directory (and anything that is inside of it) and creates a new directory with the same name on the same location, basically causing this directory to be existing and empty.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Clear (Directory)"))
void Clear();
/**
* Copies this directory, if the given NewDirectory already exists, this directory will merge with the existing directory.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Copy (Directory)", Keywords = "clone duplicate"))
void CopyTo(ULowEntryFileManagerDirectory* NewDirectory, const bool OverrideExistingFiles);
/**
* Moves/renames this directory, if the given NewDirectory already exists, this directory will merge with the existing directory.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|High Level|Directory", Meta = (DisplayName = "Move (Directory)", Keywords = "rename"))
void MoveTo(ULowEntryFileManagerDirectory* NewDirectory, const bool OverrideExistingFiles);
};
|
/*
* 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 <folly/MoveWrapper.h>
#include <folly/container/F14Map.h>
#include <folly/futures/Future.h>
#include <folly/io/async/test/MockAsyncTransport.h>
#include <folly/portability/GMock.h>
#include <folly/portability/GTest.h>
#include <quic/api/QuicStreamAsyncTransport.h>
#include <quic/api/test/Mocks.h>
#include <quic/client/QuicClientTransport.h>
#include <quic/common/test/TestClientUtils.h>
#include <quic/common/test/TestUtils.h>
#include <quic/fizz/client/handshake/FizzClientHandshake.h>
#include <quic/fizz/client/handshake/FizzClientQuicHandshakeContext.h>
#include <quic/server/QuicServer.h>
#include <quic/server/QuicServerTransport.h>
#include <quic/server/test/Mocks.h>
using namespace testing;
namespace quic::test {
class QuicStreamAsyncTransportTest : public Test {
protected:
struct Stream {
folly::test::MockWriteCallback writeCb;
folly::test::MockReadCallback readCb;
QuicStreamAsyncTransport::UniquePtr transport;
std::array<uint8_t, 1024> buf;
uint8_t serverDone{2}; // need to finish reads & writes
};
public:
void SetUp() override {
folly::ssl::init();
createServer();
connect();
}
void createServer() {
auto serverTransportFactory =
std::make_unique<MockQuicServerTransportFactory>();
// should only be invoked once since we open at most one connection; checked
// via .WillOnce()
EXPECT_CALL(*serverTransportFactory, _make(_, _, _, _))
.WillOnce(Invoke(
[&](folly::EventBase* evb,
std::unique_ptr<QuicAsyncUDPSocketType>& socket,
const folly::SocketAddress& /*addr*/,
std::shared_ptr<const fizz::server::FizzServerContext> ctx) {
auto transport = quic::QuicServerTransport::make(
evb,
std::move(socket),
&serverConnectionSetupCB_,
&serverConnectionCB_,
std::move(ctx));
// serverSocket_ only set via the factory, validate it hasn't been
// set before.
CHECK(!serverSocket_);
serverSocket_ = transport;
return transport;
}));
// server setup
server_ = QuicServer::createQuicServer();
server_->setFizzContext(test::createServerCtx());
server_->setQuicServerTransportFactory(std::move(serverTransportFactory));
// start server
server_->start(folly::SocketAddress("::1", 0), 1);
server_->waitUntilInitialized();
serverAddr_ = server_->getAddress();
}
void serverExpectNewBidiStreamFromClient() {
EXPECT_CALL(serverConnectionCB_, onNewBidirectionalStream(_))
.WillOnce(Invoke([this](StreamId id) {
auto stream = std::make_unique<Stream>();
stream->transport =
QuicStreamAsyncTransport::createWithExistingStream(
serverSocket_, id);
auto& transport = stream->transport;
auto& readCb = stream->readCb;
auto& writeCb = stream->writeCb;
auto& streamBuf = stream->buf;
auto& serverDone = stream->serverDone;
streams_[id] = std::move(stream);
EXPECT_CALL(readCb, readEOF_())
.WillOnce(Invoke([&transport, &serverDone] {
if (--serverDone == 0) {
transport->close();
}
}));
EXPECT_CALL(readCb, isBufferMovable_()).WillRepeatedly(Return(false));
EXPECT_CALL(readCb, getReadBuffer(_, _))
.WillRepeatedly(Invoke([&streamBuf](void** buf, size_t* len) {
*buf = streamBuf.data();
*len = streamBuf.size();
}));
EXPECT_CALL(readCb, readDataAvailable_(_))
.WillRepeatedly(Invoke(
[&streamBuf, &serverDone, &writeCb, &transport](auto len) {
auto echoData = folly::IOBuf::copyBuffer("echo ");
echoData->appendChain(
folly::IOBuf::wrapBuffer(streamBuf.data(), len));
EXPECT_CALL(writeCb, writeSuccess_())
.WillOnce(Return())
.RetiresOnSaturation();
if (transport->good()) {
// Echo the first readDataAvailable_ only
transport->writeChain(&writeCb, std::move(echoData));
transport->shutdownWrite();
if (--serverDone == 0) {
transport->close();
}
}
}));
transport->setReadCB(&readCb);
}))
.RetiresOnSaturation();
}
std::unique_ptr<Stream> createClient(bool setReadCB = true) {
auto clientStream = std::make_unique<Stream>();
clientStream->transport =
QuicStreamAsyncTransport::createWithNewStream(client_);
CHECK(clientStream->transport);
EXPECT_CALL(clientStream->readCb, isBufferMovable_())
.WillRepeatedly(Return(false));
EXPECT_CALL(clientStream->readCb, getReadBuffer(_, _))
.WillRepeatedly(Invoke(
[clientStream = clientStream.get()](void** buf, size_t* len) {
*buf = clientStream->buf.data();
*len = clientStream->buf.size();
}));
if (setReadCB) {
clientStream->transport->setReadCB(&clientStream->readCb);
}
return clientStream;
}
void connect() {
auto [promise, future] = folly::makePromiseContract<folly::Unit>();
EXPECT_CALL(clientConnectionSetupCB_, onTransportReady())
.WillOnce(Invoke([&p = promise]() mutable { p.setValue(); }));
clientEvb_.runInLoop([&]() {
auto sock = std::make_unique<QuicAsyncUDPSocketType>(&clientEvb_);
auto fizzClientContext =
FizzClientQuicHandshakeContext::Builder()
.setCertificateVerifier(test::createTestCertificateVerifier())
.build();
client_ = std::make_shared<QuicClientTransport>(
&clientEvb_, std::move(sock), std::move(fizzClientContext));
client_->setHostname("echo.com");
client_->addNewPeerAddress(serverAddr_);
client_->start(&clientConnectionSetupCB_, &clientConnectionCB_);
});
std::move(future).via(&clientEvb_).waitVia(&clientEvb_);
}
void TearDown() override {
if (client_) {
client_->close(folly::none);
}
clientEvb_.loop();
server_->shutdown();
server_ = nullptr;
client_ = nullptr;
}
protected:
std::shared_ptr<QuicServer> server_;
folly::SocketAddress serverAddr_;
NiceMock<MockConnectionSetupCallback> serverConnectionSetupCB_;
NiceMock<MockConnectionCallback> serverConnectionCB_;
std::shared_ptr<quic::QuicSocket> serverSocket_;
folly::F14FastMap<quic::StreamId, std::unique_ptr<Stream>> streams_;
std::shared_ptr<QuicClientTransport> client_;
folly::EventBase clientEvb_;
NiceMock<MockConnectionSetupCallback> clientConnectionSetupCB_;
NiceMock<MockConnectionCallback> clientConnectionCB_;
};
TEST_F(QuicStreamAsyncTransportTest, ReadWrite) {
serverExpectNewBidiStreamFromClient();
auto clientStream = createClient();
EXPECT_CALL(clientStream->readCb, readEOF_()).WillOnce(Return());
auto [promise, future] = folly::makePromiseContract<std::string>();
EXPECT_CALL(clientStream->readCb, readDataAvailable_(_))
.WillOnce(Invoke([&clientStream, &p = promise](auto len) mutable {
p.setValue(std::string(
reinterpret_cast<char*>(clientStream->buf.data()), len));
}));
std::string msg = "yo yo!";
EXPECT_CALL(clientStream->writeCb, writeSuccess_()).WillOnce(Return());
clientStream->transport->write(
&clientStream->writeCb, msg.data(), msg.size());
clientStream->transport->shutdownWrite();
EXPECT_EQ(
std::move(future).via(&clientEvb_).getVia(&clientEvb_), "echo yo yo!");
}
TEST_F(QuicStreamAsyncTransportTest, TwoClients) {
std::list<std::unique_ptr<Stream>> clientStreams;
std::list<folly::SemiFuture<std::string>> futures;
std::string msg = "yo yo!";
for (auto i = 0; i < 2; i++) {
serverExpectNewBidiStreamFromClient();
clientStreams.emplace_back(createClient());
auto& clientStream = clientStreams.back();
EXPECT_CALL(clientStream->readCb, readEOF_()).WillOnce(Return());
auto [promiseX, future] = folly::makePromiseContract<std::string>();
auto promise = std::move(promiseX);
futures.emplace_back(std::move(future));
EXPECT_CALL(clientStream->readCb, readDataAvailable_(_))
.WillOnce(Invoke(
[clientStream = clientStream.get(),
p = folly::MoveWrapper(std::move(promise))](auto len) mutable {
p->setValue(std::string(
reinterpret_cast<char*>(clientStream->buf.data()), len));
}));
EXPECT_CALL(clientStream->writeCb, writeSuccess_()).WillOnce(Return());
clientStream->transport->write(
&clientStream->writeCb, msg.data(), msg.size());
clientStream->transport->shutdownWrite();
}
for (auto& future : futures) {
EXPECT_EQ(
std::move(future).via(&clientEvb_).getVia(&clientEvb_), "echo yo yo!");
}
}
TEST_F(QuicStreamAsyncTransportTest, DelayedSetReadCB) {
serverExpectNewBidiStreamFromClient();
auto clientStream = createClient(/*setReadCB=*/false);
auto [promise, future] = folly::makePromiseContract<std::string>();
EXPECT_CALL(clientStream->readCb, readDataAvailable_(_))
.WillOnce(Invoke([&clientStream, &p = promise](auto len) mutable {
p.setValue(std::string(
reinterpret_cast<char*>(clientStream->buf.data()), len));
}));
std::string msg = "yo yo!";
EXPECT_CALL(clientStream->writeCb, writeSuccess_()).WillOnce(Return());
clientStream->transport->write(
&clientStream->writeCb, msg.data(), msg.size());
clientEvb_.runAfterDelay(
[&clientStream] {
EXPECT_CALL(clientStream->readCb, readEOF_()).WillOnce(Return());
clientStream->transport->setReadCB(&clientStream->readCb);
clientStream->transport->shutdownWrite();
},
750);
EXPECT_EQ(
std::move(future).via(&clientEvb_).getVia(&clientEvb_), "echo yo yo!");
}
TEST_F(QuicStreamAsyncTransportTest, SetReadCbNullptr) {
/**
* invoking folly::AsyncTransport::setReadCb(nullptr) should map to
* QuicSocket::pauseRead() rather than QuicSocket::setReadCB(nullptr) which
* effectively is a terminal call that permanently uninstalls the callback
*/
serverExpectNewBidiStreamFromClient();
auto clientStream = createClient(/*setReadCB=*/true);
// unset callback before sending or receiving data from server – until we set
// the setReadCB we should never invoke readDataAvailable()
clientStream->transport->setReadCB(nullptr);
EXPECT_CALL(clientStream->readCb, readDataAvailable_(_)).Times(0);
// write data to stream
std::string msg = "yo yo!";
EXPECT_CALL(clientStream->writeCb, writeSuccess_()).WillOnce(Return());
clientStream->transport->write(
&clientStream->writeCb, msg.data(), msg.size());
auto [promise, future] = folly::makePromiseContract<std::string>();
clientEvb_.runAfterDelay(
[&clientStream, &p = promise] {
// setReadCB() to non-nullptr should resume read from QuicSocket and
// invoke readDataAvailable()
EXPECT_CALL(clientStream->readCb, readDataAvailable_(_))
.WillOnce(Invoke([&clientStream, &p](auto len) mutable {
p.setValue(std::string(
reinterpret_cast<char*>(clientStream->buf.data()), len));
}));
EXPECT_CALL(clientStream->readCb, readEOF_()).WillOnce(Return());
clientStream->transport->setReadCB(&clientStream->readCb);
clientStream->transport->shutdownWrite();
},
750);
EXPECT_EQ(
std::move(future).via(&clientEvb_).getVia(&clientEvb_), "echo yo yo!");
}
TEST_F(QuicStreamAsyncTransportTest, close) {
auto clientStream = createClient(/*setReadCB=*/false);
EXPECT_TRUE(client_->good());
clientStream->transport->close();
clientStream->transport.reset();
EXPECT_TRUE(client_->good());
clientEvb_.loopOnce();
}
TEST_F(QuicStreamAsyncTransportTest, closeNow) {
auto clientStream = createClient(/*setReadCB=*/false);
EXPECT_TRUE(client_->good());
clientStream->transport->closeNow();
clientStream->transport.reset();
// The quic socket is still good
EXPECT_TRUE(client_->good());
clientEvb_.loopOnce();
}
} // namespace quic::test
|
#include<bits/stdc++.h>
#define rep(i,n) for (int i =0; i <(n); i++)
using namespace std;
using ll = long long;
int main(){
string S;
cin >> S;
int ans = 0;
bool flag = false;
int now = 0;
for(int i = 0; i < (int)S.size(); i++){
if(S.at(i) == 'A' || S.at(i) == 'C' || S.at(i) == 'G' || S.at(i) == 'T' ){
if( flag == true){
now++;
}
else {
flag = true;
now = 1;
}
}
else {
flag = false;
ans = max(ans,now);
now = 0;
}
}
ans = max(ans,now);
cout << ans << endl;
return 0;
}
|
#include "game.h"
#include "event.h"
#include <stdio.h>
Game::Game( int argc, char* args[] )
{
fprintf( stderr, "Game::Game()\n" );
m_window = NULL;
m_screenSurface = NULL;
initialize();
loadAssets();
}
Game::~Game()
{
fprintf( stderr, "Game::~Game()\n" );
shutdown();
}
void
Game::Loop()
{
do
{
handlingEvents();
draw();
} while ( !isGameOver() );
}
void
Game::handlingEvents()
{
m_event.HandlingEvent( *this );
}
bool
Game::initialize()
{
bool initialized = true;
// Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
fprintf( stderr, "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
initialized = false;
}
else
{
// Create window
m_window = SDL_CreateWindow( DEFAULT_WINDOW_TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if( m_window == NULL )
{
fprintf( stderr, "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
initialized = false;
}
else
{
m_screenSurface = SDL_GetWindowSurface( m_window );
}
}
return initialized;
}
bool
Game::loadAssets()
{
bool assetsLoaded = true;
const char* hello_world_file_path = "assets/lazyfoo/hello_world.bmp";
const char* x_file_path = "assets/lazyfoo/x.bmp";
// Load image
m_helloWorld = SDL_LoadBMP( hello_world_file_path );
if( m_helloWorld == NULL )
{
printf( "Unable to load image %s! SDL Error: %s\n", hello_world_file_path, SDL_GetError() );
assetsLoaded = false;
}
m_x = SDL_LoadBMP( x_file_path );
if( m_x == NULL )
{
printf( "Unable to load image %s! SDL Error: %s\n", x_file_path, SDL_GetError() );
assetsLoaded = false;
}
return assetsLoaded;
}
void
Game::draw()
{
// Get window surface
m_screenSurface = SDL_GetWindowSurface( m_window );
// Fill the surface white
SDL_FillRect( m_screenSurface, NULL, SDL_MapRGB( m_screenSurface->format, 0xEC, 0xEF, 0xF4 ) );
// Center the image on screen
SDL_Rect helloWorldDstrect = {
(m_screenSurface->w - m_helloWorld->w)/2,
(m_screenSurface->h - m_helloWorld->h)/2,
m_helloWorld->w,
m_helloWorld->h,
};
SDL_Rect xDstrect = {
(m_screenSurface->w - m_x->w)/2,
(m_screenSurface->h - m_x->h)/2,
m_x->w,
m_x->h,
};
// Apply image
SDL_BlitSurface( m_helloWorld, NULL, m_screenSurface, &helloWorldDstrect );
SDL_BlitSurface( m_x, NULL, m_screenSurface, &xDstrect );
// Update the surface
SDL_UpdateWindowSurface( m_window );
}
void
Game::shutdown()
{
fprintf( stderr, "Shutdown()\n" );
// Deallocate surface
SDL_FreeSurface( m_helloWorld );
m_helloWorld = NULL;
SDL_FreeSurface( m_x );
m_x = NULL;
// Destroy window
SDL_DestroyWindow( m_window );
m_window = NULL;
// Quit SDL subsystems
SDL_Quit();
}
bool
Game::isGameOver()
{
return m_quit;
}
void
Game::gameOver()
{
m_quit = true;
}
|
#pragma once
#include "component.h"
class AudioComponent : public Component {
public:
struct AudioClip {
AudioClip(Name& audio_name, Name& file_name) :
audio_name_(audio_name),
file_name_(file_name)
{}
Name audio_name_;
Name file_name_;
};
public:
void Destroy() override;
bool Load(const rapidjson::Value& value) override;
AudioComponent* Clone() { return new AudioComponent(*this); }
void Initialize() override;
void Update() override;
void Play(int index);
void Play(const Name& name);
void PlayNext();
void PlayRandom();
private:
std::vector<AudioClip> audio_clips_;
int play_tracker_;
};
|
#include "scene.h"
#include <QGraphicsSceneMouseEvent>
#include <QMouseEvent>
#include <QKeyEvent>
Scene::Scene()
{
}
void Scene::setPlayer(Player *player)
{
this->player = player;
addItem(player);
}
void Scene::keyPressEvent(QKeyEvent *event)
{
int key = event->key();
if (key == Qt::Key_S)
{
player->stopPosAnimation();
}
}
void Scene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
player->calculateNextPosition(player->pos().toPoint(), event->scenePos().toPoint());
player->runPosAnimation(player->pos().toPoint(), event->scenePos().toPoint());
}
|
#include <iostream>
#include <random>
#include <sstream>
#include <cmath>
//Where field_size is size of a square side
#define easy_field_size 10
#define easy_bomb_amount 10
#define normal_field_size 15
#define normal_bomb_amount 50
#define hard_field_size 20
#define hard_bomb_amount 20
int GetInt() {
int user_in;
std::string str_number;
while(true) {
std::getline(std::cin, str_number);
std::stringstream convert(str_number);
if(convert >> user_in && !(convert >> str_number)) return user_in;
std::cin.clear();
std::cout << "Invalid input! Try again: ";
}
}
void GenField(int *field, int lengthX, int lengthY, int bombs) { //Fill 2D array with mines in random spots
// 0 - Empty field
// 1 - 9 - amount of bombs in nearby cells
// 10 - bomb
for (int i = 0; i < lengthX; i++) { //Set all fields to 0 - empty fields
for (int j = 0; j < lengthY; j++) {
field[i * lengthY + j] = 0;
}
}
int emptyFields[lengthX * lengthY][2]; //List of empty fields X Y
int count = 0;
for (int i = 0; i < lengthX; i++) { //Fill the list
for (int j = 0; j < lengthY; j++) {
if (field[i * lengthY + j] == 0) {
emptyFields[count][0] = i;
emptyFields[count][1] = j;
count++;
}
}
}
for (int i = 0; i < bombs; i++) { //Setting bombs and numbers around them
int position = rand()%(lengthX * lengthY - i);
field[emptyFields[position][0] * lengthY + emptyFields[position][1]] = 10; //Set bomb
//Adding 1 to surounding cells
if (emptyFields[position][0] > 0 && emptyFields[position][1] > 0 //Upper right
&& field[(emptyFields[position][0] - 1) * lengthY + emptyFields[position][1] - 1] != 10) {
field[(emptyFields[position][0] - 1) * lengthY + emptyFields[position][1] - 1] += 1;
}
if (emptyFields[position][0] > 0 && field[(emptyFields[position][0] - 1) * lengthY + emptyFields[position][1]] != 10) { //Above
field[(emptyFields[position][0] - 1) * lengthY + emptyFields[position][1]] += 1;
}
if (emptyFields[position][0] > 0 && emptyFields[position][1] < lengthY //Upper left
&& field[(emptyFields[position][0] - 1) * lengthY + emptyFields[position][1] + 1] != 10) {
field[(emptyFields[position][0] - 1) * lengthY + emptyFields[position][1] + 1] += 1;
}
if (emptyFields[position][1] < lengthY && field[(emptyFields[position][0]) * lengthY + emptyFields[position][1] + 1] != 10) { //Left
field[(emptyFields[position][0]) * lengthY + emptyFields[position][1] + 1] += 1;
}
if (emptyFields[position][0] < lengthY && emptyFields[position][1] < lengthY //Lower left
&& field[(emptyFields[position][0] + 1) * lengthY + emptyFields[position][1] + 1] != 10) {
field[(emptyFields[position][0] + 1) * lengthY + emptyFields[position][1] + 1] += 1;
}
if (emptyFields[position][0] < lengthY && field[(emptyFields[position][0] + 1) * lengthY + emptyFields[position][1]] != 10) { //Below
field[(emptyFields[position][0] + 1) * lengthY + emptyFields[position][1]] += 1;
}
if (emptyFields[position][0] < lengthY && emptyFields[position][1] > 0 //Lower right
&& field[(emptyFields[position][0] + 1) * lengthY + emptyFields[position][1] - 1] != 10) {
field[(emptyFields[position][0] + 1) * lengthY + emptyFields[position][1] - 1] += 1;
}
if (emptyFields[position][1] > 0 && field[(emptyFields[position][0]) * lengthY + emptyFields[position][1] - 1] != 10) { //Right
field[(emptyFields[position][0]) * lengthY + emptyFields[position][1] - 1] += 1;
}
//Swap elemnts with last elemt in array - i
emptyFields[position][0] = emptyFields[position][0] + emptyFields[lengthX * lengthY - 1- i][0];
emptyFields[lengthX * lengthY -1 - i][0] = emptyFields[position][0] - emptyFields[lengthX * lengthY -1 - i][0];
emptyFields[position][0] = emptyFields[position][0] - emptyFields[lengthX * lengthY -1 - i][0];
emptyFields[position][1] = emptyFields[position][1] + emptyFields[lengthX * lengthY - 1- i][1];
emptyFields[lengthX * lengthY - 1- i][1] = emptyFields[position][1] - emptyFields[lengthX * lengthY -1 - i][1];
emptyFields[position][1] = emptyFields[position][1] - emptyFields[lengthX * lengthY - 1- i][1];
}
}
void RevealField(int *field, int *user_field, int lengthX, int lengthY, int x, int y, int *flags) {
if (user_field[x * lengthY + y] == 2) *flags = *flags + 1;
user_field[x * lengthY + y] = 1;
if (x - 1 >= 0 && y - 1 >= 0 && field[x * lengthY + y] == 0) {
if (user_field[(x - 1) * lengthY + y - 1] == 0 && field[(x - 1) * lengthY + y - 1] != 10) RevealField(field, user_field, lengthX, lengthY, x - 1, y - 1, flags);
}
if (x - 1 >= 0 && field[x * lengthY + y] == 0) {
if (user_field[(x - 1) * lengthY + y] == 0 && field[(x - 1) * lengthY + y] != 10) RevealField(field, user_field, lengthX, lengthY, x - 1, y, flags);
}
if (y - 1 >= 0 && field[x * lengthY + y] == 0) {
if (user_field[x * lengthY + y - 1] == 0 && field[x * lengthY + y - 1] != 10) RevealField(field, user_field, lengthX, lengthY, x, y - 1, flags);
}
if (x + 1 <= lengthX && y + 1 <= lengthY && field[x * lengthY + y] == 0) {
if (user_field[(x + 1) * lengthY + y + 1] == 0 && field[(x + 1) * lengthY + y + 1] != 10) RevealField(field, user_field, lengthX, lengthY, x + 1, y + 1, flags);
}
if (x + 1 <= lengthX && field[x * lengthY + y] == 0) {
if (user_field[(x + 1) * lengthY + y] == 0 && field[(x + 1) * lengthY + y] != 10) RevealField(field, user_field, lengthX, lengthY, x + 1, y, flags);
}
if (y + 1 <= lengthY && field[x * lengthY + y] == 0) {
if (user_field[x * lengthY + y + 1] == 0 && field[x * lengthY + y + 1] != 10) RevealField(field, user_field, lengthX, lengthY, x, y + 1, flags);
}
}
int CountDigits(int num) {
int count = 0;
while(num > 0) {
num = num/10;
count++;
}
return count;
}
void PrintField(int *field, int *user_field, int lengthX, int lengthY, int *flags) {
for (int i = 0; i < lengthX; i++) {
for (int j = 0; j < lengthY; j++) {
if (user_field[i * lengthY + j] == 2) std::cout << "|F";
else {
if (user_field[i * lengthY + j] == 1) {
if (field[i * lengthY + j] != 0) std::cout << "|" << field[i * lengthY + j];
else std::cout << "| ";
}
else std::cout << "|·";
}
}
std::cout << "| " << i << "\n";
}
for (int i = CountDigits(lengthX); i > 0; i--) {
for (int j = 0; j < lengthX; j++) {
std::string s = std::to_string(j);
if (s[i - 1] > 0) std::cout << " " << s[i - 1];
else std::cout << " 0";
}
std::cout << "\n";
}
std::cout << "Flags available: " << *flags << "\n";
}
bool AllBombsMarked(int *field, int *user_field, int lengthX, int lengthY) {
for (int i = 0; i < lengthX; i++) {
for (int j = 0; j < lengthY; j++) {
if (field[i * lengthY + j] == 10) {
if (user_field[i * lengthY + j] != 2) return false;
}
}
}
return true;
}
void MakeMove(int *field, int *user_field, int lengthX, int lengthY, int *flags, bool *gameover) {
int x, y;
do {
std::cout << "X: ?" << " Y: ?" << "\n";
do {
std::cout << "Enter X coordinate: ";
x = GetInt();
if (x < 0) std::cout << "Invalid input, Y must be > 0" << "\n";
if (x > lengthX) std::cout << "Invalid input, X must be within the field dimensions" << "\n";
}
while(x < 0 || x > lengthX);
std::cout <<"\33[2J\33[1;1H";
PrintField(field, user_field, lengthX, lengthY, flags);
std::cout << "X: " << x << " Y: ?" << "\n";
do {
std::cout << "Enter Y coordinate: ";
y = GetInt();
if (y < 0) std::cout << "Invalid input, Y must be > 0" << "\n";
if (y > lengthX) std::cout << "Invalid input, Y must be within the field dimensions" << "\n";
}
while(y < 0 || y > lengthY);
if (user_field[x * lengthY + y] == 1) std::cout << "This field is not available for placement!" << "\n";
}
while(user_field[x * lengthY + y] == 1);
std::cout << "\33[2J\33[1;1H";
std::cout <<"\33[2J\33[1;1H";
PrintField(field, user_field, lengthX, lengthY, flags);
std::cout << "Chosen coordinates: X: " << x << " Y: " << y << "\n";
int user_in;
if (user_field[x * lengthY + y] == 2) std::cout << "This field is flaged!" << "\n"; ;
std::cout << "Possible operations:" << "\n";
std::cout << "0. Toggle flag" << "\n";
std::cout << "1. Open field" << "\n";
std::cout << "2. Choose a different field" << "\n";
do {
std::cout << "Enter a number (0-2): ";
user_in = GetInt();
} while (user_in < 0 || user_in > 2);
switch (user_in) {
case 0:
if (user_field[x * lengthY + y] == 2) {
user_field[x * lengthY + y] = 0;
*flags = *flags + 1;
}
else if (user_field[x * lengthY + y] == 0) {
user_field[x * lengthY + y] = 2;
*flags = *flags - 1;
}
break;
case 1:
if (field[x * lengthY + y] == 10) {
std::cout << "\33[2J\33[1;1H";
std::cout << "Unfortunetly " << x << "|" << y << " was a bomb!"<< "\n";
*gameover = true;
}
else RevealField(field, user_field, lengthX, lengthY, x, y, flags);
break;
}
}
void Play(int lengthX, int lengthY, int bombs) {
std::cout << "\33[2J\33[1;1H";
int *field; //Used to store bombs, nums
int *user_field; //Used to store flags and which fields are revield
field = new int[lengthX * lengthY * sizeof(int)];
user_field = new int[lengthX * lengthY * sizeof(int)];
for (int i = 0; i < lengthX; i++) { //Set all fields to 0
for (int j = 0; j < lengthY; j++) {
user_field[i * lengthY + j] = 0;
}
}
GenField(field, lengthX, lengthY, bombs);
int flags = bombs; //Storing available Flags
bool gameover = false;
while (!gameover) {
std::cout << "\33[2J\33[1;1H";
PrintField(field, user_field, lengthX, lengthY, &flags);
MakeMove(field, user_field, lengthX, lengthY, &flags, &gameover);
if (flags == 0 && AllBombsMarked(field, user_field, lengthX, lengthY)) {
std::cout << "\33[2J\33[1;1H";
PrintField(field, user_field, lengthX, lengthY, &flags);
std::cout << "Well done, all bombs were marked correctly!" << "\n";
gameover = true;
}
}
}
void PlayCustom() { //Init game with custom dimension and amount of bombs
std::cout << "\33[2J\33[1;1H" << "X: ?" << " Y: ?" << " Bombs: ?" << "\n";
int x, y, bombs;
do {
std::cout << "Enter X length of field: ";
x = GetInt();
if (x < 1) std::cout << "Invalid input, x must be over 0" << "\n";
}
while(x < 1);
std::cout <<"\33[2J\33[1;1H" << "X: " << x << " Y: ?" << " Bombs: ?" << "\n";
if (x > 100) std::cout << "Displaying the field might look broken with such X" << "\n";
do {
std::cout << "Enter Y length of field: ";
y = GetInt();
if (y < 1) std::cout << "Invalid input, y must be over 0" << "\n";
}
while(y < 1);
std::cout <<"\33[2J\33[1;1H" << "X: " << x << " Y: " << y << " Bombs: ?" << "\n";
if (y > 100) std::cout << "Displaying the field might look broken with such Y" << "\n";
do {
std::cout << "Enter amount of bombs to be placed: ";
bombs = GetInt();
if (bombs < 1) std::cout << "Invalid input, at least one bomb must be placed" << "\n";
if (bombs > x * y) std::cout << "Invalid input, only " << y * x << " bombs can be placed" << "\n";
}
while(bombs < 1 || bombs > x * y);
Play(x, y, bombs);
}
void StartGame() {
std::cout << "\33[2J\33[1;1H";
int user_in;
std::cout << "Welcome to Minesweeper" << "\n";
std::cout << "0. Easy - " << easy_field_size << ", " << easy_bomb_amount << " bombs" << "\n";
std::cout << "1. Normal - " << normal_field_size << ", " << normal_bomb_amount << " bombs" << "\n";
std::cout << "2. Hard - " << hard_field_size << ", " << hard_bomb_amount << " bombs" << "\n";
std::cout << "3. Cusom - enter field dimensions and amount of bombs manually" << "\n";
do {
std::cout << "Enter a number (0-3): ";
user_in = GetInt();
} while (user_in < 0 || user_in > 3);
switch (user_in) {
case 0:
Play(easy_field_size, easy_field_size, easy_bomb_amount);
break;
case 1:
Play(normal_field_size, normal_field_size, normal_bomb_amount);
break;
case 2:
Play(hard_field_size, hard_field_size, hard_bomb_amount);
break;
case 3:
PlayCustom();
break;
}
}
int main(int argc, char const *argv[]) {
srand (time(NULL));
StartGame();
return 0;
}
|
#pragma once
#include "CHSGameRandom.hpp"
#include "CHSMazeMap.hpp"
class CHSMazeGenerator {
private:
CHSGameRandom cRandom;
int WallNumber; //壁を示す値
int AisleNumber; //通路を示す値
bool InnerGenerate ( CHSMazeMap *pMap , unsigned int x , unsigned int y );
public:
CHSMazeGenerator ();
~CHSMazeGenerator ();
void SetWallNumber ( int NewWallNumber );
int GetWallNumber ( void );
void SetAisleNumber ( int NewAisleNumber );
int GetAisleNumber ( void );
bool Generate ( CHSMazeMap *pMap );
};
|
/********************************
Name: Saiteja Yagni
Class: CSCI 689/1
TA Name: Anthony Schroeder
Assignment: 11
Due Date: 04/28/2016
*********************************/
/*Header file which contains include file using statements and function prototypes*/
#ifndef N_QUEENS
#define N_QUEENS
#include<iostream> //For input and output streams
#include<vector> //To use vector
#include<stdlib.h> //To use random functions
#include<time.h> //To use time function
using std::cin;
using std::cout;
using std::endl;
using std::vector;
/*Function prototypes*/
void initBoard(vector< vector < bool > > &,const int);
void solveNQueens(const int);
bool solveNQueensUtil(vector < vector < bool > >&, int);
bool isSafe(vector < vector < bool > >&, int, int);
void printBoard(vector < vector < bool > >&);
#endif /*N_QUEENS*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.