text
stringlengths 8
6.88M
|
|---|
//
// Created by anggo on 6/10/2020.
//
#include "Health.h"
Health::Health(std::string filepath)
{
texture.loadFromFile(filepath);
healthIcon.setTexture(texture);
}
void Health::draw(sf::RenderTarget& window,sf::RenderStates state) const
{
window.draw(healthIcon);
}
void Health::setSize(sf::Vector2f size)
{
healthIcon.setScale(size);
}
void Health::setPosition(sf::Vector2f pos)
{
healthIcon.setPosition(pos);
}
|
#include <iostream>
#include "Plane.h"
using namespace std;
Plane::Plane() :x(2.1f), z(2.2f), Vehicle()
{ /*Default Constructor of Vehicle is called*/
cout << "Plane constructor" << endl;
x++;
z++;
}
void Plane::setX(float x)
{
this->x = ++x;
}
|
// Copyright (c) 2015 University of Szeged.
// Copyright (c) 2015 The Chromium Authors.
// All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sprocket/browser/ui/javascript_dialog.h"
#include "base/android/jni_string.h"
#include "jni/SprocketJavaScriptDialog_jni.h"
using base::android::AttachCurrentThread;
using base::android::ConvertUTF16ToJavaString;
using base::android::ConvertJavaStringToUTF16;
void SprocketJavaScriptDialog::Cancel() {
callback_.Run(false, default_prompt_text_);
}
void SprocketJavaScriptDialog::Accept() {
callback_.Run(true, default_prompt_text_);
}
void SprocketJavaScriptDialog::Accept(const base::string16& prompt_text) {
callback_.Run(true, prompt_text);
}
void SprocketJavaScriptDialog::CreateJavaObject() {
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jstring> j_message_text = ConvertUTF16ToJavaString(env, message_text_);
ScopedJavaLocalRef<jstring> j_prompt_text = ConvertUTF16ToJavaString(env, default_prompt_text_);
java_object_.Reset(
env,
Java_SprocketJavaScriptDialog_create(
env,
type_,
j_message_text.obj(),
j_prompt_text.obj(),
reinterpret_cast<intptr_t>(this)).obj());
}
base::android::ScopedJavaLocalRef<jobject>
SprocketJavaScriptDialog::GetJavaObject() {
return base::android::ScopedJavaLocalRef<jobject>(java_object_);
}
// static
bool SprocketJavaScriptDialog::Register(JNIEnv* env) {
return RegisterNativesImpl(env);
}
void CancelDialog(JNIEnv* env,
const JavaParamRef<jclass>& clazz,
jlong javaScriptDialogPtr) {
SprocketJavaScriptDialog* javascript_dialog =
reinterpret_cast<SprocketJavaScriptDialog*>(javaScriptDialogPtr);
javascript_dialog->Cancel();
}
void AcceptDialog(JNIEnv* env,
const JavaParamRef<jclass>& clazz,
jlong javaScriptDialogPtr) {
SprocketJavaScriptDialog* javascript_dialog =
reinterpret_cast<SprocketJavaScriptDialog*>(javaScriptDialogPtr);
javascript_dialog->Accept();
}
void AcceptPromptDialog(JNIEnv* env,
const JavaParamRef<jclass>& clazz,
jlong javaScriptDialogPtr,
const JavaParamRef<jstring>& jprompt_text) {
SprocketJavaScriptDialog* javascript_dialog =
reinterpret_cast<SprocketJavaScriptDialog*>(javaScriptDialogPtr);
const base::string16 prompt_text = ConvertJavaStringToUTF16(env, jprompt_text);
javascript_dialog->Accept(prompt_text);
}
|
/*
* RatingList.cpp
*
* Created on: Oct 24, 2016
* Author: Istvan
*/
#include "RatingList.h"
RatingList::RatingList() {
init();
}
RatingList::RatingList(const RatingList &rl) {
deepCopy(rl);
}
RatingList::~RatingList() {
clear();
}
void RatingList::init(){
front = NULL;
back = NULL;
length = 0;
}
void RatingList::clear(){
node *tptr;
tptr = front;
while(tptr != NULL){
front = front->next;
delete tptr;
tptr = front;
}
init();
}
void RatingList::deepCopy(const RatingList &rl){
clear();
if(rl.front==NULL){
front = NULL;
}
else if(front != NULL) clear();
else {
front = new node;
node *n;
node *tptr;
n = front;
tptr = rl.front;
while(tptr->next != NULL){
n->rating = tptr->rating;
n->next = new node;
n = n->next;
tptr= tptr->next;
length++;
}
//adding back node
n->rating = tptr->rating;
n->next = NULL;
back = n;
length++;
//making sure pointers are not deleted
n = NULL;
tptr = NULL;
}
}
Rating RatingList::getRating(const int l){
if(l>length) {
cerr<<"Error:RatingList: getRating index greater than length of RatingList.\n";
Rating err;
return err;
} else if(front==NULL) {
cerr<<"Error:RatingList: Cannot getRating if RatingList is uninitialized.\n";
Rating err;
return err;
} else {
node *tptr;
tptr = front;
for(int i = 0; i<l;i++){
tptr= tptr->next;
}
Rating copy;
copy = tptr->rating;
return copy;
}
}
void RatingList::removeAllRatings(){
clear();
}
void RatingList::addRating(const Rating &r){
node *n = new node; // creates node to store temp info
n->rating = r; // makes the temporaries pointer rating equal to r
n->next = NULL; // since n is the last node the next pointer should be NULL
if(front==NULL){ // if empty
front = n; //since front is NULL the last item on list is also first
back = n; // makes back node pointer to point to the back
length++;
} else {
back->next = n; // makes the last node point to the temporary node pointer n
back = n; // makes the last node pointer n because n is the last node;
length++;
}
}
void RatingList::addRating(const string i, const string s){
Rating temp;
temp.set(i,s);
addRating(temp);
}
void RatingList::set(const RatingList &rl){
deepCopy(rl);
}
void RatingList::addRatingList(const RatingList &rl){
if(rl.front!=NULL){
node *n = back;
node *tptr = rl.front;
n->next = new node;
n = n->next;
while(tptr->next != NULL){
n->rating = tptr->rating;
n->next = new node;
n = n->next;
tptr= tptr->next;
length++;
}
// adding back pointer
n->rating = tptr->rating;
n->next = NULL;
back = n;
length++;
// making sure not deleted
n = NULL;
tptr =NULL;
}
}
void RatingList::removeAtStart(){
if(front==NULL) cerr<<"Error:RatingList: Cannot removeAtStart in an uninitialized RatingList.\n";
else{
node *tptr;
tptr = front->next;
delete front;
front = tptr;
length--;
}
}
void RatingList::removeAtEnd(){
if(front == NULL) cerr<<"Error:RatingList: Cannot removeAtEnd in an uninitialized RatingList.\n";
else{
node *tptr,*fptr;
tptr = front;
fptr = NULL;
while(tptr->next != NULL){
fptr = tptr;
tptr = tptr->next;
}
delete tptr;
fptr->next = NULL;
back = fptr;
length--;
}
}
void RatingList::deleteRating(const Rating &r){
if(front == NULL){
cerr<<"Error:RatingList: Cannot deleteRating in an uninitialized RatingList.\n";
} else if(front->rating == r){
removeAtStart();
} else if (back->rating == r){
removeAtEnd();
} else{
node *tptr, *fptr;
tptr = front;
fptr = NULL;
while(tptr->rating != r){
fptr = tptr;
tptr=tptr->next;
}
fptr->next = tptr->next;
delete tptr;
length--;
}
}
void RatingList::print(){
if(front==NULL){
cerr<<"Error:RatingList: Cannot print uninitialized RatingList.\n";
} else {
node *tptr;
tptr = front;
for(int i = 0; i<length;i++){
tptr->rating.print();
tptr = tptr->next;
}
}
}
ostream& RatingList::print(ostream &out){
if(front==NULL){
cerr<<"Error:RatingList: Cannot print(ostream&) uninitialized RatingList.\n";
} else {
node *tptr;
tptr = front;
for(int i = 0; i<length;i++){
out << tptr->rating<<endl;
tptr = tptr->next;
}
}
return out;
}
istream& RatingList::read(istream& in){
clear();
string search, r,c;
cout<<"Input RatingList.\n";
cout<<" - Type REND to end RatingList.\n";
while(!in.fail()){
cout<<"Rating ~>";
getline(in,r);
if(r =="REND"||r =="STOP"||r =="stop") return in;
cout<<"Comment ~>";
getline(in,c);
if(r =="REND"||r =="STOP"||r =="stop") return in;
if(!in.fail()) addRating(r,c);
}
return in;
}
void RatingList::peekline(istream &in, string &s){
streampos sp = in.tellg();
getline(in, s);
in.seekg(sp);
}
ifstream& RatingList::readFile(ifstream& in){
clear();
string search, r,c;
while(!in.fail()){
peekline(in,search);
if(search == "RSTART"){
getline(in,search);
peekline(in,search);//checks if there are no reviews
}
if(search == "REND") {
getline(in, search);
return in;
}
getline(in,r);
getline(in,c);
if(!in.fail()) addRating(r,c);
}
return in;
}
RatingList& RatingList::operator=(const RatingList &rl){
deepCopy(rl);
return *this;
}
ostream& operator <<(ostream &out, RatingList &rl){
rl.print(out);
return out;
}
istream& operator >>(istream &in, RatingList &rl){
rl.read(in);
return in;
}
ifstream& operator >>(ifstream &in, RatingList &rl){
rl.readFile(in);
return in;
}
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <cmath>
#include <unordered_map>
#include <unordered_set>
#include <cstring>
#include <climits>
#include <queue>
using namespace std;
struct node{
unordered_map<char,node*> children;
bool end;
node(){
end=false;
}
};
int helper(node * dummy){
if(dummy->children.empty()){return 1;}
int currentSum=0;
for(auto it: dummy->children){
currentSum+=helper(it.second);
}
if(dummy->end){currentSum+=1;}
if(currentSum>=2){currentSum-=2;}
return currentSum;
}
int main(){
int T;
cin>>T;
for(int tt=1;tt<T+1;++tt){
int N;
cin>>N;
node dummy=node();
for(int i=0;i<N;++i){
string word;
cin>>word;
reverse(word.begin(),word.end());
node* it= & dummy;
for(char c:word){
if ((it->children).find(c)==(it->children).end() ){
it->children[c]=new node();
}
it=it->children[c];
}
it->end=true;
}
int result=0;
for(auto it:dummy.children){
result+=helper(it.second);
}
int answer=N-result;
cout<<"Case #"<<tt<<": "<<answer<<endl;
}
}
|
#include "image.h"
Image::Image(void)
{
}
Image::Image(IMAGETYPE imageType, int width, int height)
{
m_imageType = imageType;
m_width = width;
m_height = height;
}
Image::~Image(void)
{
}
int Image::GetWidth() const
{
return m_width;
}
int Image::GetHeight() const
{
return m_height;
}
IMAGETYPE Image::GetImageType()
{
return m_imageType;
}
|
//---------------------------------------------------------------------------
#ifndef UnitKT76CH
#define UnitKT76CH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <ExtCtrls.hpp>
#include <Buttons.hpp>
#include <ComCtrls.hpp>
//---------------------------------------------------------------------------
class TFormKT76C : public TForm
{
__published: // IDE-managed Components
TTrayIcon *TrayIcon1;
TSpeedButton *SpeedButton1;
TSpeedButton *BtnSupply;
TSpeedButton *SpeedButton3;
TSpeedButton *SpeedButton4;
TSpeedButton *SpeedButton5;
TSpeedButton *SpeedButton6;
TSpeedButton *SpeedButton7;
TSpeedButton *SpeedButton8;
TSpeedButton *SpeedButton9;
TSpeedButton *SpeedButton10;
TSpeedButton *SpeedButton11;
TSpeedButton *SpeedButton12;
TTrackBar *TrackBar1;
TLabel *Label1;
TLabel *Label2;
TLabel *Label3;
TLabel *Label4;
TLabel *Label5;
TPanel *Panel1;
TLabel *Label6;
TLabel *Label7;
TLabel *Label8;
TLabel *Label9;
TLabel *Label10;
TLabel *Label11;
TLabel *Label12;
TLabel *Label13;
TLabel *Label14;
void __fastcall BtnSupplyClick(TObject *Sender);
void __fastcall TrackBar1Change(TObject *Sender);
void __fastcall SpeedButton1MouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y);
void __fastcall SpeedButton1MouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y);
private: // User declarations
public: // User declarations
__fastcall TFormKT76C(TComponent* Owner);
virtual __fastcall ~TFormKT76C(void);
};
//---------------------------------------------------------------------------
extern PACKAGE TFormKT76C *FormKT76C;
//---------------------------------------------------------------------------
#endif
|
#include "include/MIDIfile.hpp"
#include <cstdio> // for std::fopen
#include <cstring>
int main(int argc, char **argv)
{
// Now that we have a class that can create MIDI files, let's create
// music.
// Begin with some chords.
static const int chords[][3] =
{
{ 12,4,7 }, // +C E G = 0
{ 12,9,5 }, // +C A F = 1
{ 12,8,3 }, // +C G# D# = 2
{ 12,7,3 }, // +C G D# = 3
{ 12,5,8 }, // +C F G# = 4
{ 12,3,8 }, // +C D# G# = 5
{ 11,2,7 }, // B D G = 6
{ 10,2,7 }, // A# D G = 7
{ 14,7,5 }, // +D G F = 8
{ 14,7,11 },// +D G B = 9
{ 14,19,11 }// +D +G B = 10
};
const char x = 99; // Arbitrary value we use here to indicate "no note"
static const char chordline[64] =
{
0,x,0,0,x,0,x, 1,x,1,x,1,1,x,1,x, 2,x,2,2,x,2,x, 3,x,3,x,3,3,x,3,x,
4,x,4,4,x,4,x, 5,x,5,x,5,5,x,5,x, 6,7,6,x,8,x,9,x,10,x,x,x,x,x,x,x
};
static const char chordline2[64] =
{
0,x,x,x,x,x,x, 1,x,x,x,x,x,x,x,x, 2,x,x,x,x,x,x, 3,x,x,x,x,x,x,x,x,
4,x,x,x,x,x,x, 5,x,x,x,x,x,x,x,x, 6,x,x,x,x,x,x,x, 6,x,x,x,x,x,x,x
};
static const char bassline[64] =
{
0,x,x,x,x,x,x, 5,x,x,x,x,x,x,x,x, 8,x,x,0,x,3,x, 7,x,x,x,x,x,x,x,x,
5,x,x,x,x,x,x, 3,x,x,x,x,x,x,x,x, 2,x,x,x,x,x,x,(char)-5,x,x,x,x,x,x,x,x
};
static const char fluteline[64] =
{
12,x,12,12, x,9, x, 17,x,16,x,14,x,12,x,x,
8,x, x,15,14,x,12, x,7, x,x, x,x, x,x,x,
8,x, x, 8,12,x, 8, x,7, x,8, x,3, x,x,x,
5,x, 7, x, 2,x,(char)-5, x,5, x,x, x,x, x,x,x
};
MIDIfile file;
file.AddLoopStart();
/* Choose instruments ("patches") for each channel: */
static const char patches[16] =
{
0,0,0, 52,52,52, 48,48,48, 0,0,0,0,0, 35,74
/* 0=piano, 52=choir aahs, 48=strings, 35=fretless bass, 74=pan flute */
};
for(unsigned c=0; c<16; ++c)
if(c != 10) // Patch any other channel but not the percussion channel.
file[0].Patch(c, patches[c]);
int keys_on[16] = {-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1 };
for(unsigned loops=0; loops<2; ++loops)
{
for(unsigned row=0; row<128; ++row)
{
for(unsigned c=0; c<16; ++c)
{
int note = x, add = 0, vol = 127;
if(c < 3) // Piano chord
{ int chord = chordline[row%64];
if(chord != x) note = chords[chord][c%3], add=12*5, vol=0x4B; }
else if(c >= 3 && c < 5) // Aux chord (choir)
{ int chord = chordline2[row%64];
if(chord != x) note = chords[chord][c%3], add=12*4, vol=0x50; }
else if(c >= 6 && c < 8) // Aux chord (strings)
{ int chord = chordline2[row%64];
if(chord != x) note = chords[chord][c%3], add=12*5, vol=0x45; }
else if(c == 14) // Bass
note = bassline[row%64], add=12*3, vol=0x6F;
else if(c == 15 && row >= 64) // Flute
note = fluteline[row%64], add=12*5, vol=0x6F;
if(note == x && (c<15 || row%31)) continue;
file[0].KeyOff(c, keys_on[c], 0x20);
keys_on[c] = -1;
if(note == x) continue;
file[0].KeyOn(c, keys_on[c] = note+add, vol);
}
file[0].AddDelay(160);
}
if(loops == 0) file.AddLoopEnd();
}
file.Finish();
FILE *fp = std::fopen("test.mid", "wb");
std::fwrite(&file.at(0), 1, file.size(), fp);
std::fclose(fp);
return 0;
}
|
class Solution {
void permuteUnique(vector<int> &nums, int pos, vector<bool> &visited,
vector<int> &value, vector<vector<int>> &result) {
if (pos == nums.size()) {
result.push_back(value);
} else {
for (int i = 0; i < nums.size(); i++) {
if (visited[i] == false) {
if (i > 0 && (nums[i] == nums[i - 1]) && visited[i - 1] == false)
continue;
visited[i] = true;
value.push_back(nums[i]);
permuteUnique(nums, pos + 1, visited, value, result);
value.pop_back();
visited[i] = false;
}
}
}
}
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<int> value;
vector<vector<int>> result;
vector<bool> visited(nums.size(), false);
sort(nums.begin(), nums.end());
permuteUnique(nums, 0, visited, value, result);
return result;
}
};
|
#include "executor.h"
#include <queue>
#include <string>
#include <vector>
#include "command.h"
#include "cmdAlways.h"
#include "cmdFailure.h"
#include "cmdSuccess.h"
// creates commands based off of the connector type
void executor::addCommand(string type, const vector<string>& cmdarg, int depth){
if (type == "&&"){
command* pCmd = new cmdSuccess(cmdarg, depth);
cmds.push(pCmd);
}
else if (type == "||"){
command* pCmd = new cmdFailure(cmdarg, depth);
cmds.push(pCmd);
}
else if (type == ";"){
command* pCmd = new cmdAlways(cmdarg, depth);
cmds.push(pCmd);
}
}
bool executor::execute(){
bool prev = true;
bool allgood = true;
int currentDepth = 0;
bool lastSkipped = false;
while (!cmds.empty()){
command* pcmd = cmds.front();
cmds.pop();
if (lastSkipped && currentDepth > 0 && pcmd->getDepth() >= currentDepth){
delete pcmd;
continue;
}
prev = pcmd->run(prev);
lastSkipped = pcmd->wasSkipped(); // for () cases
currentDepth = pcmd->getDepth(); // for () cases
if (!prev){
allgood = false;
}
delete pcmd;
}
return allgood;
}
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,k;
char a[2005];
char ch[3][5] = {"DAY","AYD","YDA"};
while(~scanf("%d%d",&n,&k)) {
cin >> a;
int minN = 2000;
for(int i = 0; i <= n-k; i++) {
for(int j = 0; j < 3; j++) {
int sum = 0;
for(int t = 0; t < k; t++) {
if(a[i+t] != ch[j][t%3])
sum++;
}
minN = min(minN,sum);
}
}
cout << minN << endl;
}
return 0;
}
|
#pragma once
ref class BitmapStack // Bitmap stack class
{
private:
ref struct BITMAP { // structure of a node in the stack
System::Drawing::Bitmap^ bitmap; // holds the previous bitmap
BITMAP^ prev; // points to bitmap which is next in the stack
};
BITMAP^ stackPtr; // points to top of the stack
public:
BitmapStack(); // default constructor
System::Void push(System::Drawing::Bitmap^ bitmapIn); // pushes previous bitmap to the top of the stack
BITMAP^ peek(); // checks if stackptr points to anything
System::Drawing::Bitmap^ bitmapPeek();
System::Drawing::Bitmap^ pop(); // returns and deletes the bitmap at the top of the stack
};
|
#include "PrimitiveRestart.h"
namespace revel
{
namespace renderer
{
PrimitiveRestart::PrimitiveRestart()
: m_Enabled(false)
, m_Index(0)
{
}
} // ::revel::renderer
} // ::revel
|
#include"BSTree.h"
void main()
{
int select;
int key;
Tree tree;
while(1)
{
cout << "1.Insert 2.Delete 3.Search 4.Print 5.Post 6.Pre 7.In: ";
cin >> select;
switch(select)
{
case 1:
cout << "Insert data : ";
cin >> key;
tree.insertTree(tree.root , key);
cout << endl << endl;
break;
case 2:
cout << "Delete data : ";
cin >> key;
tree.deleteTree(key);
cout << endl << endl;
break;
case 3:
cout << "Search data : ";
cin >> key;
tree.searchTree(key);
cout << endl << endl;
break;
case 4:
tree.drawTree();
cout << endl << endl;
break;
case 5:
tree.postorder(tree.root);
cout << endl << endl;
break;
case 6:
tree.preorder(tree.root);
cout << endl << endl;
break;
case 7:
tree.inorder(tree.root);
cout << endl << endl;
break;
case 8:
exit(1);
}
}
}
|
//KaiXinAPI_ApplicationList.h
#ifndef __KAIXINAPI_APPLICATIONLIST_H__
#define __KAIXINAPI_APPLICATIONLIST_H__
#include "KaiXinAPI.h"
#define KX_APPLIST_ITEM_X_START (10)
#define KX_APPLIST_ITEM_Y_START (70)
#define KX_APPLIST_ITEM_WIDTH (145)
#define KX_APPLIST_ITEM_HEIGHT (30)
#define KX_APPLIST_ITEM_COL (2)
#define KX_APPLIST_ITEM_LINE_SPACE (5)
#if 0
//Application List Object ID
typedef enum
{
KX_APPLICATION_FARM = 0,
KX_APPLICATION_GARDEN,
KX_APPLICATION_RANCH,
KX_APPLICATION_PARKING,
KX_APPLICATION_FISH,
KX_APPLICATION_RICH,
KX_APPLICATION_CAFE,
KX_APPLICATION_LUCKY,
KX_APPLICATION_SPIDERMAN,
KX_APPLICATION_FILM,
KX_APPLICATION_VOTE,
KX_APPLICATION_PHOTO,
KX_APPLICATION_DIARY,
KX_APPLICATION_REPASTE,
KX_APPLICATION_RECORD,
/*need to add more type here*/
KX_APPLICATION_END,
} KX_ApplicationType;
#endif
typedef struct
{
char name[32];
char url[128];
}applistItem;
typedef struct
{
int ret;
int n;
applistItem* applist;
}tResponseApplicationList;
extern void* KaiXinAPI_ApplicationList_JsonParse(char *text);
class TApplicationListForm : public TWindow
{
public:
TApplicationListForm(TApplication* pApp);
virtual ~TApplicationListForm(void);
virtual Boolean EventHandler(TApplication * appP, EventType * eventP);
private:
Boolean _OnWinInitEvent(TApplication * pApp, EventType * pEvent);
Boolean _OnWinClose(TApplication * pApp, EventType * pEvent);
Boolean _OnCtrlSelectEvent(TApplication * pApp, EventType * pEvent);
Boolean _HandleApplicationListCtlClick(TApplication * pApp,Int32 iCtlID);
Int32 _CreateTabButtons(TApplication* pApp);
protected:
Int32 ItemIndex[128];
TBarListItem* pListItem[64];
char ItemUrl[64][128];
char ItemName[64][32];
Int32 ItemCount;
Int32 m_nNewsBtnID;//动态
Int32 m_nFriendsBtnID;//好友
Int32 m_nInfosBtnID;//我的地盘
Int32 m_nAppsBtnID;//组件
Int32 m_nMoreBtnID;//更多
//退出按钮ID
Int32 m_ExitBtn;
//刷新按钮ID
Int32 m_RefreshBtn;
};
#endif
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef BIDOMAINSOLVER_HPP_
#define BIDOMAINSOLVER_HPP_
#include "UblasIncludes.hpp"
//#include <iostream>
#include <vector>
#include <petscvec.h>
#include "AbstractBidomainSolver.hpp"
#include "HeartConfig.hpp"
#include "BidomainAssembler.hpp"
#include "BidomainMassMatrixAssembler.hpp"
#include "BidomainCorrectionTermAssembler.hpp"
#include "BidomainNeumannSurfaceTermAssembler.hpp"
/**
* A bidomain solver, which uses various assemblers to set up the bidomain
* FEM linear system.
*
* The discretised bidomain equation leads to the linear system (see FEM
* implementations document)
*
* [ (chi*C/dt) M + K1 K1 ] [ V^{n+1} ] = [ (chi*C/dt) M V^{n} + M F^{n} + c1_surf ]
* [ K1 K2 ] [ PhiE^{n+1}] [ c2_surf ]
*
* where chi is the surface-area to volume ratio, C the capacitance, dt the timestep
* M the mass matrix, K1 and K2 stiffness matrices, V^{n} and PhiE^{n} the vector of
* voltages and phi_e at time n, F^{n} the vector of (chi*Iionic + Istim) at each node,
* and c1_surf and c2_surf vectors arising from any surface stimuli (usually zero).
*
* This solver uses two assemblers, one to assemble the whole LHS matrix,
* and also to compute c1_surf and c2_surf, and one to assemble the mass matrix M.
*
* Also allows state variable interpolation (SVI) to be used on elements for which it
* will be needed, if the appropriate HeartConfig boolean is set.
* See wiki page ChasteGuides/StateVariableInterpolation for more details on this. In this
* case the vector [c_correction, 0] is added to the above, and another assembler is
* used to create the c_correction.
*
*/
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
class BidomainSolver : public AbstractBidomainSolver<ELEMENT_DIM,SPACE_DIM>
{
private:
/** Mass matrix, used to computing the RHS vector (actually: mass-matrix in
* voltage-voltage block, zero elsewhere)
*/
Mat mMassMatrix;
/**
* The vector multiplied by the mass matrix. Ie, if the linear system to
* be solved is Ax=b, this vector is z where b=Mz.
*/
Vec mVecForConstructingRhs;
/** The bidomain assembler, used to set up the LHS matrix */
BidomainAssembler<ELEMENT_DIM,SPACE_DIM>* mpBidomainAssembler;
/** Assembler for surface integrals coming from any non-zero Neumann boundary conditions */
BidomainNeumannSurfaceTermAssembler<ELEMENT_DIM,SPACE_DIM>* mpBidomainNeumannSurfaceTermAssembler;
/**
* If using state variable interpolation, points to an assembler to use in
* computing the correction term to apply to the RHS.
*/
BidomainCorrectionTermAssembler<ELEMENT_DIM,SPACE_DIM>* mpBidomainCorrectionTermAssembler;
/**
* Implementation of SetupLinearSystem() which uses the assembler to compute the
* LHS matrix, but sets up the RHS vector using the mass-matrix (constructed
* using a separate assembler) multiplied by a vector
*
* @param currentSolution Solution at current time
* @param computeMatrix Whether to compute the matrix of the linear system
*/
void SetupLinearSystem(Vec currentSolution, bool computeMatrix);
public:
/**
* Constructor
*
* @param bathSimulation Whether the simulation involves a perfusing bath
* @param pMesh pointer to the mesh
* @param pTissue pointer to the tissue
* @param pBoundaryConditions pointer to the boundary conditions
*/
BidomainSolver(bool bathSimulation,
AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>* pMesh,
BidomainTissue<SPACE_DIM>* pTissue,
BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,2>* pBoundaryConditions);
~BidomainSolver();
/** Overloaded InitialiseForSolve() which calls base version but also
* initialises mMassMatrix and mVecForConstructingRhs
*
* @param initialSolution initial solution
*/
void InitialiseForSolve(Vec initialSolution);
};
#endif /*BIDOMAINSOLVER_HPP_*/
|
/**
* 说反话
* words reverse
* ATTENTION: while 能不用就不用, 坑爹
* 2018+ : gets函数无法使用, 改用fgets
**/
#include <cstdio>
#include <cstring>
int main()
{
char str[500]; // 既定内存可以更大, 一开始的100提示partitial accept
char str_arr[50][50];
int j = 0, k = 0;
// gets(str);
fgets(str, sizeof(str), stdin);
str[strlen(str)-1] = '\0';
for(int i = 0; str[i] != '\0'; i++) {
if(str[i] != ' ') {
str_arr[j][k++] = str[i];
} else {
// TODO: Close the string
str_arr[j][k] = '\0';
// ATTENTION: Re-initial
j++;
k = 0;
}
}
/** BAD circulation **/
// while(str[i] != '\0') {
// if(str[i] == ' ') {
// str_arr[j][k] = '\0';
// j++;
// k = 0;
// i++;
// } else {
// str_arr[j][k++] = str[i++];
// }
// }
while(j > 0) {
printf("%s ", str_arr[j--]);
}
printf("%s", str_arr[j]);
return 0;
}
|
#pragma once
#include <cstdlib>
#include <vector>
#include "Cell.hpp"
namespace Kruskal
{
class Board
{
public:
Board(const size_t height, const size_t width);
Cell& getCell(const size_t x, const size_t y);
Cell& getCell(const std::pair<size_t, size_t> p);
size_t getHeight() const;
size_t getWidth() const;
private:
size_t m_height;
size_t m_width;
std::vector<std::vector<Cell>> m_cells;
};
class WrongCellPositionException : public std::exception
{
public:
const char * what() const throw ()
{
return "Incorrent position of cell on the board.";
}
};
}
|
#ifndef IC_TRANSLATOR_H
#define IC_TRANSLATOR_H
#include "../symboltable.h"
#include "../instructions/instructions.h"
#include "../syntaxtree/identifier.h"
#include "../syntaxtree/aggregates.h"
#include "bexptranslator.h"
using namespace std;
//forward references
class ICOpTranslator;
class Variable;
class Function;
class Array;
class Block;
class IfStatement;
class WhileStatement;
class Assignment;
class ReturnStatement;
class Funcall;
class ReadStatement;
class WriteStatement;
class UnaryOp;
class BinaryOp;
class Number;
class QChar;
class LengthExpression;
class ArrayAccess;
class BreakStatement;
class ContinueStatement;
/**
* An Itermediate Code translator translates the abstract syntax tree to
* three address code
*/
class ICTranslator: public TreeVisitor {
public:
/**
* Create a new intermediate code translator
* @param codestream the stream to which the code should be written
* @param globalScope the global symbol table
*/
ICTranslator(Instructions* codestream,SymbolTable* globalScope);
~ICTranslator();
Instructions* getCodeStream() const { return &codestream_; }
Identifiers* getDeclarations() const { return declarations_; }
/**
* var
* translates to
* var
* place_ will be set to var
*/
virtual void visitVariable(Variable* var);
/**
* fun
* translates to
* fun
* (code will be generated for the function body)
*/
virtual void visitFunction(Function* fun);
/**
* array
* translates to
* one dimensional array
* place_ will be set to the array
* Multi-dimensional arrays are translated to one-dimensional arrays
*/
virtual void visitArray(Array* array);
/**
* block
* translates to
* create a set of instructions for all statements in the block
*/
virtual void visitBlock(Block* b);
/**
* if bexp then stmt1 else stmt2
* translates to
* generate code for bexp
* generate code for stmt1
* generate code for escaping stmt2
* generate code for stmt2
* adjust true and false sets of bexp accordingly
* (bexp is evaluated by flow of control)
*
* BEXP - true -+
* | |
* false |
* v |
* goto ---+ |
* | |
* stmt1 <-+----+
* |
* goto ---+----+
* | |
* stmt2 <-+ |
* <------+
*/
virtual void visitIfStatement(IfStatement* ifstmt);
/**
* while bexp stmt
* translates to
* generate code for bexp
* generate code for stmt
* GOTO bexp
* adjust true and false sets of bexp accordingly
* (bexp is evaluated by flow of control)
*
* BEXP - false -+
* | <---+ |
* true | |
* v | |
* stmt1 | |
* | |
* goto ------+ |
* |
* <---------+
*/
virtual void visitWhileStatement(WhileStatement* whilestmt);
/**
* var = exp
* translates to
* t1 = ... //value of exp
* var = t1
*/
virtual void visitAssignment(Assignment* assgn);
/**
* return exp
* translates to
* t1 = ... //value of exp
* RETURN t1
*/
virtual void visitReturnStatement(ReturnStatement* ret);
/**
* f(exp1,exp2,exp3)
* translates to
* t1 = ... //value of exp1
* t2 = ... //value of exp2
* t3 = ... //value of exp3
* PARAM t1
* PARAM t2
* PARAM t3
* CALL f,3
*/
virtual void visitFuncall(Funcall* funcall);
/**
* read exp
* translates to
* t1 = ... //value of exp
* READ t1
*/
virtual void visitReadStatement(ReadStatement* readstmt);
/**
* write exp
* translates to
* t1 = ... //value of exp
* WRITE t1
*/
virtual void visitWriteStatement(WriteStatement* writestmt);
/**
* op exp
* translates to
* t1 = ... //value of exp
* t2 = op t1
*/
virtual void visitUnaryOp(UnaryOp* unop);
/**
* exp1 op exp2
* translates to
* t1 = ... //value of exp1
* t2 = ... //value of exp2
* t3 = t1 op t2
*
* Note that '<', '>', ... will evaluate booleans by value
*/
virtual void visitBinaryOp(BinaryOp* binop);
/**
* num
* translates to
* a variable representing this constant
*/
virtual void visitNumber(Number* num);
/**
* char
* translates to
* a variable representing this constant
*/
virtual void visitQChar(QChar* chr);
/**
* length exp
* translates to
* t1 = ... //value of exp
* t2 = LENGTH t1
*/
virtual void visitLengthExpression(LengthExpression* len);
/**
* a[exp1,...,expn]
* translates to
* t1 = ... //value of exp1
* tn = ... //value of expn
* tn+1 = fold indices into one index for a one-dimensional array
* tn+2 = a[tn+1]
*/
virtual void visitArrayAccess(ArrayAccess* arrayaccess);
/**
* break;
* translates to
* GOTO false-exit of the WHILE loop
*/
virtual void visitBreakStatement(BreakStatement* breakstmt);
/**
* continue;
* translates to
* GOTO true-exit of the WHILE loop
*/
virtual void visitContinueStatement(ContinueStatement* ctustmt);
/**
* BexpTranslator can access the codestream and scope if necessary
*/
friend class BexpTranslator;
/**
* An ICOpTranslator can also write to my codestream
*/
friend class ICOpTranslator;
private:
/**
* Fold the indices of a multi-dimensional array into one index
* for a one-dimensional array.
* @return the temporary variable containing the folded index
*/
VarRegister* foldIndex(Array* array, Expressions& indices);
/**
* (presumably) safe downcast to a variable
*/
Variable* lexp2variable(LExpression* lexp);
/**
* (presumably) safe downcast to an array access
*/
ArrayAccess* lexp2array(LExpression* lexp);
/**
* Qualifies a name with the functionname or block scopes
* to make it unique
*/
string* qualifyName(string* name) const;
/**
* Generate code for retrieving the dimensions of a multidimensional
* array at run-time
*/
void generateMultidimOffsets(SymbolTable& scope,
Instructions& instrstream, Array& array);
//INSTANCE VARIABLES
/** the stream to which instructions are written */
Instructions& codestream_;
/** the target of a previously generated assignment */
VarRegister* place_;
/** scope of the current function */
SymbolTable* scope_;
/** helper visitor for bexp's */
ICOpTranslator* myOpTranslator_;
/** current nesting level of blocks */
int nestingLevel_;
/** the current function's name */
string functionName_;
/** declarations in current function */
Identifiers* declarations_;
/** current bexptranslator, if there is any */
BexpTranslator* currentBexpTranslator_;
/**
* label holding the beginning of the while which is currently
* being visited (only makes sense if currentBexpTranslator
* is non null)
*/
Label currentWhileBeginLabel_;
};
#endif
|
#ifndef TASKSDIALOG_H
#define TASKSDIALOG_H
#include <QDialog>
#include <QTableWidgetItem>
#include "administrator.h"
namespace Ui {
class TasksDialog;
}
/**
* @brief Клас для создания и сортировки задач
*/
class TasksDialog : public QDialog
{
Q_OBJECT
public:
/**
* @brief TasksDialog
* @param type
* @param parent
*/
explicit TasksDialog(int type, QWidget *parent = nullptr, Employee* = nullptr);
~TasksDialog();
/**
* @brief positionChanged
*/
void positionChanged();
/**
* @brief writeInFile
*/
void writeInFile();
private slots:
/**
* @brief Кнопка "Создать" задачу
*/
void on_createTask_clicked();
/**
* @brief Кнопка "Удалить" выбранную задачу
*/
void on_removeTask_clicked();
/**
* @brief Назначить задачу тестировщикам
* @param checked
*/
void on_test_toggled(bool checked);
/**
* @brief Назначить задачу программистам
* @param checked
*/
void on_progr_toggled(bool checked);
/**
* @brief Назначить задачу художникам
* @param checked
*/
void on_artists_toggled(bool checked);
/**
* @brief Назначить задачу геймдизайнерам
* @param checked
*/
void on_gamed_toggled(bool checked);
/**
* @brief on_tasks_currentCellChanged
* @param currentRow
* @param currentColumn
* @param previousRow
* @param previousColumn
*/
void on_tasks_currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn);
private:
Ui::TasksDialog *ui;
//!
Administrator* admin = nullptr;
};
#endif // TASKSDIALOG_H
|
#include <cmath>
#include <vector>
#include <iostream>
#include <stdlib.h>
#include <numeric>
#include <algorithm>
#include "metrics/metrics.h"
namespace h2o4gpu {
template <typename T>
std::vector<size_t> argsort(const std::vector<T> &v) {
std::vector<size_t> idx(v.size());
std::iota(idx.begin(), idx.end(), 0);
sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) {return v[i1] < v[i2]; });
return idx;
}
typedef double(*CMMetricFunc)(double, double, double, double);
#define CM_STATS_COLS 9
double mcc(double tp, double tn, double fp, double fn) {
auto n = tp + tn + fp + fn;
auto s = (tp + fn) / n;
auto p = (tp + fp) / n;
auto x = (tp / n) - s * p;
auto y = sqrt(p * s * (1 - s) * (1 - p));
return (std::abs(y) < 1E-15) ? 0.0 : x / y;
}
double f05(double tp, double tn, double fp, double fn) {
auto y = 1.25 * tp + fp + 0.25 * fn;
return (std::abs(y) < 1E-15) ? 0.0 : (1.25 * tp) / y;
}
double f1(double tp, double tn, double fp, double fn) {
auto y = 2 * tp + fp + fn;
return (std::abs(y) < 1E-15) ? 0.0 : (2 * tp) / y;
}
double f2(double tp, double tn, double fp, double fn) {
auto y = 5 * tp + fp + 4 * fn;
return (std::abs(y) < 1E-15) ? 0.0 : (5 * tp) / y;
}
double acc(double tp, double tn, double fp, double fn) {
auto y = tp + fp + tn + fn;
return (std::abs(y) < 1E-15) ? 0.0 : (tp + tn) / y;
}
double cm_metric_opt(std::vector<double> y, std::vector<double> yhat,
std::vector<double> w, CMMetricFunc metric) {
auto idx = argsort(yhat);
int n = static_cast<int>(y.size());
double tp = 0;
double tn = 0;
double fp = 0;
double fn = 0;
std::vector<double> y_sorted;
std::vector<double> w_sorted;
for (auto &i : idx) {
y_sorted.push_back(y[i]);
w_sorted.push_back(w[i]);
auto label = static_cast<int>(y[i]);
tp += w[i] * label;
fp += w[i] * (1 - label);
}
double best_score = 0;
double prev_proba = -1;
for (int i = 0; i < n; ++i) {
auto proba = yhat[idx[i]];
if (proba != prev_proba) {
prev_proba = proba;
best_score = std::max(best_score, metric(tp, tn, fp, fn));
}
if (static_cast<int>(y_sorted[i]) == 1) {
tp -= w_sorted[i];
fn += w_sorted[i];
} else {
tn += w_sorted[i];
fp -= w_sorted[i];
}
}
return best_score;
}
void cm_stats(std::vector<double> y, std::vector<double> yhat, std::vector<double> w,
double cm[][CM_STATS_COLS]) {
auto idx = argsort(yhat);
int n = static_cast<int>(y.size());
double tp = 0;
double tn = 0;
double fp = 0;
double fn = 0;
std::vector<double> y_sorted;
std::vector<double> w_sorted;
for (auto &i : idx) {
y_sorted.push_back(y[i]);
w_sorted.push_back(w[i]);
auto label = static_cast<int>(y[i]);
tp += w[i] * label;
fp += w[i] * (1 - label);
}
double prev_proba = -1;
int k = 0;
for (int i = 0; i < n; ++i) {
auto proba = yhat[idx[i]];
if (proba != prev_proba) {
prev_proba = proba;
cm[k][0] = proba;
cm[k][1] = tp;
cm[k][2] = tn;
cm[k][3] = fp;
cm[k][4] = fn;
cm[k][5] = fp / (fp + tn); // fpr
cm[k][6] = tp / (tp + fn); // tpr
cm[k][7] = mcc(tp, tn, fp, fn);
cm[k][8] = f1(tp, tn, fp, fn);
k += 1;
}
if (static_cast<int>(y_sorted[i]) == 1) {
tp -= w_sorted[i];
fn += w_sorted[i];
}
else {
tn += w_sorted[i];
fp -= w_sorted[i];
}
}
}
double mcc_opt(double *y, int n, double *yhat, int m) {
std::vector<double> w(n, 1.0);
return cm_metric_opt(std::vector<double>(y, y + n), std::vector<double>(yhat, yhat + m),
w, mcc);
}
double mcc_opt(double *y, int n, double *yhat, int m, double *w, int l) {
return cm_metric_opt(std::vector<double>(y, y + n), std::vector<double>(yhat, yhat + m),
std::vector<double>(w, w + l), mcc);
}
double f05_opt(double *y, int n, double *yhat, int m) {
std::vector<double> w(n, 1.0);
return cm_metric_opt(std::vector<double>(y, y + n), std::vector<double>(yhat, yhat + m),
w, f05);
}
double f05_opt(double *y, int n, double *yhat, int m, double *w, int l) {
return cm_metric_opt(std::vector<double>(y, y + n), std::vector<double>(yhat, yhat + m),
std::vector<double>(w, w + l), f05);
}
double f1_opt(double *y, int n, double *yhat, int m) {
std::vector<double> w(n, 1.0);
return cm_metric_opt(std::vector<double>(y, y + n), std::vector<double>(yhat, yhat + m),
w, f1);
}
double f1_opt(double *y, int n, double *yhat, int m, double *w, int l) {
return cm_metric_opt(std::vector<double>(y, y + n), std::vector<double>(yhat, yhat + m),
std::vector<double>(w, w + l), f1);
}
double f2_opt(double *y, int n, double *yhat, int m) {
std::vector<double> w(n, 1.0);
return cm_metric_opt(std::vector<double>(y, y + n), std::vector<double>(yhat, yhat + m),
w, f2);
}
double f2_opt(double *y, int n, double *yhat, int m, double *w, int l) {
return cm_metric_opt(std::vector<double>(y, y + n), std::vector<double>(yhat, yhat + m),
std::vector<double>(w, w + l), f2);
}
double acc_opt(double *y, int n, double *yhat, int m) {
std::vector<double> w(n, 1.0);
return cm_metric_opt(std::vector<double>(y, y + n), std::vector<double>(yhat, yhat + m),
w, acc);
}
double acc_opt(double *y, int n, double *yhat, int m, double *w, int l) {
return cm_metric_opt(std::vector<double>(y, y + n), std::vector<double>(yhat, yhat + m),
std::vector<double>(w, w + l), acc);
}
void confusion_matrices(double *y, int n, double *yhat, int m, double *cm, int k, int j) {
std::vector<double> w(n, 1.0);
cm_stats(std::vector<double>(y, y + n), std::vector<double>(yhat, yhat + m),
w, reinterpret_cast<double(*)[CM_STATS_COLS]>(cm));
}
void confusion_matrices(double *y, int n, double *yhat, int m, double* w, int l, double *cm, int k, int j) {
cm_stats(std::vector<double>(y, y + n), std::vector<double>(yhat, yhat + m),
std::vector<double>(w, w + l), reinterpret_cast<double(*)[CM_STATS_COLS]>(cm));
}
}
|
#include<iostream>
using namespace std;
struct lnode
{
int data;
struct lnode *next;
};
typedef struct lnode *lptr;
lptr L;
void addend(lptr &L,int k)
{
if(L==NULL)
{
L=new(lnode);
L->data=k;
L->next=NULL;
}
else
{ lptr T=L;
while(T->next!=NULL)
{
T=T->next;
}
T->next = new lnode;
T->next->data=k;
T->next->next=NULL;
}
}
void print(lptr &L,int k)
{
// lptr t=L;
// int sum=0;
// while(t!=NULL)
// {
// sum=sum+t->data;
// t=t->next;
// }
// if(sum<k)
// {
// cout<<"there doesn't exist any subsequence whose sum is"<<" "<<k<<endl;
// }
// else
while(L!=NULL)
{
lptr m=L;
int s=0;
lptr p=m;
while(m!=NULL)
{
if(s==k)
{
break;
}
else if(s>k)
{
break;
}
else
{
s=s+m->data;
}
m=m->next;
}
if(s==k)
{
while(p!=m)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
L=L->next;
}
}
int main()
{
int a,b,c;
cout<<"enter the no. of elements in List\n";
cin>>a;
cout<<"enter the elements of List\n";
for(int i=0;i<a;i++)
{
cin>>b;
addend(L,b);
}
cout<<"enter the sum of subsequence\n";
cin>>c;
print(L,c);
return 0;
}
|
#include "log.h"
#include "dominio.h"
#include "servicio.h"
#include "interfaz.h"
#include "util.h"
#include "configuracion.h"
#include "servicioDB.h"
#include "servicioASP.h"
#include "DeshabilitarASP.h"
#include <vector>
using namespace std;
int main(int argc, char *argv[]) {
//Inicializar el dominio
cDominio dominio;
if (!dominio.iniciar())
reportarErrorRarisimo(string("Error al iniciar el objeto dominio"));
//Inicializar el servicio
cServicioASP servicio(&dominio);
if (!servicio.iniciar())
reportarErrorRarisimo(string("Error al iniciar el objeto servicioASP"));
cServicioDB servicioDB(&dominio);
if (!servicio.iniciar())
reportarErrorRarisimo(string("Error al iniciar el objeto servicioDB"));
//Inicializar la clase interfaz
cInterfaz interfaz;
//Inicializar variables miscelaneas
string mensaje;
string error;
int derror;
string errorFile(ERROR_DESHABILITAR_ASP);
string okFile(OK_DESHABILITAR_ASP);
//Verificar que la pagina haya sido llamada por DeshabilitarASP.php
if (interfaz.verificarPagina(string("DeshabilitarASP.php")) < 0)
return(-1);
//Verificar si el cliente puede crear el servicio
derror = servicio.verificarCrearServicio();
if (derror == 0) {
error = "Su Plan no le permite deshabilitar el Soporte ASP";
interfaz.reportarErrorComando(error, errorFile, dominio);
return(-1);
}
//Verificar si el soporte ASP ya existe
derror = servicio.verificarExisteASPDB(dominio);
if (derror < 0) {
interfaz.reportarErrorFatal();
return(-1);
}
if (derror == 0) {
error = "El Soporte ASP no existe";
interfaz.reportarErrorComando(error, errorFile, dominio);
return(-1);
}
//Recuperar todas las bases de datos del dominio con su respectivo password
std::vector<std::string> nombreDB;
std::vector<std::string> passwords;
servicioDB.recuperarNombrePasswordDB(nombreDB, passwords, dominio);
//Eliminar el soporte ASP en el sistema
derror = servicio.quitarASP(nombreDB, passwords, dominio);
if (derror < 0) {
interfaz.reportarErrorFatal();
return(-1);
}
//Eliminar el soporte ASP en la base de datos
derror = servicio.quitarASPDB(dominio);
if (derror < 0) {
interfaz.reportarErrorFatal();
return(-1);
}
//Agregar al historial de la base de datos
mensaje = "Se deshabilito el Soporte ASP";
servicio.agregarHistorial(mensaje, dominio);
//Reportar el mensaje de ok al navegador
mensaje = "El Soporte ASP fue deshabilitado con éxito.";
interfaz.reportarOkComando(mensaje, okFile, dominio);
return(0);
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "XProjectGameModeBase.h"
|
#include "Square.hpp"
Square::Square(Color color)
: color(color), vertices{} {}
|
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofEnableAlphaBlending();
ofSetVerticalSync(true);
ofSetFrameRate(60);
ofBackground(22, 22, 22, 255);
font.setup("Vera.ttf", 1.0, 1024, false, 8, 1.5);
font.addFont("VeraMono-Bold.ttf");
unicodeFont.setup("Arial Unicode.ttf", //font file, ttf only
1.0, //lineheight percent
1024, //texture atlas dimension
true, //create mipmaps of the font, useful to scale down the font at smaller sizes
8, //texture atlas element padding, shouldbe >0 if using mipmaps otherwise
1.5f //dpi scaleup, render textures @2x the reso
); //lower res mipmaps wil bleed into each other
unicodeFont.setCharacterSpacing(0);
font.setCharacterSpacing(0);
}
void ofApp::update(){
//you can set a mipmap bias for fonts for which you created mipmaps
unicodeFont.setLodBias(ofMap(ofGetMouseX(), 0, ofGetWidth(), -1, 1));
}
//--------------------------------------------------------------
void ofApp::draw(){
float lineHeight = ofMap(mouseY, 0, ofGetHeight(), 0, 4, true);
ofDrawBitmapString("lineHeight: " + ofToString(lineHeight,2), ofGetWidth() - 138, ofGetHeight() - 14);
unicodeFont.setLineHeight(lineHeight);
float x = 30;
float y = 40;
ofRectangle bbox;
ofRectangle bboxMultiline;
string demoText = "This is my text in BitStream Vera font.";
float fontSize = 28;
// simple demo //////////////////////////////////////////////////////////
drawPoint(x, y); //draw insertion point
ofSetColor(255);
TIME_SAMPLE_START("simple draw");
font.draw(
demoText, //text to draw
fontSize, //font size
x, //x coord where to draw
y //y coord where to draw
);
TIME_SAMPLE_STOP("simple draw");
if(true){
auto words = {"aaa", "bbb", "sdguisd", "adfd gfsgsg"};
int xxx = 500;
float fontSize = 24;
float y = 500;
ofDrawLine(xxx, y, ofGetWidth(), y);
for(auto w : words){
ofRectangle r = font.getBBox(w, fontSize, xxx, y);
ofSetColor(255,0,0, 64);
ofDrawRectangle(r);
ofSetColor(255);
float xInc = font.draw(w, fontSize, xxx, y);
ofSetColor(0,255,0);
ofDrawCircle(xxx,y,1);
ofSetColor(255,33);
xxx += xInc;
}
}
// bounding box demo ///////////////////////////////////////////////////
ofSetColor(0, 0, 255, 64);
TIME_SAMPLE_START("bbox");
bbox = font.getBBox( demoText, fontSize, x, y);
TIME_SAMPLE_STOP("bbox");
ofRect( bbox );
// draw multiline text /////////////////////////////////////////////////
y += 25 + bbox.height;
drawPoint(x, y); //draw insertion point
ofSetColor(255);
string s = (string)"ofxFontStash can draw multiline text" + "\n" +
"It also supports unicode strings: " + "\n" +
"槊監しゅ祟䤂לרפובליקה. אם מיזם銆銌 憉 圩芰敔 तकनिकल कार्यलय" + "\n" +
"bananas from russia!";
ofAlignHorz align = OF_ALIGN_HORZ_CENTER;
float width = ofGetMouseX() - x; //when centering, we need a box w to center around
TIME_SAMPLE_START("drawMultiLine");
bbox = unicodeFont.drawMultiLine( s, fontSize, x, y, align, width);
TIME_SAMPLE_STOP("drawMultiLine");
ofSetColor(0, 255, 255, 64);
ofRect( bbox );
// multiline bbox /////////////////////////////////////////////////////
TIME_SAMPLE_START("getBoundingBoxSize");
bboxMultiline = unicodeFont.getBBox( s, fontSize, x, y, align, width);
TIME_SAMPLE_STOP("getBoundingBoxSize");
ofNoFill();
ofColor c; c.setHsb((44 * ofGetFrameNum())%255, 255, 255);
ofSetColor(c, 128);
ofRect( bboxMultiline );
ofFill();
// draw multiline column with a fixed width ///////////////////////////
y += 25 + bboxMultiline.height;
drawPoint(x, y); //draw insertion point
ofSetColor(255);
s = "And you can wrap text to a certain (mouseX) width:\n\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.\n";
s += "總覺故歷身象果國家行、林年年顯我線覺們屋國驗態人!";
//s = "international bananas";
int numLines = 0;
bool wordsWereCropped;
ofRectangle column;
TIME_SAMPLE_START("drawMultiLineColumn");
column = unicodeFont.drawMultiLineColumn( s, /*string*/
16, /*size*/
x, y, /*where*/
MAX( 10, mouseX - x), /*column width*/
numLines, /*get back the number of lines*/
false, /* if true, we wont draw (just get bbox back) */
9, /* max number of lines to draw, crop after that */
true, /*get the final text formatting (by adding \n's) in the supplied string;
BE ARWARE that using TRUE in here will modify your supplied string! */
&wordsWereCropped, /* this bool will b set to true if the box was to small to fit all text*/
true /*centered*/
);
TIME_SAMPLE_STOP("drawMultiLineColumn");
//report if some words had to be cropped to fit in the column when using drawMultiLineColumn()
if(!wordsWereCropped) ofSetColor(255,32);
else (ofGetFrameNum()%6 <= 2) ? ofSetColor(255,32):ofSetColor(255,0,0,32); //flash if cropped
ofRect(column);
// batch drawing, optimized for multiple drawing calls /////////////////
y += column.height + 25;
drawPoint(x, y); //draw insertion point
ofSetColor(255);
TIME_SAMPLE_START("drawBatch");
font.beginBatch(); //call "begin" before drawing fonts
for (int i = 0; i < 5; i++){
font.drawBatch("batch mode #" + ofToString(i+1), fontSize, x, y + i * fontSize );
}
font.endBatch(); //call "end" once finished
TIME_SAMPLE_STOP("drawBatch");
// formatted text //////////////////////////////////////////////////////
string formattedText = "the #0xff0000 @1 %2.0 red %1.0 #0xffffff @0 apple is on the big %4.0 #0x00ff00 tree.";
ofPushMatrix();
ofTranslate(20,500);
ofSetColor(255);
ofVec2f size = font.drawMultiColumnFormatted(formattedText, 22, mouseX);
ofSetColor(255,10);
ofRect(0, 0, size.x, size.y);
ofPopMatrix();
// rotating text ///////////////////////////////////////////////////////
ofPushMatrix();
ofTranslate(x + 400, y + 50);
ofRotate( -200 * ofGetElapsedTimef(), 0, 0, 1);
ofSetColor(ofRandom(255), ofRandom(255), ofRandom(255));
font.draw("surrealismoooo!", fontSize, 0, 0 );
drawPoint(0,0);
ofPopMatrix();
// scaling text with mipmaps ///////////////////////////////////////////
ofPushMatrix();
ofTranslate(600, 40);
float scale = mouseY /(float) ofGetHeight();
ofPushMatrix();
ofScale(scale, scale);
ofSetColor(255);
unicodeFont.draw("MIPMAPS :)", fontSize * 2, 0, 0 );
drawPoint(0,0);
ofPopMatrix();
ofTranslate(0, 30);
ofScale(scale, scale);
font.draw("NO MIPMAPS :(", fontSize * 2, 0, 0 );
drawPoint(0,0);
ofPopMatrix();
}
void ofApp::drawPoint(float x, float y){
ofSetColor(0, 255, 0, 128);
ofCircle(x, y, 2);
}
void ofApp::keyPressed(int k){
font.setKerning(!font.getKerning());
unicodeFont.setKerning(!unicodeFont.getKerning());
}
|
#include <iostream>
#pragma once
using namespace std;
class Node{
private:
int value;
Node* lChild;
Node* rChild;
public:
Node();
Node(int value);
int getValue();
Node* getLChild();
Node* getRChild();
void setValue(int value);
void setLChild(Node* n);
void setRChild(Node* n);
};
|
// glfw_testDll.h : Defines the exported functions for the DLL application.
//
#include <windows.h>
#include <cstdlib>
#define GLFW_INCLUDE_GLU
#include <GLFW/glfw3.h>
#ifdef GLFW_TESTDLL_EXPORTS
#define GLFW_TESTDLL_API __declspec(dllexport)
#else
#define GLFW_TESTDLL_API __declspec(dllimport)
#endif
namespace glfw_testFunc {
typedef GLFWwindow* hGl;
class glfw_test {
public:
GLFW_TESTDLL_API hGl WINAPI init();
GLFW_TESTDLL_API void WINAPI terminate();
GLFW_TESTDLL_API void WINAPI mainLoop();
public:
hGl window;
};
}
|
#include "gui\Singularity.Gui.h"
namespace Singularity
{
namespace Gui
{
#pragma region Static Variables
VertexDeclaration* GuiFontVertexDeclaration::Declaration = GuiFontVertexDeclaration::GetVertexDeclaration();
#pragma endregion
#pragma region Static Methods
VertexDeclaration* GuiFontVertexDeclaration::GetVertexDeclaration()
{
D3D10_INPUT_ELEMENT_DESC vertexElements[4] =
{
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0},
{"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0},
{"TEXCOORD", 1, DXGI_FORMAT_R32G32_FLOAT, 0, 20, D3D10_INPUT_PER_VERTEX_DATA, 0},
{"TEXCOORD", 2, DXGI_FORMAT_R32G32_FLOAT, 0, 28, D3D10_INPUT_PER_VERTEX_DATA, 0}
};
return new VertexDeclaration(vertexElements, 4, sizeof(GuiFontVertexDeclaration));
}
#pragma endregion
#pragma region Constructors and Finalizers
GuiFontVertexDeclaration::GuiFontVertexDeclaration()
: position(0.0f, 0.0f, 0.0f), scale(0.0f, 0.0f), texOffset(0.0f, 0.0f), texSize(0.0f, 0.0f) { }
GuiFontVertexDeclaration::GuiFontVertexDeclaration(float x, float y, float z, float sx, float sy, float ou, float ov, float u, float v)
: position(x, y, z), scale(sx, sy), texOffset(ou, ov), texSize(u, v) { }
GuiFontVertexDeclaration::GuiFontVertexDeclaration(Vector3 position, Vector2 scale, Vector2 texSize, Vector2 texOffset)
: position(position), scale(scale), texOffset(texOffset), texSize(texSize) { }
#pragma endregion
#pragma region Overriden Operator
bool GuiFontVertexDeclaration::operator== (const GuiFontVertexDeclaration &other) const
{
return (memcmp(this, &other, sizeof(GuiFontVertexDeclaration)) == 0);
}
#pragma endregion
}
}
|
#include "TaskAction.h"
using namespace Task;
void Move::init()
{
entity->position.round();
target->position.round();
pathfinder = new Pathfinding::Pathfinder(grid->getWidth(), grid->getHeight());
path = pathfinder->findPath(entity->position, target->position, grid);
}
bool Move::run()
{
// moving - next position reached
if (EuclideanDistance(entity->position, nextPos) <= entity->speed)
{
path.erase(path.begin());
}
// moving - if there are more positions to travel to
if (!path.empty())
{
nextPos = *path.begin();
entity->moveTowards(nextPos, entity->speed);
}
// position reached
if (path.empty())
{
entity->position.round();
target->position.round();
result = true;
return false;
}
return true;
}
void Push::init()
{
entity->position.round();
target->position.round();
nextEntityPos = target->position;
nextTargetPos = target->position.getNeighbor(entity->position.getDirection(nextEntityPos));
//entity->target = target->position;
//target->target = target->position.getNeighbor(entity->position.getDirection(entity->target));
}
bool Push::run()
{
if (grid->at(nextTargetPos) == false)
{
entity->moveTowards(nextEntityPos);
target->moveTowards(nextTargetPos, entity->speed);
if (EuclideanDistance(entity->position, nextEntityPos) <= entity->speed)
{
entity->position.round();
target->position.round();
result = true;
return false;
}
return true;
}
return false;
}
void Pull::init()
{
entity->position.round();
target->position.round();
nextTargetPos = entity->position;
Direction dir = target->position.getDirection(nextTargetPos);
nextEntityPos = entity->position.getNeighbor(dir);
//target->target = entity->position;
//entity->target = entity->position.getNeighbor(dir);
}
bool Pull::run()
{
if (grid->at(nextEntityPos) == false)
{
entity->moveTowards(nextEntityPos);
target->moveTowards(nextTargetPos, entity->speed);
if (EuclideanDistance(entity->position, nextEntityPos) <= entity->speed)
{
entity->position.round();
target->position.round();
result = true;
return false;
}
return true;
}
return false;
}
bool Pickup::run()
{
entityManager->heldItem = targetName;
result = true;
return false;
}
bool Drop::run()
{
target->position = entity->position;
entityManager->heldItem = "";
result = true;
return false;
}
|
#include<iostream>
using namespace std;
enum Color
{
Red,
Black
};
template<class K, class V>
struct RBTreeNode
{
RBTreeNode<K, V>* _pLeft;
RBTreeNode<K, V>* _pRight;
RBTreeNode<K, V>* _pParent;
K _key;
V _value;
Color _color;
RBTreeNode(const K& key, const V& value)
:_pLeft(NULL)
, _pRight(NULL)
, _pParent(NULL)
, _key(key)
, _value(value)
, _color(Red){}
};
template<class K, class V>
class RBTree
{
public:
typedef RBTreeNode<K, V> Node;
typedef Node* PNode;
private:
PNode _pRoot;
public:
RBTree()
:_pRoot(NULL){}
bool Insert(const K& key, const V& value)
{
if (NULL == _pRoot)//根节点为黑色
{
_pRoot = new Node(key, value);
_pRoot->_color = Black;
return true;
}
PNode cur = _pRoot;
PNode pParent = NULL;
while (cur)//找插入的位置
{
if (cur->_key == key)
return false;
else if (cur->_key > key)
{
pParent = cur;
cur = cur->_pLeft;
}
else
{
pParent = cur;
cur = cur->_pRight;
}
}
//找到插入的位置以后开始插入
PNode pNewNode = new Node(key, value);//新插入的结点的颜色默认是红的
if (key<pParent->_key)
{
pParent->_pLeft = pNewNode;
pNewNode->_pParent = pParent;
}
else
{
pParent->_pRight = pNewNode;
pNewNode->_pParent = pParent;
}
////当结点插入好了以后我们就要根据红黑树的性质来判断结点是否满足,从而调整结点
while (pParent)
{
if (pParent->_color == Black)//父结点是黑的,不用调整直接退出
{
break;
}
//记录祖父结点和定义保存叔叔结点
PNode gparent = pParent->_pParent;
PNode uncle = NULL;
if (pParent == gparent->_pLeft)//在其左子节点上
{
uncle = gparent->_pRight;
if (uncle&& uncle->_color == Red)//叔叔结点存在切为红情况3,4
{
gparent->_color = Red;
uncle->_color = pParent->_color = Black;
pNewNode = gparent;//保存gg结点
pParent = gparent->_pParent;
continue;
}
else if (uncle == NULL || uncle->_color == Black)//叔叔不存在或者为黑
{
if (pNewNode == pParent->_pLeft)//外侧插入
{
_RBRolateR(gparent);
gparent->_color = Red;
pParent->_color = Black;
}
else//内测插入
{
_RBRolateL(pParent);
std::swap(pParent, pNewNode);//交换pParent和插入结点指针的值
_RBRolateR(gparent);
gparent->_color = Red;
pParent->_color = Black;
}
}
break;//直接跳出循环
}
else//右边的情况
{
uncle = gparent->_pLeft;
if (uncle&&uncle->_color == Red)//叔叔存在而且为红色
{
gparent->_color = Red;
uncle->_color = pParent->_color = Black;
pNewNode = gparent;
pParent = pNewNode->_pParent;
continue;
}
else if (uncle == NULL || uncle->_color == Black)//叔叔不存在或者为黑
{
if (pNewNode == pParent->_pRight)
{
_RBRolateL(gparent);
gparent->_color = Red;
pParent->_color = Black;
}
else
{
_RBRolateR(pParent);
std::swap(pParent, pNewNode);
_RBRolateL(gparent);
gparent->_color = Red;
pParent->_color = Black;
}
}
break;
}
}
_pRoot->_color = Black;
return true;
}
void InOrder()
{
_InOrder(_pRoot);
}
bool IsRBTree()
{
if (_pRoot == NULL)//根节点 为空是红黑树
return true;
if (_pRoot->_color == Red)//根节点为红色肯定不是红黑树
return false;
int count = 0;//统计黑色结点的数目
PNode cur = _pRoot;
while (cur)//根出一条参考路径的黑色结点的数目
{
if (cur->_color == Black)
++count;
cur = cur->_pLeft;
}
int k = 0;
return _IsRBTree(_pRoot, count, k);
}
private:
bool _IsRBTree(PNode pRoot, int& count, int k)//这里的K不能传引用
{
if (pRoot == NULL)
return true;
//出现两个连续的红色的结点
if (pRoot->_pParent&&pRoot->_color == Red&&pRoot->_pParent->_color == Red)
return false;
//如果是黑色结点k++
if (pRoot->_color == Black)
k++;
if (pRoot->_pLeft == NULL&&pRoot->_pRight == NULL)//如果是叶子结点的话进行判断k和count
{
if (k == count)
return true;
else
return false;
}
return _IsRBTree(pRoot->_pLeft, count, k) && _IsRBTree(pRoot->_pRight, count, k);
}
//右单旋转
void _RBRolateR(PNode parent)
{
if (NULL == parent)
return;
PNode SubL = parent->_pLeft;//
PNode SubLR = SubL->_pRight;
parent->_pLeft = SubLR;
if (SubLR != NULL)
SubLR->_pParent = parent;
PNode pParent = parent->_pParent;
SubL->_pRight = parent;
parent->_pParent = SubL;
if (pParent == NULL)
{
_pRoot = SubL;
SubL->_pParent = NULL;
}
else
{
if (pParent->_pLeft == parent)
{
pParent->_pLeft = SubL;
SubL->_pParent = parent;
}
else
{
pParent->_pRight = SubL;
SubL->_pParent = parent;
}
}
}
void _RBRolateL(PNode parent)
{
if (NULL == parent)
return;
PNode SubR = parent->_pRight;
PNode SubRL = SubR->_pLeft;
parent->_pRight = SubRL;
if (SubRL)
{
SubRL->_pParent = parent;
}
PNode pParent = parent->_pParent;
SubR->_pLeft = parent;
parent->_pParent = SubR;
if (pParent == NULL)
{
_pRoot = SubR;
SubR->_pParent = NULL;
}
else
{
if (pParent->_pLeft == parent)
{
pParent->_pLeft = SubR;
SubR->_pParent = pParent;
}
else
{
pParent->_pRight = SubR;
SubR->_pRight = pParent;
}
}
}
void _InOrder(PNode pRoot)
{
if (pRoot)
{
_InOrder(pRoot->_pLeft);
cout << pRoot->_key << " ";
_InOrder(pRoot->_pRight);
}
}
};
int main()
{
RBTree<int, int> s;
int arr[] = { 5, 3, 7, 1, 4, 6, 13, 8, 15, 12 };
int size = sizeof(arr) / sizeof(*arr);
for (int i = 0; i < size; i++)
s.Insert(arr[i], i);
s.InOrder();
cout << s.IsRBTree();
system("pause");
return 0;
}
|
#pragma once
#include <string>
#include <vector>
/* This is a utility class that reads, creates and stores shader programs for GLSL*/
class ShaderReader
{
public:
enum class shaderType
{
vertex, fragment
};
struct shader
{
shaderType type;
const char* shader;
unsigned int shaderObject;
};
static unsigned int readShader(shaderType shad, const std::string& path);
static unsigned int linkShaders(unsigned int vertexShader, unsigned int fragmentShader);
static std::vector<unsigned int> vertexShaders;
static std::vector<unsigned int> fragmentShaders;
static std::vector<unsigned int> shaderPrograms;
};
|
//
// SMMenuTransitionScene.cpp
// FreeTrip
//
// Created by N15051 on 2020/04/07.
//
#include "SMMenuTransitionScene.h"
#include "../Util/ViewUtil.h"
#include "ViewAction.h"
SMMenuTransitionScene::SMMenuTransitionScene() : _menuBarTitle("")
, _menuBar(nullptr)
, _swipeStarted(false)
, _prevMenuTitle("")
, _toMenuType(ActionBar::MenuType::NONE)
, _fromMenuType(ActionBar::MenuType::NONE)
{
_menuBarButton[0] = ActionBar::MenuType::NONE;
_menuBarButton[1] = ActionBar::MenuType::NONE;
}
SMMenuTransitionScene::~SMMenuTransitionScene()
{
}
bool SMMenuTransitionScene::initWithMenuBar(ActionBar * menuBar, Intent* sceneParam, SwipeType type)
{
if (!SMScene::initWithSceneParam(sceneParam, type)) {
return false;
}
_fromMenuType = menuBar->getMenuButtonType();
_menuBar = menuBar;
auto s = cocos2d::Director::getInstance()->getWinSize();
if (_menuBar) {
SMView * layer = (SMView*)_director->getSharedLayer(cocos2d::Director::SharedLayer::BETWEEN_SCENE_AND_UI);
if (layer) {
_menuBar->changeParent(layer);
_prevMenuTitle = _menuBar->getMenuText();
_prevManuBarButton = _menuBar->getButtonTypes();
_menuBar->setTextTransitionType(ActionBar::TextTransition::FADE);
switch (getSwipeType()) {
case SwipeType::MENU:
_toMenuType = ActionBar::MenuType::MENU_MENU;
break;
case SwipeType::DISMISS:
_toMenuType = ActionBar::MenuType::MENU_CLOSE;
break;
default:
_toMenuType = ActionBar::MenuType::MENU_BACK;
break;
}
_menuBar->setMenuButtonType(_toMenuType, false);
_menuBar->setButtonTransitionType(ActionBar::ButtonTransition::BTN_FADE);
_menuBar->setActionBarListener(nullptr);
}
return true;
}
return false;
}
void SMMenuTransitionScene::setActionBarButton(ActionBar::MenuType btn1, ActionBar::MenuType btn2)
{
_menuBarButton[0] = btn1;
_menuBarButton[1] = btn2;
}
void SMMenuTransitionScene::setActionBarTitle(const std::string& titleText)
{
_menuBarTitle = titleText;
}
void SMMenuTransitionScene::setActionBarMenu(ActionBar::MenuType menuButtonType)
{
_menuBarMenu = menuButtonType;
}
void SMMenuTransitionScene::setActionBarColorSet(const ActionBar::ColorSet& colorSet)
{
_menuBarColorSet = colorSet;
}
bool SMMenuTransitionScene::onActionBarClick(SMView *view)
{
return false;
}
void SMMenuTransitionScene::goHome()
{
}
void SMMenuTransitionScene::onTransitionStart(const Transition type, const int tag)
{
if (type==Transition::Transition_IN) {
if (_menuBar) {
_menuBar
->setColorSet(_menuBarColorSet, false);
_menuBar->setText(_menuBarTitle, false);
_menuBar->setTwoButton(_menuBarButton[0], _menuBarButton[1], false);
}
}
if (type==Transition::Transition_OUT || type==Transition::Transition_SWIPE_OUT) {
if (_menuBar==nullptr) {
return;
}
SMView * layer = (SMView*)_director->getSharedLayer(cocos2d::Director::SharedLayer::BETWEEN_SCENE_AND_UI);
_menuBar->changeParent(layer);
if (type==Transition::Transition_OUT) {
_menuBar->setTextTransitionType(ActionBar::TextTransition::FADE);
_menuBar->setText(_prevMenuTitle, false);
_menuBar->setMenuButtonType(_fromMenuType, false, false);
_menuBar->setButtonTransitionType(ActionBar::ButtonTransition::BTN_FADE);
int numButtons = (int)_prevManuBarButton.size();
if (numButtons == 1) {
_menuBar->setOneButton(_prevManuBarButton.at(0), false, false);
} else if (numButtons == 2) {
_menuBar->setTwoButton(_prevManuBarButton.at(0), _prevManuBarButton.at(1), false, false);
} else {
_menuBar->setOneButton(ActionBar::MenuType::NONE, false, false);
}
} else {
_menuBar->setTextTransitionType(ActionBar::TextTransition::SWIPE);
_menuBar->setText(_prevMenuTitle, false);
_menuBar->setMenuButtonType(_fromMenuType, false, true);
_menuBar->setButtonTransitionType(ActionBar::ButtonTransition::BTN_FADE);
int numButtons = (int)_prevManuBarButton.size();
if (numButtons == 1) {
_menuBar->setOneButton(_prevManuBarButton.at(0), true, true);
} else if (numButtons == 2) {
_menuBar->setTwoButton(_prevManuBarButton.at(0), _prevManuBarButton.at(1), true, true);
} else {
_menuBar->setOneButton(ActionBar::MenuType::NONE, true, true);
}
_menuBar->onSwipeStart();
}
}
}
void SMMenuTransitionScene::onTransitionProgress(const Transition type, const int tag, const float progress)
{
if (type == Transition::Transition_SWIPE_OUT) {
if (_menuBar) {
_menuBar->onSwipeUpdate(progress);
}
_swipeStarted = true;
}
}
void SMMenuTransitionScene::onTransitionComplete(const Transition type, const int tag)
{
bool actionBarReturn = false;
if (_swipeStarted) {
if (type == Transition::Transition_SWIPE_OUT) {
_menuBar->onSwipeComplete();
} else if (type == Transition::Transition_RESUME) {
_menuBar->onSwipeCancel();
actionBarReturn = true;
}
}
_swipeStarted = false;
if (type == Transition::Transition_IN || actionBarReturn) {
// 액션바 회수
auto layer = _director->getSharedLayer(cocos2d::Director::SharedLayer::BETWEEN_SCENE_AND_UI);
auto children = layer->getChildren();
for (auto child : children) {
if (child == _menuBar) {
ViewUtil::adoptionTo(child, this);
_menuBar->setActionBarListener(this);
break;
}
}
}
}
|
//============================================================================
// Name : ExperimentalTest.cpp
// Author : Goran Kostadinov
// Version :
// Copyright :
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <gtest/gtest.h>
using namespace std;
int main(int argc, char **argv)
{
cout << "Running main() from ExperimentalTest.cpp" << endl;
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
#pragma once
#include "std_lib_facilities.h"
class Image
{
static constexpr int N_DIM{ 5 };
public:
// Internally used data types
typedef short T;
typedef std::array<int, N_DIM> dimension;
// STL container and iterator typedefs
typedef T value_type;
typedef T* iterator;
typedef const T* const_iterator;
typedef T& reference;
typedef const T& const_reference;
// Constructors and destructor
Image(dimension);
Image(const Image&);
Image(Image&&);
//default constructor
Image();
virtual ~Image();
// Assignment operators
Image& operator=(const Image&);
Image& operator=(Image&&);
// Basic iterators, this generates a C4996 error in Visual Studio.
// Disable that in main.cpp with: #pragma warning(default:4996)
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
// Size and resize
dimension size() const; // the dimension object
unsigned int dim(unsigned int d) const; // get the size of a dimension
unsigned int nr_dims() const; // number of dimensions > 1
void resize(const dimension& d); // resize this image
// Pixel value lookup, should support out-of-image coordinates by clamping to 0..dim
value_type operator()(int x = 0, int y = 0, int z = 0, int c = 0, int t = 0) const;
reference operator()(int x = 0, int y = 0, int z = 0, int c = 0, int t = 0);
int imageVoxels() const; //returns the number of voxels in an image
private:
dimension _dimensions;
T* _data;
};
|
#include <stdio.h>
#include <deque>
#include <iostream>
using namespace std;
typedef long long int lli;
int main(int argc, char const *argv[])
{
int T;
scanf("%d", &T);
while (T-- > 0)
{
deque<lli> dq;
lli noStations;
lli maximumSum;
scanf("%lli", &noStations);
scanf("%lli", &maximumSum);
lli currentNumber = 0;
lli maximumPossibleSum = 0;
lli maximumPossibleStationCount = 0;
lli currentDqSum = 0;
lli currentDqStationCount = 0;
lli tempSum = 0;
bool bestAchieved = false;
for (lli i = 0 ; i < noStations ; i++)
{
scanf("%lli", ¤tNumber);
if (currentDqStationCount + 1 == maximumPossibleStationCount && currentDqSum + currentNumber <= maximumSum && currentDqSum + currentNumber <= maximumPossibleSum)
{
maximumPossibleStationCount = currentDqStationCount + 1;
maximumPossibleSum = currentDqSum + currentNumber;
currentDqSum += currentNumber;
currentDqStationCount++;
dq.push_back(currentNumber);
}
else if (currentDqStationCount + 1 > maximumPossibleStationCount && currentDqSum + currentNumber <= maximumSum)
{
maximumPossibleStationCount = currentDqStationCount + 1;
maximumPossibleSum = currentDqSum + currentNumber;
currentDqSum += currentNumber;
currentDqStationCount++;
dq.push_back(currentNumber);
}
else
{
while (!dq.empty() && currentDqSum + currentNumber > maximumSum)
{
lli frontNum = dq.front();
currentDqSum -= frontNum;
currentDqStationCount--;
dq.pop_front();
}
if (currentNumber <= maximumSum)
{
if (currentDqStationCount + 1 == maximumPossibleStationCount && currentDqSum + currentNumber <= maximumSum && currentDqSum + currentNumber <= maximumPossibleSum)
{
maximumPossibleStationCount = currentDqStationCount + 1;
maximumPossibleSum = currentDqSum + currentNumber;
}
else if (currentDqStationCount + 1 > maximumPossibleStationCount && currentDqSum + currentNumber <= maximumSum)
{
maximumPossibleStationCount = currentDqStationCount + 1;
maximumPossibleSum = currentDqSum + currentNumber;
}
currentDqSum += currentNumber;
currentDqStationCount++;
dq.push_back(currentNumber);
}
}
}
if (currentDqStationCount > maximumPossibleStationCount && currentDqSum <= maximumSum)
{
printf("%lli %lli\n", currentDqSum, currentDqStationCount);
}
else
{
printf("%lli %lli\n", maximumPossibleSum, maximumPossibleStationCount);
}
}
return 0;
}
|
#pragma once
#include "Vehicle.h"
#include <string>
#include <iostream>
#include "math.h"
#include "locale.h"
#define DEFAULT_FACTOR_OF_SAFITY_CAR 500 // км без ремонта
#define DEFAULT_LIFTING_CAPACITY_CAR 450 // кг перевозит без прицепа
#define DEFAULT_AVERAGE_SPEED_CAR 80 // км/ч
#define DEFAULT_COST_OF_REPAIR_CAR 300 // монет за разовую починку
#define DEFAULT_COST_OF_SERVICE_CAR 14 // монет за км
class Automobile :
public Vehicle
{
public:
void ShowModel() override;
void LockTrailer();
void UnlockTrailer();
void PrintCostOfTransit(int km, int kg) override;
Automobile(std::string modelS);
~Automobile();
private:
bool trailer;
};
void Automobile::LockTrailer()
{
if (!trailer)
{
trailer = true;
liftingCapacity += 800;
averageSpeed -= 15;
}
}
void Automobile::UnlockTrailer()
{
if (trailer)
{
trailer = false;
liftingCapacity -= 800;
averageSpeed += 15;
}
}
void Automobile::PrintCostOfTransit(int km, int kg)
{
int pathLength = GetPathLength(km, kg);
std::cout << "Груз " << kg << " кг на " << km << " км \n";
int finalCost = costOfServices * pathLength + RepairSelf(pathLength);
std::cout << "Стоимость перевозки составила " << finalCost << " монет\n";
}
Automobile::Automobile(std::string modelS)
{
model = modelS;
factorOfSafety = DEFAULT_FACTOR_OF_SAFITY_CAR;
liftingCapacity = DEFAULT_LIFTING_CAPACITY_CAR;
averageSpeed = DEFAULT_AVERAGE_SPEED_CAR;
costOfRepair = DEFAULT_COST_OF_REPAIR_CAR;
costOfServices = DEFAULT_COST_OF_SERVICE_CAR;
trailer = false;
}
void Automobile::ShowModel()
{
std::cout << "Это " << model;
if (trailer) std::cout << " с прицепом";
std::cout << "\n";
}
Automobile::~Automobile()
{
}
|
/***********************************************************************
created: 21/2/2004
author: Paul D Turner
purpose: Defines the Property class which forms part of a
PropertySet
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#ifndef _CEGUIProperty_h_
#define _CEGUIProperty_h_
#include "CEGUI/String.h"
namespace CEGUI
{
class XMLSerializer;
/*!
\brief
Dummy base class to ensure correct casting of receivers.
*/
class CEGUIEXPORT PropertyReceiver
{
public:
virtual ~PropertyReceiver() = default;
};
/*!
\brief
An abstract class that defines the interface to access object properties by name.
Property objects allow (via a PropertySet) access to certain properties of objects
by using simple get/set functions and the name of the property to be accessed.
*/
class CEGUIEXPORT Property
{
public:
static const String XMLElementName;
static const String NameXMLAttributeName;
static const String ValueXMLAttributeName;
/*!
\brief
Creates a new Property object.
\param name
String containing the name of the new Property.
\param help
String containing a description of the Property and it's usage.
\param defaultValue
String holding the textual representation of the default value for this Property
\param writesXML
Specifies whether the writeXMLToStream method should do anything for this Property. This
enables selectivity in what properties within a PropertySet will get output as XML.
\param dataType
String representation of the data type this property is held in ("int", "UVector2", ...)
\param origin
String describing the origin class of this Property (Window, FrameWindow, ...)
*/
Property(const String& name, const String& help, const String& defaultValue = "", bool writesXML = true, const String& dataType = "Unknown", const String& origin = "Unknown") :
d_name(name),
d_help(help),
d_default(defaultValue),
d_writeXML(writesXML),
d_dataType(dataType),
d_origin(origin)
{}
/*!
\brief
Destructor for Property objects
*/
virtual ~Property(void) {}
/*!
\brief
Return a String that describes the purpose and usage of this Property.
\return
String that contains the help text
*/
const String& getHelp(void) const {return d_help;}
/*!
\brief
Return a the name of this Property
\return
String containing the name of the Property
*/
const String& getName(void) const {return d_name;}
/*!
\brief
Return string data type of this Property
\return
String containing the data type of the Property
*/
const String& getDataType(void) const {return d_dataType;}
/*!
\brief
Return string origin of this Property
\return
String containing the origin of the Property
*/
const String& getOrigin(void) const {return d_origin;}
/*!
\brief
Return the current value of the Property as a String
\param receiver
Pointer to the target object.
\return
String object containing a textual representation of the current value of the Property
*/
virtual String get(const PropertyReceiver* receiver) const = 0;
/*!
\brief
Sets the value of the property
\param receiver
Pointer to the target object.
\param value
A String object that contains a textual representation of the new value to assign to the Property.
\return
Nothing.
\exception InvalidRequestException Thrown when the Property was unable to interpret the content of \a value.
*/
virtual void set(PropertyReceiver* receiver, const String& value) = 0;
/*!
\brief
Returns whether the property is at it's default value.
\param receiver
Pointer to the target object.
\return
- true if the property has it's default value.
- false if the property has been modified from it's default value.
*/
virtual bool isDefault(const PropertyReceiver* receiver) const;
/*!
\brief
Returns the default value of the Property as a String.
\param receiver
Pointer to the target object.
\return
String object containing a textual representation of the default value for this property.
*/
virtual String getDefault(const PropertyReceiver* receiver) const;
/*!
\brief
Writes out an XML representation of this class to the given stream.
\note
This would normally have been implemented via XMLGenerator base class, but in this
case we require the target PropertyReceiver in order to obtain the property value.
*/
virtual void writeXMLToStream(const PropertyReceiver* receiver, XMLSerializer& xml_stream) const;
/*!
\brief
Returns whether the property is readable.
\return
- true if the property is readable.
- false if the property isn't readable.
*/
virtual bool isReadable() const;
/*!
\brief
Returns whether the property is writable.
\return
- true if the property is writable.
- false if the property isn't writable.
*/
virtual bool isWritable() const;
/*!
\brief
Returns whether the property writes to XML streams.
*/
virtual bool doesWriteXML() const;
//! function to allow initialisation of a PropertyReceiver.
virtual void initialisePropertyReceiver(PropertyReceiver* /*receiver*/) const {}
virtual Property* clone() const = 0;
protected:
String d_name; //!< String that stores the Property name.
String d_help; //!< String that stores the Property help text.
String d_default; //!< String that stores the Property default value string.
bool d_writeXML; //!< Specifies whether writeXMLToStream should do anything for this property.
// TODO: This is really ugly but PropertyDefinition forced me to do this to support operator=
String d_dataType; //!< Holds data type of this property
// TODO: This is really ugly but PropertyDefinition forced me to do this to support operator=
String d_origin; //!< Holds origin of this property
};
} // End of CEGUI namespace section
#endif // end of guard _CEGUIProperty_h_
|
#include<bits/stdc++.h>
using namespace std;
int n, m, ans = 0;
struct farmer
{
int p;
int a;
}f[5010];
bool cmp(farmer a. farmer b)
{
if (a.p != b.p) return a.p < b.p;
return a.a > b.a;
}
int main()
{
freopen("P1208.in", "r", stdin);
cin>>n>>m;
for (int i = 1; i <= m; ++i) cin>>f[i].p>>f[i].a;
sort(f + 1, f + 1 + m, cmp);
int i = 1;
while(n)
{
if (f[i].a != 0)
{
f[i].a--;
ans += f[i].p;
n--;
}
else i++;
}
cout<<ans<<endl;
return 0;
}
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
float funcao (float a0,float a1,float a2,float a3,float a4,float a5,float x){
float y;
y=a0*cos(a1*x)+a2*sin(a3*x)+exp(a4*x)+a5;
return y;
}
float funcaoderiv (float a0,float a1,float a2,float a3,float a4,float a5,float x){
float y;
y= (-a1)*a0*sin(a1*x)+a3*a2*cos(a3*x)+a4*exp(a4*x);
return y;
}
float funcaosecderiv (float a0,float a1,float a2,float a3,float a4,float a5,float x){
float y;
y= (-a1)*a1*a0*cos(a1*x)+(-a3)*a3*a2*sin(a3*x)+a4*a4*exp(a4*x);
return y;
}
float *bissecao (float a0,float a1,float a2,float a3,float a4,float a5,float NMax,float e1,float e2,float a,float b){
float c, x0,x1,d,e,z;
float *r;
float i=0;
z=NMax;
x0=(b+a)/2;
d=fabs(funcao(a0, a1, a2, a3, a4, a5, x0));
if(d<=e2){
r=(float*)malloc(5*sizeof(float));
r[0]=1;
r[1]=i;
r[2]=x0;
r[3]=0;
r[4]=d;
}
else {
while(i!=z){
i++;
if (funcao(a0, a1, a2, a3, a4, a5, a)*funcao(a0, a1, a2, a3, a4, a5, x0)<0)
{b=x0;}
if (funcao(a0, a1, a2, a3, a4, a5, a)*funcao(a0, a1, a2, a3, a4, a5, x0)>0)
{a=x0;}
x1=x0;
x0=(b+a)/2;
c=x1-x0;
d=fabs(funcao(a0, a1, a2, a3, a4, a5, x0));
if(d<=e2){
if(fabs(c)<=e1){
break;
}
}
}
r=(float*)malloc(5*sizeof(float));
if (i==z)
r[0]=0;
else
r[0]=1;
r[1]=i;
r[2]=x0;
r[3]=fabs(x1-x0);
r[4]=d;}
return r;
}
float *newton (float a0,float a1,float a2,float a3, float a4, float a5,float NumMax, float e1,float e2,float a,float b) {
float x0,x1,k,pm,m,c,d,z;
float i=0;
float *r;
z=NumMax;
pm=(a+b)/2;
k=funcao(a0, a1,a2,a3,a4,a5,pm);
m=funcaoderiv(a0, a1,a2,a3,a4,a5,pm);
if((fabs(k))<=(e2)){
r=(float*)malloc(5*sizeof(float));
r[0]=1;
r[1]=i;
r[2]=pm;
r[3]=0;
r[4]=fabs(k);
}
else{
x0=pm;
while(i!=z){
i++;
k=funcao(a0,a1,a2,a3,a4,a5,x0);
m=funcaoderiv(a0,a1,a2,a3,a4,a5,x0);
x1=x0;
x0=x0-(k/m);
c=x1-x0;
d=fabs(funcao(a0, a1, a2, a3, a4, a5, x0));
if(fabs(c)<=e1){
if(d<=e2){
break;
}
}
}
r=(float*)malloc(5*sizeof(float));
if(i==z)
r[0]=0;
else
r[0]=1;
r[1]=i;
r[2]=x0;
r[3]=fabs(x1-x0);
r[4]=d;
}
return r;
}
float *halley (float a0,float a1,float a2,float a3, float a4, float a5,float NumMax, float e1,float e2,float a,float b){
float *r;
float x0,x1,k,pm,m,g,d,c,z;
float i=0;
z=NumMax;
pm=(a+b)/2;
k=funcao(a0, a1,a2,a3,a4,a5,pm);
m=funcaoderiv(a0, a1,a2,a3,a4,a5,pm);
g=funcaosecderiv(a0, a1,a2,a3,a4,a5,pm);
if((fabs(k))<=(e2)){
r=(float*)malloc(5*sizeof(float));
r[0]=1;
r[1]=i;
r[2]=pm;
r[3]=0;
r[4]=fabs(k);
}
else{
x0=pm;
while(i!=z){
i++;
k=funcao(a0, a1,a2,a3,a4,a5,x0);
m=funcaoderiv(a0, a1,a2,a3,a4,a5,x0);
g=funcaosecderiv(a0, a1,a2,a3,a4,a5,x0);
x1=x0;
x0=x0-(2*k*m)/(2*pow(m,2)-k*g);
c=x1-x0;
d=fabs(funcao(a0,a1,a2,a3,a4,a5,x0));
if(fabs(c)<=e1){
if(d<=e2){
break;
}
}
}
r=(float*)malloc(5*sizeof(float));
if(i==z)
r[0]=0;
else
r[0]=1;
r[1]=i;
r[2]=x0;
r[3]=fabs(x1-x0);
r[4]=d;
}
return r;
}
int main(){
FILE *p,*q;
float A0,A1,A2,A3,A4,A5,NMAX,E1,E2,A,B;
float *result;
int i=1,j,f,g=0,h,l,k;
int c;
int nlinhas=0,ncaract=0;
float conv,ite,raiz,er1,er2;
p=fopen("entrada.txt","r");
q=fopen("saida.txt","w");
fscanf(p,"%f %f %f %f %f %f %f %f %f %f %f",&A0,&A1,&A2,&A3,&A4,&A5,&NMAX,&E1,&E2,&A,&B);
while((c=fgetc(p))!=EOF){
result=bissecao (A0, A1, A2, A3, A4, A5, NMAX, E1, E2, A, B);
conv=result[0];
ite=result[1];
raiz=result[2];
er1=result[3];
er2=result[4];
fprintf(q,"RESULTADO BISSEÇÃO (EQUAÇÃO %d) :\n",i);
if (conv==1)
fprintf(q,"CONVERGIU, O NÚMERO DE ITERAÇÕES FOI: %.5f, O VALOR ENCONTRADO PARA X FOI: %.5f, |X(i)-X(i-1)|: %.5f, |F(Xi)|: %.5f \n\n", ite, raiz, er1, er2);
else
fprintf(q,"NÃO CONVERGIU, PORÉM, O NÚMERO DE ITERAÇÕES FOI: %.5f, O VALOR ENCONTRADO PARA X FOI: %.5f, |X(i)-X(i-1)|: %.5f, |F(Xi)|: %.5f \n\n",ite, raiz, er1, er2);
result=newton (A0, A1, A2, A3, A4, A5, NMAX, E1, E2, A, B);
conv=result[0];
ite=result[1];
raiz=result[2];
er1=result[3];
er2=result[4];
fprintf(q,"RESULTADO NEWTON (EQUAÇÃO %d) :\n",i);
if (conv==1)
fprintf(q,"CONVERGIU, O NÚMERO DE ITERAÇÕES FOI: %.5f, O VALOR ENCONTRADO PARA X FOI: %.5f, |X(i)-X(i-1)|: %.5f, |F(Xi)|: %.5f \n\n", ite, raiz, er1, er2);
else
fprintf(q,"NÃO CONVERGIU, PORÉM, O NÚMERO DE ITERAÇÕES FOI: %.5f, O VALOR ENCONTRADO PARA X FOI: %.5f, |X(i)-X(i-1)|: %.5f, |F(Xi)|: %.5f \n\n",ite, raiz, er1, er2);
result=halley (A0, A1, A2, A3, A4, A5, NMAX, E1, E2, A, B);
conv=result[0];
ite=result[1];
raiz=result[2];
er1=result[3];
er2=result[4];
fprintf(q,"RESULTADO HALLEY (EQUAÇÃO %d) :\n",i);
if (conv==1)
fprintf(q,"CONVERGIU, O NÚMERO DE ITERAÇÕES FOI: %.5f, O VALOR ENCONTRADO PARA X FOI: %.5f, |X(i)-X(i-1)|: %.5f, |F(Xi)|: %.5f \n\n", ite, raiz, er1, er2);
else
fprintf(q,"NÃO CONVERGIU, PORÉM, O NÚMERO DE ITERAÇÕES FOI: %.5f, O VALOR ENCONTRADO PARA X FOI: %.5f, |X(i)-X(i-1)|: %.5f, |F(Xi)|: %.5f \n\n",ite, raiz, er1, er2);
fprintf(q,"\n \n \n \n");
i++;
fscanf(p,"%f %f %f %f %f %f %f %f %f %f %f",&A0,&A1,&A2,&A3,&A4,&A5,&NMAX,&E1,&E2,&A,&B);
}
fclose(q);
fclose(p);
}
|
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "GeneratedCppIncludes.h"
#include "QBERTGameMode.h"
PRAGMA_DISABLE_OPTIMIZATION
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeQBERTGameMode() {}
// Cross Module References
QBERT_PROJECT_API UClass* Z_Construct_UClass_AQBERTGameMode_NoRegister();
QBERT_PROJECT_API UClass* Z_Construct_UClass_AQBERTGameMode();
ENGINE_API UClass* Z_Construct_UClass_AGameModeBase();
UPackage* Z_Construct_UPackage__Script_QBert_Project();
QBERT_PROJECT_API UClass* Z_Construct_UClass_ACube_NoRegister();
COREUOBJECT_API UClass* Z_Construct_UClass_UClass();
QBERT_PROJECT_API UClass* Z_Construct_UClass_AUIElements_NoRegister();
QBERT_PROJECT_API UClass* Z_Construct_UClass_AElevator_NoRegister();
// End Cross Module References
void AQBERTGameMode::StaticRegisterNativesAQBERTGameMode()
{
}
UClass* Z_Construct_UClass_AQBERTGameMode_NoRegister()
{
return AQBERTGameMode::StaticClass();
}
UClass* Z_Construct_UClass_AQBERTGameMode()
{
static UClass* OuterClass = NULL;
if (!OuterClass)
{
Z_Construct_UClass_AGameModeBase();
Z_Construct_UPackage__Script_QBert_Project();
OuterClass = AQBERTGameMode::StaticClass();
if (!(OuterClass->ClassFlags & CLASS_Constructed))
{
UObjectForceRegistration(OuterClass);
OuterClass->ClassFlags |= (EClassFlags)0x20900288u;
UProperty* NewProp_tempCube = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("tempCube"), RF_Public|RF_Transient|RF_MarkAsNative) UClassProperty(CPP_PROPERTY_BASE(tempCube, AQBERTGameMode), 0x0044000000020015, Z_Construct_UClass_ACube_NoRegister(), Z_Construct_UClass_UClass());
UProperty* NewProp_tempUI = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("tempUI"), RF_Public|RF_Transient|RF_MarkAsNative) UClassProperty(CPP_PROPERTY_BASE(tempUI, AQBERTGameMode), 0x0044000000020015, Z_Construct_UClass_AUIElements_NoRegister(), Z_Construct_UClass_UClass());
UProperty* NewProp_ElevatorObj2 = new(EC_InternalUseOnlyConstructor, OuterClass, TEXT("ElevatorObj2"), RF_Public|RF_Transient|RF_MarkAsNative) UObjectProperty(CPP_PROPERTY_BASE(ElevatorObj2, AQBERTGameMode), 0x0040000000020015, Z_Construct_UClass_AElevator_NoRegister());
static TCppClassTypeInfo<TCppClassTypeTraits<AQBERTGameMode> > StaticCppClassTypeInfo;
OuterClass->SetCppTypeInfo(&StaticCppClassTypeInfo);
OuterClass->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = OuterClass->GetOutermost()->GetMetaData();
MetaData->SetValue(OuterClass, TEXT("HideCategories"), TEXT("Info Rendering MovementReplication Replication Actor Input Movement Collision Rendering Utilities|Transformation"));
MetaData->SetValue(OuterClass, TEXT("IncludePath"), TEXT("QBERTGameMode.h"));
MetaData->SetValue(OuterClass, TEXT("ModuleRelativePath"), TEXT("QBERTGameMode.h"));
MetaData->SetValue(OuterClass, TEXT("ShowCategories"), TEXT("Input|MouseInput Input|TouchInput"));
MetaData->SetValue(OuterClass, TEXT("ToolTip"), TEXT("Let this know what a ACube class is"));
MetaData->SetValue(NewProp_tempCube, TEXT("AllowPrivateAccess"), TEXT("true"));
MetaData->SetValue(NewProp_tempCube, TEXT("Category"), TEXT("Cube"));
MetaData->SetValue(NewProp_tempCube, TEXT("ModuleRelativePath"), TEXT("QBERTGameMode.h"));
MetaData->SetValue(NewProp_tempUI, TEXT("AllowPrivateAccess"), TEXT("true"));
MetaData->SetValue(NewProp_tempUI, TEXT("Category"), TEXT("UI"));
MetaData->SetValue(NewProp_tempUI, TEXT("ModuleRelativePath"), TEXT("QBERTGameMode.h"));
MetaData->SetValue(NewProp_tempUI, TEXT("ToolTip"), TEXT("This Subclasses are not necessary to spawn the actors"));
MetaData->SetValue(NewProp_ElevatorObj2, TEXT("AllowPrivateAccess"), TEXT("true"));
MetaData->SetValue(NewProp_ElevatorObj2, TEXT("Category"), TEXT("Elevators"));
MetaData->SetValue(NewProp_ElevatorObj2, TEXT("ModuleRelativePath"), TEXT("QBERTGameMode.h"));
#endif
}
}
check(OuterClass->GetClass());
return OuterClass;
}
IMPLEMENT_CLASS(AQBERTGameMode, 620918909);
static FCompiledInDefer Z_CompiledInDefer_UClass_AQBERTGameMode(Z_Construct_UClass_AQBERTGameMode, &AQBERTGameMode::StaticClass, TEXT("/Script/QBert_Project"), TEXT("AQBERTGameMode"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(AQBERTGameMode);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
PRAGMA_ENABLE_OPTIMIZATION
|
#include <gtest/gtest.h>
#include "hs_math/random/normal_random_var.hpp"
#include "hs_math/random/uniform_random_var.hpp"
#include "hs_sfm/sfm_utility/ransac_fit_plane.hpp"
namespace
{
template <typename _Scalar>
class TestRansacFitPlannar
{
public:
typedef _Scalar Scalar;
typedef EIGEN_VECTOR(Scalar, 2) Vector2;
typedef EIGEN_VECTOR(Scalar, 3) Vector3;
typedef EIGEN_VECTOR(Scalar, 4) Vector4;
typedef EIGEN_MATRIX(Scalar, 3, 3) Matrix33;
typedef Vector3 Point;
/**
* 测试ransac拟合三维点平面。
* 平面真值为xy平面作相似变换后的平面。
*/
static int Test(const Matrix33& rotation,
const Vector3& translate,
Scalar scale,
const Vector2& min,
const Vector2& max,
Scalar sigma,
Scalar outlier_ratio,
Scalar outlier_threshold,
size_t number_of_points)
{
Matrix33 covariance = Matrix33::Identity();
covariance *= sigma;
std::vector<Point> points;
for (size_t i = 0; i < number_of_points; i++)
{
Vector2 planar_point;
hs::math::random::UniformRandomVar<Scalar, 2>::Generate(
min, max, planar_point);
Vector3 mean;
mean << planar_point[0],
planar_point[1],
0;
Vector3 point;
hs::math::random::NormalRandomVar<Scalar, 3>::Generate(
mean, covariance, point);
Scalar random;
hs::math::random::UniformRandomVar<Scalar, 1>::Generate(
Scalar(0), Scalar(1), random);
if (random < outlier_ratio)
{
Scalar outlier;
hs::math::random::UniformRandomVar<Scalar, 1>::Generate(
outlier_threshold, outlier_threshold * 3, outlier);
point[0] += outlier;
point[1] += outlier;
point[2] += outlier;
}
point = rotation * point * scale + translate;
Point p;
p[0] = point[0];
p[1] = point[1];
p[2] = point[2];
points.push_back(p);
}
Vector4 plane;
hs::sfm::RansacFitPlane<Point> ransac_fitter;
if (ransac_fitter(points, plane, outlier_threshold) != 0) return -1;
size_t number_of_outliers = 0;
for (size_t i = 0; i < number_of_points; i++)
{
Vector4 point_homogeneous;
point_homogeneous << points[i][0],
points[i][1],
points[i][2],
1;
Scalar distance = point_homogeneous.dot(plane) /
plane.segment(0, 3).norm();
if (distance > outlier_threshold * scale)
{
number_of_outliers++;
}
}
Scalar statistical_outliers_ratio =
Scalar(number_of_outliers) / Scalar(number_of_points);
return statistical_outliers_ratio < outlier_ratio * 2 ? 0 : -1;
}
};
TEST(TestRansacFitPlannar, SimpleTest)
{
typedef double Scalar;
typedef EIGEN_VECTOR(Scalar, 2) Vector2;
typedef EIGEN_VECTOR(Scalar, 3) Vector3;
typedef EIGEN_VECTOR(Scalar, 4) Vector4;
typedef EIGEN_MATRIX(Scalar, 3, 3) Matrix33;
Matrix33 rotation = Matrix33::Identity();
Vector3 translate;
translate << 0,
0,
10;
Scalar scale = 5.0;
Vector2 min;
min << -10,
-10;
Vector2 max;
max << 10,
10;
Scalar sigma = 1.0;
Scalar outlier_ratio = 0.2;
Scalar outlier_threshold = 5;
size_t number_of_points = 100;
ASSERT_EQ(0, TestRansacFitPlannar<Scalar>::
Test(rotation,
translate,
scale,
min,
max,
sigma,
outlier_ratio,
outlier_threshold,
number_of_points));
}
}
|
#include "WebGL.hxx"
int main() {
return WebGLExample().Main();
}
|
#pragma once
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "drake/common/eigen_types.h"
#include "drake/geometry/frame_kinematics_vector.h"
#include "drake/multibody/rigid_body.h"
#include "drake/multibody/rigid_body_tree.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace manipulation {
namespace util {
/**
* Implements a class that maintains pose information for a set of specified
* RigidBodyFrames. Frame information is communicated via a FramePoseVector
* object. Frames can be specified at construction in one of two ways: (1) by
* providing a set of RigidBody names (of bodies already existing in the
* RigidBodyTree), which specify which RigidBodies these newly created frames
* should be attached to, or (2) by providing a set of RigidBodyFrames directly.
* The former simply searches the RigidBodyTree and assigns a RigidBodyFrame to
* the specified body. Frame pose w.r.t. the base RigidBody frame can also be
* specified. This system takes an abstract valued input of type
* KinematicResults<double> and generates an abstract value output of type
* geometry::FramePoseVector<double>.
*
* @ingroup manipulation_systems
*/
// TODO(rcory): Template FramePoseTracker on type T
class FramePoseTracker : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(FramePoseTracker)
/**
* Constructs a FramePoseTracker object by directly taking in the
* RigidBodyFrames to track.
* @param tree The RigidBodyTree containing the named bodies. FramePoseTracker
* keeps a reference to this tree to calculate frame poses in the world
* frame.
* @param frames a std::vector of unique pointers to RigidBodyFrames that are
* to be tracked. Pointer ownership is transferred to this class and
* @p frames is cleared before returning. Each RigidBodyFrame in this
* vector should have a name that is unique, i.e., the std::string
* returned by RigidBodyFrame::get_name() should not match any other
* frame name.
* @throws std::runtime_error if any frame has a non-unique name or the frame
* is not attached to a RigidBody (i.e., its RigidBody pointer is
* nullptr) or @p frames is a nullptr or points to an empty
* std::vector.
*/
FramePoseTracker(
const RigidBodyTree<double>& tree,
std::vector<std::unique_ptr<RigidBodyFrame<double>>>* frames);
/**
* Constructs a FramePoseTracker object from the information contained in
* @p frames_info, which is a std::map whose keys denote unique names.
* Each key is mapped to a std::pair that includes a RigidBody or
* RigidBodyFrame name (std::string) specifying which parent this frame
* should be attached to, and the model instance id in the @p tree that
* contains the corresponding parent frame.
*
* @param tree The RigidBodyTree containing the named bodies. FramePoseTracker
* keeps a reference to this tree to calculate frame poses in the world
* frame.
* @param frames_info A mapping from a name (unique in this mapping) to a
* std::pair consisting of the parent name and model instance id. The
* parent is either a frame or body. If model instance id is -1, every
* model is searched.
* @param frame_poses A vector containing each frame's pose relative to the
* parent body or frame. If this vector is empty, it assumes identity
* for all poses.
*/
FramePoseTracker(
const RigidBodyTree<double>& tree,
const std::map<std::string, std::pair<std::string, int>> frames_info,
std::vector<Eigen::Isometry3d> frame_poses =
std::vector<Eigen::Isometry3d>());
/**
* This InputPort represents an abstract valued input port of type
* KinematicsResults<double>.
*/
const systems::InputPort<double>& get_kinematics_input_port()
const {
return this->get_input_port(kinematics_input_port_index_);
}
int get_kinematics_input_port_index() const {
return this->kinematics_input_port_index_;
}
/**
* This OutputPort represents an abstract valued output port of type
* geometry::FramePoseVector. This port cannot be connected to
* geometry::SceneGraph (an exception will be thrown). This port exists only
* to connect to other systems which expect a FramePoseVector
* (e.g. systems::sensors::OptitrackLcmFrameSender).
*/
const systems::OutputPort<double>& get_pose_vector_output_port() const {
return this->get_output_port(pose_vector_output_port_index_);
}
int get_pose_vector_output_port_index() const {
return this->pose_vector_output_port_index_;
}
const std::map<std::string, geometry::FrameId>&
get_frame_name_to_id_map() const {
return frame_name_to_id_map_;
}
RigidBodyFrame<double>* get_mutable_frame(std::string frame_name) {
return this->frame_name_to_frame_map_[frame_name].get();
}
private:
void Init();
void OutputStatus(const systems::Context<double>& context,
geometry::FramePoseVector<double>* output) const;
int kinematics_input_port_index_{-1};
int pose_vector_output_port_index_{-1};
const RigidBodyTree<double>* tree_;
std::map<std::string,
std::unique_ptr<RigidBodyFrame<double>>> frame_name_to_frame_map_;
const geometry::SourceId source_id_;
std::map<std::string, geometry::FrameId> frame_name_to_id_map_;
};
} // namespace util
} // namespace manipulation
} // namespace drake
|
/*-----------------------------------------------------------------------
Matt Marchant 2015 - 2016
http://trederia.blogspot.com
Robomower - Zlib license.
This software is provided 'as-is', without any express or
implied warranty.In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions :
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
-----------------------------------------------------------------------*/
#include <components/InputWindow.hpp>
#include <Messages.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/RenderStates.hpp>
#include <SFML/Window/Event.hpp>
#include <xygine/util/Position.hpp>
#include <xygine/Entity.hpp>
namespace
{
const sf::Vector2f size(200.f, 80.f);
const sf::Color fillColour(180u, 40u, 20u, 180u);
const sf::Color borderColour(15u, 30u, 100u);
const float blinkTime = 0.7f;
const float cursorPadding = 8.f;
const float cursorTop = -40.f;
}
InputWindow::InputWindow(xy::MessageBus& mb)
: xy::Component (mb, this),
m_targetId (0),
m_value (1),
m_blink (true),
m_close (false)
{
m_background.setSize(size);
m_background.setFillColor(fillColour);
m_background.setOutlineThickness(10.f);
m_background.setOutlineColor(borderColour);
xy::Util::Position::centreOrigin(m_background);
m_text.setPosition(-56.f, -60.f);
m_text.setString("1");
m_cursor.setSize({ 10.f, 58.f });
m_cursor.setPosition(-1.f, cursorTop);
}
InputWindow::~InputWindow()
{
auto msg = sendMessage<InputBoxEvent>(MessageId::InputBoxMessage);
msg->action = InputBoxEvent::WindowClosed;
msg->entityId = m_targetId;
msg->value = m_value;
}
//public
void InputWindow::entityUpdate(xy::Entity& entity, float)
{
m_globalBounds = entity.getWorldTransform().transformRect(m_background.getGlobalBounds());
if (m_blinkClock.getElapsedTime().asSeconds() > blinkTime)
{
m_blink = !m_blink;
m_blinkClock.restart();
sf::Color c = (m_blink) ? sf::Color::White : sf::Color::Transparent;
m_cursor.setFillColor(c);
}
if (m_close) entity.destroy();
}
void InputWindow::handleTextEvent(const sf::Event& evt)
{
if (evt.type == sf::Event::KeyPressed)
{
if (evt.key.code == sf::Keyboard::BackSpace && !m_strValue.empty())
{
m_strValue.pop_back();
}
else if (evt.key.code == sf::Keyboard::Return)
{
//close input
m_close = true;
}
}
else
{
if (m_strValue.size() < 2)
{
//only want numeric input, and only 0 when second digit
if (evt.text.unicode > (48 - m_strValue.size()) && evt.text.unicode < 58)
{
m_strValue += static_cast<char>(evt.text.unicode);
}
}
}
//update m_value
m_value = (m_strValue.empty()) ? 1 : std::atoi(m_strValue.c_str());
m_text.setString(m_strValue);
auto bounds = m_text.getGlobalBounds();
float posX = bounds.left + bounds.width + cursorPadding;
m_cursor.setPosition(posX, cursorTop);
}
void InputWindow::setFont(const sf::Font& font)
{
m_text.setFont(font);
}
void InputWindow::setCharacterSize(sf::Uint32 size)
{
m_text.setCharacterSize(size);
}
void InputWindow::setTargetId(sf::Uint64 id)
{
m_targetId = id;
}
sf::FloatRect InputWindow::globalBounds() const
{
return m_globalBounds;
}
//private
void InputWindow::draw(sf::RenderTarget& rt, sf::RenderStates states) const
{
rt.draw(m_background, states);
rt.draw(m_text, states);
rt.draw(m_cursor, states);
}
|
//
// Created by nickolay on 21.02.2021.
//
#ifndef DRONEAPP_VEHICLEDATA_H
#define DRONEAPP_VEHICLEDATA_H
#include <opencv2/core/core_c.h>
#include <QString>
#include "../Utils/AsyncVar.h"
enum VehicleMode{QUADROCOPTER = 0, CAR = 1};
class VehicleData {
public:
AsyncVar<CvPoint3D32f> targetpoint{CvPoint3D32f{0,0,0}};
AsyncVar<VehicleMode> vehicleMode{QUADROCOPTER};
AsyncVar<bool> connectedToPx;
AsyncVar<int> connectionCounter{0};
AsyncVar<double> ramTotal{0};
AsyncVar<double> ramFree{0};
AsyncVar<double> fps{0};
AsyncVar<QString> ping{""};
AsyncVar<double> cpuTemp{0};
AsyncVar<double> cpuAVGLoad{0};
std::vector<double> cpuCoreLoad;
};
#endif //DRONEAPP_VEHICLEDATA_H
|
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "math.h"
#include <algorithm> // std::sort
//Librerias propias usadas
#include "constantes.hpp"
#include "camina8/v_repConst.h"
#include "../../Convexhull/vector3d.hpp"
#include "../../Convexhull/convexhull.cpp"
#include "../../Convexhull/analisis.cpp"
// Used data structures:
#include "camina8/InfoMapa.h"
#include "camina8/CinversaParametros.h"
#include "camina8/UbicacionRobot.h"
#include "camina8/PlanificadorParametros.h"
#include "camina8/SenalesCambios.h"
// Used API services:
#include "vrep_common/VrepInfo.h"
// Definiciones
#define delta_correccion 0.005
//Clientes y Servicios
ros::ServiceClient client_Cinversa1;
camina8::CinversaParametros srv_Cinversa1;
//-- Variables Globales
bool simulationRunning=true;
bool sensorTrigger=false;
float simulationTime=0.0f;
//-- Log de planificador
FILE *fp1,*fp2;
//-- Entrada
int Tripode=0, tripode[Npatas], Tripode1[Npatas/2], Tripode2[Npatas/2], cuentaPasos=0, cuentaErrores[Npatas]={0,0,0,0,0,0},errorPata[Npatas][2];
float velocidadApoyo=0.0, beta=0.0, phi[Npatas], alfa=0.0;
//-- Variables de mapa
camina8::InfoMapa infoMapa;
bool matrizMapa[100][20];
int nCeldas_i=0, nCeldas_j=0;
float LongitudCeldaY=0, LongitudCeldaX=0;
//-- Variables de ubicacion robot
double tiempo_ahora=0.0, tiempo_anterior=0.0;
//float ajuste_Vel=vel_esperada/vel_teorica;
float velocidadCuerpo_y=0.0, delta_x=0.0, delta_y=0.0, x_anterior=0.0, y_anterior=0.0, x_actual=0.0, y_actual=0.0;
float posicionActualPata_y[Npatas], posicionActualPata_x[Npatas];
float posicionActualPataSistemaPata_y[Npatas],posicionActualPataSistemaPata_x[Npatas],posicionActualPataSistemaPata_z[Npatas];
float teta_CuerpoRobot=0.0;
//-- Envio de señal de stop
camina8::SenalesCambios senales;
//-- Obstaculos
Obstaculo obstaculo[100][20];
float di=0.0;
//-- Publishers
ros::Publisher chatter_pub1;
ros::Publisher chatter_pub2;
//-- Funciones
void transformacion_yxTOij(int *ptr_ij, float y, float x);
void FilePrint_matrizMapa();
void Limpiar_matrizMapa();
int Construye_matrizMapa(std::string fileName);
void print_matrizMapa();
void Info_Obstaculos(std::string fileName, int N_Obstaculos);
//-- Topic subscriber callbacks:
void infoCallback(const vrep_common::VrepInfo::ConstPtr& info)
{
simulationTime=info->simulationTime.data;
simulationRunning=(info->simulatorState.data&1)!=0;
}
void ubicacionRobCallback(camina8::UbicacionRobot msgUbicacionRobot)
{
teta_CuerpoRobot = msgUbicacionRobot.orientacionCuerpo_yaw;
for(int k=0; k<Npatas;k++) {
posicionActualPata_x[k] = msgUbicacionRobot.coordenadaPata_x[k];
posicionActualPata_y[k] = msgUbicacionRobot.coordenadaPata_y[k];
posicionActualPataSistemaPata_x[k] = msgUbicacionRobot.coordenadaPataSistemaPata_x[k];
posicionActualPataSistemaPata_y[k] = msgUbicacionRobot.coordenadaPataSistemaPata_y[k];
posicionActualPataSistemaPata_z[k] = msgUbicacionRobot.coordenadaPataSistemaPata_z[k];
}
}
bool PlanificadorPisada(camina8::PlanificadorParametros::Request &req,
camina8::PlanificadorParametros::Response &res)
{
// ROS_INFO("Llamado a servicio planificador");
// fprintf(fp2,"\ntiempo de simulacion: %.3f\t",simulationTime);
//-- Datos para envio de mensajes
res.modificacion_T = 0.0;
res.modificacion_lambda = 0.0;
res.result = 0;
//-- Variables locales
int Tripode_Transferencia[Npatas/2];
int PisadaProxima_i=0, PisadaProxima_j=0;
int ij[2]={0,0}, *p_ij; //Apuntadores a arreglos de coordenadas e indices
bool cinversaOK;
float PisadaProxima_x=0.0, PisadaProxima_y=0.0, PisadaProxima_z=0.0;
float delta_x_S0=0.0, delta_y_S0=0.0, delta_x=0.0, delta_y=0.0;
float modificacion_lambda[Npatas/2];
float T_actual=0.0,lambda_Apoyo_actual=0.0;
p_ij = ij; // Inicialización de apuntador
Tripode=req.Tripode;
// T_actual = req.T;
lambda_Apoyo_actual = req.lambda;
velocidadCuerpo_y = req.velApoyo_y;
cuentaPasos++;
ROS_INFO("INICIO server_PlanificadorPisada::T[%d]::P[%d] ((((v_y=%.3f))))",Tripode,cuentaPasos,velocidadCuerpo_y);
fprintf(fp2,"\nINICIO T[%d],Paso[%d]\n",Tripode,cuentaPasos);
fprintf(fp2,"server_PlanificadorPisada::T[%d]: tiempo de simulacion: %.3f ((((v_y=%.3f))))\n",Tripode,simulationTime,velocidadCuerpo_y);
ros::spinOnce();
if (req.Tripode == T1){
//-- se intercambian los tripodes
for(int k=0;k<Npatas/2;k++) {
Tripode_Transferencia[k] = Tripode2[k];
//-- se reporta posicion de tripode en apoyo
// infoMapa.coordenadaPata_x[Tripode1[k]] = posicionActualPata_x[Tripode1[k]];
// infoMapa.coordenadaPata_y[Tripode1[k]] = posicionActualPata_y[Tripode1[k]];
// transformacion_yxTOij(p_ij, posicionActualPata_y[Tripode1[k]], posicionActualPata_x[Tripode1[k]]);
// infoMapa.coordenadaPata_i[Tripode1[k]] = ij[0];
// infoMapa.coordenadaPata_j[Tripode1[k]] = ij[1];
}
} else{
for(int k=0;k<Npatas/2;k++){
Tripode_Transferencia[k] = Tripode1[k];
//-- se reporta posicion de tripode en apoyo
// infoMapa.coordenadaPata_x[Tripode2[k]] = posicionActualPata_x[Tripode2[k]];
// infoMapa.coordenadaPata_y[Tripode2[k]] = posicionActualPata_y[Tripode2[k]];
// transformacion_yxTOij(p_ij, posicionActualPata_y[Tripode2[k]], posicionActualPata_x[Tripode2[k]]);
// infoMapa.coordenadaPata_i[Tripode2[k]] = ij[0];
// infoMapa.coordenadaPata_j[Tripode2[k]] = ij[1];
}
}
//-- La correccion del tiempo se hace solo para mantener la velocidad al lambda que llevavas
res.modificacion_T = T_actual = lambda_Apoyo_actual/velocidadApoyo;
for(int k=0;k<Npatas/2;k++){
ros::spinOnce();
//-- Calculamos proximo movimiento en el sistema de pata
delta_x_S0 = -lambda_maximo*cos(alfa);
delta_y_S0 = lambda_maximo*sin(alfa);
delta_x = delta_x_S0*cos(phi[Tripode_Transferencia[k]]+alfa)-delta_y_S0*sin(phi[Tripode_Transferencia[k]]+alfa);
delta_y = delta_x_S0*sin(phi[Tripode_Transferencia[k]]+alfa)+delta_y_S0*cos(phi[Tripode_Transferencia[k]]+alfa);
PisadaProxima_x=posicionActualPataSistemaPata_x[Tripode_Transferencia[k]] + delta_x;
PisadaProxima_y=posicionActualPataSistemaPata_y[Tripode_Transferencia[k]] + delta_y;
PisadaProxima_z=posicionActualPataSistemaPata_z[Tripode_Transferencia[k]];
//-- Verificamos que pisada sea factible
// ROS_INFO("server_Plan: revisando cinversa");
srv_Cinversa1.request.x = PisadaProxima_x;
srv_Cinversa1.request.y = PisadaProxima_y;
srv_Cinversa1.request.z = PisadaProxima_z;
if (client_Cinversa1.call(srv_Cinversa1)){
//-- Funciona servicio
cinversaOK=true;
} else {
ROS_ERROR("server_PlanificadorPisada: servicio de Cinversa no funciona\n");
cinversaOK=false;
}
if (cinversaOK){
// ROS_INFO("server_Plan: cinversaOK");
//-- Calculamos proximo movimiento en el sistema mundo
// PisadaProxima_x=posicionActualPata_x[Tripode_Transferencia[k]] + (lambda_maximo+velocidadCuerpo_y*T_actual)*sin((teta_CuerpoRobot-teta_Offset)+alfa);
PisadaProxima_x=posicionActualPata_x[Tripode_Transferencia[k]] - (lambda_maximo+velocidadCuerpo_y*T_actual)*sin((teta_CuerpoRobot-teta_Offset)+alfa);
PisadaProxima_y=posicionActualPata_y[Tripode_Transferencia[k]] + (lambda_maximo+velocidadCuerpo_y*T_actual)*cos((teta_CuerpoRobot-teta_Offset)+alfa);
transformacion_yxTOij(p_ij, PisadaProxima_y, PisadaProxima_x);
PisadaProxima_i=ij[0];
PisadaProxima_j=ij[1];
if(matrizMapa[PisadaProxima_i][PisadaProxima_j]){
//-- La pisada COINCIDE con obstaculo
ROS_WARN("server_PlanificadorPisada: pata [%d] coincidira con obstaculo [%d][%d]",Tripode_Transferencia[k]+1,PisadaProxima_i,PisadaProxima_j);
fprintf(fp2,"pata [%d] coincidira con obstaculo[%d][%d]\n",Tripode_Transferencia[k]+1,PisadaProxima_i,PisadaProxima_j);
punto3d Pata, puntosObstaculo[4];
recta3d recta_inf_o;
float correccion=0.0;
Pata.x = PisadaProxima_x;
Pata.y = PisadaProxima_y;
puntosObstaculo[0].x=obstaculo[PisadaProxima_i][PisadaProxima_j].P1_x;
puntosObstaculo[0].y=obstaculo[PisadaProxima_i][PisadaProxima_j].P1_y;
puntosObstaculo[1].x=obstaculo[PisadaProxima_i][PisadaProxima_j].P2_x;
puntosObstaculo[1].y=obstaculo[PisadaProxima_i][PisadaProxima_j].P2_y;
puntosObstaculo[2].x=obstaculo[PisadaProxima_i][PisadaProxima_j].P3_x;
puntosObstaculo[2].y=obstaculo[PisadaProxima_i][PisadaProxima_j].P3_y;
puntosObstaculo[3].x=obstaculo[PisadaProxima_i][PisadaProxima_j].P4_x;
puntosObstaculo[3].y=obstaculo[PisadaProxima_i][PisadaProxima_j].P4_y;
ROS_WARN("Puntos: Pata:%.3f,%.3f; Recta:%.3f,%.3f;%.3f,%.3f",Pata.x,Pata.y,puntosObstaculo[2].x,puntosObstaculo[2].y,puntosObstaculo[3].x,puntosObstaculo[3].y);
recta_inf_o = recta3d(puntosObstaculo[3],puntosObstaculo[2]);
correccion = recta_inf_o.distancia(Pata);
ROS_WARN("correccion:%.3f",correccion);
modificacion_lambda[k] = lambda_maximo-correccion-delta_correccion;
} else {
// ROS_INFO("TripodeOK");
//-- Todo salio bien! Esta proxima_pisada es valida! :D
modificacion_lambda[k] = lambda_maximo;
// //-- Pisada maxima
infoMapa.coordenadaAjuste_i[Tripode_Transferencia[k]] = PisadaProxima_i;
infoMapa.coordenadaAjuste_j[Tripode_Transferencia[k]] = PisadaProxima_j;
}
} else {
ROS_WARN("server_PlanificadorPisada: pata [%d] error cinversa",k+1);
fprintf(fp2,"pata [%d] error cinversa\n",Tripode_Transferencia[k]+1);
}
} // Fin de revision de pisadas
infoMapa.correccion=false;
//---> Aqui va codigo para arreglar pisadas invalidas
//-- Si hay alguna pisada invalida detengo la planificacion
// for(int k=0;k<Npatas/2;k++) {
// if(PisadaInvalida[k]){
// ROS_ERROR("server_PlanificadorPisada: No se pudo corregir pisada pata[%d]",Tripode_Transferencia[k]+1);
//// fprintf(fp2,"tiempo de simulacion: %.3f\n",simulationTime);
// fprintf(fp2,"No se pudo corregir pisada pata[%d]\n",Tripode_Transferencia[k]+1);
// senales.Stop=true;
// chatter_pub1.publish(senales);
//// fclose(fp2);
//// ROS_INFO("Adios_server_PlanificadorPisada!");
//// ros::shutdown();
//// res.result = -1;
//// return -1;
// }
// }
//-- Escojo el largo de pisada mas corto y lo impongo a todas las patas del tripode
std::sort (modificacion_lambda, modificacion_lambda+3);
if(modificacion_lambda[0]<lambda_minimo){
res.modificacion_lambda = lambda_minimo;
} else {
res.modificacion_lambda = modificacion_lambda[0];
}
//-- Envio trayectoria planificada D: chanchanchaaaaaan
fprintf(fp2,"server_PlanificadorPisada: Tripode=%d, lambda_correccion=%.3f, T_correccion=%.3f\n",req.Tripode,res.modificacion_lambda,res.modificacion_T);
for(int k=0;k<Npatas;k++){
infoMapa.coordenadaPata_x[k] = posicionActualPata_x[k];
infoMapa.coordenadaPata_y[k] = posicionActualPata_y[k];
transformacion_yxTOij(p_ij, posicionActualPata_y[k], posicionActualPata_x[k]);
infoMapa.coordenadaPata_i[k] = ij[0];
infoMapa.coordenadaPata_j[k] = ij[1];
if(errorPata[k][0]!=ij[0] && errorPata[k][1]!=ij[1]){
if(matrizMapa[infoMapa.coordenadaPata_i[k]][infoMapa.coordenadaPata_j[k]]){
// fprintf(fp2,"---ERROR--- pata[%d] Coincide con obstaculo[%d][%d]\n",k+1,ij[0],ij[1]);
errorPata[k][0]=ij[0];
errorPata[k][1]=ij[1];
ROS_WARN("---ERROR--- pata[%d] Coincide con obstaculo[%d][%d]",k+1,ij[0],ij[1]);
cuentaErrores[k]++;
}
} else {
infoMapa.coordenadaPata_i[k] = nCeldas_i-1;
infoMapa.coordenadaPata_j[k] = nCeldas_j-1;
}
}
chatter_pub2.publish(infoMapa);
return 1;
}
int main(int argc, char **argv)
{
int Narg=0, cuentaObs=0;
std::string fileName,M_fileName,O_fileName;
Narg=20;
if (argc>=Narg)
{
beta = atof(argv[1]);
velocidadApoyo = atof(argv[2]);
alfa = atof(argv[3])*pi/180.0;
fileName = argv[4];
nCeldas_i = atoi(argv[5]);
nCeldas_j = atoi(argv[6]);
LongitudCeldaY = atof(argv[7]);
LongitudCeldaX = atof(argv[8]);
for(int k=0;k<Npatas;k++) phi[k] = atof(argv[9+k])*pi/180.0;
for(int k=0;k<Npatas;k++) tripode[k] = atoi(argv[9+Npatas+k]);
} else{
ROS_ERROR("server_PlanificadorPisada: Indique argumentos completos!\n");
return (0);
}
/*Inicio nodo de ROS*/
ros::init(argc, argv, "server_PlanificadorPisada");
ros::NodeHandle node;
ROS_INFO("server_PlanificadorPisada just started\n");
//-- Topicos susbcritos y publicados
chatter_pub1=node.advertise<camina8::SenalesCambios>("Senal", 100);
chatter_pub2=node.advertise<camina8::InfoMapa>("Plan", 100);
ros::Subscriber sub1=node.subscribe("/vrep/info",100,infoCallback);
ros::Subscriber sub2=node.subscribe("UbicacionRobot",100,ubicacionRobCallback);
//-- Clientes y Servicios
ros::ServiceServer service = node.advertiseService("PlanificadorPisada", PlanificadorPisada);
client_Cinversa1=node.serviceClient<camina8::CinversaParametros>("Cinversa");
/* Log de planificador */
fp1 = fopen("../fuerte_workspace/sandbox/TesisMaureen/ROS/camina8/datos/RegistroCorridas.txt","a+");
fp2 = fopen("../fuerte_workspace/sandbox/TesisMaureen/ROS/camina8/datos/LogPlanificador.txt","w+");
for(int k=0;k<Npatas;k++) {
infoMapa.coordenadaPata_x.push_back(0);
infoMapa.coordenadaPata_y.push_back(0);
infoMapa.coordenadaPata_i.push_back(0);
infoMapa.coordenadaPata_j.push_back(0);
infoMapa.coordenadaAjuste_i.push_back(0);
infoMapa.coordenadaAjuste_j.push_back(0);
}
//-- Patas de [0-5]
int cuenta_T1=0, cuenta_T2=0;
for(int k=0;k<Npatas;k++) {
if(tripode[k]==1){
Tripode1[cuenta_T1]=k;
cuenta_T1++;
} else {
Tripode2[cuenta_T2]=k;
cuenta_T2++;
}
}
ROS_INFO("server_PlanificadorPisada: Tripode1[%d,%d,%d] - Tripode2[%d,%d,%d]",Tripode1[0]+1,Tripode1[1]+1,Tripode1[2]+1,Tripode2[0]+1,Tripode2[1]+1,Tripode2[2]+1);
for(int i=0;i<Npatas;i++){
for(int j=0;j<2;j++){
errorPata[i][j]=0;
}
}
for(int i=0;i<100;i++){
for(int j=0;j<20;j++){
obstaculo[i][j].P1_x=-100;
obstaculo[i][j].P1_y=-100;
obstaculo[i][j].P2_x=-100;
obstaculo[i][j].P2_y=-100;
obstaculo[i][j].P3_x=-100;
obstaculo[i][j].P3_y=-100;
obstaculo[i][j].P4_x=-100;
obstaculo[i][j].P4_y=-100;
}
}
Limpiar_matrizMapa();
M_fileName = O_fileName = fileName;
std::string txt(".txt");
std::string obs("_o");
M_fileName+=txt;
cuentaObs = Construye_matrizMapa(M_fileName);
O_fileName+=obs;
O_fileName+=txt;
Info_Obstaculos(O_fileName,cuentaObs);
// print_matrizMapa(nCeldas_i,nCeldas_j);
// ROS_INFO("Nobstaculos=%d",cuentaObs);
// ROS_INFO("variables de mapa: Ni=%d,Nj=%d,LY=%.3f,LX=%.3f",nCeldas_i,nCeldas_j,LongitudCeldaY,LongitudCeldaX);
while (ros::ok() && simulationRunning){
ros::spinOnce();
}
fprintf(fp1,"%d\t%d\t",cuentaObs,cuentaPasos);
for(int k=0;k<Npatas;k++) fprintf(fp1,"%d\t",cuentaErrores[k]);
fprintf(fp1,"\n");
fclose(fp1);
fclose(fp2);
ROS_INFO("Adios_server_PlanificadorPisada!");
ros::shutdown();
return 0;
}
/*En matriz de mapa las coordenadas van de i=[0,99], j=[0,19] */
void transformacion_yxTOij(int *ptr_ij, float y, float x){
ptr_ij[0] = (int) (nCeldas_i/2 - floor(y/LongitudCeldaY)-1);
ptr_ij[1] = (int) (nCeldas_j/2 + floor(x/LongitudCeldaX));
}
void Limpiar_matrizMapa(){
int i=0, j=0;
for(i=0;i<nCeldas_i;i++){
for(j=0;j<nCeldas_j;j++){
matrizMapa[i][j]=false;
}
}
}
int Construye_matrizMapa(std::string fileName){
//--- Construccion de mapa mediante lectura de archivo
// printf ("%s \n", fileName.c_str());
FILE *fp;
int int_aux=0, i=0, j=0, cuentaObs=0, aux=0;
fp = fopen(fileName.c_str(), "r");
if(fp!=NULL){
printf("\n");
for(i=0;i<nCeldas_i;i++){
for(j=0;j<nCeldas_j;j++){
aux=fscanf(fp, "%d", &int_aux);
if (int_aux==0) matrizMapa[i][j]=false;
if (int_aux==1) {
matrizMapa[i][j]=true;
cuentaObs++;
// ROS_INFO("obstaculo_i: %d",i);
}
}
}
// printf("Mapa inicial\n");
// print_matrizMapa(nCeldas_i,nCeldas_j);
}
fclose(fp);
return (cuentaObs);
}
void print_matrizMapa(){
printf("\n");
for(int i=0;i<nCeldas_i;i++){
for(int j=0;j<nCeldas_j;j++){
if (matrizMapa[i][j]){
printf ("o.");
} else {
printf("-.");
}
}
printf("\n");
}
}
void Info_Obstaculos(std::string fileName, int N_Obstaculos){
//--- Construccion de mapa mediante lectura de archivo
// printf ("%s \n", fileName.c_str());
FILE *fp;
int int_aux=0, i=0, j=0, aux=0;
float f_aux=0.0;
fp = fopen(fileName.c_str(), "r");
if(fp!=NULL){
for(int k=0;k<N_Obstaculos;k++){
aux=fscanf(fp, "%d", &int_aux);
i=int_aux;
aux=fscanf(fp, "%d", &int_aux);
j=int_aux;
aux=fscanf(fp, "%f", &f_aux);
obstaculo[i][j].O_x=f_aux;
aux=fscanf(fp, "%f", &f_aux);
obstaculo[i][j].O_y=f_aux;
aux=fscanf(fp, "%f", &f_aux);
obstaculo[i][j].P1_x=f_aux;
aux=fscanf(fp, "%f", &f_aux);
obstaculo[i][j].P1_y=f_aux;
aux=fscanf(fp, "%f", &f_aux);
obstaculo[i][j].P2_x=f_aux;
aux=fscanf(fp, "%f", &f_aux);
obstaculo[i][j].P2_y=f_aux;
aux=fscanf(fp, "%f", &f_aux);
obstaculo[i][j].P3_x=f_aux;
aux=fscanf(fp, "%f", &f_aux);
obstaculo[i][j].P3_y=f_aux;
aux=fscanf(fp, "%f", &f_aux);
obstaculo[i][j].P4_x=f_aux;
aux=fscanf(fp, "%f", &f_aux);
obstaculo[i][j].P4_y=f_aux;
}
} else{
ROS_ERROR("Error al leer archivo %s",fileName.c_str());
}
fclose(fp);
}
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* ans = new ListNode(0);
ListNode* cur = ans;
int ret = 0;
while (l1 && l2)
{
int tmp = l1->val + l2->val + ret;
ListNode* p = new ListNode(tmp % 10);
ret = tmp / 10;
cur->next = p;
cur = p;
l1 = l1->next;
l2 = l2->next;
}
if (l1)
{
while (l1)
{
ListNode* p = new ListNode((l1->val + ret) % 10);
ret = (ret + l1->val) / 10;
l1 = l1->next;
cur->next = p;
cur = p;
}
}
if (l2)
{
while (l2)
{
ListNode* p = new ListNode((l2->val + ret) % 10);
ret = (ret + l2->val) / 10;
l2 = l2->next;
cur->next = p;
cur = p;
}
}
if (ret)
{
ListNode* p = new ListNode(ret);
cur->next = p;
cur = p;
}
ans = ans->next;
return ans;
}
};
|
#ifndef __DOG_H
#define __DOG_H
#include<string>
#include "animal.h"
class Dog:public Animal{
public:
Dog();
Dog(/*Dog_breed breed, */std::string name/*, Gender gender*/, int age);
~Dog();
void family();
void breed();
private:
// Dog_breed _breed;
};
#endif
|
const int ledPin = 13;
char inByte = 0;
char buffer[32];
int pos = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void contralLED(char *str) {
int num = atoi(str);
Serial.print("num ");
Serial.println(num);
//digitalWrite(ledPin,HIGH);
analogWrite(ledPin, num);
}
void loop() {
if (Serial.available() > 0) {
// read the incoming byte:
inByte = Serial.read();
if (inByte == '\r' || inByte == '\n')
{
buffer[pos] = '\0';
Serial.println(buffer);
pos = 0;
contralLED(buffer);
}
else
{
if (pos < 31)
buffer[pos++] = inByte;
else
buffer[pos] = '\0';
}
// say what you got:
}
delay(5);
// put your main code here, to run repeatedly:
}
|
#ifndef HELPERFUNCS_H
#define HELPERFUNCS_H
#include <string>
#include <vector>
#include <iostream>
#include <limits>
#include <cstdio>
#define PRINT_DEBUG_INFO 0
#define DEBUG_PRINT(...) \
do { if (PRINT_DEBUG_INFO) std::fprintf(stderr, __VA_ARGS__); } while (0)
/**
* @brief Pausa o programa ate o utilizador pressionar ENTER
*/
void pauseProgram();
/**
* @brief Limpa a consola
*/
void clearScreen();
/**
* @brief Verifica se um utilizador inseriu um 0(zero).
* @return True se o utilizador inseriu zero, false caso contrário
*/
bool checkForZero();
/**
* @brief Converte todos os carateres de uma string para maiúsculas.
* @return A string com todos os careteres em maiúsculas
*/
std::string stringToUpper(const std::string& str);
/**
* @brief Converte todos os carateres de uma string para maiúsculas.
* @param str String a converter em maiúsculas
*/
void stringToUpperInPlace(std::string& str);
/**
* @brief Converte todos os carateres de uma string para minúsculas.
* @return A string com todos os careteres em minúsculas
*/
std::string stringToLower(const std::string& str);
/**
* @brief Verifica se uma string tem um dado número mínimo de carateres alfabéticos.
* @param str String cujos carateres se querem verificar
* @param min_characters
* @return True se a string tem o número mínimo de carateres alfabéticos, false caso contrário
*/
bool hasMinAlphaChars(const std::string& str, unsigned int min_characters);
/**
* @brief Coloca todos as substrings de uma string seprados por um dado separador num vetor
* @param str String a fragmentar
* @param sep Separador que divide a string
* @return Vetor com as várias substrings
*/
std::vector<std::string> stringExplode(const std::string& str, const std::string& sep);
/**
* @brief Devolve um valor aleatório no intervalo [min, max]
* @param min Valor minimo
* @param max Valor maximo
* @return Numero aleatório
*/
int getRandomNumber(int min, int max);
/**
* @brief Converte uma string ASCII para OEM.
* @param str String a converter para OEM
* @return String em OEM
*/
std::string convertToOEM(const std::string& str);
/*
COLOR CODES: windows
1 blue
2 green
3 cyan
4 red
5 magenta
6 brown
7 lightgray
8 darkgray
9 lightblue
10 lightgreen
11 lightcyan
12 lightred
13 lightmagenta
14 yellow
15 white
*/
/*
Foreground colors linux
30 Black
31 Red
32 Green
33 Yellow
34 Blue
35 Magenta
36 Cyan
37 White
*/
enum ConsoleCharColor {
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
CC_COLOR_BLUE = 1,
CC_COLOR_GREEN = 2,
CC_COLOR_CYAN = 3,
CC_COLOR_RED = 4,
CC_COLOR_MAGENTA = 5,
CC_COLOR_YELLOW = 14,
CC_COLOR_WHITE = 15,
CC_COLOR_DEFAULT = 7
#else
CC_COLOR_RED = 31,
CC_COLOR_GREEN = 32,
CC_COLOR_YELLOW = 33,
CC_COLOR_BLUE = 34,
CC_COLOR_MAGENTA = 35,
CC_COLOR_CYAN = 36,
CC_COLOR_WHITE = 37,
CC_COLOR_DEFAULT = 37
#endif
};
/**
* @brief Muda a cor da letra da consola
* @param color Nova cor da letra da consola
*/
void setConsoleCharColor(ConsoleCharColor color);
/**
* @brief Pede um número ao utilizador num dado intervalo [min_value, max_value]
* @param message Mensagem a mostrar ao utilizador antes de este inserir o número
* @param error_message Mensagem a mostrar ao utilizador caso o número inserido não esteja no intervalo
* @param min_value Valor mínimo permitido
* @param max_value Valor máximo permitido
* @return O número inserido pelo utilizador
*/
template< class T >
T inputValidator(const std::string& message, const std::string& error_message,
T min_value = std::numeric_limits<T>::min(), T max_value = std::numeric_limits<T>::max())
{
bool valid_input = false;
T return_number;
do // repeat this cycle until the user entered a number between min_value and max_value;
{
std::cout << convertToOEM(message) << std::flush;
if (!(std::cin >> return_number) || return_number > max_value || return_number < min_value )
{
std::cout << convertToOEM(error_message) << std::endl;
std::cin.clear();
}
else
{
valid_input = true;
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
} while (!valid_input);
return return_number;
}
#endif //HELPERFUNCS_H
|
#pragma once
#include <string>
class Subject;
class Observer
{
public:
virtual ~Observer() = default;
virtual void on_notify(const Subject& subject) const = 0;
};
class CelsiusDisplay : public Observer
{
public:
void on_notify(const Subject& subject) const override;
};
class KelvinDisplay : public Observer
{
public:
void on_notify(const Subject& subject) const override;
};
class FahrenheitDisplay : public Observer
{
public:
void on_notify(const Subject& subject) const override;
};
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "../base.h"
#include "Windows.Foundation.0.h"
#include "Windows.Foundation.Collections.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Foundation {
struct __declspec(uuid("ed32a372-f3c8-4faa-9cfb-470148da3888")) __declspec(novtable) DeferralCompletedHandler : IUnknown
{
virtual HRESULT __stdcall abi_Invoke() = 0;
};
struct __declspec(uuid("30d5a829-7fa4-4026-83bb-d75bae4ea99e")) __declspec(novtable) IClosable : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_Close() = 0;
};
struct __declspec(uuid("d6269732-3b7f-46a7-b40b-4fdca2a2c693")) __declspec(novtable) IDeferral : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_Complete() = 0;
};
struct __declspec(uuid("65a1ecc5-3fb5-4832-8ca9-f061b281d13a")) __declspec(novtable) IDeferralFactory : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_Create(Windows::Foundation::DeferralCompletedHandler * handler, Windows::Foundation::IDeferral ** result) = 0;
};
struct __declspec(uuid("4edb8ee2-96dd-49a7-94f7-4607ddab8e3c")) __declspec(novtable) IGetActivationFactory : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_GetActivationFactory(hstring activatableClassId, Windows::Foundation::IInspectable ** factory) = 0;
};
struct __declspec(uuid("fbc4dd2a-245b-11e4-af98-689423260cf8")) __declspec(novtable) IMemoryBuffer : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_CreateReference(Windows::Foundation::IMemoryBufferReference ** reference) = 0;
};
struct __declspec(uuid("fbc4dd2b-245b-11e4-af98-689423260cf8")) __declspec(novtable) IMemoryBufferFactory : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_Create(uint32_t capacity, Windows::Foundation::IMemoryBuffer ** value) = 0;
};
struct __declspec(uuid("fbc4dd29-245b-11e4-af98-689423260cf8")) __declspec(novtable) IMemoryBufferReference : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_Capacity(uint32_t * value) = 0;
virtual HRESULT __stdcall add_Closed(Windows::Foundation::TypedEventHandler<Windows::Foundation::IMemoryBufferReference, Windows::Foundation::IInspectable> * handler, event_token * cookie) = 0;
virtual HRESULT __stdcall remove_Closed(event_token cookie) = 0;
};
struct __declspec(uuid("96369f54-8eb6-48f0-abce-c1b211e627c3")) __declspec(novtable) IStringable : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_ToString(hstring * value) = 0;
};
struct __declspec(uuid("c1d432ba-c824-4452-a7fd-512bc3bbe9a1")) __declspec(novtable) IUriEscapeStatics : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_UnescapeComponent(hstring toUnescape, hstring * value) = 0;
virtual HRESULT __stdcall abi_EscapeComponent(hstring toEscape, hstring * value) = 0;
};
struct __declspec(uuid("9e365e57-48b2-4160-956f-c7385120bbfc")) __declspec(novtable) IUriRuntimeClass : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_AbsoluteUri(hstring * value) = 0;
virtual HRESULT __stdcall get_DisplayUri(hstring * value) = 0;
virtual HRESULT __stdcall get_Domain(hstring * value) = 0;
virtual HRESULT __stdcall get_Extension(hstring * value) = 0;
virtual HRESULT __stdcall get_Fragment(hstring * value) = 0;
virtual HRESULT __stdcall get_Host(hstring * value) = 0;
virtual HRESULT __stdcall get_Password(hstring * value) = 0;
virtual HRESULT __stdcall get_Path(hstring * value) = 0;
virtual HRESULT __stdcall get_Query(hstring * value) = 0;
virtual HRESULT __stdcall get_QueryParsed(Windows::Foundation::IWwwFormUrlDecoderRuntimeClass ** ppWwwFormUrlDecoder) = 0;
virtual HRESULT __stdcall get_RawUri(hstring * value) = 0;
virtual HRESULT __stdcall get_SchemeName(hstring * value) = 0;
virtual HRESULT __stdcall get_UserName(hstring * value) = 0;
virtual HRESULT __stdcall get_Port(int32_t * value) = 0;
virtual HRESULT __stdcall get_Suspicious(bool * value) = 0;
virtual HRESULT __stdcall abi_Equals(Windows::Foundation::IUriRuntimeClass * pUri, bool * value) = 0;
virtual HRESULT __stdcall abi_CombineUri(hstring relativeUri, Windows::Foundation::IUriRuntimeClass ** instance) = 0;
};
struct __declspec(uuid("44a9796f-723e-4fdf-a218-033e75b0c084")) __declspec(novtable) IUriRuntimeClassFactory : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_CreateUri(hstring uri, Windows::Foundation::IUriRuntimeClass ** instance) = 0;
virtual HRESULT __stdcall abi_CreateWithRelativeUri(hstring baseUri, hstring relativeUri, Windows::Foundation::IUriRuntimeClass ** instance) = 0;
};
struct __declspec(uuid("758d9661-221c-480f-a339-50656673f46f")) __declspec(novtable) IUriRuntimeClassWithAbsoluteCanonicalUri : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_AbsoluteCanonicalUri(hstring * value) = 0;
virtual HRESULT __stdcall get_DisplayIri(hstring * value) = 0;
};
struct __declspec(uuid("125e7431-f678-4e8e-b670-20a9b06c512d")) __declspec(novtable) IWwwFormUrlDecoderEntry : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_Name(hstring * value) = 0;
virtual HRESULT __stdcall get_Value(hstring * value) = 0;
};
struct __declspec(uuid("d45a0451-f225-4542-9296-0e1df5d254df")) __declspec(novtable) IWwwFormUrlDecoderRuntimeClass : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_GetFirstValueByName(hstring name, hstring * phstrValue) = 0;
};
struct __declspec(uuid("5b8c6b3d-24ae-41b5-a1bf-f0c3d544845b")) __declspec(novtable) IWwwFormUrlDecoderRuntimeClassFactory : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_CreateWwwFormUrlDecoder(hstring query, Windows::Foundation::IWwwFormUrlDecoderRuntimeClass ** instance) = 0;
};
}
namespace ABI {
template <> struct traits<Windows::Foundation::Deferral> { using default_interface = Windows::Foundation::IDeferral; };
template <> struct traits<Windows::Foundation::MemoryBuffer> { using default_interface = Windows::Foundation::IMemoryBuffer; };
template <> struct traits<Windows::Foundation::Uri> { using default_interface = Windows::Foundation::IUriRuntimeClass; };
template <> struct traits<Windows::Foundation::WwwFormUrlDecoder> { using default_interface = Windows::Foundation::IWwwFormUrlDecoderRuntimeClass; };
template <> struct traits<Windows::Foundation::WwwFormUrlDecoderEntry> { using default_interface = Windows::Foundation::IWwwFormUrlDecoderEntry; };
}
namespace Windows::Foundation {
template <typename D>
struct WINRT_EBO impl_IClosable
{
void Close() const;
};
template <typename D>
struct WINRT_EBO impl_IDeferral
{
void Complete() const;
};
template <typename D>
struct WINRT_EBO impl_IDeferralFactory
{
Windows::Foundation::Deferral Create(const Windows::Foundation::DeferralCompletedHandler & handler) const;
};
template <typename D>
struct WINRT_EBO impl_IGetActivationFactory
{
Windows::Foundation::IInspectable GetActivationFactory(hstring_view activatableClassId) const;
};
template <typename D>
struct WINRT_EBO impl_IMemoryBuffer
{
Windows::Foundation::IMemoryBufferReference CreateReference() const;
};
template <typename D>
struct WINRT_EBO impl_IMemoryBufferFactory
{
Windows::Foundation::MemoryBuffer Create(uint32_t capacity) const;
};
template <typename D>
struct WINRT_EBO impl_IMemoryBufferReference
{
uint32_t Capacity() const;
event_token Closed(const Windows::Foundation::TypedEventHandler<Windows::Foundation::IMemoryBufferReference, Windows::Foundation::IInspectable> & handler) const;
using Closed_revoker = event_revoker<IMemoryBufferReference>;
Closed_revoker Closed(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Foundation::IMemoryBufferReference, Windows::Foundation::IInspectable> & handler) const;
void Closed(event_token cookie) const;
};
template <typename D>
struct WINRT_EBO impl_IStringable
{
hstring ToString() const;
};
template <typename D>
struct WINRT_EBO impl_IUriEscapeStatics
{
hstring UnescapeComponent(hstring_view toUnescape) const;
hstring EscapeComponent(hstring_view toEscape) const;
};
template <typename D>
struct WINRT_EBO impl_IUriRuntimeClass
{
hstring AbsoluteUri() const;
hstring DisplayUri() const;
hstring Domain() const;
hstring Extension() const;
hstring Fragment() const;
hstring Host() const;
hstring Password() const;
hstring Path() const;
hstring Query() const;
Windows::Foundation::WwwFormUrlDecoder QueryParsed() const;
hstring RawUri() const;
hstring SchemeName() const;
hstring UserName() const;
int32_t Port() const;
bool Suspicious() const;
bool Equals(const Windows::Foundation::Uri & pUri) const;
Windows::Foundation::Uri CombineUri(hstring_view relativeUri) const;
};
template <typename D>
struct WINRT_EBO impl_IUriRuntimeClassFactory
{
Windows::Foundation::Uri CreateUri(hstring_view uri) const;
Windows::Foundation::Uri CreateWithRelativeUri(hstring_view baseUri, hstring_view relativeUri) const;
};
template <typename D>
struct WINRT_EBO impl_IUriRuntimeClassWithAbsoluteCanonicalUri
{
hstring AbsoluteCanonicalUri() const;
hstring DisplayIri() const;
};
template <typename D>
struct WINRT_EBO impl_IWwwFormUrlDecoderEntry
{
hstring Name() const;
hstring Value() const;
};
template <typename D>
struct WINRT_EBO impl_IWwwFormUrlDecoderRuntimeClass
{
hstring GetFirstValueByName(hstring_view name) const;
};
template <typename D>
struct WINRT_EBO impl_IWwwFormUrlDecoderRuntimeClassFactory
{
Windows::Foundation::WwwFormUrlDecoder CreateWwwFormUrlDecoder(hstring_view query) const;
};
}
namespace impl {
template <> struct traits<Windows::Foundation::DeferralCompletedHandler>
{
using abi = ABI::Windows::Foundation::DeferralCompletedHandler;
};
template <> struct traits<Windows::Foundation::IClosable>
{
using abi = ABI::Windows::Foundation::IClosable;
template <typename D> using consume = Windows::Foundation::impl_IClosable<D>;
};
template <> struct traits<Windows::Foundation::IDeferral>
{
using abi = ABI::Windows::Foundation::IDeferral;
template <typename D> using consume = Windows::Foundation::impl_IDeferral<D>;
};
template <> struct traits<Windows::Foundation::IDeferralFactory>
{
using abi = ABI::Windows::Foundation::IDeferralFactory;
template <typename D> using consume = Windows::Foundation::impl_IDeferralFactory<D>;
};
template <> struct traits<Windows::Foundation::IGetActivationFactory>
{
using abi = ABI::Windows::Foundation::IGetActivationFactory;
template <typename D> using consume = Windows::Foundation::impl_IGetActivationFactory<D>;
};
template <> struct traits<Windows::Foundation::IMemoryBuffer>
{
using abi = ABI::Windows::Foundation::IMemoryBuffer;
template <typename D> using consume = Windows::Foundation::impl_IMemoryBuffer<D>;
};
template <> struct traits<Windows::Foundation::IMemoryBufferFactory>
{
using abi = ABI::Windows::Foundation::IMemoryBufferFactory;
template <typename D> using consume = Windows::Foundation::impl_IMemoryBufferFactory<D>;
};
template <> struct traits<Windows::Foundation::IMemoryBufferReference>
{
using abi = ABI::Windows::Foundation::IMemoryBufferReference;
template <typename D> using consume = Windows::Foundation::impl_IMemoryBufferReference<D>;
};
template <> struct traits<Windows::Foundation::IStringable>
{
using abi = ABI::Windows::Foundation::IStringable;
template <typename D> using consume = Windows::Foundation::impl_IStringable<D>;
};
template <> struct traits<Windows::Foundation::IUriEscapeStatics>
{
using abi = ABI::Windows::Foundation::IUriEscapeStatics;
template <typename D> using consume = Windows::Foundation::impl_IUriEscapeStatics<D>;
};
template <> struct traits<Windows::Foundation::IUriRuntimeClass>
{
using abi = ABI::Windows::Foundation::IUriRuntimeClass;
template <typename D> using consume = Windows::Foundation::impl_IUriRuntimeClass<D>;
};
template <> struct traits<Windows::Foundation::IUriRuntimeClassFactory>
{
using abi = ABI::Windows::Foundation::IUriRuntimeClassFactory;
template <typename D> using consume = Windows::Foundation::impl_IUriRuntimeClassFactory<D>;
};
template <> struct traits<Windows::Foundation::IUriRuntimeClassWithAbsoluteCanonicalUri>
{
using abi = ABI::Windows::Foundation::IUriRuntimeClassWithAbsoluteCanonicalUri;
template <typename D> using consume = Windows::Foundation::impl_IUriRuntimeClassWithAbsoluteCanonicalUri<D>;
};
template <> struct traits<Windows::Foundation::IWwwFormUrlDecoderEntry>
{
using abi = ABI::Windows::Foundation::IWwwFormUrlDecoderEntry;
template <typename D> using consume = Windows::Foundation::impl_IWwwFormUrlDecoderEntry<D>;
};
template <> struct traits<Windows::Foundation::IWwwFormUrlDecoderRuntimeClass>
{
using abi = ABI::Windows::Foundation::IWwwFormUrlDecoderRuntimeClass;
template <typename D> using consume = Windows::Foundation::impl_IWwwFormUrlDecoderRuntimeClass<D>;
};
template <> struct traits<Windows::Foundation::IWwwFormUrlDecoderRuntimeClassFactory>
{
using abi = ABI::Windows::Foundation::IWwwFormUrlDecoderRuntimeClassFactory;
template <typename D> using consume = Windows::Foundation::impl_IWwwFormUrlDecoderRuntimeClassFactory<D>;
};
template <> struct traits<Windows::Foundation::Deferral>
{
using abi = ABI::Windows::Foundation::Deferral;
static constexpr const wchar_t * name() noexcept { return L"Windows.Foundation.Deferral"; }
};
template <> struct traits<Windows::Foundation::MemoryBuffer>
{
using abi = ABI::Windows::Foundation::MemoryBuffer;
static constexpr const wchar_t * name() noexcept { return L"Windows.Foundation.MemoryBuffer"; }
};
template <> struct traits<Windows::Foundation::Uri>
{
using abi = ABI::Windows::Foundation::Uri;
static constexpr const wchar_t * name() noexcept { return L"Windows.Foundation.Uri"; }
};
template <> struct traits<Windows::Foundation::WwwFormUrlDecoder>
{
using abi = ABI::Windows::Foundation::WwwFormUrlDecoder;
static constexpr const wchar_t * name() noexcept { return L"Windows.Foundation.WwwFormUrlDecoder"; }
};
template <> struct traits<Windows::Foundation::WwwFormUrlDecoderEntry>
{
using abi = ABI::Windows::Foundation::WwwFormUrlDecoderEntry;
static constexpr const wchar_t * name() noexcept { return L"Windows.Foundation.WwwFormUrlDecoderEntry"; }
};
}
}
|
#include <iostream>
using namespace std;
int factorial(int n){
if (n <= 1)
return 1;
else
return n*factorial(n-1);
}
int main() {
cout << factorial(1000) << endl;
return 0;
}
|
/*
* Author : BurningTiles
* Problem : Swayamvar
* File : A.cpp
*/
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main(){
int n;
cin >> n;
string temp1,temp2;
cin >> temp1 >> temp2;
vector<char> bride(temp1.begin(),temp1.end()), groom(temp2.begin(),temp2.end());
vector<char>::iterator it;
for(int i=0; i<n; i++){
it = find(groom.begin(),groom.end(),bride[i]);
if( it != groom.end() )
groom.erase(it);
else
break;
}
cout << int(groom.size()) << endl;
return 0;
}
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
using namespace std;
using namespace __gnu_pbds;
double INF = 1e100;
double EPS = 1e-12;
typedef long long int ll;
typedef pair < int,int > PII;
typedef pair < ll,ll > PLL;
typedef tree<
int,
null_type,
less<int>,
rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define F first
#define S second
#define all(v) (v).begin(),(v).end()
ostream& operator<<(ostream & os, PLL h){
return os << "( " << h.F << ", " << h.S << " )" << endl;
}
PLL operator+ (PLL a, ll x) {return {a.F + x, a.S + x} ;}
PLL operator- (PLL a, ll x) {return {a.F - x, a.S - x} ;}
PLL operator* (PLL a, ll x) {return {a.F * x, a.S * x} ;}
PLL operator+(PLL x, PLL y) { return {x.F + y.F,x.S + y.S} ;}
PLL operator-(PLL x,PLL y) { return {x.F - y.F, x.S - y.S} ;}
PLL operator*(PLL x,PLL y) { return {x.F * y.F , x.S * y.S} ;}
PLL operator%(PLL x,PLL y) { return {x.F % y.F, x.S % y.S} ;}
ll const MOD = 1e9 + 7;
ll bigmod(ll a, ll b){
if(!b) return 1;
ll x = bigmod(a,b/2);
x = (x * x)%MOD;
if(b&1)
x = (x * a) %MOD;
return x;
}
vector < ll > primes;
vector < bool > marks;
void sieve(int n)
{
marks.resize(n+10,0);
marks[1] = 1;
for(int i = 2; i < n; i++){
if(!marks[i]){
for(int j = 2*i; j < n; j += i){
marks[j] = 1;
}
primes.push_back(i);
}
}
}
map < int, vector< int > > cnt;
int const N = 2e5 ;
void do_it(ll n){
for(auto p : primes){
if( p * p > n ) break;
if(n % p == 0){
int c = 0;
while(n % p == 0) n /= p, c++;
cnt[p].push_back(c);
}
}
if(n != 1) cnt[n].push_back(1);
}
int main(){
ios::sync_with_stdio(false); cin.tie(0);
sieve( N + 10);
int n;
cin >> n;
for(int i = 0; i < n; i++){
int tmp;
cin >> tmp;
do_it(tmp);
}
// for(auto &x : cn
// sort(all(x.second)greater< int >() );
// }
ll ans = 1;
for(auto x : cnt) {
vector< int > &v = x.second;
ll p = x.first;
if((int) v.size() < n - 1) continue;
sort(all(v));
int c = 0;
if(v.size() == n) c = v[1];
else c = v[0] ;
while(c) ans *= p, c--;
}
cout << ans << '\n';
return 0;
}
|
#include <graphene/chain/loyalty_evaluator.hpp>
#include <cmath>
namespace graphene { namespace chain {
void_result balance_lock_evaluator::do_evaluate(const balance_lock_operation& op)
{ try {
database& _db = db();
// insurs assets
FC_ASSERT(op.amount.asset_id == GRAPHENE_INSURS_ASSET, "lock asset must be INSURS");
FC_ASSERT(op.amount <= _db.get_balance(op.account, GRAPHENE_INSURS_ASSET), "account balance not enough");
FC_ASSERT(op.amount.amount >= GRAPHENE_BLOCKCHAIN_PRECISION, "lock amount must > 1");
//meme length must less than 63 characters
FC_ASSERT(op.memo.size() <= GRAPHENE_MAX_ACCOUNT_NAME_LENGTH, "memo too long");
const chain_parameters& chain_params = _db.get_global_properties().parameters;
vector< pair<string, interest_rate_t> > params;
for (auto& ext : chain_params.extensions) {
if (ext.which() == future_extensions::tag<lock_balance_params_t>::value) {
params = ext.get<lock_balance_params_t>().params;
break;
}
}
FC_ASSERT(!params.empty(), "no lock balance params");
auto iter_param = find_if(params.begin(), params.end(), [&](pair<string, interest_rate_t> p) {
return p.first == op.program_id;
});
FC_ASSERT(iter_param != params.end(), "program_id invalid");
FC_ASSERT(iter_param->second.is_valid, "program_id offline");
FC_ASSERT(iter_param->second.interest_rate == op.interest_rate, "input interest_rate invalid");
uint32_t lock_days = iter_param->second.lock_days;
FC_ASSERT(lock_days == op.lock_days, "input lock days invalid");
int32_t delta_seconds = op.create_date_time.sec_since_epoch() - _db.head_block_time().sec_since_epoch();
FC_ASSERT(std::fabs(delta_seconds) <= LOCKED_BALANCE_EXPIRED_TIME, "create_date_time invalid");
return void_result();
} FC_CAPTURE_AND_RETHROW( (op) ) }
object_id_type balance_lock_evaluator::do_apply(const balance_lock_operation& op, int32_t billed_cpu_time_us)
{ try {
database& _db = db();
const auto& new_object = _db.create<lock_balance_object>([&](lock_balance_object& obj){
obj.owner = op.account;
obj.create_date_time = op.create_date_time;
obj.lock_days = op.lock_days;
obj.program_id = op.program_id;
obj.amount = op.amount;
obj.interest_rate = op.interest_rate;
obj.memo = op.memo;
});
_db.adjust_balance(op.account, -op.amount);
return new_object.id;
} FC_CAPTURE_AND_RETHROW( (op) ) }
void_result balance_unlock_evaluator::do_evaluate(const balance_unlock_operation& op)
{ try {
database& _db = db();
FC_ASSERT(_db.find_object(op.lock_id) != nullptr, "lock_id not found, lock_id ${p}", ("p", op.lock_id));
lock_balance_obj = &op.lock_id(_db);
FC_ASSERT(lock_balance_obj->owner == op.account, "account not owner");
// T+1 mode
uint32_t past_days = (_db.head_block_time().sec_since_epoch() - lock_balance_obj->create_date_time.sec_since_epoch()) / SECONDS_PER_DAY;
FC_ASSERT(lock_balance_obj->lock_days <= past_days, "unlock timepoint has not arrived yet");
return void_result();
} FC_CAPTURE_AND_RETHROW( (op) ) }
void_result balance_unlock_evaluator::do_apply(const balance_unlock_operation& op, int32_t billed_cpu_time_us)
{ try {
database& _db = db();
if (nullptr != lock_balance_obj) {
_db.adjust_balance(op.account, lock_balance_obj->amount);
_db.remove(*lock_balance_obj);
}
return void_result();
} FC_CAPTURE_AND_RETHROW( (op) ) }
} } // namespace graphene::chain
|
#include "mainwin.h"
#include "entrydialog.h"
#include <string>
Mainwin::Mainwin() : Mainwin{*(new Store)} { }
Mainwin::Mainwin(Store& store) : _store{&store} {
// /////////////////
// G U I S E T U P
// /////////////////
set_default_size(640,480);
set_title("Some kind of Sweets shop");
// Set up a vertical box to hold the main window elements
Gtk::Box* vbox = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_VERTICAL,0));
add(*vbox);
// ///////
// M E N U
// Add and configure a menu bar as the top item in the vertical box
Gtk::MenuBar* menubar = Gtk::manage(new Gtk::MenuBar());
vbox->pack_start(*menubar, Gtk::PACK_SHRINK,0);
//FILE SUBMENU
Gtk::MenuItem* item_file = Gtk::manage(new Gtk::MenuItem("_File",true));
menubar->append(*item_file);
Gtk::Menu *file_menu = Gtk::manage(new Gtk::Menu());
item_file->set_submenu(*file_menu);
Gtk::MenuItem* item_new = Gtk::manage(new Gtk::MenuItem("_New Store", true));
item_new->signal_activate().connect([this]{this->on_new_store_click();});
file_menu->append(*item_new);
Gtk::MenuItem* item_quit = Gtk::manage(new Gtk::MenuItem("_Quit", true));
item_quit->signal_activate().connect([this]{this->on_quit_click();});
file_menu->append(*item_quit);
//SWEETS SUBMENU
Gtk::MenuItem* item_sweets = Gtk::manage(new Gtk::MenuItem("_Sweets",true));
menubar->append(*item_sweets);
Gtk::Menu *sweet_menu = Gtk::manage(new Gtk::Menu());
item_sweets->set_submenu(*sweet_menu);
Gtk::MenuItem* item_add_sweet = Gtk::manage(new Gtk::MenuItem("_Add Sweet", true));
item_add_sweet->signal_activate().connect([this]{this->on_add_sweet_click();});
sweet_menu->append(*item_add_sweet);
Gtk::MenuItem* item_list_sweets = Gtk::manage(new Gtk::MenuItem("_List Sweets", true));
item_list_sweets->signal_activate().connect([this]{this->on_list_sweets_click();});
sweet_menu->append(*item_list_sweets);
//ADD ORDER SUBMENU
Gtk::MenuItem* item_orders = Gtk::manage(new Gtk::MenuItem("_Orders",true));
menubar->append(*item_orders);
Gtk::Menu *orders_menu = Gtk::manage(new Gtk::Menu());
item_orders->set_submenu(*orders_menu);
Gtk::MenuItem* item_add_order = Gtk::manage(new Gtk::MenuItem("_Add Order", true));
item_add_order->signal_activate().connect([this]{this->on_place_order_click();});
orders_menu->append(*item_add_order);
Gtk::MenuItem* item_list_orders = Gtk::manage(new Gtk::MenuItem("_List Orders", true));
item_list_orders->signal_activate().connect([this]{this->on_list_orders_click();});
orders_menu->append(*item_list_orders);
//HELP SUBMENU
Gtk::MenuItem* item_help = Gtk::manage(new Gtk::MenuItem("_Help",true));
menubar->append(*item_help);
Gtk::Menu *help_menu = Gtk::manage(new Gtk::Menu());
item_help->set_submenu(*help_menu);
Gtk::MenuItem* item_about = Gtk::manage(new Gtk::MenuItem("_About", true));
item_about->signal_activate().connect([this]{this->on_about_click();});
help_menu->append(*item_about);
// /////////////
// T O O L B A R
// Add a toolbar to the vertical box just below the menu (bonus level)
Gtk::Toolbar *toolbar = Gtk::manage(new Gtk::Toolbar);
vbox->add(*toolbar);
//NEW STORE BUTTON
Gtk::ToolButton *new_button = Gtk::manage(new Gtk::ToolButton(Gtk::Stock::NEW));
new_button->set_tooltip_markup("add new store");
new_button->signal_clicked().connect([this]{this->on_new_store_click();});
toolbar->append(*new_button);
//QUIT BUTTON
Gtk::ToolButton *quit_button = Gtk::manage(new Gtk::ToolButton(Gtk::Stock::QUIT));
quit_button->set_tooltip_markup("quit");
quit_button->signal_clicked().connect([this]{this->on_quit_click();});
toolbar->append(*quit_button);
//ADD SWEET BUTTON
Gtk::ToolButton *new_sweet_button = Gtk::manage(new Gtk::ToolButton(Gtk::Stock::NEW));
new_sweet_button->set_tooltip_markup("add extra sweetness");
new_sweet_button->signal_clicked().connect([this]{this->on_add_sweet_click();});
toolbar->append(*new_sweet_button);
//LIST SWEETS BUTTON
Gtk::ToolButton *list_button = Gtk::manage(new Gtk::ToolButton(Gtk::Stock::QUIT));
list_button->set_tooltip_markup("list sweets");
list_button->signal_clicked().connect([this]{this->on_list_sweets_click();});
toolbar->append(*list_button);
//PLACE ORDER BUTTON
Gtk::ToolButton *place_order_button = Gtk::manage(new Gtk::ToolButton(Gtk::Stock::NEW));
place_order_button->set_tooltip_markup("place an order");
place_order_button->signal_clicked().connect([this]{this->on_place_order_click();});
toolbar->append(*place_order_button);
//LIST ORDERS BUTTON
Gtk::ToolButton *list_orders_button = Gtk::manage(new Gtk::ToolButton(Gtk::Stock::QUIT));
list_orders_button->set_tooltip_markup("list orders");
list_orders_button->signal_clicked().connect([this]{this->on_list_orders_click();});
toolbar->append(*list_orders_button);
// ///////////////////////
// D A T A D I S P L A Y
// Provide a text entry box to show the sweets and orders
// Gtk::Label* data = Gtk::manage(new Gtk::Label("JUST A LABEL"));
// vbox->add(*data);
data = Gtk::manage(new Gtk::Label());
data->set_hexpand(true);
data->set_vexpand(true);
vbox->add(*data);
// ///////////////////////////////////
// S T A T U S B A R D I S P L A Y
// Provide a status bar for transient messages
Gtk::Label* status = Gtk::manage(new Gtk::Label("status bar"));
Gtk::Label* status2 = Gtk::manage(new Gtk::Label("-------------------------------"));
status->set_hexpand(true);
status2->set_hexpand(true);
vbox->add(*status2);
vbox->add(*status);
// Make the vertical box and everything in it visible
vbox->show_all();
}
Mainwin::~Mainwin() { }
// /////////////////
// C A L L B A C K S
// /////////////////
void Mainwin::on_new_store_click(){
free(_store);
_store = new Store();
#ifdef __SENSITIVITY1
reset_sensitivity();
#endif
data->set_text("");
#ifdef __STATUSBAR
msg->set_text("New Mav's Ultimate Sweet Shop created");
#endif
Gtk::MessageDialog dialog(*this,"added new store");
dialog.run();
}
/*
void Mainwin::on_add_sweet_click(){
EntryDialog name{*this, "name of sweet: "};
name.run();
EntryDialog price{*this, "price of sweet: "};
price.run();
}
*/
//ADDING SWEET
void Mainwin::on_add_sweet_click() {
std::string name = "";
double price = -1;
#ifndef __SWEETSADDDLG
EntryDialog dialog{*this, "Name of new sweet?"};
dialog.run();
name = dialog.get_text();
if(name.size() == 0) {
#ifdef __STATUSBAR
msg->set_text("New sweet cancelled");
#endif
return;
}
std::string prompt = "Price?";
while (price < 0) {
EntryDialog dialog{*this, prompt};
dialog.run();
try {
price = std::stod(dialog.get_text());
} catch(std::exception e) {
prompt = "Invalid Price! Price?";
price = -1;
}
}
#else
Gtk::Dialog *dialog = new Gtk::Dialog{"Create a Sweet", *this};
// Name
Gtk::HBox b_name;
Gtk::Label l_name{"Name:"};
l_name.set_width_chars(15);
b_name.pack_start(l_name, Gtk::PACK_SHRINK);
Gtk::Entry e_name;
e_name.set_max_length(50);
b_name.pack_start(e_name, Gtk::PACK_SHRINK);
dialog->get_vbox()->pack_start(b_name, Gtk::PACK_SHRINK);
// Price
Gtk::HBox b_price;
Gtk::Label l_price{"Price:"};
l_price.set_width_chars(15);
b_price.pack_start(l_price, Gtk::PACK_SHRINK);
Gtk::Entry e_price;
e_price.set_max_length(50);
b_price.pack_start(e_price, Gtk::PACK_SHRINK);
dialog->get_vbox()->pack_start(b_price, Gtk::PACK_SHRINK);
// Show dialog
dialog->add_button("Cancel", 0);
dialog->add_button("Create", 1);
dialog->show_all();
int result; // of the dialog (1 = OK)
bool fail = true; // set to true if any data is invalid
while (fail) {
fail = false; // optimist!
result = dialog->run();
if (result != 1) {
#ifdef __STATUSBAR
msg->set_text("New sweet cancelled");
#endif
delete dialog;
return;}
try {
price = std::stod(e_price.get_text());
} catch(std::exception e) {
e_price.set_text("### Invalid ###");
fail = true;
}
name = e_name.get_text();
if (name.size() == 0) {
e_name.set_text("### Invalid ###");
fail = true;
}
}
delete dialog;
#endif
Sweet sweet{name, price};
_store->add(sweet);
on_list_sweets_click();
#ifdef __STATUSBAR
msg->set_text("Added " + sweet.name());
#endif
#ifdef __SENSITIVITY1
reset_sensitivity();
#endif
}
//LISTING SWEETS
void Mainwin::on_list_sweets_click(){
// Gtk::MessageDialog dialog(*this,"listing sweets");
// dialog.run();
if (_store->num_sweets() == 0) {
data->set_markup("<span size='large' weight='bold'>No sweets have been defined yet</span>");
#ifdef __STATUSBAR
msg->set_text("");
#endif
return;
}
// The string manipulation way
std::string s = "<span size='large' weight='bold'>";
for(int i=0; i<_store->num_sweets(); ++i)
s += std::to_string(i)+". "+_store->sweet(i).name() + ": $" + std::to_string(_store->sweet(i).price()) + "\n";
s += "</span>";
data->set_markup(s);
#ifdef __STATUSBAR
msg->set_text("");
#endif
}
//PLACING ORDERS
void Mainwin::on_place_order_click(){
// Gtk::MessageDialog dialog(*this,"place order");
// dialog.run();
bool exit=false;
Order *order = new Order();
#ifndef __SWEETSORDERDLG
while(!exit){
int item_number =-2;
int quantity = -1;
std::string prompt2 = "Items? (-1 to stop)";
while (item_number < -1) {
EntryDialog dialog{*this, prompt2};
dialog.run();
try {
item_number = std::stoi(dialog.get_text());
if(_store->num_sweets()<=item_number){
Gtk::MessageDialog dialog2{*this, "Invalid item"};
dialog2.run();
}
} catch(std::exception e) {
prompt2 = "Invalid item, item?";
item_number = -1;
}
}
if(item_number <= -1) {
#ifdef __STATUSBAR
msg->set_text("New order cancelled");
#endif
return;
}
if(!(_store->num_sweets()<=item_number))
if(item_number!=-1 &&exit!=true){
std::string prompt = "Quantity?";
while (quantity < 0) {
EntryDialog dialog{*this, prompt};
dialog.run();
try {
quantity = std::stoi(dialog.get_text());
} catch(std::exception e) {
prompt = "Invalid Quantity, Quantity?";
quantity = -1;
}
}
}
/* #else
Gtk::Dialog *dialog = new Gtk::Dialog{"Added to order", *this};
// ITEM NUMBER
Gtk::HBox b_items;
Gtk::Label l_item_number{"Item:"};
l_item_number.set_width_chars(15);
b_items.pack_start(l_item_number, Gtk::PACK_SHRINK);
Gtk::Entry e_item_number;
e_item_number.set_max_length(50);
b_items.pack_start(e_item_number, Gtk::PACK_SHRINK);
dialog->get_vbox()->pack_start(b_items, Gtk::PACK_SHRINK);
// QUANTITY
Gtk::HBox b_quantity;
Gtk::Label l_quantity{"Quantity:"};
l_quantity.set_width_chars(15);
b_quantity.pack_start(l_quantity, Gtk::PACK_SHRINK);
Gtk::Entry e_quantity;
e_quantity.set_max_length(50);
b_quantity.pack_start(e_quantity, Gtk::PACK_SHRINK);
dialog->get_vbox()->pack_start(b_quantity, Gtk::PACK_SHRINK);
// Show dialog
dialog->add_button("Cancel", 0);
dialog->add_button("Create", 1);
dialog->show_all();
int result; // of the dialog (1 = OK)
bool fail = true; // set to true if any data is invalid
while (fail) {
fail = false; // optimist!
result = dialog->run();
if (result != 1) {
#ifdef __STATUSBAR
msg->set_text("New order cancelled");
#endif
delete dialog;
return;}
try {
quantity = std::stoi(e_quantity.get_text());
} catch(std::exception e) {
e_quantity.set_text("### Invalid ###");
fail = true;
}
name = e_item_number.get_text();
if (item_number.size() == 0) {
e_item_number.set_text("### Invalid ###");
fail = true;
}
}
delete dialog;
*/ #endif
// if(exit!=true)
// order.add(quantity,_store->sweet(item_number));
if(!(_store->num_sweets()<=item_number))
order->add(quantity, _store->sweet(item_number));
}
_store->add(*order);
free(order);
on_list_orders_click();
#ifdef __SENSITIVITY1
reset_sensitivity();
#endif
}
//LIST ORDERS
void Mainwin::on_list_orders_click(){
data->set_markup("<span size='large' weight='bold'>LISTING ORDERS code not yet finished (check mainwin.cpp)</span>");
//PSEUDO CODE FOR LISTING ORDER
//CHOOSE ORDER NUMBER saved into order_num;
//IF order_num > _store->num_order() return error message; ELSE continue to steps below
/*
int order_num;
if (_store->num_orders() == 0) {
data->set_markup("<span size='large' weight='bold'>No Orders have been defined yet</span>");
#ifdef __STATUSBAR
msg->set_text("");
#endif
return;
}
// The string manipulation way
std::string s = "<span size='large' weight='bold'>";
s += "\n Order #" + order_num + " ($" + _store.order(order).price() + ")\n" + _store.order(order) + "<\span>";
data->set_markup(s);
#ifdef __STATUSBAR
msg->set_text("");
#endif
*/ }
void Mainwin::on_about_click(){
Glib::ustring st = R"(<span size='24000' weight='bold'>Sweetness</span>
<span size='large'>Hoang Luu: 1000969998</span>
<span size='small'>Professor RICE: CSE1325 P05</span>
<span size='small'>icons are included in gtkmm libary</span>)";
Gtk::MessageDialog dialog(*this, st, true, Gtk::MESSAGE_INFO, Gtk::BUTTONS_OK, true);
dialog.run();
}
void Mainwin::on_quit_click(){
std::exit(0); }
void Mainwin::reset_sensitivity(){
menuitem_list_sweets->set_sensitive(_store->num_sweets() > 0);
#ifdef __TOOLBAR
list_sweets_button->set_sensitive(_store->num_sweets() > 0);
#endif
}
// /////////////////
// U T I L I T I E S
// /////////////////
|
int Solution::singleNumber(const vector<int> &a) {
int n=a.size();
int val=0;
for(int i=0;i<n;i++)
val^=a[i];
return val;
}
|
/**
* **** Code generated by the RIDL Compiler ****
* RIDL has been developed by:
* Remedy IT
* Westervoort, GLD
* The Netherlands
* http://www.remedy.nl
*/
#ifndef __RIDL_TESTC_H_HBDCIAAA_INCLUDED__
#define __RIDL_TESTC_H_HBDCIAAA_INCLUDED__
#pragma once
#include /**/ "ace/pre.h"
#include "tao/x11/stddef.h"
#include "tao/x11/basic_traits.h"
#include "tao/x11/corba.h"
#include "tao/x11/system_exception.h"
#include "tao/x11/orb.h"
#include "tao/x11/object.h"
#include "tao/x11/corba_ostream.h"
#include /**/ "tao/x11/versionx11.h"
#if TAOX11_MAJOR_VERSION != 1 || TAOX11_MINOR_VERSION != 7 || TAOX11_MICRO_VERSION != 1
#error This file was generated with another RIDL C++11 backend version (1.7.1). Please re-generate.
#endif
using namespace TAOX11_NAMESPACE;
// generated from StubHeaderWriter#enter_module
/// @copydoc test.idl::Test
namespace Test
{
// generated from StubHeaderWriter#enter_interface
// generated from c++11/templates/cli/hdr/interface_fwd.erb
#if !defined (_INTF_TEST_FOO_FWD_)
#define _INTF_TEST_FOO_FWD_
class Foo;
#endif // !_INTF_TEST_FOO_FWD_
// generated from Base::CodeWriter#at_global_scope
} // namespace Test
// entering Base::CodeWriter#at_global_scope
// generated from c++11/templates/cli/hdr/interface_object_traits.erb
#if !defined (_INTF_TEST_FOO_TRAITS_DECL_)
#define _INTF_TEST_FOO_TRAITS_DECL_
namespace TAOX11_NAMESPACE
{
namespace CORBA
{
template<>
object_traits< ::Test::Foo>::shared_ptr_type
object_traits< ::Test::Foo>::lock_shared (
::Test::Foo* p);
} // namespace CORBA
namespace IDL
{
template<>
struct traits < ::Test::Foo> :
public IDL::common_byval_traits <CORBA::object_reference < ::Test::Foo>>,
public CORBA::object_traits < ::Test::Foo>
{
/// std::false_type or std::true_type type indicating whether
/// this interface is declared as local
typedef std::true_type is_local;
/// std::false_type or std::true_type type indicating whether
/// this interface is declared as abstract
typedef std::false_type is_abstract;
/// Trait for the type from which a local implementation needs
/// to be derived from
typedef ::Test::Foo base_type;
template <typename OStrm_, typename Formatter = formatter< ::Test::Foo, OStrm_>>
static inline OStrm_& write_on(
OStrm_& os_, in_type val_,
Formatter fmt_ = Formatter ())
{
return fmt_ (os_, val_);
}
template <typename Formatter = std::false_type>
static inline __Writer<Formatter> write (in_type val) { return {val}; }
};
} // namespace IDL
} // namespace TAOX11_NAMESPACE
#endif // !_INTF_TEST_FOO_TRAITS_DECL_
// leaving Base::CodeWriter#at_global_scope
namespace Test
{
// generated from c++11/templates/cli/hdr/interface_pre.erb
/// @copydoc test.idl::Test::Foo
class Foo
: public virtual TAOX11_NAMESPACE::CORBA::LocalObject
{
public:
template <typename T> friend struct TAOX11_CORBA::object_traits;
/// @name Member types
//@{
typedef TAOX11_IDL::traits< Foo> _traits_type;
/// Strong reference type
typedef TAOX11_IDL::traits< Foo>::ref_type _ref_type;
//@}
/// Determine if we are of the type specified by the @a logical_type_id.
virtual bool _is_a (const std::string& local_type_id) override;
// generated from c++11/templates/cli/hdr/operation.erb
/// @copydoc test.idl::Test::Foo::do_something
virtual
void
do_something () = 0;
// generated from c++11/templates/cli/hdr/interface_post.erb
protected:
typedef std::shared_ptr<Foo> _shared_ptr_type;
#if defined (_MSC_VER) && (_MSC_VER < 1920)
/// Default constructor
Foo () {};
#else
/// Default constructor
Foo () = default;
#endif /* _MSC_VER < 1920 */
/// Destructor
~Foo () = default;
/// Returns a strong client reference for the local object you are calling
IDL::traits< ::Test::Foo>::ref_type _this ();
private:
/** @name Illegal to be called. Deleted explicitly to let the compiler detect any violation */
//@{
Foo (const Foo&) = delete;
Foo (Foo&&) = delete;
Foo& operator= (const Foo&) = delete;
Foo& operator= (Foo&&) = delete;
//@}
}; // class Foo
// generated from StubHeaderWriter#enter_interface
// generated from c++11/templates/cli/hdr/interface_fwd.erb
#if !defined (_INTF_TEST_BAR_FWD_)
#define _INTF_TEST_BAR_FWD_
class Bar;
#endif // !_INTF_TEST_BAR_FWD_
// generated from Base::CodeWriter#at_global_scope
} // namespace Test
// entering Base::CodeWriter#at_global_scope
// generated from c++11/templates/cli/hdr/interface_object_traits.erb
#if !defined (_INTF_TEST_BAR_TRAITS_DECL_)
#define _INTF_TEST_BAR_TRAITS_DECL_
namespace TAOX11_NAMESPACE
{
namespace CORBA
{
template<>
object_traits< ::Test::Bar>::shared_ptr_type
object_traits< ::Test::Bar>::lock_shared (
::Test::Bar* p);
} // namespace CORBA
namespace IDL
{
template<>
struct traits < ::Test::Bar> :
public IDL::common_byval_traits <CORBA::object_reference < ::Test::Bar>>,
public CORBA::object_traits < ::Test::Bar>
{
/// std::false_type or std::true_type type indicating whether
/// this interface is declared as local
typedef std::true_type is_local;
/// std::false_type or std::true_type type indicating whether
/// this interface is declared as abstract
typedef std::false_type is_abstract;
/// Trait for the type from which a local implementation needs
/// to be derived from
typedef ::Test::Bar base_type;
template <typename OStrm_, typename Formatter = formatter< ::Test::Bar, OStrm_>>
static inline OStrm_& write_on(
OStrm_& os_, in_type val_,
Formatter fmt_ = Formatter ())
{
return fmt_ (os_, val_);
}
template <typename Formatter = std::false_type>
static inline __Writer<Formatter> write (in_type val) { return {val}; }
};
} // namespace IDL
} // namespace TAOX11_NAMESPACE
#endif // !_INTF_TEST_BAR_TRAITS_DECL_
// leaving Base::CodeWriter#at_global_scope
namespace Test
{
// generated from c++11/templates/cli/hdr/interface_pre.erb
/// @copydoc test.idl::Test::Bar
class Bar
: public virtual TAOX11_NAMESPACE::CORBA::LocalObject
{
public:
template <typename T> friend struct TAOX11_CORBA::object_traits;
/// @name Member types
//@{
typedef TAOX11_IDL::traits< Bar> _traits_type;
/// Strong reference type
typedef TAOX11_IDL::traits< Bar>::ref_type _ref_type;
//@}
/// Determine if we are of the type specified by the @a logical_type_id.
virtual bool _is_a (const std::string& local_type_id) override;
// generated from c++11/templates/cli/hdr/operation.erb
/// @copydoc test.idl::Test::Bar::do_foo
virtual
void
do_foo (
IDL::traits< ::Test::Foo>::ref_type f) = 0;
// generated from c++11/templates/cli/hdr/interface_post.erb
protected:
typedef std::shared_ptr<Bar> _shared_ptr_type;
#if defined (_MSC_VER) && (_MSC_VER < 1920)
/// Default constructor
Bar () {};
#else
/// Default constructor
Bar () = default;
#endif /* _MSC_VER < 1920 */
/// Destructor
~Bar () = default;
/// Returns a strong client reference for the local object you are calling
IDL::traits< ::Test::Bar>::ref_type _this ();
private:
/** @name Illegal to be called. Deleted explicitly to let the compiler detect any violation */
//@{
Bar (const Bar&) = delete;
Bar (Bar&&) = delete;
Bar& operator= (const Bar&) = delete;
Bar& operator= (Bar&&) = delete;
//@}
}; // class Bar
} // namespace Test
// generated from StubHeaderIDLTraitsWriter#pre_visit
namespace TAOX11_NAMESPACE
{
namespace IDL
{
// generated from c++11/templates/cli/hdr/interface_idl_traits.erb
#if !defined (_INTF_FMT_TEST_FOO_TRAITS_DECL_)
#define _INTF_FMT_TEST_FOO_TRAITS_DECL_
template <typename OStrm_>
struct formatter< ::Test::Foo, OStrm_>
{
OStrm_& operator ()(
OStrm_& ,
IDL::traits< ::Test::Foo>::ref_type);
};
template <typename OStrm_, typename Fmt>
OStrm_& operator <<(
OStrm_&,
IDL::traits< ::Test::Foo>::__Writer<Fmt>);
#endif // !_INTF_FMT_TEST_FOO_TRAITS_DECL_
// generated from c++11/templates/cli/hdr/interface_idl_traits.erb
#if !defined (_INTF_FMT_TEST_BAR_TRAITS_DECL_)
#define _INTF_FMT_TEST_BAR_TRAITS_DECL_
template <typename OStrm_>
struct formatter< ::Test::Bar, OStrm_>
{
OStrm_& operator ()(
OStrm_& ,
IDL::traits< ::Test::Bar>::ref_type);
};
template <typename OStrm_, typename Fmt>
OStrm_& operator <<(
OStrm_&,
IDL::traits< ::Test::Bar>::__Writer<Fmt>);
#endif // !_INTF_FMT_TEST_BAR_TRAITS_DECL_
} // namespace IDL
} // namespace TAOX11_NAMESPACE
// generated from StubHeaderIDLTraitsDefWriter#pre_visit
namespace TAOX11_NAMESPACE
{
namespace IDL
{
// generated from c++11/templates/cli/hdr/interface_idl_traits_def.erb
template <typename OStrm_>
inline OStrm_&
formatter< ::Test::Foo, OStrm_>::operator ()(
OStrm_& os_,
IDL::traits< ::Test::Foo>::ref_type val_)
{
os_ << IDL::traits<TAOX11_CORBA::Object>::_dump (
std::move (val_),
"Test::Foo");
return os_;
}
template <typename OStrm_, typename Fmt>
inline OStrm_& operator <<(
OStrm_& os,
IDL::traits< ::Test::Foo>::__Writer<Fmt> w)
{
typedef IDL::traits< ::Test::Foo>::__Writer<Fmt> writer_t;
typedef typename std::conditional<
std::is_same<
typename writer_t::formatter_t,
std::false_type>::value,
formatter< ::Test::Foo, OStrm_>,
typename writer_t::formatter_t>::type formatter_t;
return IDL::traits< ::Test::Foo>::write_on (
os, w.val_,
formatter_t ());
}
// generated from c++11/templates/cli/hdr/interface_idl_traits_def.erb
template <typename OStrm_>
inline OStrm_&
formatter< ::Test::Bar, OStrm_>::operator ()(
OStrm_& os_,
IDL::traits< ::Test::Bar>::ref_type val_)
{
os_ << IDL::traits<TAOX11_CORBA::Object>::_dump (
std::move (val_),
"Test::Bar");
return os_;
}
template <typename OStrm_, typename Fmt>
inline OStrm_& operator <<(
OStrm_& os,
IDL::traits< ::Test::Bar>::__Writer<Fmt> w)
{
typedef IDL::traits< ::Test::Bar>::__Writer<Fmt> writer_t;
typedef typename std::conditional<
std::is_same<
typename writer_t::formatter_t,
std::false_type>::value,
formatter< ::Test::Bar, OStrm_>,
typename writer_t::formatter_t>::type formatter_t;
return IDL::traits< ::Test::Bar>::write_on (
os, w.val_,
formatter_t ());
}
} // namespace IDL
} // namespace TAOX11_NAMESPACE
// generated from c++11/templates/cli/hdr/interface_os.erb
inline std::ostream& operator<< (
std::ostream& strm,
IDL::traits< ::Test::Foo>::ref_type _v)
{
return IDL::traits< ::Test::Foo>::write_on (strm, std::move(_v));
}
// generated from c++11/templates/cli/hdr/interface_os.erb
inline std::ostream& operator<< (
std::ostream& strm,
IDL::traits< ::Test::Bar>::ref_type _v)
{
return IDL::traits< ::Test::Bar>::write_on (strm, std::move(_v));
}
// generated from c++11/templates/cli/hdr/post.erb
#if defined (__TAOX11_INCLUDE_STUB_PROXY__)
#include "testCP.h"
#endif
#include /**/ "ace/post.h"
#endif /* __RIDL_TESTC_H_HBDCIAAA_INCLUDED__ */
// -*- END -*-
|
#include "HeadList.h"
struct TMonom
{
double coeff;
int x, y, z;
};
bool operator<(const TMonom& p, const TMonom& g) {
bool k=false;
if (p.x==g.x) {
if (p.y==g.y) {
if (p.z==g.z) {
if (p.coeff<g.coeff)
k=true;
}
else if (p.z<g.z)
k=true;
}
else if (p.y<g.y)
k=true;
}
else if (p.x<g.x)
k=true;
return k;
}
bool operator>(const TMonom& p, const TMonom& g) {
bool k=false;
if (p.x==g.x) {
if (p.y==g.y) {
if (p.z==g.z) {
if (p.coeff>g.coeff)
k=true;
}
else if (p.z>g.z)
k=true;
}
else if (p.y>g.y)
k=true;
}
else if (p.x>g.x)
k=true;
return k;
}
/*
bool operator<(const TMonom& p, const TMonom& g) {
if (p.x<g.x) {
return true;
}
else
{
if (p.x>g.x) {
return false;
}
else
{
if (p.x==g.x)
{
if (p.y<g.y) {
return true;
}
else
{
if (p.y>g.y) {
return false;
}
else
{
if (p.y==g.y)
{
if (p.z<g.z) {
return true;
}
else
{
if (p.z>g.z) {
return false;
}
}
}
}
}
}
}
}
}
bool operator>(const TMonom& p, const TMonom& g) {
if (p.x>g.x) {
return true;
}
else
{
if (p.x<g.x) {
return false;
}
else
{
if (p.x==g.x)
{
if (p.y>g.y) {
return true;
}
else
{
if (p.y<g.y) {
return false;
}
else
{
if (p.y==g.y)
{
if (p.z>g.z) {
return true;
}
else
{
if (p.z<g.z) {
return false;
}
}
}
}
}
}
}
}
}
*/
bool operator==(const TMonom& p, const TMonom& g) {
bool k=false;
if (p.x==g.x && p.y==g.y && p.z==g.z)
k=true;
return k;
}
void operator+=(const TMonom& p, const TMonom& g) {
if (p==g)
(double)p.coeff += g.coeff;
else
throw -1;
}
TMonom operator*(const TMonom& p, const TMonom& g) {
TMonom tmp;
tmp.coeff=p.coeff*g.coeff;
tmp.x=p.x+g.x;
tmp.y=p.y+g.y;
tmp.z=p.z+g.z;
return tmp;
}
TMonom operator*(const TMonom& p, const int& c) {
TMonom tmp=p;
tmp.coeff*=c;
return tmp;
}
class TPolinom: public THList<TMonom> {
public:
TPolinom():THList() {
pHead->val.coeff=0;
pHead->val.x=-1;
}
TPolinom& operator*(const int& c) {
TPolinom tmp_p;
int tmp_poz=GetPoz();
for (Reset(); !IsEnd(); GoNext())
tmp_p.Push(pCurr->val*c);
if (pHead->val.coeff != 0)
tmp_p.pHead->val.coeff = pHead->val.coeff * c;
poz=tmp_poz;
return tmp_p;;
}
TPolinom& operator*(const TMonom& m) {
TPolinom tmp_p;
int tmp_poz=GetPoz();
for (Reset(); !IsEnd(); GoNext())
tmp_p.Push(pCurr->val * m);
if (pHead->val.coeff != 0) {
TMonom tmp;
tmp = m * pHead->val.coeff;
tmp_p.Push(tmp);
tmp_p.pHead->val.coeff = 0;
}
poz=tmp_poz;
return tmp_p;
}
void InsByOrder (const TMonom& m) {
for(Reset(); !IsEnd(); GoNext()) {
if (pCurr->val == m) {
pCurr->val.coeff += m.coeff;
if (pCurr->val.coeff == 0)
DelCurr();
return;
}
if (pCurr->val < m) {
InsCurr(m);
return;
}
}
InsLast(m);
}
void operator+=(TPolinom Q) {
Reset();
Q.Reset();
while (!IsEnd() || !Q.IsEnd()) {
if(pCurr->val == Q.pCurr->val) {
pCurr->val.coeff += Q.pCurr->val.coeff;
if (pCurr->val.coeff == 0) {
DelCurr();
Q.GoNext();
}
else if (pCurr->val.coeff != 0) {
Q.GoNext(); GoNext();
}
Q.GoNext();
}
else if (pCurr->val < Q.pCurr->val) {
InsCurr(Q.pCurr->val);
Q.GoNext();
}
else // P>Q
GoNext();
}
}
void GetCurr() {
if (this->pCurr->val.coeff>0)
std::cout << "+" <<this->pCurr->val.coeff << " x^" << this->pCurr->val.x <<
" y^" << this->pCurr->val.y << " z^" << this->pCurr->val.z;
else
std::cout <<this->pCurr->val.coeff << " x^" << this->pCurr->val.x <<
" y^" << this->pCurr->val.y << " z^" << this->pCurr->val.z;
}
double GetHeadCof() {
return pHead->val.coeff;
}
friend ostream& operator<<(ostream &out, TPolinom &p)
{
int tmp_pos = p.GetPoz();
for (p.Reset(); !p.IsEnd(); p.GoNext()) {
p.GetCurr();
out << " ";
}
// if (p.GetHeadCof() < 0)
// out << p.GetHeadCof() << endl;
// else
// out << "+ " << p.GetHeadCof() << endl;
p.SetPoz(tmp_pos);
return out;
}
};
|
#include "drake/automotive/idm_controller.h"
#include <algorithm>
#include <limits>
#include <utility>
#include <vector>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_assert.h"
namespace drake {
namespace automotive {
using maliput::api::GeoPosition;
using maliput::api::GeoPositionT;
using maliput::api::Lane;
using maliput::api::LanePosition;
using maliput::api::LanePositionT;
using maliput::api::RoadGeometry;
using maliput::api::RoadPosition;
using systems::rendering::FrameVelocity;
using systems::rendering::PoseBundle;
using systems::rendering::PoseVector;
static constexpr int kIdmParamsIndex{0};
template <typename T>
IdmController<T>::IdmController(const RoadGeometry& road,
ScanStrategy path_or_branches,
RoadPositionStrategy road_position_strategy,
double period_sec)
: systems::LeafSystem<T>(
systems::SystemTypeTag<automotive::IdmController>{}),
road_(road),
path_or_branches_(path_or_branches),
road_position_strategy_(road_position_strategy),
period_sec_(period_sec),
ego_pose_index_(
this->DeclareVectorInputPort(PoseVector<T>()).get_index()),
ego_velocity_index_(
this->DeclareVectorInputPort(FrameVelocity<T>()).get_index()),
traffic_index_(this->DeclareAbstractInputPort().get_index()),
acceleration_index_(
this->DeclareVectorOutputPort(systems::BasicVector<T>(1),
&IdmController::CalcAcceleration)
.get_index()) {
this->DeclareNumericParameter(IdmPlannerParameters<T>());
// TODO(jadecastro) It is possible to replace the following AbstractState with
// a caching scheme once #4364 lands, preventing the need to use abstract
// states and periodic sampling time.
if (road_position_strategy == RoadPositionStrategy::kCache) {
this->DeclareAbstractState(systems::AbstractValue::Make<RoadPosition>(
RoadPosition()));
this->DeclarePeriodicUnrestrictedUpdate(period_sec, 0);
}
}
template <typename T>
IdmController<T>::~IdmController() {}
template <typename T>
const systems::InputPort<T>& IdmController<T>::ego_pose_input()
const {
return systems::System<T>::get_input_port(ego_pose_index_);
}
template <typename T>
const systems::InputPort<T>& IdmController<T>::ego_velocity_input()
const {
return systems::System<T>::get_input_port(ego_velocity_index_);
}
template <typename T>
const systems::InputPort<T>& IdmController<T>::traffic_input() const {
return systems::System<T>::get_input_port(traffic_index_);
}
template <typename T>
const systems::OutputPort<T>& IdmController<T>::acceleration_output() const {
return systems::System<T>::get_output_port(acceleration_index_);
}
template <typename T>
void IdmController<T>::CalcAcceleration(
const systems::Context<T>& context,
systems::BasicVector<T>* accel_output) const {
// Obtain the parameters.
const IdmPlannerParameters<T>& idm_params =
this->template GetNumericParameter<IdmPlannerParameters>(context,
kIdmParamsIndex);
// Obtain the input/output data structures.
const PoseVector<T>* const ego_pose =
this->template EvalVectorInput<PoseVector>(context, ego_pose_index_);
DRAKE_ASSERT(ego_pose != nullptr);
const FrameVelocity<T>* const ego_velocity =
this->template EvalVectorInput<FrameVelocity>(context,
ego_velocity_index_);
DRAKE_ASSERT(ego_velocity != nullptr);
const PoseBundle<T>* const traffic_poses =
this->template EvalInputValue<PoseBundle<T>>(context, traffic_index_);
DRAKE_ASSERT(traffic_poses != nullptr);
// Obtain the state if we've allocated it.
RoadPosition ego_rp;
if (context.template get_state().get_abstract_state().size() != 0) {
DRAKE_ASSERT(context.get_num_abstract_states() == 1);
ego_rp = context.template get_abstract_state<RoadPosition>(0);
}
ImplCalcAcceleration(*ego_pose, *ego_velocity, *traffic_poses, idm_params,
ego_rp, accel_output);
}
template <typename T>
void IdmController<T>::ImplCalcAcceleration(
const PoseVector<T>& ego_pose, const FrameVelocity<T>& ego_velocity,
const PoseBundle<T>& traffic_poses,
const IdmPlannerParameters<T>& idm_params,
const RoadPosition& ego_rp,
systems::BasicVector<T>* command) const {
using std::abs;
using std::max;
DRAKE_DEMAND(idm_params.IsValid());
RoadPosition ego_position = ego_rp;
if (!ego_rp.lane) {
const auto gp =
GeoPositionT<T>::FromXyz(ego_pose.get_isometry().translation());
ego_position =
road_.ToRoadPosition(gp.MakeDouble(), nullptr, nullptr, nullptr);
}
// Find the single closest car ahead.
const ClosestPose<T> lead_car_pose = PoseSelector<T>::FindSingleClosestPose(
ego_position.lane, ego_pose, traffic_poses,
idm_params.scan_ahead_distance(), AheadOrBehind::kAhead,
path_or_branches_);
const T headway_distance = lead_car_pose.distance;
const LanePositionT<T> lane_position(T(ego_position.pos.s()),
T(ego_position.pos.r()),
T(ego_position.pos.h()));
const T s_dot_ego = PoseSelector<T>::GetSigmaVelocity(
{ego_position.lane, lane_position, ego_velocity});
const T s_dot_lead =
(abs(lead_car_pose.odometry.pos.s()) ==
std::numeric_limits<T>::infinity())
? T(0.)
: PoseSelector<T>::GetSigmaVelocity(lead_car_pose.odometry);
// Saturate the net_distance at `idm_params.distance_lower_limit()` away from
// the ego car to avoid near-singular solutions inherent to the IDM equation.
const T actual_headway = headway_distance - idm_params.bloat_diameter();
const T net_distance = max(actual_headway, idm_params.distance_lower_limit());
const T closing_velocity = s_dot_ego - s_dot_lead;
// Compute the acceleration command from the IDM equation.
(*command)[0] = IdmPlanner<T>::Evaluate(idm_params, s_dot_ego, net_distance,
closing_velocity);
}
template <typename T>
void IdmController<T>::DoCalcUnrestrictedUpdate(
const systems::Context<T>& context,
const std::vector<const systems::UnrestrictedUpdateEvent<T>*>&,
systems::State<T>* state) const {
DRAKE_ASSERT(context.get_num_abstract_states() == 1);
// Obtain the input and state data.
const PoseVector<T>* const ego_pose =
this->template EvalVectorInput<PoseVector>(context, ego_pose_index_);
DRAKE_ASSERT(ego_pose != nullptr);
const FrameVelocity<T>* const ego_velocity =
this->template EvalVectorInput<FrameVelocity>(context,
ego_velocity_index_);
DRAKE_ASSERT(ego_velocity != nullptr);
RoadPosition& rp =
state->template get_mutable_abstract_state<RoadPosition>(0);
CalcOngoingRoadPosition(*ego_pose, *ego_velocity, road_, &rp);
}
} // namespace automotive
} // namespace drake
// These instantiations must match the API documentation in idm_controller.h.
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_NONSYMBOLIC_SCALARS(
class ::drake::automotive::IdmController)
|
#include<iostream>
#include<algorithm>
#include<initializer_list>
#include<memory>
using namespace std;
//vector是动态数组
//内存遵循的规则,当前的内存不可用的时候,开二倍的内存
template <class T>
void destroy(T *pointer)
{
pointer->~T();
}
template <class ForwardIterator>
void destroy(ForwardIterator first, ForwardIterator last)
{
for (ForwardIterator it = first; it != last; ++it)
{
destroy(&*it);
}
}
template <typename T>
class Myvector
{
friend ostream &operator<<(ostream &os, const Myvector<T>&rhs)
{
os << rhs.begin();
return os;
}
friend istream&operator>> (istream&is,Myvector<T> &rhs)
{
is >> rhs.begin();
return is;
}
public:
Myvector();
Myvector(T* begin , T* end);
Myvector(size_t type , T value = T());
~Myvector();
Myvector( initializer_list<T> lst);
Myvector(const Myvector&) ;
Myvector & operator= (const Myvector&);
public:
bool empty()
{
return start == finish;
}
size_t size() const//成员函数不会被改变 //已经保存了的数量
{
return ((size_t) finish - (size_t)start)/4;
}
size_t capactity() const //可以保存多少个元素
{
return ((size_t) end_of_storage - (size_t)start)/4;
}
public:
T* begin()
{
return start;
}
T* end()
{
return finish;
}
const T* begin() const
{
return *start;
}
const T* end() const
{
return *finish;
}
T& operator [](size_t i)
{
return *(start+i);
}
const T& operator [] (size_t i) const
{
return *(start+i);
}
protected:
T* start ; // 动态数组的头
T* finish;//动态数组的尾巴
T* end_of_storage; // 可用空间的尾巴/最后一位
private:
static allocator<T> alloc;
public:
void insert(int size,size_t n ,const T& value);
void push_back(const T&value);
void pop_back();
void erase(T* first,T*last);
void clear();
void reserve(size_t n);
void Swap(Myvector &rhs);
};
//static class member needed to be defined outside of class
//静态的成员函数必须在类外面显示
template<typename T>
allocator<T> Myvector<T>::alloc;
template < typename T>
Myvector<T>::Myvector() : start(NULL),finish(NULL),end_of_storage(NULL)//如果没有申请出来新的内存空间,vector是不能主动申请内存出来的
{
cout << "4" << endl;
}
template< typename T>
Myvector<T>::Myvector(initializer_list<T> lst)
{
const size_t n = 20;
start = alloc.allocate(n);
finish = start;
end_of_storage = start + n;
for (auto beg = lst.begin(); beg != lst.end(); beg++)
{
this->push_back(*beg);
}
}
template< typename T>
Myvector<T>::Myvector(T* begin,T* end)
{
cout << "3" << endl;
const size_t n = end - begin ;
start = alloc.allocate(n); // 分配出来n的内存
finish = start + n ; // 分配出来的内存空间指向
//allocator算法,copy赋值产生的内存
uninitialized_copy(begin,end,start);
}
template < typename T>
Myvector<T>::Myvector(size_t n , T value)
{
cout << "1" << endl;
start = alloc.allocate(n);//创建一个n的内存
end_of_storage = finish = start + n ; // 可用空间的最后尾巴
for(T* i = start ; i!=finish ; ++i)
alloc.construct(i,value); // 构造一个对象
}
template < typename T>
Myvector<T>::Myvector(const Myvector & rhs) // 右值运算符
{
cout << "2" << endl;
start = alloc.allocate(rhs.capacity());
uninitialized_copy(rhs.start,rhs.finish,start);
finish = start + (rhs.finish - rhs.start) ; // 赋值运算符的长度
end_of_storage = start + (rhs.end_of_storage - rhs.satrt) ; // 可用的长度
}
template <typename T>
Myvector<T>& Myvector<T>::operator=(const Myvector & rhs)
{
start = alloc.allocate(rhs.capacity());
uninitialized_copy(rhs.start,rhs.finish,start);//start指向的内存空间
finish = start + (rhs.finish - rhs.start);
end_of_storage = start + (rhs.end_of_storage - rhs.start) ;
return *this;
}
template < typename T>
Myvector<T>::~Myvector()
{//shanchui
::destroy(start,finish);
alloc.deallocate(start,end_of_storage - start);
}
template <typename T>
void Myvector<T>:: insert(int size, size_t n, const T &value)
{
T * position = start + size;
cout << "position = " << *position << endl;
if(n <= end_of_storage-finish)
{ // enough empty
cout << "first" << endl;
if(n <= finish - position) // 插的位置
{
uninitialized_copy(finish-n,finish,finish);//从finish-n往后挪n个数
copy(position,finish-n,position+n);//copy函数从begin,end拷贝在position+n的位置
fill_n(position,n,value);
}
else
{
uninitialized_fill_n(finish,n-(finish-position),value);//拷贝创建对象
uninitialized_copy(position,finish,position + n);
fill(position,finish,value);
}
finish += n;//finish的长度增加为finish += n
}
else
{
//reallocate重新创建一个数组,将他的大小扩大为之前的二倍
T * newstart(NULL),*newfinish(NULL),*newend_of_storge(NULL);
size_t old_type = end_of_storage - start;
size_t new_size = old_type + max(n,old_type);
newstart = alloc.allocate(new_size ); // 扩大为原来的二倍,在这里防止n比之前的数组都大
newfinish = uninitialized_copy(start,position,newstart); // 这里应该是position
uninitialized_fill_n(newfinish,n,value);//这里注意偏移梁的问题
newfinish += n;
newfinish = uninitialized_copy(position,finish,newfinish);
newend_of_storge = newstart +new_size;
while(start != end_of_storage)
{
alloc.destroy(--end_of_storage);
}
alloc.deallocate(start,end_of_storage-start);//第二个参数表示第几个对象
start = newstart;
finish = newfinish;
}
}
template <typename T>
void Myvector<T>::push_back(const T &value)
{
insert(this->size() ,1,value);
}
template < typename T>
void Myvector<T>::pop_back()
{
alloc.destroy(--finish);
//会调用析构函数
}
template <typename T>
void Myvector<T>::erase(T *first, T *last)
{
T* newfirst(NULL),*newlast(NULL),*newend_of_lange(NULL);
size_t old_type = end_of_storage - start;
size_t new_type = old_type - (last-first);
newfirst = alloc.allocate(new_type);
newend_of_lange = newfirst + new_type;
newlast = uninitialized_copy(start,first,newfirst);
newlast += (first - start);
newlast = uninitialized_copy(last,finish,newlast);
start = newfirst;
finish = newlast;
//T * old_finish = finish ;
//finish = copy(last,finish,first);
//destory(finish,old_finish);
}
template < typename T>
void Myvector<T>::clear()
{
while(finish != start){
pop_back();
}
}
template < typename T>
void Myvector<T>::reserve(size_t n)//容器预留空间,但在空间内并不真正创建元素对象
{
if(capactity() < n)
{
T * new_start = alloc.allocate(n);
uninitialized_copy(start,finish,new_start);
const size_t old_size = finish - start;
::destroy(start,finish);
alloc.deallocate(start,size());
start = new_start;
finish = new_start + old_size ;
end_of_storage = new_start + n;
}
}
template < typename T>
void Myvector<T>::Swap(Myvector &rhs)
{
swap(rhs.start,start);
swap(rhs.finish,finish);
swap(rhs.end_of_storage,end_of_storage);
}
int main()
{
Myvector<int> a1 = {3,2,5,6,7};
Myvector<int> b1 = {6,7,8};
//a1.clear();
a1.Swap(b1);
cout << a1.size() << endl;
cout << a1[0] << a1[1] << a1 [2] << endl;
return 0;
}
|
//
// Created by clo on 13/09/2019.
//
#include "AudioCapture.h"
#include <iostream>
using namespace Eigen;
template<typename T, T min, T max>
static void convertToFloat(ArrayXd & dst, T * src, unsigned long len);
int AudioCapture::readCallback(const void * input, void * output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo * timeInfo,
PaStreamCallbackFlags statusFlags,
void * userData)
{
auto ctx = static_cast<RecordContext *>(userData);
ArrayXd block;
if (ctx->format == paFloat32) {
auto inPtr = static_cast<const float *>(input);
block = Map<const ArrayXf>(inPtr, frameCount).cast<double>();
}
else if (ctx->format == paInt32) {
auto inPtr = static_cast<const int32_t *>(input);
convertToFloat<const int32_t, 0, INT32_MAX>(block, inPtr, frameCount);
}
else if (ctx->format == paInt16) {
auto inPtr = static_cast<const int16_t *>(input);
convertToFloat<const int16_t, 0, INT16_MAX>(block, inPtr, frameCount);
}
else if (ctx->format == paInt8) {
auto inPtr = static_cast<const int8_t *>(input);
convertToFloat<const int8_t, 0, INT8_MAX>(block, inPtr, frameCount);
}
else if (ctx->format == paUInt8) {
auto inPtr = static_cast<const uint8_t *>(input);
convertToFloat<const uint8_t, 128, INT8_MAX>(block, inPtr, frameCount);
}
ctx->buffer.writeInto(block);
return paContinue;
}
template<typename T, T offset, T max>
void convertToFloat(ArrayXd & dst, T * src, unsigned long len)
{
for (int i = 0; i < len; ++i) {
dst(i) = static_cast<double>(offset + src[i]) / static_cast<double>(max);
}
}
|
#pragma once
#include <queue>
#include <vector>
#include <cmath>
#include <iostream>
#include "Passenger.h"
enum Indicator {
UP, DOWN, STOP, NONE
};
class Elevator {
public:
Elevator(int maxFloor) : maxFloor(maxFloor), timer(0), currentFloor(0), achievedPassenger(0) { }
void goToFloor(int); // 前往指定楼层
void stop(); // 停靠在当前楼层
void addPassenger(const Passenger&); // 添加乘客
bool isAllAchieved() const; // 是否完成调度
void Execute(Indicator); // 执行指令
int getMaxFloor() const;
int getTimer() const;
int getCurrentFloor() const;
const std::vector<Passenger>& getPassengers() const;
private:
int maxFloor; // 最大楼层
int timer; // 计时器
int currentFloor; // 当前位置
int achievedPassenger; // 已抵达乘客数
std::vector<Passenger> passengers; // 乘客们
std::queue<std::pair<int, int>> destinationQueue; // 电梯运行队列
friend std::ostream &operator<< (std::ostream&, Elevator&);
};
|
/*
BAEKJOON
17281. 야구
DFS + 시뮬레이션
*/
#include <iostream>
#include <algorithm>
#include <cstring>
#define MAX 51
using namespace std;
int N, Answer = 0;
int Game[MAX][10];
int Player[10];
bool Selected[10];
int Roo[4];
void Input()
{
cin >> N;
for(int i = 1; i <= N; i++)
{
for(int j = 1; j <= 9; j++)
{
cin >> Game[i][j];
}
}
}
void Initialize()
{
Player[4] = 1;
memset(Selected, false, sizeof(Selected));
}
int Shoot(int Result)
{
int Score = 0;
for(int i = 3; i >= 0; i--)
{
if(Roo[i] > 0)
{
int N_Roo = i + Result;
if(N_Roo > 3)
{
Score++;
}
else
{
Roo[N_Roo] = Roo[i];
}
Roo[i] = 0;
}
}
return Score;
}
void Play()
{
int Score = 0, Starter = 1;
for(int t = 1; t <= N; t++)
{
memset(Roo, 0, sizeof(Roo));
int Out = 0;
int Shooter_Num = Starter;
while(1)
{
if(Shooter_Num > 9)
{
Shooter_Num = 1;
}
int Shooter_Idx = Player[Shooter_Num];
int Shooter_Result = Game[t][Shooter_Idx];
Roo[0] = Shooter_Idx;
if(Shooter_Result == 0)
{
Out++;
}
else
{
Score += Shoot(Shooter_Result);
}
Shooter_Num++;
if(Out == 3)
{
Starter = Shooter_Num;
break;
}
}
}
Answer = max(Answer, Score);
}
void DFS(int Cnt)
{
if(Cnt == 4)
{
Cnt++;
}
if(Cnt > 9)
{
Play();
return;
}
for(int i = 2; i <= 9; i++)
{
if(Selected[i] == true) continue;
Player[Cnt] = i;
Selected[i] = true;
DFS(Cnt + 1);
Selected[i] = false;
}
}
void Solve()
{
DFS(1);
cout << Answer << endl;
}
int main()
{
Initialize();
Input();
Solve();
return 0;
}
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <cmath>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <cstring>
#include <climits>
#include <queue>
#include <assert.h>
using namespace std;
int N;
vector<vector<pair<int,int>>> costume;
vector<vector<int>> graph;
vector<bool> seen;
vector<int> matched;
bool compute(int point){
for(int v=1;v<=N;++v){
if( graph[point][v] && seen[v]==false){
seen[v]=true;
if(matched[v]==-1 || compute(matched[v])){
matched[v]=point;
return true;
}
}
}
return false;
}
int match(int cloth){
vector<vector<int>> v2(N+1,vector<int>(N+1,0));
graph=v2;
vector<int> v4(N+1,-1);
matched=v4;
for(pair<int,int> p: costume[cloth]){
graph[p.first][p.second]=1;
}
int answer=0;
for(int i=1;i<=N;++i){
vector<bool> v3(N+1,false);
seen=v3;
if(compute(i)){answer++;}
}
return answer;
}
int main(){
int T;
cin>>T;
int clothes;
for(int tt=1;tt<T+1;++tt){
cin>>N;
vector<vector<pair<int,int>>> v1(2*N+1);
costume=v1;
for(int i=1;i<=N;++i){
for(int j=1;j<=N;++j){
cin>>clothes;
costume[clothes+N].push_back(make_pair(i,j));
}
}
int result=0;
for(int i=0;i<=2*N;++i){
if(i==N){continue;}
result+=costume[i].size()-match(i);
}
cout<<"Case #"<<tt<<": "<<result<<endl;
}
}
|
/**
* @file ventana.h
* @brief Fichero de interfaz gráfica
*
* Esta interfaz se ha diseñado de la forma más simple y ajustada al problema
* Otelo de la asignatura Metodología de la Programación. Está basada en el uso
* de la biblioteca SFML.
*
* El código no está diseñado para su reutilización ni para su mantenimiento. Sólo
* será útil primero para mostrar cómo la sustitución de un componente del proyecto
* puede modificar completamente la interfaz del juego y segundo para que el estudiante
* pueda realizar pruebas más ágilmente.
*/
#ifndef __VENTANA_H_
#define __VENTANA_H_
/**
* @brief La clase Ventana contiene la interfaz que usará el estudiante
*
* Es posible que una interfaz basada en funciones generales se hubiera entendido
* más fácilmente. Sin embargo, los detalles de este diseño, donde:
*
* -# sólo existe un único objeto de la clase,
* -# se evita mostrar la implementación en el archivo de cabecera
* -# se define un enumerado y una estructura dentro de la clase
*
* hacen del ejemplo un buen código para introducir al estudiante en nuevos detalles
* de diseño así como para repasar algunas ideas del curso.
*
* Una forma sencilla y eficaz de conocer lo que hace es consultar el ejemplo:
*
* @include test_tablero.cpp
*/
class Ventana {
public:
/**
* @brief El singleton
*
* Un singleton se refiere a un único objeto de la clase. No es posible definir
* más, pues la clase no admite que el usuario llame a un constructor.
*/
static Ventana win;
/**
* @brief init Es la primera función a llamar para crear el único objeto ventana a usar
* @param resource_dir Directorio donde se encuentran los sonidos/imágenes/fuentes
* @param filas Filas del tablero
* @param columnas Columnas del tablero
* @param titulo Título de la ventana que muestra el juego
* @param wpix Ancho en píxeles de la ventana con el juego
* @param hpix Alto en píxeles de la ventana con el juego
* @return Si se ha iniciado con éxito
*/
bool init(const char* resource_dir,unsigned int filas, unsigned int columnas,
const char* titulo= "Otelo", unsigned int wpix= 1024, unsigned int hpix= 768);
/**
* @brief setTablero Cambia el contenido que se mostrará cuando se vuelva a dibujar el tablero
* @param turno Turno (0/1/2) del que tiene que escoger casilla
* @param tablero Cadena de caracteres con los contenidos del tablero
* @pre La cadena \a tablero sólo admitirá los carateres '1','2','0','?'
* para indicar ficha de jugador 1, del 2, posición vacía y posible posición para poner
* @note Es una función incómoda, pues hay que montar la cadena. Se hace así para hacerla independiente
* de cómo haya implementado el tablero. Sería una buena idea crear una función global junto al
* \c main que recibe un objeto de la clase Tablero (con booleano para indicar si desea ayuda)
* y llame a esta función.
*/
void setTablero(int turno, const char *tablero);
/**
* @brief setEstado Asigna el mensaje que aparecerá debajo cada vez que se pinta el tablero
* @param mensaje La cadena con el mensaje codificado con ISO 8859-15
* @param esperarClick Indica si esperará a que el usuario pulse en el tablero para continuar
*/
void setEstado(const char *mensaje, bool esperarClick= false);
/**
* @brief setError Cambia el estado y genera un sonido de error
* @param mensaje Cadena codificada como ISO-8859-15 que parece como nuevo estado hasta
* que se llame a otra función que lo cambie
* @see setEstado
*/
void setError(const char *mensaje);
/** @brief Avisa que el jugador ha tenido que pasar con un sonido
* @param turno El jugador que seguirá jugando
* @post Indicará un mensaje y esperará a pulsar en el tablero para confirmar
*/
void paso(int turno);
/**
* @brief final Muestra un mensaje de ganador, un sonido y una animación
* @param ganador La ficha que se mostrará como ganadora
* @note El ganador se muestra aumentando el tamaño de su ficha
*/
void final(int ganador);
/**
* @brief Este enumerado describe el tipo de la entrada seleccionada
* @see input
*/
enum TipoEntrada {Casilla, ///< Se ha pulsado en el tablero
Ayuda, ///< Se ha pulsado la tecla ?
Interrumpir, ///< Se ha pulsado la tecla !
Cerrar ///< Se ha pulsado el cierre de la ventana
};
/**
* @brief Incluye la información asociada a una selección en el tablero
*
* Observe que tiene un primer campo \a tipo que nos sirve para distinguir el
* tipo de entrada. Los otros campos son válidos sólo en el caso en que el tipo
* sea que ha seleccionado una casilla dentro del tablero.
*
* Este diseño puede recordar la forma que tiene el tipo sf::Event de la biblioteca
* SFML, pero es bastante más simple. El tipo asociado a un evento suele ser más complejo,
* pues cambiando el tipo del evento normalmente cambian los campos asociados; además,
* para aprovechar el espacio, el diseño de este tipo a bajo nivel suelen implicar el
* uso de uniones.
*/
struct Input {
TipoEntrada tipo; ///< Tipo de entrada
int fila; ///< Fila que se ha pinchado (desde 0)
int columna; ///< Columna que se ha pinchado (desde 0)
};
/**
* @brief input Espera a que el usuario decida una acción y la devuelve
* @return Alguna posible entrada del enumerado \a TipoEntrada
*/
Input input();
private:
// Evitamos que se pueda copiar o asignar un objeto. Esto se implementa más adecuadamente
// con "delete" en C++14
Ventana(const Ventana&);
Ventana& operator= (const Ventana&);
~Ventana();
Ventana();
// La implementación interna queda oculta, podríamos dar el .h con los cpp compilados
// para evitar incluir ningún detalle sobre la implementación
struct pimpl;
pimpl *rep;
};
#endif //__VENTANA_H_
|
//
// SMViewConstValue.h
// SMFrameWork
//
// Created by KimSteve on 2016. 11. 3..
//
//
#ifndef SMViewConstValue_h
#define SMViewConstValue_h
#include <base/ccTypes.h>
class SMViewConstValue {
public:
/*************************************************************************
레이어별 로컬 Z Order 정의
*************************************************************************/
class ZOrder {
public:
static const int BG;
static const int USER;
static const int BUTTON_NORMAL;
static const int BUTTON_PRESSED;
static const int BUTTON_ICON_NORMAL;
static const int BUTTON_ICON_PRESSED;
static const int BUTTON_TEXT;
};
/*************************************************************************
뷰 세팅
*************************************************************************/
class Config {
public:
static const float DEFAULT_FONT_SIZE;
static const float TAP_TIMEOUT;
static const float DOUBLE_TAP_TIMEOUT;
static const float LONG_PRESS_TIMEOUT;
static const float SCALED_TOUCH_SLOPE;
static const float SCALED_DOUBLE_TAB_SLOPE;
static const float SMOOTH_DIVIDER;
static const float TOLERANCE_POSITION;
static const float TOLERANCE_ROTATE;
static const float TOLERANCE_SCALE;
static const float MIN_VELOCITY;
static const float MAX_VELOCITY;
static const float SCROLL_TOLERANCE;
static const float SCROLL_HORIZONTAL_TOLERANCE;
static const float BUTTON_PUSHDOWN_PIXELS;
static const float BUTTON_PUSHDOWN_SCALE;
static const float BUTTON_STATE_CHANGE_PRESS_TO_NORMAL_TIME;
static const float BUTTON_STATE_CHANGE_NORMAL_TO_PRESS_TIME;
static const float ZOOM_SHORT_TIME;
static const float ZOOM_NORMAL_TIME;
static const float LIST_HIDE_REFRESH_TIME;
};
/*************************************************************************
태그 정의
*************************************************************************/
class Tag {
public:
static const int USER;
static const int SYSTEM;
static const int ACTION_VIEW_SHOW;
static const int ACTION_VIEW_HIDE;
static const int ACTION_BG_COLOR;
static const int ACTION_VIEW_STATE_CHANGE_NORMAL_TO_PRESS;
static const int ACTION_VIEW_STATE_CHANGE_PRESS_TO_NORMAL;
static const int ACTION_VIEW_STATE_CHANGE_DELAY;
static const int ACTION_ZOOM;
static const int ACTION_STICKER_REMOVE;
static const int ACTION_LIST_ITEM_DEFAULT;
static const int ACTION_LIST_HIDE_REFRESH;
static const int ACTION_LIST_JUMP;
static const int ACTION_PROGRESS1;
static const int ACTION_PROGRESS2;
static const int ACTION_PROGRESS3;
};
class Const {
public:
static const cocos2d::Color4F COLOR4F_TRANSPARENT;
static const cocos2d::Color3B LOADING_SPRITE_COLOR;
static const cocos2d::Color4F KNOB_ON_BGCOLOR;
static const cocos2d::Color4F KNOB_OFF_BGCOLOR;
static const cocos2d::Color4F KNOB_COLOR;
};
class Size {
public:
static float getStatusHeight();
static const float TOP_STATUS_HEIGHT;
static const float TOP_MENU_HEIGHT;
static const float LEFT_SIDE_MENU_WIDTH;
static const float RIGHT_SIDE_MENU_WIDTH;
static const float EDGE_SWIPE_MENU;
static const float EDGE_SWIPE_TOP;
};
};
#endif /* SMViewConstValue_h */
|
class TrieCollision{
public:
/*float distance(sf::Vector2f depart, sf::Vector2f arrive){
float saveX(arrive.x - depart.x), saveY(arrive.y - depart.y);
return sqrt(saveX*saveX + saveY*saveY);
}
sf::Vector2f astar(sf::Vector2f depart, sf::Vector2f arrive){
}*/
/*void algoAstar(sf::Vector2f actuel, sf::Vector2f arrive, uint8_t mouvements){
}*/
void add(sf::Vector2f newPos, bool colli){
++newPos.x;
++newPos.y;
if(newPos.x < 0){
newPos.x -= 16;
}
if(newPos.y < 0){
newPos.y -= 16;
}
newPos.x /= 16;
newPos.y /= 16;
cordToIndex_[newPos.x][newPos.y] = colli;
}
bool operator[](sf::Vector2f pos){
int x(pos.x), y(pos.y);
if(x<0){
x -= 16;
}
if(y<0){
y -= 16;
}
x /= 16;
y /= 16;
return cordToIndex_[pos.x/16][pos.y/16];
}
bool at(int x, int y){
if(x<0){
x -= 16;
}
if(y<0){
y -= 16;
}
x /= 16;
y /= 16;
return cordToIndex_[x][y];
}
private:
std::unordered_map<int, std::unordered_map<int, bool>> cordToIndex_;
};
|
#pragma once
#include <Transformation.h>
#include <iosfwd>
class MetaEvent;
class Channel{
public:
using TransPtr = Transformation::TransPtr;
protected:
enum class Errors {
InvalidEvent,
MissingAttribute,
IncompatibleType
};
TransPtr mTrans;
virtual void fixType(MetaEvent& e) const;
virtual void error(Errors error, const MetaEvent& e) const {}
void handleEvent(const MetaEvent& e);
virtual void publishEvent(MetaEvent& e) const =0;
public:
Channel() = default;
Channel(TransPtr&& trans);
const Transformer* trans() const {return mTrans.get();}
friend std::ostream& operator<<(std::ostream&, const Channel&);
};
std::ostream& operator<<(std::ostream& o, const Channel& c);
|
int lib1();
int lib2();
int main()
{
return lib1() + lib2();
}
|
#include "../include/loadFile.h"
#include <vector>
using std::vector;
loadFile *loadFile::_loadFile=loadFile::getInstance();
loadFile::AutoRelease loadFile::_auto;
loadFile *loadFile::getInstance()
{
if(!_loadFile)
{
_loadFile=new loadFile();
}
return _loadFile;
}
void loadFile::loadPageLib(const string &page_path,const string &offset_path,Configuration & conf)
{
vector<string> vecfiles;
ifstream in_page(page_path,std::ios::binary | std::ios::ate);
if(!in_page.good())
{
cout<<"the ifstream "<<page_path<< "open failed "<<endl;
return;
}
ifstream in_offset(offset_path);
if(!in_offset.good())
{
cout<<"the ifstream "<<offset_path<<" open failed "<<endl;
return;
}
//读取偏移库,根据偏移库获取网页库
int id=0;
int start=0;
int len=0;
string line;//获取偏移库的每一行
while(getline(in_offset,line))
{
istringstream iss(line);
iss>>id;
iss>>start;
iss>>len;
string text(len,0); //每一篇文章的内容
_offsetLib[id]=std::make_pair(start,len);
in_page.seekg(start,std::ios::beg);
in_page.read(&text[0],len);
/* cout<<text<<endl; */
vecfiles.push_back(text);
}
for(size_t i=0;i!=vecfiles.size();++i)
{
WebPage w;
w.processDoc(vecfiles[i]);
w.createDictMap(conf);
_pageLib[w.getDocId()]=w;
}
}
void loadFile::loadInvertIndexTable(const string &invertIndex_path)
{
ifstream ifs(invertIndex_path);
if(!ifs.good())
{
cout<<"the ifstream "<<invertIndex_path<<" oen failed "<<endl;
return;
}
//读取倒排索引表
string line;
while(getline(ifs,line))
{
int docId;
double weight;
string word;
istringstream iss(line);
iss>>word;
while(iss>>docId && iss>>weight)
{
_invertIndexTable[word].insert(std::make_pair(docId,weight));
}
}
}
//获取到内存中的网页库以及倒排索引表
unordered_map<int,WebPage>& loadFile::getPageLib()
{
return _pageLib;
}
unordered_map<int,std::pair<int,int>> &loadFile::getOffSetLib()
{
return _offsetLib;
}
unordered_map<string,set<std::pair<int,double>>> & loadFile::getInvertIndexTable()
{
return _invertIndexTable;
}
|
//**************************************************************************
//**
//** See jlquake.txt for copyright info.
//**
//** This program is free software; you can redistribute it and/or
//** modify it under the terms of the GNU General Public License
//** as published by the Free Software Foundation; either version 3
//** of the License, or (at your option) any later version.
//**
//** This program is distributed in the hope that it will be useful,
//** but WITHOUT ANY WARRANTY; without even the implied warranty of
//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//** included (gnu.txt) GNU General Public License for more details.
//**
//**************************************************************************
//**
//** Endianess handling, swapping 16bit and 32bit.
//**
//**************************************************************************
// HEADER FILES ------------------------------------------------------------
#include "endian.h"
// MACROS ------------------------------------------------------------------
// TYPES -------------------------------------------------------------------
// EXTERNAL FUNCTION PROTOTYPES --------------------------------------------
// PUBLIC FUNCTION PROTOTYPES ----------------------------------------------
// PRIVATE FUNCTION PROTOTYPES ---------------------------------------------
// EXTERNAL DATA DECLARATIONS ----------------------------------------------
// PUBLIC DATA DEFINITIONS -------------------------------------------------
bool GBigEndian;
qint16 ( * LittleShort )( qint16 );
qint16 ( * BigShort )( qint16 );
qint32 ( * LittleLong )( qint32 );
qint32 ( * BigLong )( qint32 );
float ( * LittleFloat )( float );
float ( * BigFloat )( float );
// PRIVATE DATA DEFINITIONS ------------------------------------------------
// CODE --------------------------------------------------------------------
//==========================================================================
//
// ShortSwap
//
//==========================================================================
static qint16 ShortSwap( qint16 x ) {
return ( ( quint16 )x >> 8 ) |
( ( quint16 )x << 8 );
}
//==========================================================================
//
// ShortNoSwap
//
//==========================================================================
static qint16 ShortNoSwap( qint16 x ) {
return x;
}
//==========================================================================
//
// LongSwap
//
//==========================================================================
static qint32 LongSwap( qint32 x ) {
return ( ( quint32 )x >> 24 ) |
( ( ( quint32 )x >> 8 ) & 0xff00 ) |
( ( ( quint32 )x << 8 ) & 0xff0000 ) |
( ( quint32 )x << 24 );
}
//==========================================================================
//
// LongNoSwap
//
//==========================================================================
static qint32 LongNoSwap( qint32 x ) {
return x;
}
//==========================================================================
//
// FloatSwap
//
//==========================================================================
static float FloatSwap( float x ) {
union { float f; qint32 l; } a;
a.f = x;
a.l = LongSwap( a.l );
return a.f;
}
//==========================================================================
//
// FloatNoSwap
//
//==========================================================================
static float FloatNoSwap( float x ) {
return x;
}
//==========================================================================
//
// Com_InitByteOrder
//
//==========================================================================
void Com_InitByteOrder() {
quint8 swaptest[ 2 ] = {1, 0};
// set the byte swapping variables in a portable manner
if ( *( qint16* )swaptest == 1 ) {
GBigEndian = false;
BigShort = ShortSwap;
LittleShort = ShortNoSwap;
BigLong = LongSwap;
LittleLong = LongNoSwap;
BigFloat = FloatSwap;
LittleFloat = FloatNoSwap;
} else {
GBigEndian = true;
BigShort = ShortNoSwap;
LittleShort = ShortSwap;
BigLong = LongNoSwap;
LittleLong = LongSwap;
BigFloat = FloatNoSwap;
LittleFloat = FloatSwap;
}
}
|
#pragma once
struct _DROP_BLOOD
{
BYTE index[7];
BYTE id[7];
BYTE level[7];
BYTE skill[7];
BYTE luck[7];
BYTE addopt[7];
BYTE addoptex[7];
};
class _blood_castle
{
public:
int blood[7];
_DROP_BLOOD drop[255];
void _iniciar_blood_castle(char * filename);
void _blood_drop(LPOBJ lpObj, char vector);
private:
void _reload();
};
extern _blood_castle _blood;
void _blood_castle_hook(int aIndex);
|
#include<bits/stdc++.h>
using namespace std;
string solve(string a,string b,string output)
{
if(a.size()==0 || b.size()==0)
{
return output;
}
if(a[0]==b[0])
{
output = output + a[0];
return output;
}
string suni = solve(a.substr(1),b,output);
string ani = solve(a,b.substr(1),output);
if(suni.size() > ani.size())
{
return suni + output;
}
else
{
return ani + output;
}
}
int main()
{
string a,b;
cin >> a >> b;
cout << solve(a,b,"") << endl;
return 0;
}
|
#include "mbed.h"
DigitalOut arrLeds[3] = {PB_3, PB_5, PB_4};
DigitalIn Button(PC_13);
int main() {
while (1) {
for (int i = 0; i < 3; i += 1) {
arrLeds[0] = i == 0;
arrLeds[1] = i == 1;
arrLeds[2] = i == 2;
wait(0.05);
}
}
}
|
//
// FirstScene.hpp
// demo_ddz
//
// Created by 谢小凡 on 2018/2/8.
//
#ifndef FirstScene_hpp
#define FirstScene_hpp
#include "cocos2d.h"
#include "ui/UIButton.h"
class FirstScene : public cocos2d::Scene
{
public:
static cocos2d::Scene* createScene();
static cocos2d::Scene* createEntryScene();
CREATE_FUNC(FirstScene);
// override
bool init() override;
void onEnter() override;
void onExit() override;
void resumeFirstScene();
private:
void initBgLayer();
void initBtnLayer();
void initEntryLayer();
// btn callback
void callbackForExit(cocos2d::Ref*);
void callbackForStart(cocos2d::Ref*, cocos2d::ui::Widget::TouchEventType type);
void callbackForReview(cocos2d::Ref*, cocos2d::ui::Widget::TouchEventType type);
void callbackForControl(cocos2d::Ref*, cocos2d::ui::Widget::TouchEventType type);
private:
cocos2d::Layer* _bg_layer;
cocos2d::Layer* _btn_layer;
cocos2d::Layer* _entry_layer;
};
#endif /* FirstScene_hpp */
|
#pragma once
#include "Common.h"
extern int MemoryDebugLevel;
#define MEMORY_PROCESS( block, memory ) \
if( MemoryDebugLevel > 0 ) \
Debugger::Memory( block, memory )
#define MEMORY_PROCESS_STR( block, memory ) \
if( MemoryDebugLevel > 1 ) \
Debugger::MemoryStr( block, memory )
#define MEMORY_STATIC ( 0 )
#define MEMORY_NPC ( 1 )
#define MEMORY_CLIENT ( 2 )
#define MEMORY_MAP ( 3 )
#define MEMORY_MAP_FIELD ( 4 )
#define MEMORY_PROTO_MAP ( 5 )
#define MEMORY_NET_BUFFER ( 6 )
#define MEMORY_ITEM ( 9 )
#define MEMORY_DIALOG ( 10 )
#define MEMORY_IMAGE ( 13 )
#define MEMORY_ANGEL_SCRIPT ( 17 )
namespace Debugger
{
void BeginCycle();
void BeginBlock( int num_block );
void ProcessBlock( int num_block, int identifier );
void EndCycle( double lag_to_show );
void ShowLags( int num_block, double lag_to_show );
void Memory( int block, int value );
void MemoryStr( const char* block, int value );
const char* GetMemoryStatistics();
void StartTraceMemory();
string GetTraceMemory();
};
|
#include <sstream>
#include <iomanip>
#include "cqp.h"
#include "pee.h"
#include "appmain.h"
#include "group.h"
#include "cpp-base64/base64.h"
namespace pee {
void modifyCurrency(int64_t qq, int64_t c)
{
db.exec("UPDATE pee SET currency=? WHERE qqid=?", { c, qq });
}
void modifyBoxCount(int64_t qq, int64_t c)
{
db.exec("UPDATE pee SET cases=? WHERE qqid=?", { c, qq });
}
void modifyDrawTime(int64_t qq, time_t c)
{
db.exec("UPDATE pee SET dailytime=? WHERE qqid=?", { c, qq });
}
void modifyKeyCount(int64_t qq, int64_t c)
{
db.exec("UPDATE pee SET keys=? WHERE qqid=?", { c, qq });
}
int64_t nosmoking(int64_t group, int64_t target, int duration)
{
if (duration < 0) return -1;
if (grp::groups.find(group) != grp::groups.end())
{
if (grp::groups[group].haveMember(target))
{
if (grp::groups[group].members[target].permission >= 2) return -2;
CQ_setGroupBan(ac, group, target, int64_t(duration) * 60);
if (duration > 0) smokeGroups[target][group] = time(nullptr) + int64_t(duration) * 60;
else if (duration == 0) smokeGroups[target].erase(group);
return duration;
}
}
else
{
const char* cqinfo = CQ_getGroupMemberInfoV2(ac, group, target, FALSE);
if (cqinfo && strlen(cqinfo) > 0)
{
std::string decoded = base64_decode(std::string(cqinfo));
if (!decoded.empty())
{
if (getPermissionFromGroupInfoV2(decoded.c_str()) >= 2) return -2;
CQ_setGroupBan(ac, group, target, int64_t(duration) * 60);
if (duration > 0) smokeGroups[target][group] = time(nullptr) + int64_t(duration) * 60;
else if (duration == 0) smokeGroups[target].erase(group);
return duration;
}
}
}
return -1;
}
std::string nosmokingWrapper(int64_t qq, int64_t group, int64_t target, int64_t cost)
{
int duration = (int)cost;
if (duration > 30 * 24 * 60) duration = 30 * 24 * 60;
cost *= cost; // 打土豪 分批
if (cost < 0) return "你会不会烟人?";
if (cost > plist[qq].currency) return std::string(CQ_At(qq)) + ",你的余额不足,需要" + std::to_string(cost) + "个批";
if (cost == 0)
{
nosmoking(group, target, duration);
return "解禁了";
}
double reflect = randReal();
if (reflect < 0.1) return "烟突然灭了,烟起失败";
else if (reflect < 0.3)
{
auto ret = nosmoking(group, qq, duration);
if (ret > 0)
{
return "你自己烟起吧";
}
else if (ret == -2)
{
return "烟突然灭了,烟起失败";
}
else if (ret == 0 || ret == -1)
{
return "你会不会烟人?";
}
}
else
{
auto ret = nosmoking(group, target, duration);
if (ret > 0)
{
plist[qq].currency -= cost;
modifyCurrency(qq, plist[qq].currency);
std::stringstream ss;
if (qq == target)
ss << "?我从来没听过这样的要求,消费" << cost << "个批";
else
ss << "烟起哦,消费" << cost << "个批";
return ss.str();
}
else if (ret == 0 || ret == -1)
{
return "你会不会烟人?";
}
else if (ret == -2)
{
return "禁烟管理请联系群主哦";
}
}
return "你会不会烟人?";
}
std::tuple<bool, int, time_t> updateStamina(int64_t qq, int cost, bool extra)
{
time_t t = time(nullptr);
time_t last = staminaRecoveryTime[qq];
int stamina = MAX_STAMINA;
if (last > t) stamina -= (last - t) / STAMINA_TIME + !!((last - t) % STAMINA_TIME);
bool enough = false;
if (cost > 0)
{
if (staminaExtra[qq] >= cost)
{
enough = true;
staminaExtra[qq] -= cost;
}
else if (stamina + staminaExtra[qq] >= cost)
{
enough = true;
cost -= staminaExtra[qq];
staminaExtra[qq] = 0;
stamina -= cost;
}
else
{
enough = false;
}
}
else if (cost < 0)
{
enough = true;
if (stamina - cost <= MAX_STAMINA)
{
// do nothing
}
else if (extra) // part of cost(recovery) goes to extra
{
staminaExtra[qq] += stamina - cost - MAX_STAMINA;
}
}
if (enough)
{
if (last > t)
staminaRecoveryTime[qq] += STAMINA_TIME * cost;
else
staminaRecoveryTime[qq] = t + STAMINA_TIME * cost;
}
if (enough && stamina >= MAX_STAMINA) staminaRecoveryTime[qq] = t;
return { enough, stamina, staminaRecoveryTime[qq] - t };
}
std::tuple<bool, int, time_t> testStamina(int64_t qq, int cost)
{
time_t t = time(nullptr);
time_t last = staminaRecoveryTime[qq];
int stamina = MAX_STAMINA;
if (last > t) stamina -= (last - t) / STAMINA_TIME + !!((last - t) % STAMINA_TIME);
bool enough = false;
if (cost > 0)
{
if (staminaExtra[qq] >= cost)
{
enough = true;
}
else if (stamina + staminaExtra[qq] >= cost)
{
enough = true;
}
else
{
enough = false;
}
}
if (enough)
{
if (last > t)
last += STAMINA_TIME * cost;
else
last = t + STAMINA_TIME * cost;
}
if (enough && stamina >= MAX_STAMINA) last = t;
return { enough, stamina, last - t };
}
command msgDispatcher(const char* msg)
{
command c;
auto query = msg2args(msg);
if (query.empty()) return c;
auto cmd = query[0];
if (commands_str.find(cmd) == commands_str.end()) return c;
c.args = query;
switch (c.c = commands_str[cmd])
{
case commands::开通提示:
c.func = [](::int64_t group, ::int64_t qq, std::vector<std::string> args, std::string raw) -> std::string
{
if (plist.find(qq) != plist.end()) return std::string(CQ_At(qq)) + ",你已经注册过了";
return "是我要开通菠菜,你会不会开通菠菜";
};
break;
case commands::开通:
c.func = [](::int64_t group, ::int64_t qq, std::vector<std::string> args, std::string raw) -> std::string
{
if (plist.find(qq) != plist.end()) return std::string(CQ_At(qq)) + ",你已经注册过了";
plist[qq].currency = INITIAL_BALANCE;
db.exec("INSERT INTO pee(qqid, currency, cases, dailytime, keys) VALUES(? , ? , ? , ? , ?)",
{ qq, plist[qq].currency, 0, 0, 0 });
std::stringstream ss;
ss << "你可以开始开箱了,送给你" << plist[qq].currency << "个批";
return ss.str();
};
break;
case commands::余额:
c.func = [](::int64_t group, ::int64_t qq, std::vector<std::string> args, std::string raw) -> std::string
{
if (plist.find(qq) == plist.end()) return std::string(CQ_At(qq)) + ",你还没有开通菠菜";
std::stringstream ss;
ss << CQ_At(qq) << ",你的余额为" << plist[qq].currency << "个批,"
<< plist[qq].keys << "把钥匙";
auto[enough, stamina, rtime] = updateStamina(qq, 0);
ss << "\n你还有" << stamina + staminaExtra[qq] << "点体力";
if (stamina < MAX_STAMINA)
ss << ",回满还需" << rtime / (60 * 60) << "小时" << rtime / 60 % 60 << "分钟";
return ss.str();
};
break;
case commands::禁烟:
c.func = [](::int64_t group, ::int64_t qq, std::vector<std::string> args, std::string raw) -> std::string
{
if (grp::groups.find(group) != grp::groups.end())
{
if (grp::groups[group].haveMember(CQ_getLoginQQ(ac)))
{
if (grp::groups[group].members[CQ_getLoginQQ(ac)].permission < 2)
return "";
}
}
else
{
const char* cqinfo = CQ_getGroupMemberInfoV2(ac, group, CQ_getLoginQQ(ac), FALSE);
if (cqinfo && strlen(cqinfo) > 0)
{
std::string decoded = base64_decode(std::string(cqinfo));
if (!decoded.empty())
{
if (getPermissionFromGroupInfoV2(decoded.c_str()) < 2)
return "";
}
}
}
if (plist.find(qq) == plist.end()) return std::string(CQ_At(qq)) + ",你还没有开通菠菜";
int64_t target = 0;
if (true || args.size() == 1)
{
if (prevUser.find(group) == prevUser.end()) return "";
target = prevUser[group];
}
int64_t cost = -1;
try {
if (args.size() >= 2)
cost = std::stoll(args[1]);
}
catch (std::exception&) {
//ignore
}
return nosmokingWrapper(qq, group, target, cost);
};
break;
case commands::解禁:
c.func = [](::int64_t group, ::int64_t qq, std::vector<std::string> args, std::string raw) -> std::string
{
if (grp::groups.find(group) != grp::groups.end())
{
if (grp::groups[group].haveMember(CQ_getLoginQQ(ac)))
{
if (grp::groups[group].members[CQ_getLoginQQ(ac)].permission < 2)
return "";
}
}
else
{
const char* cqinfo = CQ_getGroupMemberInfoV2(ac, group, CQ_getLoginQQ(ac), FALSE);
if (cqinfo && strlen(cqinfo) > 0)
{
std::string decoded = base64_decode(std::string(cqinfo));
if (!decoded.empty())
{
if (getPermissionFromGroupInfoV2(decoded.c_str()) < 2)
return "";
}
}
}
if (args.size() < 1) return "";
try {
//unsmoke(std::stoll(args[1]));
CQ_setGroupBan(ac, group, std::stoll(args[1]), 0);
return "";
}
catch (std::exception&) {}
return "";
};
break;
case commands::领批:
c.func = [](::int64_t group, ::int64_t qq, std::vector<std::string> args, std::string raw) -> std::string
{
if (plist.find(qq) == plist.end()) return std::string(CQ_At(qq)) + ",你还没有开通菠菜";
time_t lastDailyTime = plist[qq].last_draw_time;
if (lastDailyTime > daily_refresh_time)
{
std::stringstream ss;
ss << CQ_At(qq) << ",你今天已经领过了,明天再来8";
return ss.str();
}
std::stringstream ss;
ss << CQ_At(qq) << ",你今天领到" << FREE_BALANCE_ON_NEW_DAY << "个批";
if (remain_daily_bonus)
{
int bonus = randInt(1, remain_daily_bonus > 66 ? 66 : remain_daily_bonus);
remain_daily_bonus -= bonus;
plist[qq].currency += FREE_BALANCE_ON_NEW_DAY + bonus;
ss << ",甚至还有先到的" << bonus << "个批\n"
<< "现在批池还剩" << remain_daily_bonus << "个批";
}
else
{
plist[qq].currency += FREE_BALANCE_ON_NEW_DAY;
ss << "\n每日批池么得了,明天请踩点";
}
plist[qq].last_draw_time = time(nullptr);
modifyCurrency(qq, plist[qq].currency);
modifyDrawTime(qq, plist[qq].last_draw_time);
return ss.str();
/*
if (plist[qq].last_draw_time > daily_time_point)
if (remain_daily_bonus > 0)
{
int bonus = randInt(0, remain_daily_bonus);
remain_daily_bonus -= bonus;
}
*/
return "";
};
break;
case commands::生批:
c.func = [](::int64_t group, ::int64_t qq, std::vector<std::string> args, std::string raw) -> std::string
{
if (plist.find(qq) == plist.end()) return std::string(CQ_At(qq)) + ",你还没有开通菠菜";
auto[enough, stamina, rtime] = updateStamina(qq, 1);
std::stringstream ss;
if (!enough) ss << CQ_At(qq) << ",你的体力不足,回满还需"
<< rtime / (60 * 60) << "小时" << rtime / 60 % 60 << "分钟";
plist[qq].currency += 1;
modifyCurrency(qq, plist[qq].currency);
return std::string(CQ_At(qq)) + "消耗1点体力得到1个批";
};
break;
case commands::开箱:
c.func = [](::int64_t group, ::int64_t qq, std::vector<std::string> args, std::string raw) -> std::string
{
if (plist.find(qq) == plist.end()) return std::string(CQ_At(qq)) + ",你还没有开通菠菜";
//CQ_setGroupBan(ac, group, qq, 60);
//return "不准开";
std::stringstream ss;
if (plist[qq].keys >= 1)
{
plist[qq].keys--;
modifyKeyCount(qq, plist[qq].keys);
}
else if (plist[qq].currency >= FEE_PER_CASE)
{
auto [enough, stamina, rtime] = updateStamina(qq, 1);
if (!enough)
{
ss << CQ_At(qq) << ",你的体力不足,回满还需"
<< rtime / (60 * 60) << "小时" << rtime / 60 % 60 << "分钟";
return ss.str();
}
plist[qq].currency -= FEE_PER_CASE;
}
else
return std::string(CQ_At(qq)) + ",你的余额不足";
const case_detail& reward = draw_case(randReal());
if (reward > 300) ss << "歪哟," << CQ_At(qq) << "发了,开出了";
else ss << CQ_At(qq) << ",恭喜你开出了";
ss << reward.full() << ",获得" << reward.worth() << "个批";
plist[qq].currency += reward.worth();
if (plist[qq].currency < 0) plist[qq].currency = 0;
modifyCurrency(qq, plist[qq].currency);
modifyBoxCount(qq, ++plist[qq].opened_box_count);
//ss << "你还有" << stamina << "点体力,";
return ss.str();
};
break;
case commands::开箱10:
c.func = [](::int64_t group, ::int64_t qq, std::vector<std::string> args, std::string raw) -> std::string
{
if (plist.find(qq) == plist.end()) return std::string(CQ_At(qq)) + ",你还没有开通菠菜";
//CQ_setGroupBan(ac, group, qq, 60);
//return "不准开";
std::stringstream ss;
if (plist[qq].keys >= 10)
{
plist[qq].keys -= 10;
modifyKeyCount(qq, plist[qq].keys);
}
else if (plist[qq].currency >= FEE_PER_CASE * 10)
{
auto [enough, stamina, rtime] = updateStamina(qq, 10);
if (!enough)
{
ss << CQ_At(qq) << ",你的体力不足,回满还需"
<< rtime / (60 * 60) << "小时" << rtime / 60 % 60 << "分钟";
return ss.str();
}
plist[qq].currency -= FEE_PER_CASE * 10;
}
else
return std::string(CQ_At(qq)) + ",你的余额不足";
std::vector<int> case_counts(CASE_POOL.size() + 1, 0);
int r = 0;
/*
for (size_t i = 0; i < 10; ++i)
{
const case_detail& reward = draw_case(randReal());
case_counts[reward.type_idx()]++;
r += reward.worth();
}
if (r > 300) ss << "歪哟," << CQ_At(qq) << "发了,开出了";
else ss << CQ_At(qq) << ",恭喜你开出了";
for (size_t i = 0; i < case_counts.size(); ++i)
{
if (case_counts[i])
{
ss << case_counts[i] << "个" <<
((i == CASE_POOL.size()) ? CASE_DEFAULT.name() : CASE_POOL[i].name()) << ",";
}
}
ss << "一共" << r << "个批";
*/
ss << CQ_At(qq) << ",恭喜你开出了:\n";
for (size_t i = 0; i < 10; ++i)
{
const case_detail& reward = draw_case(randReal());
case_counts[reward.type_idx()]++;
r += reward.worth();
ss << "- " << reward.full() << " (" << reward.worth() << "批)\n";
}
ss << "上面有";
for (size_t i = 0; i < case_counts.size(); ++i)
{
if (case_counts[i])
{
ss << case_counts[i] << "个" <<
((i == CASE_POOL.size()) ? CASE_DEFAULT.name() : CASE_POOL[i].name()) << ",";
}
}
ss << "一共" << r << "个批";
plist[qq].currency += r;
if (plist[qq].currency < 0) plist[qq].currency = 0;
plist[qq].opened_box_count += 10;
modifyCurrency(qq, plist[qq].currency);
modifyBoxCount(qq, plist[qq].opened_box_count);
return ss.str();
};
break;
case commands::开红箱:
c.func = [](::int64_t group, ::int64_t qq, std::vector<std::string> args, std::string raw) -> std::string
{
if (plist.find(qq) == plist.end()) return std::string(CQ_At(qq)) + ",你还没有开通菠菜";
//CQ_setGroupBan(ac, group, qq, 60);
//return "不准开";
if (plist[qq].currency < COST_OPEN_RED)
return std::string(CQ_At(qq)) + ",你的余额不足";
auto[enough, stamina, rtime] = updateStamina(qq, COST_OPEN_RED_STAMINA);
std::stringstream ss;
if (!enough) ss << CQ_At(qq) << ",你的体力不足,回满还需"
<< rtime / (60 * 60) << "小时" << rtime / 60 % 60 << "分钟";
else
{
plist[qq].currency -= COST_OPEN_RED;
ss << getCard(group, qq) << "消耗" << COST_OPEN_RED << "个批和" << COST_OPEN_RED_STAMINA <<"点体力发动技能!\n";
std::vector<int> case_counts(CASE_POOL.size() + 1, 0);
int count = 0;
int cost = 0;
int res = 0;
case_detail reward;
do {
++count;
cost += FEE_PER_CASE;
reward = draw_case(randReal());
case_counts[reward.type_idx()]++;
res += reward.worth();
plist[qq].currency += reward.worth() - FEE_PER_CASE;
plist[qq].opened_box_count++;
if (reward.type_idx() == 2)
{
ss << CQ_At(qq) << "开了" << count << "个箱子终于开出了" << reward.full() << " (" << reward.worth() << "批),"
<< "本次净收益" << res - cost - COST_OPEN_RED << "个批";
if (plist[qq].currency < 0) plist[qq].currency = 0;
modifyCurrency(qq, plist[qq].currency);
modifyBoxCount(qq, plist[qq].opened_box_count);
return ss.str();
}
else
if (reward.type_idx() == 1)
{
ss << "歪哟," << CQ_At(qq) << "发了,开了" << count << "个箱子居然开出了" << reward.full() << " (" << reward.worth() << "批),"
<< "本次净收益" << res - cost - COST_OPEN_RED << "个批";
if (plist[qq].currency < 0) plist[qq].currency = 0;
modifyCurrency(qq, plist[qq].currency);
modifyBoxCount(qq, plist[qq].opened_box_count);
return ss.str();
}
} while (plist[qq].currency >= FEE_PER_CASE);
ss << CQ_At(qq) << "破产了,开了" << count << "个箱子也没能开出红箱,"
<< "本次净收益" << res - cost - COST_OPEN_RED << "个批";
if (plist[qq].currency < 0) plist[qq].currency = 0;
modifyCurrency(qq, plist[qq].currency);
modifyBoxCount(qq, ++plist[qq].opened_box_count);
return ss.str();
//ss << "你还有" << stamina << "点体力,";
}
return ss.str();
};
break;
case commands::开黄箱:
c.func = [](::int64_t group, ::int64_t qq, std::vector<std::string> args, std::string raw) -> std::string
{
if (plist.find(qq) == plist.end()) return std::string(CQ_At(qq)) + ",你还没有开通菠菜";
//CQ_setGroupBan(ac, group, qq, 60);
//return "不准开";
if (plist[qq].currency < COST_OPEN_YELLOW)
return std::string(CQ_At(qq)) + ",你的余额不足";
auto[enough, stamina, rtime] = updateStamina(qq, MAX_STAMINA);
std::stringstream ss;
if (!enough) ss << CQ_At(qq) << ",你的体力不足,回满还需"
<< rtime / (60 * 60) << "小时" << rtime / 60 % 60 << "分钟";
else
{
plist[qq].currency -= COST_OPEN_YELLOW;
ss << getCard(group, qq) << "消耗" << COST_OPEN_YELLOW << "个批和全部体力发动技能!\n";
std::vector<int> case_counts(CASE_POOL.size() + 1, 0);
int count = 0;
int cost = 0;
int res = 0;
case_detail reward;
do {
++count;
cost += FEE_PER_CASE;
reward = draw_case(randReal());
case_counts[reward.type_idx()]++;
res += reward.worth();
plist[qq].currency += reward.worth() - FEE_PER_CASE;
plist[qq].opened_box_count++;
if (reward.type_idx() == 1)
{
ss << CQ_At(qq) << "开了" << count << "个箱子终于开出了" << reward.full() << " (" << reward.worth() << "批),"
<< "本次净收益" << res - cost - COST_OPEN_YELLOW << "个批";
if (plist[qq].currency < 0) plist[qq].currency = 0;
modifyCurrency(qq, plist[qq].currency);
modifyBoxCount(qq, plist[qq].opened_box_count);
return ss.str();
}
} while (plist[qq].currency >= FEE_PER_CASE);
ss << CQ_At(qq) << "破产了,开了" << count << "个箱子也没能开出黄箱,"
<< "本次净收益" << res - cost - COST_OPEN_YELLOW << "个批";
if (plist[qq].currency < 0) plist[qq].currency = 0;
modifyCurrency(qq, plist[qq].currency);
modifyBoxCount(qq, plist[qq].opened_box_count);
return ss.str();
//ss << "你还有" << stamina << "点体力,";
}
return ss.str();
};
break;
case commands::开箱endless:
c.func = [](::int64_t group, ::int64_t qq, std::vector<std::string> args, std::string raw) -> std::string
{
return "梭哈台被群主偷了,没得梭了";
};
break;
/*
case commands::开箱endless:
c.func = [](::int64_t group, ::int64_t qq, std::vector<std::string> args, std::string raw) -> std::string
{
if (plist.find(qq) == plist.end()) return std::string(CQ_At(qq)) + ",你还没有开通菠菜";
//CQ_setGroupBan(ac, group, qq, 60);
//return "不准开";
if (plist[qq].currency < COST_OPEN_ENDLESS)
return std::string(CQ_At(qq)) + ",你的余额不足";
auto [enough, stamina, rtime] = updateStamina(qq, COST_OPEN_ENDLESS_STAMINA);
std::stringstream ss;
if (!enough) ss << CQ_At(qq) << ",你的体力不足,回满还需"
<< rtime / (60 * 60) << "小时" << rtime / 60 % 60 << "分钟";
else
{
plist[qq].currency -= COST_OPEN_ENDLESS;
long long total_cases = plist[qq].currency / FEE_PER_CASE;
plist[qq].currency %= FEE_PER_CASE;
long long extra_cost = 0.1 * total_cases * FEE_PER_CASE;
total_cases -= long long(std::floor(total_cases * 0.1));
ss << getCard(group, qq) << "消耗" << COST_OPEN_ENDLESS + extra_cost << "个批和" << COST_OPEN_ENDLESS_STAMINA << "点体力发动技能!\n";
std::vector<int> case_counts(CASE_POOL.size() + 1, 0);
int count = 0;
int cost = 0;
int res = 0;
case_detail max;
case_detail reward;
do {
++count;
cost += FEE_PER_CASE;
reward = draw_case(randReal());
case_counts[reward.type_idx()]++;
res += reward.worth();
plist[qq].currency += reward.worth();
plist[qq].opened_box_count++;
if (max.worth() < reward.worth()) max = reward;
} while (--total_cases > 0);
ss << CQ_At(qq) << "本次梭哈开了" << count << "个箱子,开出了" << case_counts[1] << "个黄箱," << case_counts[2] << "个红箱," << case_counts[0] << "个黑箱,\n"
<< "最值钱的是" << max.full() << " (" << max.worth() << "批),"
<< "本次净收益" << res - cost - COST_OPEN_ENDLESS - extra_cost << "个批";
if (plist[qq].currency < 0) plist[qq].currency = 0;
modifyCurrency(qq, plist[qq].currency);
modifyBoxCount(qq, plist[qq].opened_box_count);
return ss.str();
//ss << "你还有" << stamina << "点体力,";
}
return ss.str();
};
break;
*/
default: break;
}
return c;
}
command smokeIndicator(const char* msg)
{
if (msg == nullptr) return command();
std::stringstream ss(msg);
std::vector<std::string> query;
while (ss)
{
std::string s;
ss >> s;
if (!s.empty())
query.push_back(s);
}
if (query.empty()) return command();
auto cmd = query[0];
if (cmd.length() <= 4) return command();
if (cmd.substr(0, 4) != "禁烟" && cmd.substr(0, 4) != "禁言") return command();
command c;
c.args = query;
c.func = [](::int64_t group, ::int64_t qq, std::vector<std::string> args, std::string raw)->std::string
{
if (args.size() == 1)
{
return "";
}
auto cmd = args[0];
std::string targetName = cmd.substr(4);
int64_t target = 0;
// @
if (int64_t tmp; tmp = stripAt(targetName))
{
target = tmp;
}
// qqid_str
else if (qqid_str.find(targetName) != qqid_str.end())
target = qqid_str[targetName];
// nick, card
else
if (grp::groups.find(group) != grp::groups.end())
{
if (int64_t qq = grp::groups[group].getMember(targetName.c_str()); qq != 0)
target = qq;
}
int64_t cost = -1;
try {
cost = std::stoll(args[1]);
}
catch (std::exception&) {
//ignore
}
return nosmokingWrapper(qq, group, target, cost);
};
return c;
}
void peeCreateTable()
{
if (db.exec(
"CREATE TABLE IF NOT EXISTS pee( \
qqid INTEGER PRIMARY KEY NOT NULL, \
currency INTEGER NOT NULL, \
cases INTEGER NOT NULL, \
dailytime INTEGER NOT NULL, \
keys INTEGER NOT NULL \
)") != SQLITE_OK)
CQ_addLog(ac, CQLOG_ERROR, "pee", db.errmsg());
}
void peeLoadFromDb()
{
auto list = db.query("SELECT * FROM pee", 5);
for (auto& row : list)
{
int64_t qq = std::any_cast<int64_t>(row[0]);
int64_t p1, p2, p4;
time_t p3;
p1 = std::any_cast<int64_t>(row[1]);
p2 = std::any_cast<int64_t>(row[2]);
p3 = std::any_cast<time_t> (row[3]);
p4 = std::any_cast<int64_t>(row[4]);
plist[qq] = { p1, p2, p3, p4 };
plist[qq].freeze_assets_expire_time = INT64_MAX;
}
char msg[128];
sprintf(msg, "added %u users", plist.size());
CQ_addLog(ac, CQLOG_DEBUG, "pee", msg);
}
const double UNSMOKE_COST_RATIO = 3;
std::string unsmoke(int64_t qq)
{
if (smokeGroups.find(qq) == smokeGroups.end() || smokeGroups[qq].empty())
return "你么得被烟啊";
if (plist.find(qq) == plist.end()) return "你还没有开通菠菜";
time_t t = time(nullptr);
int total_remain = 0;
for (auto& g : smokeGroups[qq])
{
if (t <= g.second)
{
int remain = (g.second - t) / 60; // min
int extra = (g.second - t) % 60; // sec
total_remain += remain + !!extra;
}
}
std::stringstream ss;
ss << "你在" << smokeGroups[qq].size() << "个群被烟" << total_remain << "分钟,";
int total_cost = total_remain * UNSMOKE_COST_RATIO;
if (plist[qq].currency < total_cost)
{
ss << "你批不够,需要" << total_cost << "个批,哈";
}
else
{
plist[qq].currency -= total_cost;
ss << "本次接近消费" << total_cost << "个批";
modifyCurrency(qq, plist[qq].currency);
for (auto& g : smokeGroups[qq])
{
if (t > g.second) continue;
std::string qqname = getCard(g.first, qq);
CQ_setGroupBan(ac, g.first, qq, 0);
std::stringstream sg;
int remain = (g.second - t) / 60; // min
int extra = (g.second - t) % 60; // sec
sg << qqname << "花费巨资" << (long long)std::round((remain + !!extra) * UNSMOKE_COST_RATIO) << "个批申请接近成功";
CQ_sendGroupMsg(ac, g.first, sg.str().c_str());
}
smokeGroups[qq].clear();
}
return ss.str();
}
void flushDailyTimep(bool autotriggered)
{
daily_refresh_time = time(nullptr);
daily_refresh_tm = getLocalTime(TIMEZONE_HR, TIMEZONE_MIN);
if (autotriggered) daily_refresh_tm_auto = daily_refresh_tm;
remain_daily_bonus = DAILY_BONUS + extra_tomorrow;
extra_tomorrow = 0;
broadcastMsg("每日批池刷新了;额", grp::Group::MASK_FLIPCOIN | grp::Group::MASK_ROULETTE | grp::Group::MASK_MONOPOLY);
CQ_addLog(ac, CQLOG_DEBUG, "pee", std::to_string(daily_refresh_time).c_str());
}
const case_detail& draw_case(double p)
{
size_t idx = 0;
if (p >= 0.0 && p <= 1.0)
{
double totalp = 0;
for (const auto& c : CASE_POOL)
{
if (p <= totalp + c.prob()) break;
++idx;
totalp += c.prob();
}
// idx = CASE_POOL.size() if not match any case
}
size_t detail_idx = randInt(0, CASE_DETAILS[idx].size() - 1);
return CASE_DETAILS[idx][detail_idx];
}
}
|
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include "opencv2/core/core.hpp"
#include <algorithm>
#include <math.h>
using namespace cv;
using namespace std;
int main()
{
int x = 0, y = 0, n;
Mat img = imread("C:\\Users\\ariji\\Desktop\\Extra\\image.jpg", 0);
Mat img1;
namedWindow("Original", WINDOW_AUTOSIZE);
namedWindow("Canny", WINDOW_AUTOSIZE);
createTrackbar("Low_Th", "Canny", &x, 1000);
createTrackbar("High_Th", "Canny", &y, 1000);
while (1)
{
Canny(img, img1, x, y, 3);
imshow("Original", img);
imshow("Canny", img1);
n = waitKey(50);
if (n == (int)'e')
break;
}
return 0;
}
|
#ifndef OBSERVE_LOOP_TREE
#define OBSERVE_LOOP_TREE
#include <DepRel.h>
#include <ObserveObject.h>
#include <SymbolicBound.h>
class LoopTreeNode;
class BlockLoopInfo ;
class MergeLoopInfo ;
class DistNodeInfo ;
class SwapNodeInfo ;
class InsertLoopInfo;
class MergeStmtLoopInfo ;
class SwapStmtLoopInfo;
class DeleteStmtLoopInfo;
class InsertStmtLoopInfo;
class SplitStmtInfo;
class SplitStmtInfo2;
class LoopTreeCodeGenInfo;
class LoopTreeObserver
{
LoopTreeObserver *next;
public:
LoopTreeObserver( LoopTreeObserver *n = 0) { next = n; }
virtual ~LoopTreeObserver() {}
virtual void UpdateBlockLoop(const BlockLoopInfo &info)
{ if (next != 0) next->UpdateBlockLoop( info ); }
virtual void UpdateMergeLoop(const MergeLoopInfo &info)
{ if (next != 0) next->UpdateMergeLoop( info ); }
virtual void UpdateDistNode(const DistNodeInfo &info)
{ if (next != 0) next->UpdateDistNode( info ); }
virtual void UpdateSwapNode( const SwapNodeInfo &info)
{ if (next != 0) next->UpdateSwapNode( info ); }
virtual void UpdateCodeGen(const LoopTreeCodeGenInfo& info)
{ if (next != 0) next->UpdateCodeGen( info ); }
virtual void UpdateSplitStmt( const SplitStmtInfo &info)
{ if (next != 0) next->UpdateSplitStmt( info ); }
virtual void UpdateSplitStmt2( const SplitStmtInfo2 &info)
{ if (next != 0) next->UpdateSplitStmt2( info ); }
virtual void UpdateMergeStmtLoop( const MergeStmtLoopInfo &info)
{ if (next != 0) next->UpdateMergeStmtLoop( info ); }
virtual void UpdateInsertLoop( const InsertLoopInfo &info)
{ if (next != 0) next->UpdateInsertLoop(info); }
virtual void UpdateInsertStmtLoop( const InsertStmtLoopInfo &info)
{ if (next != 0) next->UpdateInsertStmtLoop(info); }
virtual void UpdateDeleteStmtLoop( const DeleteStmtLoopInfo &info)
{ if (next != 0) next->UpdateDeleteStmtLoop(info); }
virtual void UpdateSwapStmtLoop( const SwapStmtLoopInfo &info)
{ if (next != 0) next->UpdateSwapStmtLoop(info); }
virtual void UpdateDeleteNode( const LoopTreeNode *n )
{ if (next != 0) next->UpdateDeleteNode( n ); }
virtual void write(std::ostream& out) const {}
};
class LoopTreeObserveInfo : public ObserveInfo<LoopTreeObserver>
{
const LoopTreeNode *orig;
protected:
LoopTreeObserveInfo( const LoopTreeNode *n ) { orig = n; }
public:
virtual ~LoopTreeObserveInfo() {}
const LoopTreeNode * GetObserveNode() const { return orig; }
};
class LoopTreeCodeGenInfo : public LoopTreeObserveInfo
{
AstNodePtr res;
public:
LoopTreeCodeGenInfo( const LoopTreeNode *n, const AstNodePtr& _res)
: LoopTreeObserveInfo(n), res(_res) {}
virtual ~LoopTreeCodeGenInfo() {}
virtual void UpdateObserver( LoopTreeObserver &o) const
{ o.UpdateCodeGen( *this ); }
AstNodePtr GetAST() const { return res; }
};
class DeleteNodeInfo : public LoopTreeObserveInfo
{
public:
DeleteNodeInfo( LoopTreeNode *n) : LoopTreeObserveInfo(n) {}
virtual ~DeleteNodeInfo() {}
virtual void UpdateObserver( LoopTreeObserver &o) const
{ o.UpdateDeleteNode( GetObserveNode() ); }
};
class DistNodeInfo : public LoopTreeObserveInfo
{
protected:
LoopTreeNode *newNode;
public:
DistNodeInfo( LoopTreeNode *o, LoopTreeNode *n)
: LoopTreeObserveInfo(o) { newNode = n; }
virtual ~DistNodeInfo() {}
LoopTreeNode * GetNewNode() const { return newNode; }
virtual void UpdateObserver(LoopTreeObserver &o) const
{ o.UpdateDistNode( *this ); }
};
class BlockLoopInfo : public LoopTreeObserveInfo
{
protected:
SymbolicVal blocksize;
public:
BlockLoopInfo( LoopTreeNode *o, const SymbolicVal& bsize)
: LoopTreeObserveInfo( o), blocksize(bsize) {}
virtual ~BlockLoopInfo() {}
SymbolicVal GetBlockSize() const { return blocksize; }
virtual void UpdateObserver(LoopTreeObserver &o) const
{ o.UpdateBlockLoop( *this ); }
};
class MergeLoopInfo : public LoopTreeObserveInfo
{
protected:
LoopTreeNode *newLoop;
int align;
public:
MergeLoopInfo( LoopTreeNode *o, LoopTreeNode *n,
int a)
: LoopTreeObserveInfo( o) { newLoop = n; align = a; }
virtual ~MergeLoopInfo() {}
LoopTreeNode * GetNewLoop() const { return newLoop; }
int GetMergeAlign() const { return align; }
virtual void UpdateObserver(LoopTreeObserver &o) const
{ o.UpdateMergeLoop( *this ); }
};
class MergeStmtLoopInfo : public LoopTreeObserveInfo
{
int align, loop1, loop2;
public:
MergeStmtLoopInfo( LoopTreeNode *stmt, int l1, int l2, int _align)
: LoopTreeObserveInfo( stmt ) { loop1 = l1; loop2 = l2; align = _align; }
virtual ~MergeStmtLoopInfo() {}
int GetLoop1() const { return loop1; }
int GetLoop2() const { return loop2; }
int GetMergeAlign() const { return align; }
virtual void UpdateObserver( LoopTreeObserver &o) const
{ o.UpdateMergeStmtLoop( *this ); }
};
class InsertStmtLoopInfo : public LoopTreeObserveInfo
{
int loop;
public:
InsertStmtLoopInfo( LoopTreeNode *s, int level)
: LoopTreeObserveInfo( s ), loop(level) {}
virtual ~InsertStmtLoopInfo() {}
int GetLoop() const { return loop; }
virtual void UpdateObserver( LoopTreeObserver &o) const
{ o.UpdateInsertStmtLoop( *this ); }
};
class InsertLoopInfo : public LoopTreeObserveInfo
{
public:
InsertLoopInfo( LoopTreeNode *l)
: LoopTreeObserveInfo( l ) {}
virtual ~InsertLoopInfo() {}
virtual void UpdateObserver( LoopTreeObserver &o) const
{ o.UpdateInsertLoop( *this ); }
};
class DeleteStmtLoopInfo : public LoopTreeObserveInfo
{
int loop;
public:
DeleteStmtLoopInfo( LoopTreeNode *s, int l)
: LoopTreeObserveInfo( s ), loop(l) {}
virtual ~DeleteStmtLoopInfo() {}
int GetLoop() const { return loop; }
virtual void UpdateObserver( LoopTreeObserver &o) const
{ o.UpdateDeleteStmtLoop( *this ); }
};
class SwapStmtLoopInfo : public LoopTreeObserveInfo
{
int index1, index2;
public:
SwapStmtLoopInfo( LoopTreeNode *s, int i1, int i2)
: LoopTreeObserveInfo( s ),index1(i1),index2(i2) {}
virtual ~SwapStmtLoopInfo() {}
int GetLoop1() const { return index1; }
int GetLoop2() const { return index2; }
virtual void UpdateObserver( LoopTreeObserver &o) const
{ o.UpdateSwapStmtLoop( *this ); }
};
class SwapNodeInfo : public LoopTreeObserveInfo
{
int direction;
LoopTreeNode *othernode;
VarInfo varinfo;
public:
SwapNodeInfo( LoopTreeNode *o, LoopTreeNode *other, int dir,
const VarInfo& v)
: LoopTreeObserveInfo( o ), direction(dir), othernode(other),
varinfo(v) {}
virtual ~SwapNodeInfo() {}
int GetDirection() const { return direction; }
LoopTreeNode* GetOtherNode() const { return othernode; }
VarInfo GetVarInfo() const { return varinfo; }
virtual void UpdateObserver( LoopTreeObserver &o) const
{ o.UpdateSwapNode( *this ); }
};
class SplitStmtInfo : public LoopTreeObserveInfo
{
LoopTreeNode* splitstmt;
int loop1, loop2;
DepRel rel;
public:
SplitStmtInfo( LoopTreeNode *stmt, LoopTreeNode *n,
int l1, int l2, const DepRel& r)
: LoopTreeObserveInfo(stmt),splitstmt(n),loop1(l1),loop2(l2),rel(r) {}
virtual ~SplitStmtInfo() {}
LoopTreeNode * GetSplitStmt() const { return splitstmt; }
int GetLoop1() const { return loop1; }
int GetLoop2() const { return loop2; }
DepRel GetRel() const { return rel; }
virtual void UpdateObserver( LoopTreeObserver &o) const
{ o.UpdateSplitStmt( *this ); }
};
class SplitStmtInfo2 : public LoopTreeObserveInfo
{
LoopTreeNode* splitstmt;
int loop;
SymbolicVal le;
public:
SplitStmtInfo2( LoopTreeNode *stmt, LoopTreeNode* n, int l, const SymbolicVal& mid)
: LoopTreeObserveInfo(stmt),splitstmt(n),loop(l),le(mid) {}
virtual ~SplitStmtInfo2() {}
LoopTreeNode * GetSplitStmt() const { return splitstmt; }
int GetLoop() const { return loop; }
SymbolicVal GetLE() const { return le; }
virtual void UpdateObserver( LoopTreeObserver &o) const
{ o.UpdateSplitStmt2( *this ); }
};
#endif
|
#include <iostream>
#include <conio.h>
#define _WIN32_WINNT 0x0500
#include<windows.h>
#include <string>
#include "Design.h"
using namespace std;
bool recaptcha(string u, string p)
{
char temp1[100],temp2[100];
int a;
FILE *fp_userpass = fopen("../userpass.txt","w");
while (fscanf(fp_userpass, "%s\t%s", temp1, temp2)+1)
{
if (temp1 == u && temp2 == p)
return 1;
}
return 0;
}
void login(int length, int with)
{
system("cls");
background(31);
border(length, with);
string u, p;
//================================== Username ==================================
gotoxy((columns - length) / 2 + 1, rows / 2 + 1);
cout << " Password: ";
gotoxy((columns - length) / 2 + 1, rows / 2 - 1);
cout << " Username: ";
char ch;
while (1)
{
ch = _getch();
if (ch == 13) break;
if (u.length() == length - 13 && ch != 8) continue;
if (ch == 8)
{
if (u.length() == 0) continue;
cout << '\b' << " " << '\b';
u.erase(u.end() - 1);
}
else
{
u += ch;
cout << ch;
}
}
//================================== Password ==================================
gotoxy((columns - length) / 2 + 12, rows / 2 + 1);
while (1)
{
ch = _getch();
if (ch == 13) break;
if (p.length() == length - 13 && ch != 8) continue;
if (ch == 8)
{
if (p.length() == 0) continue;
cout << '\b' << " " << '\b';
p.erase(p.end() - 1);
}
else
{
cout << '*';
p += ch;
}
}
//==================================== Check =====================================
int check = 0;//recaptcha(u, p);
gotoxy(0, 0);
if (check == 1)
{
background(160);
gotoxy(columns / 2 - 11, rows / 2);
cout << "Welcome to your panel";
Sleep(1000);
login(32, 5);
}
else
{
background(79);
gotoxy(columns / 2 - 7, rows / 2);
cout << "Access Denied";
Sleep(1000);
login(32,5);
}
}
void welcome()
{
background(31);
system("cls");
gotoxy(columns / 2 - 12, rows / 2 - 1);
char s[25] = "Welcome to MAPSH ticket.";
for (int i = 0; i < 24; i++)
{
cout << s[i];
Sleep(50);
}
gotoxy(columns / 2 - 39, rows / 2);
char str[78] = "to sign in press \"S\", to sign up press \"U\" and for using as guest press \"G\".\n";
for (int i = 0; i < 78; i++)
{
cout << str[i];
Sleep(50);
}
char c;
c = _getche();
if (c == 's' || c == 'S') login(32, 5);
else if (c == 'u' || c == 'U');
else if (c == 'g' || c == 'G');
else;
}
inline void process(int time, int color, int n, int i)
{
Sleep(time);
gotoxy((columns - n) / 2 + i, rows / 2);
print(char(219), color);
Sleep(time);
gotoxy(columns / 2 - 5, rows / 2 - 2);
}
void loading(int time, int processcolor, int backcolor, int n)
{
background(backcolor);
gotoxy(columns / 2 - 4, rows / 2 - 2);
cout << " Loading\n";
border(n + 2, 1);
for (int i = 0; i < n;)
{
process(time, processcolor, n, i);
i++;
if (i > n) break;
process(time, processcolor, n, i);
i++;
if (i > n) break;
print("|", backcolor);
process(time, processcolor, n, i);
i++;
if (i > n) break;
process(time, processcolor, n, i);
i++;
if (i > n) break;
print("/", backcolor);
process(time, processcolor, n, i);
i++;
if (i > n) break;
process(time, processcolor, n, i);
i++;
if (i > n) break;
print("-", backcolor);
process(time, processcolor, n, i);
i++;
if (i > n) break;
process(time, processcolor, n, i);
i++;
if (i > n) break;
print("\\", backcolor);
}
gotoxy(0, 0);
Sleep(200);
}
void pnl_drivers(string user)
{
background(31);
long int ID2;
char name[50], family[50], usern[50], username[50], passw[50], phonenum[50], vehicle[50];
int n, t, t2;
char temp[5000];
for (int i = 0; i < user.length(); i++)
{
username[i] = user[i];
}
username[user.length()] = 0;
FILE *AAIP = fopen("../All account information.txt", "r");
while (1 + fscanf(AAIP, "%d\t%s\t%s\n", &ID2, usern, passw))
{
if (!strcmp(usern, username))
break;
}
FILE *DTP = fopen("../Drivers travels.txt", "r");
while (1)
{
fscanf(DTP, "%d\t%d\n", &t, &n);
if (t == ID2) break;
for (int i = 0; i < n; i++)
{
fgets(temp, 4999, DTP);
fgets(temp, 4999, DTP);
}
}
long int ID;
fclose(AAIP);
AAIP = fopen("../All account information.txt","r");
FILE *DIP = fopen("../Drivers information.txt", "r");
while (1 + fscanf(AAIP, "%d\t%s\t%s\n", &ID, usern, passw))
{
if (!strcmp(usern, username))
break;
}
while (1 + fscanf(DIP, "%d\t%s\t%s\t%s\t%s", &t, name, family,phonenum,vehicle))
{
if (t==ID)
break;
}
gotoxy((columns - 60) / 2 + 1, (rows - 2 * n - 1) / 2 - 2);
cout << "Hi " << name << " " << family;
border(60, 2 * n + 1);
gotoxy((columns - 60) / 2 + 1, (rows - 2 * n - 1) / 2 + 1);
cout << "Your travels:\n";
char s[5000];
fclose(DTP);
DTP=fopen("../Drivers travels.txt", "r");
while (1 + fscanf(DTP, "%d\t%d\n", &t,&t2))
{
if (t == ID)
{
for (int i = 0; i < n; i++)
{
gotoxy((columns - 60) / 2 + 1, (rows - 2 * n - 1) / 2 + 3 + 2 * i);
fgets(s, 50, DTP);
cout << s << endl;
fgets(s, 50, DTP);
}
}
for (int i = 0; i < t2; i++)
{
fgets(s, 4999, DTP);
fgets(s, 4999, DTP);
}
}
gotoxy((columns - 60) / 2 + 1, (rows + 2 * n + 1) / 2 + 3);
cout << "To show your history press \"S\"\tTo show your info press \"I\"";
gotoxy((columns - 60) / 2 + 1, (rows + 2 * n + 1) / 2 + 4);
cout << "To change your info press \"T\"\tTo define your new travel, press \"N\"";
gotoxy((columns - 60) / 2 + 1, (rows + 2 * n + 1) / 2 + 5);
cout << "To change your travel press \"M\"\tTo cncel your travel, press \"L\"";
gotoxy((columns - 60) / 2 + 1, (rows + 2 * n + 1) / 2 + 6);
cout << "To go back press Ctrl+B\t\tTo go home press Ctrl+H";
gotoxy((columns - 60) / 2 + 1, (rows + 2 * n + 1) / 2 + 7);
cout << "To show details of travels press \"D\"";
cin >> n;
}
int main()
{
fullscreen();
screensize();
pnl_drivers("mp64");
/*loading(50, 250, 31, 50);
welcome();
gotoxy(0, rows);*/
}
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <functionstree.h>
#include <bintree.h>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
scene = new QGraphicsScene;
ui->graphicsView->setScene(scene);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_onPrint_clicked()
{
QString rinput = ui->lineEdit->text();
QString input = delSpace(rinput);
if (input != ""){
if (input[0] != '(' || input[input.size() - 1] != ')'){
QMessageBox::critical(this, "Error!", "Дерево введенно некорректно");
return;
}
}
else {
QMessageBox::critical(this, "Error!", "Введите дерево");
return;
}
BinTree* BT = new (BinTree);
BT->Head = BT->createTree(mySplit(input));
QString out;
out.append("Глубина дерева: ");
int depth = BT->max_depth(BT->Head);
out.append(QString::number(depth - 1));
ui->label->setText(out);
graphic(BT, scene,depth);
}
void MainWindow::on_onLeavesonLevel_clicked()
{
QString rinput = ui->lineEdit->text();
QString level_i = ui->lineEdit_2->text();
int level = level_i.toInt();
QString input = delSpace(rinput);
if (input != ""){
}
else {
QMessageBox::critical(this, "Error!", "Введите дерево");
return;
}
BinTree* BT = new (BinTree);
BT->Head = BT->createTree(mySplit(input));
QString out;
out.append("Количество узлов: ");
int count = BT->count_node(BT->Head,level, 1, 0);
out.append(QString::number(count));
ui->label->setText(out);
}
void MainWindow::on_on_file_clicked()
{
QString file_name = QFileDialog().getOpenFileName();
if(!file_name.isNull()){
QFile file(file_name);
if(file.open(file.ReadOnly)){
QString data = file.readAll();
QString input = delSpace(data);
if (input == "") {
QMessageBox::critical(this, "Error!", "Введите дерево");
return;
}
else{
if (input[0] != '(' || input[input.size() - 1] != ')'){
QMessageBox::critical(this, "Error!", "Дерево введенно некорректно");
return;
}
else{
BinTree* BT = new (BinTree);
BT->Head = BT->createTree(mySplit(input));
QString out;
out.append("Глубина дерева: ");
int depth = BT->max_depth(BT->Head);
out.append(QString::number(depth - 1));
ui->label->setText(out);
graphic(BT, scene,depth);
}
}
}
}
else QMessageBox::warning(this,"Error", "Not Found");
}
|
#include "span/Sleep.hh"
#include "span/Common.hh"
#include "span/exceptions/Assert.hh"
#include "span/fibers/Fiber.hh"
#include "span/fibers/Scheduler.hh"
#include "span/Timer.hh"
namespace span {
static void scheduleMe(fibers::Scheduler *scheduler, fibers::Fiber::ptr fiber) {
scheduler->schedule(fiber);
}
void sleep(TimerManager *timerManager, uint64 us) {
SPAN_ASSERT(fibers::Scheduler::getThis());
timerManager->registerTimer(us, std::bind(&scheduleMe, fibers::Scheduler::getThis(), fibers::Fiber::getThis()));
fibers::Scheduler::yieldTo();
}
void sleep(uint64 us) {
#if PLATFORM == PLATFORM_WIN32
Sleep(static_cast<DWORD>(us / 1000));
#else
struct timespec ts;
ts.tv_sec = us / 1000000;
ts.tv_nsec = (us % 1000000) * 1000;
while (true) {
if (nanosleep(&ts, &ts) == -1) {
if (errno == EINTR) {
continue;
}
throw std::runtime_error("nanosleep");
}
break;
}
#endif
}
} // namespace span
|
#pragma once
#include <dsnutil/chrono/dsnutil_cpp_chrono_Export.h>
#include <dsnutil/chrono/duration.hpp>
#include <dsnutil/chrono/time_point.hpp>
namespace dsn {
namespace chrono {
class dsnutil_cpp_chrono_EXPORT timer {
protected:
time_point m_point;
public:
time_point point() const;
void reset();
duration elapsed() const;
};
}
}
|
#ifndef __WHISKEY_AST_Predicates_HPP
#define __WHISKEY_AST_Predicates_HPP
#include <whiskey/AST/NodeType.hpp>
namespace whiskey {
enum class Arity {
Unary,
Binary,
NAry
};
bool isAtomicType(NodeType type);
bool isLiteralExpr(NodeType type);
bool isOpExpr(NodeType type);
Arity getExprArity(NodeType type);
}
#endif
|
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
this->setupMenu();
}
void MainWindow::setupMenu()
{
QMenuBar* menuBar = this->menuBar();
menuProfiles = new QMenu("Profils");
menuAPI = new QMenu("API");
QAction *manageProfiles = new QAction("Gérer les profils", this);
QAction *apiRequests = new QAction("Requêtes API", this);
menuProfiles->addAction(manageProfiles);
menuAPI->addAction(apiRequests);
menuBar->addMenu(menuAPI);
menuBar->addMenu(menuProfiles);
// connect(manageProfiles, SIGNAL(triggered()), this, SLOT());
}
MainWindow::~MainWindow()
{
}
|
/* COMP11 Fall 2017
* Homework 6
* Ryan Sheehan
* Signoff by [Leah Stern] [11/16/2017]*/
#ifndef Score_H
#define Score_H
using namespace std;
class Score {
private:
// current score
int total_score;
public:
// constructor
Score();
// show top 5 highscores
void show_highscores();
// sort highscore file
void update_highscores(string name_to_update);
// getters and setters
// get function for returning user score
int get_user_score();
// set function for changing current user score
void set_user_score(int score);
};
#endif
|
#include "framework.h"
#include "node.h"
#include "headers.h"
using namespace std;
using namespace Gdiplus;
extern HWND ghWnd;
extern HDC hMainDC;
extern HDC hBufferDC;
extern HDC hBackBufferDC;
map<string, MapManager::TilesetData> MapManager::tilesetTable;
map<string, Map::MapData> MapManager::mapTable;
Map* MapManager::loadedMap = NULL;
int cellMask[4][4] =
{
{1 << 15, 1 << 14, 1 << 13, 1 << 12},
{1 << 11, 1 << 10, 1 << 9, 1 << 8},
{1 << 7, 1 << 6, 1 << 5, 1 << 4},
{1 << 3, 1 << 2, 1 << 1, 1}
};
MapManager::MapManager()
{
SpriteManager& s = SpriteManager::getInstance();
initMapTable();
initTilesetTable();
wfstream mapDataFile;
}
void MapManager::initMapTable()
{
SpriteManager& s = SpriteManager::getInstance();
int i, j;
vector<wstring> mapList;
GetFiles(mapList, L"Data\\Map", false);
for (i = 0; i < mapList.size(); i++)
{
fstream mapDataFile;
mapDataFile.open(mapList[i]);
if (mapDataFile.is_open())
{
Map::MapData mapData;
fstream tilesetFile;
mapDataFile >> mapData.tilesetName
>> mapData.nx >> mapData.ny;
mapData.cellData[0].resize(mapData.ny);
mapData.cellData[1].resize(mapData.ny);
mapData.cellData[2].resize(mapData.ny);
for (int i = 0; i < mapData.cellData[0].size(); i++)
{
mapData.cellData[0][i].resize(mapData.nx);
mapData.cellData[1][i].resize(mapData.nx);
mapData.cellData[2][i].resize(mapData.nx);
}
for(int i = 0 ; i < mapData.ny ; i++)
for (int j = 0; j < mapData.nx; j++)
{
mapDataFile >> mapData.cellData[0][i][j].x
>> mapData.cellData[0][i][j].y;
}
for (int i = 0; i < mapData.ny; i++)
for (int j = 0; j < mapData.nx; j++)
{
mapDataFile >> mapData.cellData[1][i][j].x
>> mapData.cellData[1][i][j].y;
}
for (int i = 0; i < mapData.ny; i++)
for (int j = 0; j < mapData.nx; j++)
{
mapDataFile >> mapData.cellData[2][i][j].x
>> mapData.cellData[2][i][j].y;
}
string multiByteName;
string subStr;
multiByteName.assign(mapList[i].begin(), mapList[i].end());
for (j = multiByteName.size(); j >= 0 && multiByteName[j] != '\\'; j--);
subStr = multiByteName.c_str() + j + 1;
mapTable.insert(pair<string, Map::MapData>(subStr, mapData));
mapDataFile.close();
}
}
}
void MapManager::initTilesetTable()
{
SpriteManager& s = SpriteManager::getInstance();
int i, j;
vector<wstring> tilesetList;
GetFiles(tilesetList, L"Data\\Tilesets", false);
for (i = 0; i < tilesetList.size(); i++)
{
fstream tilesetDataFile;
tilesetDataFile.open(tilesetList[i]);
if (tilesetDataFile.is_open())
{
TilesetData tilesetData;
fstream tilesetFile;
tilesetDataFile >> tilesetData.spriteName
>> tilesetData.nx >> tilesetData.ny;
char autotileName[512];
stringstream wss;
int stringSize, autotileCount = 0;
tilesetDataFile.get();
tilesetDataFile.getline(autotileName, 512);
wss << autotileName;
stringSize = strlen(autotileName);
while (wss.tellg() < stringSize - 1)
{
int i = 0;
wss >> autotileName;
tilesetData.autotile[autotileCount].ID = POINT({ autotileCount + 1, 0 });
for (i = strlen(autotileName) - 1; i >= 0 && autotileName[i] != '/' && autotileName[i] != '\\'; i--);
tilesetData.autotile[autotileCount++].name = autotileName + i + 1;
}
tilesetData.cellData.resize(tilesetData.ny);
for (int i = 0; i < tilesetData.cellData.size(); i++)
tilesetData.cellData[i].resize(tilesetData.nx);
for (int i = 0; i < tilesetData.ny; i++)
for (int j = 0; j < tilesetData.nx; j++)
{
tilesetDataFile >> tilesetData.cellData[i][j];
}
string multiByteName;
string subStr;
multiByteName.assign(tilesetList[i].begin(), tilesetList[i].end());
for (j = multiByteName.size(); j >= 0 && multiByteName[j] != '\\'; j--);
subStr = multiByteName.c_str() + j + 1;
tilesetTable.insert(pair<string, TilesetData>(subStr, tilesetData));
tilesetDataFile.close();
}
}
}
void MapManager::drawUnitTile(Graphics & g, string mapName, int layer, POINT & srcPoint, Rect & dest)
{
if (srcPoint.y)
{
SpriteManager& sm = SpriteManager::getInstance();
Image* srcImg = sm.getTilesetSprite(tilesetTable[mapTable[mapName].tilesetName].spriteName);
g.DrawImage(
srcImg,
dest,
srcPoint.x * TILE_PIXEL,
(srcPoint.y - 1) * TILE_PIXEL,
TILE_PIXEL, TILE_PIXEL,
UnitPixel );
}
else
{
if (srcPoint.x)
{
tilesetTable[mapTable[mapName].tilesetName].autotile[srcPoint.x - 1].draw(g, layer, dest, mapName);
}
}
}
Map* MapManager::loadMap(string mapName)
{
Bitmap* layer[3];
Bitmap* grid;
string tilesetName = mapTable[mapName].tilesetName;
layer[0] = new Bitmap(mapTable[mapName].nx * TILE_PIXEL,
mapTable[mapName].ny* TILE_PIXEL, PixelFormat32bppARGB);
layer[1] = new Bitmap(mapTable[mapName].nx * TILE_PIXEL,
mapTable[mapName].ny* TILE_PIXEL, PixelFormat32bppARGB);
layer[2] = new Bitmap(mapTable[mapName].nx * TILE_PIXEL,
mapTable[mapName].ny* TILE_PIXEL, PixelFormat32bppARGB);
grid = new Bitmap(mapTable[mapName].nx * TILE_PIXEL,
mapTable[mapName].ny* TILE_PIXEL, PixelFormat32bppARGB);
const TilesetData& tilesetData = tilesetTable[mapTable[mapName].tilesetName];
SpriteManager& sm = SpriteManager::getInstance();
Image* tilesetImg = sm.getTilesetSprite(tilesetTable[tilesetName].spriteName);
Rect drawDest = { 0, 0, TILE_PIXEL, TILE_PIXEL };
Graphics canvas0(layer[0]);
Graphics canvas1(layer[1]);
Graphics canvas2(layer[2]);
Graphics g(grid);
Pen gridPen(Color(255, 0, 0), 3);
Pen cellPen(Color(0, 0, 255), 1);
Map* loadedMap = new Map(mapName, layer[0], layer[1], layer[2], grid);
loadedMap->blockMap.resize(mapTable[mapName].ny);
for (int i = 0; i < loadedMap->blockMap.size(); i++)
loadedMap->blockMap[i].resize(mapTable[mapName].nx);
loadedMap->objectMap = loadedMap->blockMap;
for (int i = 0; i < mapTable[mapName].ny; i++)
{
for (int j = 0; j < mapTable[mapName].nx; j++)
{
drawDest.X = j * TILE_PIXEL;
drawDest.Y = i * TILE_PIXEL;
drawUnitTile(canvas0, mapName, 0, mapTable[mapName].cellData[0][i][j], drawDest);
loadedMap->blockMap[i][j] = tilesetData.cellData[mapTable[mapName].cellData[0][i][j].y][mapTable[mapName].cellData[0][i][j].x];
drawUnitTile(canvas1, mapName, 1, mapTable[mapName].cellData[1][i][j], drawDest);
if (mapTable[mapName].cellData[1][i][j] != POINT({0, 0}))
loadedMap->blockMap[i][j] = tilesetData.cellData[mapTable[mapName].cellData[1][i][j].y][mapTable[mapName].cellData[1][i][j].x];
drawUnitTile(canvas2, mapName, 2, mapTable[mapName].cellData[2][i][j], drawDest);
if (mapTable[mapName].cellData[2][i][j] != POINT({ 0, 0 }))
loadedMap->blockMap[i][j] = tilesetData.cellData[mapTable[mapName].cellData[2][i][j].y][mapTable[mapName].cellData[2][i][j].x];
/*
g.DrawLine(&gridPen, Point(j * TILE_PIXEL, 0), Point(j*TILE_PIXEL,
mapTable[mapName].ny * TILE_PIXEL));
g.DrawLine(&cellPen, Point(j * TILE_PIXEL + 8, 0), Point(j*TILE_PIXEL + 8,
mapTable[mapName].ny * TILE_PIXEL));
g.DrawLine(&cellPen, Point(j * TILE_PIXEL + 16, 0), Point(j*TILE_PIXEL + 16,
mapTable[mapName].ny * TILE_PIXEL));
g.DrawLine(&cellPen, Point(j * TILE_PIXEL + 24, 0), Point(j*TILE_PIXEL + 24,
mapTable[mapName].ny * TILE_PIXEL));*/
}/*
g.DrawLine(&gridPen, Point(0, i * TILE_PIXEL), Point(mapTable[mapName].nx * TILE_PIXEL,
i*TILE_PIXEL));
g.DrawLine(&cellPen, Point(0, i * TILE_PIXEL + 8), Point(mapTable[mapName].nx * TILE_PIXEL,
i*TILE_PIXEL + 8));
g.DrawLine(&cellPen, Point(0, i * TILE_PIXEL + 16), Point(mapTable[mapName].nx * TILE_PIXEL,
i*TILE_PIXEL + 16));
g.DrawLine(&cellPen, Point(0, i * TILE_PIXEL + 24), Point(mapTable[mapName].nx * TILE_PIXEL,
i*TILE_PIXEL + 24));*/
}
MapManager::loadedMap = loadedMap;
return loadedMap;
}
Map::Map(string name, Bitmap * l1, Bitmap * l2, Bitmap * l3, Bitmap * grid) : mapName(name)
{
layer[0] = l1; layer[1] = l2; layer[2] = l3; Map::grid = grid;
cellNy = layer[0]->GetWidth() / CELL_PIXEL;
cellNx = layer[0]->GetHeight() / CELL_PIXEL;
graph = vector<vector<Node*>>(cellNy, vector<Node*>(cellNx));
for (int i = 0; i < cellNy; i++)
for (int j = 0; j < cellNx; j++)
graph[i][j] = new Node({ j, i });
}
void Map::draw(HDC& hdc, POINT pos, int l)
{
Graphics g(hdc);
RECT clientRect;
GetClientRect(ghWnd, &clientRect);
if(l == 0)
g.FillRectangle(&SolidBrush(Color(255, 255, 255)),
Rect({ 0, 0, clientRect.right, clientRect.bottom }));
g.DrawImage(layer[l],
Rect({ 0, 0, clientRect.right, clientRect.bottom }),
pos.x, pos.y, clientRect.right, clientRect.bottom, UnitPixel);
}
bool Map::isBlock(POINT p) const
{
if (p.x < 0 || p.y < 0 || p.x >= cellNx || p.y >= cellNy)
return true;
return objectMap[p.y / 4][p.x / 4] & cellMask[p.y % 4][p.x % 4]
|| blockMap[p.y / 4][p.x / 4] & cellMask[p.y % 4][p.x % 4];
}
void Map::setBlock(POINT p)
{
if (p.x < 0 || p.y < 0 || p.x >= cellNx || p.y >= cellNy)
return;
objectMap[p.y / 4][p.x / 4] |= cellMask[p.y % 4][p.x % 4];
}
void Map::unsetBlock(POINT p)
{
if (p.x < 0 || p.y < 0 || p.x >= cellNx || p.y >= cellNy)
return;
objectMap[p.y / 4][p.x / 4] &= ~cellMask[p.y % 4][p.x % 4];
}
bool Map::isBlock(POINT p, int size) const
{
for (int i = 0; i < size; i++)
for(int j = 0 ; j < size ; j++)
if (isBlock(p+ POINT({i, j})))
return true;
return false;
}
void Map::setBlock(POINT p, int size)
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
setBlock(p + POINT({ i, j }));
}
void Map::unsetBlock(POINT p, int size)
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
unsetBlock(p + POINT({ i, j }));
}
|
#include "LineTracer.h"
LineTracer::LineTracer( ushort hx, ushort hy, ushort tx, ushort ty, ushort maxhx, ushort maxhy, float angle, bool is_square )
{
maxHx = maxhx;
maxHy = maxhy;
if( is_square )
{
dir = atan2( (float) ( ty - hy ), (float) ( tx - hx ) ) + angle;
dx = cos( dir );
dy = sin( dir );
if( fabs( dx ) > fabs( dy ) )
{
dy /= fabs( dx );
dx = ( dx > 0 ? 1.0f : -1.0f );
}
else
{
dx /= fabs( dy );
dy = ( dy > 0 ? 1.0f : -1.0f );
}
x1 = (float) hx + 0.5f;
y1 = (float) hy + 0.5f;
}
else
{
float nx = 3.0f * ( float(tx) - float(hx) );
float ny = ( float(ty) - float(hy) ) * SQRT3T2_FLOAT - ( float(tx & 1) - float(hx & 1) ) * SQRT3_FLOAT;
this->dir = 180.0f + RAD2DEG* atan2f( ny, nx );
if( angle != 0.0f )
{
this->dir += angle;
NormalizeDir();
}
if( dir >= 30.0f && dir < 90.0f )
{
dir1 = 5;
dir2 = 0;
}
else if( dir >= 90.0f && dir < 150.0f )
{
dir1 = 4;
dir2 = 5;
}
else if( dir >= 150.0f && dir < 210.0f )
{
dir1 = 3;
dir2 = 4;
}
else if( dir >= 210.0f && dir < 270.0f )
{
dir1 = 2;
dir2 = 3;
}
else if( dir >= 270.0f && dir < 330.0f )
{
dir1 = 1;
dir2 = 2;
}
else
{
dir1 = 0;
dir2 = 1;
}
x1 = 3.0f * float(hx) + BIAS_FLOAT;
y1 = SQRT3T2_FLOAT * float(hy) - SQRT3_FLOAT * ( float(hx & 1) ) + BIAS_FLOAT;
x2 = 3.0f * float(tx) + BIAS_FLOAT + BIAS_FLOAT;
y2 = SQRT3T2_FLOAT * float(ty) - SQRT3_FLOAT * ( float(tx & 1) ) + BIAS_FLOAT;
if( angle != 0.0f )
{
x2 -= x1;
y2 -= y1;
float xp = cos( angle / RAD2DEG ) * x2 - sin( angle / RAD2DEG ) * y2;
float yp = sin( angle / RAD2DEG ) * x2 + cos( angle / RAD2DEG ) * y2;
x2 = x1 + xp;
y2 = y1 + yp;
}
dx = x2 - x1;
dy = y2 - y1;
}
}
uchar LineTracer::GetNextHex( ushort& cx, ushort& cy )
{
ushort t1x = cx;
ushort t2x = cx;
ushort t1y = cy;
ushort t2y = cy;
MoveHexByDir( t1x, t1y, dir1, maxHx, maxHy );
MoveHexByDir( t2x, t2y, dir2, maxHx, maxHy );
float dist1 = dx * ( y1 - ( SQRT3T2_FLOAT * float(t1y) - ( float(t1x & 1) ) * SQRT3_FLOAT ) ) - dy * ( x1 - 3 * float(t1x) );
float dist2 = dx * ( y1 - ( SQRT3T2_FLOAT * float(t2y) - ( float(t2x & 1) ) * SQRT3_FLOAT ) ) - dy * ( x1 - 3 * float(t2x) );
dist1 = ( dist1 > 0 ? dist1 : -dist1 );
dist2 = ( dist2 > 0 ? dist2 : -dist2 );
if( dist1 <= dist2 ) // Left hand biased
{
cx = t1x;
cy = t1y;
return dir1;
}
else
{
cx = t2x;
cy = t2y;
return dir2;
}
}
void LineTracer::GetNextSquare( ushort& cx, ushort& cy )
{
x1 += dx;
y1 += dy;
cx = (ushort) floor( x1 );
cy = (ushort) floor( y1 );
if( cx >= maxHx )
cx = maxHx - 1;
if( cy >= maxHy )
cy = maxHy - 1;
}
void LineTracer::NormalizeDir()
{
if( dir <= 0.0f )
dir = 360.0f - fmod( -dir, 360.0f );
else if( dir >= 0.0f )
dir = fmod( dir, 360.0f );
}
|
#ifndef NULL
#define NULL 0
#endif
#define MAX_LEN_RC 150
#define MAX_LEN_NAME 10
#define SIZE 150*150
#define BUF_SIZE 100000
void strcpy(char* dest, char* origin) {
while (*origin && ('a'<=*origin && *origin <='z')) *dest++ = *origin++;
*dest = 0;
}
int strcmp(char* s1, char* s2) {
while (('a'<=*s1 && *s1<='z')&& ('a' <= *s2 && *s2 <= 'z') && *s1 && (*s1 == *s2)) {
++s1; ++s2;
}
return *s1 - *s2;
}
// rR, rC 값이 (-1, -1) 들은 최초. ← 부모를 가리키거나, 자신이 부모이거나.
struct {
bool root;
int mR, mC, sIdx, areaCnt;
}data[MAX_LEN_RC + 1][MAX_LEN_RC + 1];
struct cStack {
char name[MAX_LEN_NAME + 1];
int cellCnt, areaCnt;
}stkArr[MAX_LEN_RC * MAX_LEN_RC+10];
struct node {
char name[MAX_LEN_NAME+1];
int sIdx;
node * next;
node* alloc(char * _name, int _sIdx, node* _next) {
strcpy(name, _name);
sIdx = _sIdx, next = _next;
return this;
}
}*bucket[SIZE], buf[BUF_SIZE];
int bCnt, sCnt;
void init(int Row, int Col) {
bCnt = 0, sCnt = 1;
for (int i = 1; i<= Row; i++) {
for (int j = 1; j <= Col; j++) {
data[i][j] = { true, 0, 0, 0, 1 };
}
}
for (int i = 0; i < SIZE; i++) {
bucket[i] = NULL;
}
}
int getHash(char * name) {
int sum = 5831;
for (int i = 0; ('a' <= name[i] && name[i] <= 'z'); i++) {
sum = (((sum << 5) | name[i])%SIZE);
}
return sum;
}
int search(char * name) {
int hash = getHash(name);
for (node * p = bucket[hash]; p; p = p->next) {
if (!strcmp(name, p->name)) return p->sIdx;
}
bucket[hash] = buf[bCnt].alloc(name, sCnt, bucket[hash]);
bCnt++;
strcpy(stkArr[sCnt].name, name);
return sCnt++;
}
int findRootCrop(int row, int col, int* rootR, int* rootC) {
int isExist = false;
// 최초 빈 땅은 부모 좌표 NULL
if (data[row][col].mR && data[row][col].mC) {
int nR = row, nC = col;
// root에서 신분 벗어나면, root key 값 NULL 조치 필요
while (!data[nR][nC].root) {
int tmpR = data[nR][nC].mR;
int tmpC= data[nR][nC].mC;
nR = tmpR, nC = tmpC;
}
*rootR = nR, *rootC = nC;
isExist = true;
}
else if(data[row][col].sIdx){
// 자기가 농작물이 존재하는 곳의 root
*rootR = row, *rootC = col;
isExist = true;
}
else {
*rootR = row, *rootC = col;
}
return isExist;
}
void setFarm(int row, int col, char crop[]) {
int rootR, rootC;
int sIdx = search(crop);
if (findRootCrop(row, col, &rootR, &rootC)) {
stkArr[data[rootR][rootC].sIdx].areaCnt -= data[rootR][rootC].areaCnt;
stkArr[data[rootR][rootC].sIdx].cellCnt--;
}
// root가 존재 X (자기 자신만?)
else {
data[rootR][rootC].root = true;
}
stkArr[sIdx].areaCnt += data[rootR][rootC].areaCnt;
data[rootR][rootC].sIdx = sIdx;
stkArr[sIdx].cellCnt++;
}
void getCrop(int row, int col, char crop[]) {
int rootR, rootC;
findRootCrop(row, col, &rootR, &rootC);
int sIdx = data[rootR][rootC].sIdx;
strcpy(crop, stkArr[sIdx].name);
}
void mergeCell(int row1, int col1, int row2, int col2, int sw) {
int destRR, destRC, srcRR, srcRC;
if (sw == 1) {
findRootCrop(row1, col1, &destRR, &destRC);
findRootCrop(row2, col2, &srcRR, &srcRC);
}
else {
findRootCrop(row2, col2, &destRR, &destRC);
findRootCrop(row1, col1, &srcRR, &srcRC);
}
data[srcRR][srcRC].root = false;
data[srcRR][srcRC].mR = destRR;
data[srcRR][srcRC].mC = destRC;
int srcSIdx = data[srcRR][srcRC].sIdx;
stkArr[srcSIdx].cellCnt--;
stkArr[srcSIdx].areaCnt -= data[srcRR][srcRC].areaCnt;
int destSIdx = data[destRR][destRC].sIdx;
stkArr[destSIdx].areaCnt += data[srcRR][srcRC].areaCnt;
data[destRR][destRC].areaCnt += data[srcRR][srcRC].areaCnt;
data[srcRR][srcRC].areaCnt = 0;
}
int cntCell(char crop[]) {
int sIdx = search(crop);
return stkArr[sIdx].cellCnt;
}
int cntArea(char crop[]) {
int sIdx = search(crop);
return stkArr[sIdx].areaCnt;
}
|
/**
* Trying to figure out how to return huge objects when they are created
* inside a function or changed inside a function (i.e. avoiding copy constructors).
*
* Code and output should be easy to understand.
*/
#include <iostream>
using namespace std;
class InnerDummy {
public:
InnerDummy(){
cout << "\t -> InnerDummy Default Constructor" << endl;
}
virtual ~InnerDummy() {
cout << "\t -> InnerDummy desctructor" << endl;
}
InnerDummy(const InnerDummy& other) {
cout << "\t -> InnerDummy Copy Constructor" << endl;
}
// Two existing objects!
InnerDummy& operator=(const InnerDummy& other) {
cout << "\t -> InnerDummy Copy Assignment Operator" << endl;
return *this;
}
//C++11
InnerDummy(InnerDummy&& other) {
cout << "\t -> InnerDummy C++11 Move Constructor" << endl;
}
//C++11
InnerDummy& operator=(InnerDummy&& other) {
cout << "\t -> InnerDummy C++11 Move Operator" << endl;
return *this;
}
};
class Dummy {
public:
Dummy() :
x(0) {
cout << "\t -> Default Constructor" << endl;
}
virtual ~Dummy() {
cout << "\t -> desctructor" << endl;
}
Dummy(int i) :
x(i) {
cout << "\t -> Parameter Constructor" << endl;
}
Dummy(const Dummy& other) :
x(other.x) {
cout << "\t -> Copy Constructor" << endl;
}
// Two existing objects!
Dummy& operator=(const Dummy& other) {
x = other.x;
cout << "\t -> Copy Assignment Operator" << endl;
return *this;
}
//C++11
Dummy(Dummy&& other) {
x = std::move(other.x);
cout << "\t -> C++11 Move Constructor" << endl;
}
//C++11
Dummy& operator=(Dummy&& other) {
x = std::move(other.x);
cout << "\t -> C++11 Move Operator" << endl;
return *this;
}
void setX(int x) {
this->x = x;
}
void setInnerDummy(InnerDummy d){
this->innerDummy = d;
}
InnerDummy getInnerDummyValue() const {
return this->innerDummy;
}
InnerDummy &getInnerDummyRef() {
return this->innerDummy;
}
friend ostream& operator<<(ostream &out, const Dummy &m);
private:
int x;
InnerDummy innerDummy;
};
ostream& operator<<(ostream &out, const Dummy &m) {
out << "\t -> Dummy.x=" << m.x << endl;
return out;
}
Dummy fRetClassValue() {
return Dummy();
}
Dummy fRetClassValue(int x) {
Dummy d = Dummy(x);
return d;
}
// Cant't return references to local variables
//Dummy& fRetClassRef() {
// return Dummy();
//}
//
//Dummy& fRetClassRef(int x) {
// Dummy d = Dummy(x);
// return d;
//}
/**
* This will return a reference for the class passed by param
* No copy constructors involved
*/
Dummy& fRetClassRef(Dummy &d) {
return d;
}
Dummy& fRetClassRef(Dummy &d, int x) {
d.setX(x);
return d;
}
/**
* This will return a copy for the class passed by param
* Copy constructors involved!
*/
Dummy fRetClassValue(Dummy &d) {
return d;
}
Dummy fRetClassValue(Dummy &d, int x) {
d.setX(x);
return d;
}
Dummy& f3(Dummy &m) {
m.setX(21);
return m;
}
int main_return_opt(void) {
cout << "1........................." <<endl;
Dummy d1 = fRetClassValue();
cout << d1;
Dummy d2 = fRetClassValue(2);
cout << d2;
cout << "1_2......................... (Need const to work!)" <<endl;
const Dummy &d1_2 = fRetClassValue();
cout << d1_2;
const Dummy &d2_2 = fRetClassValue(22);
cout << d2_2;
cout << "2........................." <<endl;
Dummy d3 = fRetClassRef(d1);
cout << d3;
Dummy d4 = fRetClassRef(d1,4);
cout << d4;
cout << "2_2........................." <<endl;
Dummy &d3_2 = fRetClassRef(d1);
cout << d3_2;
Dummy &d4_2 = fRetClassRef(d1,42);
cout << d4_2;
cout << "3........................." <<endl;
Dummy &d5 = fRetClassRef(d1);
cout << d5;
Dummy &d6 = fRetClassRef(d1,6);
cout << "d1" << d1;
cout << "d6" << d6;
d6.setX(123);
cout << "d1" << d1;
cout << "d6" << d6;
cout << "4........................." <<endl;
const Dummy &d7 = fRetClassValue(d1);
cout << d7;
const Dummy &d8 = fRetClassValue(d1,7);
cout << "d1" << d1;
cout << "d8" << d8;
d6.setX(1234);
cout << "d1" << d1;
cout << "d8" << d8;
cout << "5........................." <<endl;
Dummy d9(1);
InnerDummy id1;
d9.setInnerDummy(id1);
cout << " --- copy const:" << endl;
const InnerDummy id2 = d9.getInnerDummyValue();
cout << " --- copy const:" << endl;
const InnerDummy &id3 = d9.getInnerDummyValue();
cout << " --- No copy const:" << endl;
const InnerDummy &id4 = d9.getInnerDummyRef();
cout << "END ........................." <<endl;
return 0;
}
|
//
// CommonDefineSet.hpp
// demo_ddz
//
// Created by 谢小凡 on 2018/2/13.
//
#ifndef CommonDefineSet_hpp
#define CommonDefineSet_hpp
namespace _xxf {
/**
* opt_event_name set 玩家的牌局按钮选项操作
*/
const std::string en_call = "en_call";
const std::string en_nocall = "en_nocall";
const std::string en_bet_one = "en_bet_one";
const std::string en_bet_two = "en_bet_two";
const std::string en_bet_thr = "en_bet_thr";
const std::string en_rob = "en_rob";
const std::string en_norob = "en_norob";
const std::string en_double = "en_double";
const std::string en_nodouble = "en_nodouble";
const std::string en_ming = "en_ming";
const std::string en_pass = "en_pass"; //不出
const std::string en_play = "en_play"; //出牌
const std::string en_tip = "en_tip"; //提示
const std::string en_trust = "en_trust"; //托管
const std::string en_ready = "en_ready"; //开始
};
#endif /* CommonDefineSet_hpp */
|
#include <iostream>
#include <cmath>
using namespace std;
double Mean(double x[], int N);
double StdDev(double x[], double mean, int N);
void instrucciones(int&);
void SoliData(double x[], int);//esta función guarda los datos en el arreglo x[]
//el arreglo se pasa a la función como de costumbre
//aún cuando se escribe en él
int main(int argc, char* argv[])
{
int N;
instrucciones(N); //Solicita el número N de datos a introducir
double* x;
x = new double [N];
SoliData(x, N); //Solicita los N datos
double mean;
mean = Mean(x, N); //se usa la variable mean para futuros cálculos
cout << "Promedio de los datos introducidos: " << mean << endl;
double dev;
dev = StdDev(x, mean, N);
cout << "Desviación estándar de los datos introducidos: " << dev << endl;
delete[] x;
return 0;
}
void instrucciones(int& N)
{
cout << "Este programa calcula la desviación estándar de un conjunto de números." << endl;
cout << "Cuántos datos? ";
cin >> N;
}
void SoliData(double x[], int N)
{
for(int i = 0; i < N; i++)
{
cout << "x_" << i + 1 << " = ";
cin >> x[i];
}
}
double Mean(double x[], int N)
{
double sum = 0;
for(int i = 0; i < N; i++)
{
sum += x[i];
}
return sum/N;
}
double StdDev(double x[], double mean, int N)
{
double sum = 0;
for(int i = 0; i < N; i++)
{
sum += pow((x[i]-mean),2);
}
return sqrt(sum/(N-1));
}
|
#include <bits/stdc++.h>
using namespace std;
int findMaxConsecutiveOnes(vector<int> &nums)
{
int ans = 0, itr = 0, curr = 0;
while (itr < nums.size())
{
if (nums[itr] != 1)
curr = 0;
else
{
curr++;
ans = max(curr, ans);
}
itr++;
}
return ans;
}
int main()
{
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
map<int, int> m;
void solve(int n)
{
int sol = 0;
for (int i = 1; i <= n; i++)
{
sol += (m[i - 1] * m[n - i]);
}
m[n] = sol;
}
int numTrees(int n)
{
m[0] = 1, m[1] = 1, m[2] = 2, m[3] = 5;
if (n == 0 || n == 1 || n == 2 || n == 3)
return m[n];
for (int i = 4; i <= n; i++)
{
solve(i);
}
return m[n];
}
};
|
#include <iostream>
using namespace std;
class B;
class A
{
// 友元类, 要在前面声明
friend class B;
public:
string name;
A()
{
}
A(string name, int age) : name(name), age(age)
{
}
private:
int age;
};
class B
{
public:
A a;
string name;
B(string name, int age, A &a) : name(name), age(age)
{
this->a = a;
cout << "a age " << a.age << endl;
}
private:
int age;
};
int main(int argc, char *argv[])
{
return 0;
}
|
//
// Created by Benjamin Steinert on 05/11/15.
//
#ifndef CHROMA_CPP_BENCHMARKS_HAYAI_JSON_OUTPUTTER_MOD_HPP
#define CHROMA_CPP_BENCHMARKS_HAYAI_JSON_OUTPUTTER_MOD_HPP
#include "hayai_outputter.hpp"
#include "hayai_console.hpp"
#include <vector>
#include <string>
#include <cstddef>
#include <sstream>
namespace mod_hayai
{
#define WRITE_PROPERTY(stream, key, value, indent) { \
stream << std::setw(indent*4) << "\"" << key << "\": \"" << value << "\"," << std::endl; \
}
#define WRITE_PROPERTY_NO_COMMA(stream, key, value, indent) { \
stream << std::setw(indent*4) << "\"" << key << "\": \"" << value << "\"" << std::endl; \
}
#define WRITE_DELIMITER(stream, sign, indent) { \
stream << std::setw(indent*4) << sign << std::endl; \
}
class JsonOutputter
: public hayai::Outputter {
private:
bool initialWrite;
FILE *jsonFile;
public:
virtual void Begin(const std::size_t& enabledCount, const std::size_t& disabledCount) {
initialWrite = true;
jsonFile = fopen("./result.json", "w");
if (!jsonFile) {
return;
}
fprintf(jsonFile, "[\n");
}
virtual void End(const std::size_t& enabledCount, const std::size_t& disabledCount) {
if (!jsonFile) {
return;
}
fprintf(jsonFile, "]\n");
fclose(jsonFile);
}
virtual void BeginTest(const std::string &fixtureName, const std::string &testName,
const hayai::TestParametersDescriptor ¶meters, const std::size_t &runsCount,
const std::size_t &iterationsCount);
virtual void EndTest(const std::string &fixtureName, const std::string &testName,
const hayai::TestParametersDescriptor ¶meters, const hayai::TestResult &result);
virtual void SkipDisabledTest(const std::string &fixtureName, const std::string &testName,
const hayai::TestParametersDescriptor ¶meters, const std::size_t &runsCount,
const std::size_t &iterationsCount);
};
void JsonOutputter::BeginTest(const std::string &fixtureName, const std::string &testName,
const hayai::TestParametersDescriptor ¶meters, const std::size_t &runsCount,
const std::size_t &iterationsCount) {
if (!jsonFile) {
return;
}
std::stringstream stream("");
if (initialWrite) {
initialWrite = false;
} else {
WRITE_DELIMITER(stream, ",", 1);
}
WRITE_DELIMITER(stream, "{", 1);
WRITE_PROPERTY(stream, "group", fixtureName, 2);
WRITE_PROPERTY(stream, "name", testName, 2);
//WRITE_PROPERTY(stream, "benchmarkParameters", parameters, 2);
WRITE_PROPERTY(stream, "numberOfRuns", runsCount, 2);
WRITE_PROPERTY(stream, "numberOfIterationsPerRun", iterationsCount, 2);
const std::string &jsonBegin = stream.str();
fwrite(jsonBegin.c_str(), 1, jsonBegin.length(), jsonFile);
}
void JsonOutputter::EndTest(const std::string &fixtureName, const std::string &testName,
const hayai::TestParametersDescriptor ¶meters, const hayai::TestResult &result) {
if (!jsonFile) {
return;
}
std::stringstream stream("");
WRITE_PROPERTY(stream, "totalTime", result.TimeTotal(), 2);
WRITE_PROPERTY(stream, "averagePerRun", result.RunTimeAverage(), 2);
WRITE_PROPERTY(stream, "fastestRun", result.RunTimeMinimum(), 2);
WRITE_PROPERTY_NO_COMMA(stream, "slowestRun", result.RunTimeMaximum(), 2);
WRITE_DELIMITER(stream, "}", 1);
const std::string &listEntry = stream.str();
fwrite(listEntry.c_str(), 1, listEntry.length(), jsonFile);
}
void JsonOutputter::SkipDisabledTest(const std::string &fixtureName, const std::string &testName,
const hayai::TestParametersDescriptor ¶meters,
const std::size_t &runsCount, const std::size_t &iterationsCount) {
}
}
#endif //CHROMA_CPP_BENCHMARKS_HAYAI_JSON_OUTPUTTER_MOD_HPP
|
/**
* @file Optimizer.h
* @brief Class implementing batch and incremental nonlinear equation solvers.
* @author Michael Kaess
* @author David Rosen
* @version $Id: Optimizer.h 6368 2012-03-28 23:01:19Z kaess $
*
* Copyright (C) 2009-2013 Massachusetts Institute of Technology.
* Michael Kaess, Hordur Johannsson, David Rosen,
* Nicholas Carlevaris-Bianco and John. J. Leonard
*
* This file is part of iSAM.
*
* iSAM is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at
* your option) any later version.
*
* iSAM is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with iSAM. If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
#include <Eigen/Dense>
#include "Properties.h"
#include "OptimizationInterface.h"
#include "SparseSystem.h"
#include "Cholesky.h"
#include "Node.h"
namespace isam
{
class Optimizer
{
private:
/**
* Provides an interface for manipulating the linearized system in
* the Slam class.
*/
OptimizationInterface& function_system;
/**
* This data member is used to compute the thin QR decomposition of
* the linear system during the relinearization steps.
*/
Cholesky* _cholesky;
/**
* Cached gradient vector; only used with increment Powell's Dog-Leg.
*/
Eigen::VectorXd gradient;
/**
* Current radius of trust region; only used with Powell's Dog-Leg.
*/
double Delta;
/**
* Used to restore the previous estimate for cases in which the proposed step
* is rejected; only used with Powell's Dog-Leg in incremental mode.
*/
Eigen::VectorXd last_accepted_hdl;
/**
* This keeps a running count of the sum of squared errors at the
* linearization point; only used with Powell's Dog-Leg in incremental mode.
*/
double current_SSE_at_linpoint;
void update_trust_radius(double rho, double hdl_norm);
/**
* Computes and returns the dog-leg step given the parameter alpha, the
* trust region radius delta, and the steepest-descent and Gauss-Newton
* steps. Also computes and returns the value of the denominator that
* will be used to compute the gain ratio.
*/
Eigen::VectorXd compute_dog_leg(double alpha, const Eigen::VectorXd& h_sd,
const Eigen::VectorXd& h_gn, double delta,
double& gain_ratio_denominator);
bool powells_dog_leg_update(double epsilon1, double epsilon3,
SparseSystem& jacobian, Eigen::VectorXd& f_x, Eigen::VectorXd& gradient);
/**
* Given an input vector v and an array of ints representing a permutation,
* applies the permutation to the elements of v and returns the permuted vector
* @param v Input vector.
* @param permutation An array of ints representing the permutation to be
* applied to the elements of v.
* @return The returned permuted vector p satisfies p(permutation[i]) = v(i)
* i.e., p is formed by mapping the ith element of v to the
* permutation[i]-th element of p.
*/
void permute_vector(const Eigen::VectorXd& v, Eigen::VectorXd& p,
const int* permutation);
/**
* Helper method for computing the Gauss-Newton step h_{gn} in Gauss-Newton,
* Levenberg-Marquardt, and Powell's dog-leg algorithms in batch mode.
* Specifically, this function can compute the Gauss-Newton step h_gn as
* part of the factorization of the relinearized SparseSystem computed at
* each iteration of batch processing algorithm.
*
* @param jacobian The SparseSystem representing the linearization
* @param R
* @param lambda
* @return h_gn
*/
Eigen::VectorXd compute_gauss_newton_step(const SparseSystem& jacobian,
SparseSystem* R = NULL, double lambda = 0.);
void gauss_newton(const Properties& prop, int* num_iterations = NULL);
/**
* Perform Levenberg-Marquardt
* @param prop Properties including stopping criteria max_iterations and
* epsilon, and lm_... parameters
* @param num_iterations Upon return, contains number of iterations performed.
*/
void levenberg_marquardt(const Properties& prop, int* num_iterations = NULL);
/**
* Powell's dog leg algorithm, a trust region method that combines
* Gauss-Newton and steepest descent, similar to Levenberg-Marquardt,
* but requiring less iterations (matrix factorizations). See
* Manolis05iccv for a comparison to LM. Implemented according to
* Madsen, Nielson, Tingleff, "Methods for Non-Linear Least Squares
* Problems", lecture notes, Denmark, 2004
* (http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/3215/pdf/imm3215.pdf).
* @param num_iterations Contains number of iterations on return if not NULL.
* @param delta0 Initial trust region.
* @param max_iterations Maximum number of iterations (0 means unlimited).
* @param epsilon1
* @param epsilon2
* @param epsilon3
*/
void powells_dog_leg(int* num_iterations = NULL, double delta0 = 1.0,
int max_iterations = 0, double epsilon1 = 1e-4, double epsilon2 = 1e-4,
double epsilon3 = 1e-4);
public:
Optimizer(OptimizationInterface& fs)
: function_system(fs), Delta(1.0) {
//Initialize the Cholesky object
_cholesky = Cholesky::Create();
}
/**
* Perform batch optimization using the method set in prop
*/
void batch_optimize(const Properties& prop, int* num_iterations);
/**
* Used to augment the sparse linear system by adding new measurements.
* Only useful in incremental mode.
*/
void augment_sparse_linear_system(SparseSystem& W, const Properties& prop);
/**
* Computes the Jacobian J(x_est) of the residual error function about the
* current estimate x_est, computes the thin QR factorization of J(x_est),
* and then stores (R,d) as a SparseSystem, where
*
* Q^t f(x_est) = | d |
* | e |
*
* and || e ||^2 is the squared residual error.
*
*
*
* NOTA BENE: (Deeply) Internally, this algorithm uses the SuiteSparse
* library to perform the matrix decomposition shown above. The SuiteSparse
* library utilizes variable reordering in order to reduce fill-in and boost
* efficiency. Consequently, the ordering (i.e., naming) of variables in the
* SparseSystem computed by this function differs from the ordering (naming)
* of the variables in the Graph object contained in the Slam class.
*
* The mappings between the two orderings can be obtained using
* OrderedSparseMatrix::a_to_r() and OrderedSparseMatrix::r_to_a(). These
* functions return const int*'s that point to internal arrays encoding the
* permutation between the naming of variables passed in to the factorization
* routine, and the naming of variables in the factored matrices returned
* by the relinearization.
*
* More precisely, if
*
* const int* order = function_system._R.a_to_r();
*
* then the variable x_i from the Graph object stored the Slam class is
* mapped to the variable x_{order[i]} in the SparseSystem obtained after
* linearization.
*
* The call
*
* const int* inverse_order = function_system._R.r_to_a();
*
* retrieves the inverse permutation.
*/
void relinearize(const Properties& prop);
/**
* Updates the current estimated solution
*/
void update_estimate(const Properties& prop);
~Optimizer() {
delete _cholesky;
}
};
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.