text
stringlengths 8
6.88M
|
|---|
// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
//
// File names used by DB code
#ifndef STORAGE_LEVELDB_DB_FILENAME_H_
#define STORAGE_LEVELDB_DB_FILENAME_H_
#include <stdint.h>
#include <string>
#include "leveldb/slice.h"
#include "leveldb/status.h"
#include "port/port.h"
#include "util/logging.h"
namespace leveldb {
class Env;
enum FileType {
kUnknown,
kLogFile,
kDBLockFile,
kTableFile,
kDescriptorFile,
kCurrentFile,
kTempFile,
kInfoLogFile // Either the current one, or an old one
};
// Return the name of the log file with the specified number
// in the db named by "dbname". The result will be prefixed with
// "dbname".
extern std::string LogFileName(const std::string& dbname, uint64_t number);
// for qinan
extern std::string LogHexFileName(const std::string& dbname, uint64_t number);
// Return the name of the sstable with the specified number
// in the db named by "dbname". The result will be prefixed with
// "dbname".
extern std::string TableFileName(const std::string& dbname, uint64_t number);
// Return the name of the descriptor file for the db named by
// "dbname" and the specified incarnation number. The result will be
// prefixed with "dbname".
extern std::string DescriptorFileName(const std::string& dbname,
uint64_t number);
// Return the name of the current file. This file contains the name
// of the current manifest file. The result will be prefixed with
// "dbname".
extern std::string CurrentFileName(const std::string& dbname);
// Return the name of the lock file for the db named by
// "dbname". The result will be prefixed with "dbname".
extern std::string LockFileName(const std::string& dbname);
// Return the name of a temporary file owned by the db named "dbname".
// The result will be prefixed with "dbname".
extern std::string TempFileName(const std::string& dbname, uint64_t number);
// Return the name of the info log file for "dbname".
extern std::string InfoLogFileName(const std::string& dbname);
// Return the name of the old info log file for "dbname".
extern std::string OldInfoLogFileName(const std::string& dbname);
// If filename is a leveldb file, store the type of the file in *type.
// The number encoded in the filename is stored in *number. If the
// filename was successfully parsed, returns true. Else return false.
extern bool ParseFileName(const std::string& filename,
uint64_t* number,
FileType* type);
// Make the CURRENT file point to the descriptor file with the
// specified number.
extern Status SetCurrentFile(Env* env, const std::string& dbname,
uint64_t descriptor_number);
const char* FileTypeToString(FileType type);
// build a full path file number from dbname&filenumber, format:
// |--tabletnum(4B)--|--filenum(4B)--|
// tabletnum = 0x80000000|real_tablet_num
extern uint64_t BuildFullFileNumber(const std::string& dbname,
uint64_t number);
// Build file path from lg_num & full file number
// E.g. construct "/table1/tablet000003/0/00000001.sst"
// from (/table1, 0, 0x8000000300000001)
std::string BuildTableFilePath(const std::string& prefix,
uint64_t lg, uint64_t number);
// Parse a db_impl name to prefix, tablet number, lg number...
// db_impl name format maybe:
// /.../tablename/tablet000012/2 (have tablet name, allow split)
// or /.../tablename/2 (have none tablet name, donot allow split)
bool ParseDbName(const std::string& dbname, std::string* prefix,
uint64_t* tablet, uint64_t* lg);
// Parse a full file number to tablet number & file number
bool ParseFullFileNumber(uint64_t full_number, uint64_t* tablet, uint64_t* file);
// Construct a db_impl name from a cur-db_impl name and a tablet number.
// E.g. construct "/table1/tablet000003/0" from (/table1/tablet000001/0, 3)
std::string RealDbName(const std::string& dbname, uint64_t tablet);
// Construct a db_table name from a cur-db_table name and a tablet number.
// E.g. construct "/table1/tablet000003" from (/table1/tablet000001, 3)
std::string GetChildTabletPath(const std::string& parent_path, uint64_t tablet);
// Construct a db_table name from a table name and a tablet number.
// E.g. construct "/table1/tablet000003" from (/table1, 3)
std::string GetTabletPathFromNum(const std::string& tablename, uint64_t tablet);
// Parse tablet number from a db_table name.
// E.g. get 3 from "table1/tablet000003"
uint64_t GetTabletNumFromPath(const std::string& tabletpath);
// Check if this table file is inherited.
bool IsTableFileInherited(uint64_t tablet, uint64_t number);
std::string FileNumberDebugString(uint64_t full_number);
} // namespace leveldb
#endif // STORAGE_LEVELDB_DB_FILENAME_H_
|
#ifndef Student_hpp
#define Student_hpp
#include <string>
using namespace std;
class Room;
class Student
{
private:
Room* currRoom;
public:
string name;
Student(string name);
void setRoom(Room* room);
};
#endif
|
int led1 = 4;
int led2 = 5;
int led3 = 6;
int led4 = 9;
int led5 = 10;
int potValue;
int ledValue;
void setup() {
}
void loop() {
potValue = analogRead(0);
ledValue = map(potValue, 1023, 0, 0, 255);
analogWrite(led1, ledValue);
analogWrite(led2, ledValue);
analogWrite(led3, ledValue);
analogWrite(led4, ledValue);
analogWrite(led5, ledValue);
}
|
#include <ros/ros.h>
#include <nav_msgs/Odometry.h>
#include <tf/tf.h>
void callback ( const nav_msgs::OdometryConstPtr &msg){
double yaw = tf::getYaw(msg->pose.pose.orientation);
yaw = (yaw*180/M_PI);
ROS_INFO ("yaw: %lf", yaw);
}
int main(int argc, char **argv){
ros::init(argc,argv,"qYaw");
ros::NodeHandle node;
ros::Subscriber odometrySub = node.subscribe("/vrep/vehicle/odometry",1,callback);
ros::spin();
return 0;
}
|
#include <cmath>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <set>
#include <stack>
#include <sstream>
#include <string>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/* Solution */
const int MOD = 1000000007;
class Solution {
public:
int trapRainWater(vector<vector<int>>& heightMap)
{
// TODO
}
};
int main()
{
Solution sol;
vector<vector<int>> heightMap = {{12, 13, 1, 12},
{13, 4, 13, 12},
{13, 8, 10, 12},
{12, 13, 12, 12},
{13, 13, 13, 13}};
// vector<vector<int>> heightMap = {{5,5,5,1},
// {5,1,1,5},
// {5,1,5,5},
// {5,2,5,8}};
cout << sol.trapRainWater(heightMap) << endl;
}
|
#include "renderer/ShaderProgram.h"
namespace revel
{
namespace renderer
{
ShaderProgram::ShaderProgram()
{
}
ShaderProgram::~ShaderProgram()
{
}
} // ::revel::renderer
} // ::revel
|
//! @file soundmanager.h
//! @brief SoundManagerクラスの宣言
/**
* LynxOPS
*
* Copyright (c) 2015 Nilpaca
*
* Licensed under the MIT License.
* https://github.com/Nilpaca/LynxOPS/blob/master/LICENSE
*/
//--------------------------------------------------------------------------------
//
// OpenXOPS
// Copyright (c) 2014-2015, OpenXOPS Project / [-_-;](mikan) All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the OpenXOPS Project 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 OpenXOPS Project 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 SOUNDMANAGER_H
#define SOUNDMANAGER_H
#define MAX_SOUNDMGR_LIST 100 //!< サウンドリストの最大数
#define MAX_SOUNDHITMAP 95 //!< マップ着弾音の最大音量
#define MAX_SOUNDHITSMALLOBJ 110 //!< 小物着弾音の最大音量
#define MAX_SOUNDHITHUMAN 75 //!< 人着弾(被弾)音の最大音量
#define MAX_SOUNDPASSING 80 //!< 弾が横切る音の最大音量
#define MAX_SOUNDCCOGRENADE 100 //!< 手榴弾 バウンド・跳ね返り音の最大音量
#define MAX_SOUNDHITGRENADE 120 //!< 手榴弾 爆発音の最大音量
#ifndef H_LAYERLEVEL
#define H_LAYERLEVEL 2 //!< Select include file.
#endif
#include "main.h"
//! サウンドリスト "paramid" 用定数
enum SoundmgrID {
SHOT_WEAPON = 0, //!< 発砲音
SHOT_WEAPON_PLAYER, //!< プレイヤー自身の発砲音
HIT_MAP, //!< マップ着弾音
HIT_HUMAN, //!< 被弾音
HIT_SMALLOBJECT, //!< 小物破壊音
BULLET, //!< 銃弾の音・横切る音
GRE_BOUND, //!< 手榴弾 バウンド音
GRE_EXPLOSION, //!< 手榴弾 爆発音
FOOTSTEPS, //!< 足音・走る音
WEAPON_RELOAD //!< リロード音
};
//! サウンドリスト用構造体
struct soundlist {
int paramid; //!< 音源の種類番号・SoundmgrID定数
int dataid; //!< データ番号
float x; //!< X座標
float y; //!< Y座標
float z; //!< Z座標
float move_x; //!< 1フレーム後の X座標移動量
float move_y; //!< 1フレーム後の Y座標移動量
float move_z; //!< 1フレーム後の Z座標移動量
int teamid; //!< チーム番号
};
//! @brief サウンド管理クラス
//! @details 各サウンドの初期化・計算・再生などを行い管理します
class SoundManager
{
class SoundControl *SoundCtrl; //!< サウンド再生クラス
class ResourceManager *Resource; //!< リソース管理クラス
class ParameterInfo *Param; //!< 設定値を管理するクラス
soundlist *soundlistA; //!< サウンドリスト A
soundlist *soundlistB; //!< サウンドリスト B
bool changeAB; //!< サウンドリストの反転
int listAdatas; //!< サウンドリスト A の登録数
int listBdatas; //!< サウンドリスト B の登録数
bool GetNewList(soundlist **plist);
int GetTargetList(soundlist **plist);
bool CheckApproach(soundlist *plist, float camera_x, float camera_y, float camera_z, float *min_x, float *min_y, float *min_z);
void PlaySound(soundlist *plist, float camera_x, float camera_y, float camera_z);
public:
SoundManager(SoundControl *in_SoundCtrl = NULL, ResourceManager *in_Resource = NULL, ParameterInfo *in_Param = NULL);
~SoundManager();
void SetClass(SoundControl *in_SoundCtrl, ResourceManager *in_Resource, ParameterInfo *in_Param);
void InitWorldSound();
bool ShotWeapon(float x, float y, float z, int id, int teamID, bool player);
bool HitMap(float x, float y, float z);
bool HitHuman(float x, float y, float z);
bool HitSmallObject(float x, float y, float z, int id);
bool PassinfgBullet(float x, float y, float z, float move_x, float move_y, float move_z);
bool GrenadeBound(float x, float y, float z);
bool GrenadeExplosion(float x, float y, float z);
bool SetFootsteps(float x, float y, float z, int teamID);
bool ReloadWeapon(float x, float y, float z, int teamID);
int GetWorldSound(float pos_x, float pos_y, float pos_z, int teamID, soundlist *psoundlist);
void PlayWorldSound(float camera_x, float camera_y, float camera_z, float camera_rx);
};
#endif
|
#include "holereview.h"
HoleReview::HoleReview(QGraphicsItem *parent) : BoardPart(parent), black(false), white(false)
{ }
QRectF HoleReview::boundingRect() const
{
return QRectF(0, 0, 50, 50);
}
void HoleReview::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
if(black)
{
painter->setBrush(Qt::black);
painter->drawEllipse(0, 0, 20, 20);
}
else if(white)
{
painter->setBrush(Qt::white);
painter->drawEllipse(0, 0, 20, 20);
}
else
{
painter->setBrush(Qt::gray);
painter->drawEllipse(0, 0, 20, 20);
}
}
void HoleReview::blackPaint()
{
black = true;
}
void HoleReview::whitePaint()
{
white = true;
}
|
#ifndef INVALIDMAPPEDFILESTATE_H_INCLUDED
#define INVALIDMAPPEDFILESTATE_H_INCLUDED
#include <exception>
namespace Utilities
{
class InvalidMappedFileState : public std::exception
{
std::string _Message;
public:
InvalidMappedFileState(std::string message) : _Message(message) { }
virtual ~InvalidMappedFileState() {}
};
}
#endif // INVALIDMAPPEDFILESTATE_H_INCLUDED
|
//
// Compiler/AST/Context.h
//
// Brian T. Kelley <brian@briantkelley.com>
// Copyright (c) 2007, 2008, 2011, 2012, 2014 Brian T. Kelley
//
// Chris Leahy <leahycm@gmail.com>
// Copyright (c) 2007 Chris Leahy
//
// This software is licensed as described in the file LICENSE, which you should have received as part of this distribution.
//
#ifndef COMPILER_LANGUAGE_CONTEXT_H
#define COMPILER_LANGUAGE_CONTEXT_H
#include "Compiler/Convenience.h"
#include <memory>
#include <vector>
namespace Compiler { namespace AST {
class Class;
class Type;
class Context {
DELETE_COPY_AND_ASSIGN(Context);
protected:
Context();
virtual ~Context();
public: // MARK: -- Source Information --
virtual const std::vector<const std::shared_ptr<const Compiler::AST::Class>>& GetClasses() const = 0;
public: // MARK: -- Language Characteristics --
virtual bool AllowsInstanceVariableShadowing() const = 0;
virtual bool IsTypeAssignableFromType(const Compiler::AST::Type& destination, const Compiler::AST::Type& source) const = 0;
public: // MARK: -- Convenience Functions --
std::shared_ptr<const Compiler::AST::Class> ResolveClass(std::string name) const;
};
} /*namespace AST */ } /*namespace Compiler*/
#endif // COMPILER_LANGUAGE_CONTEXT_H
|
#include <iostream>
#include <string>
#include <vector>
#include "eBook.h"
#include "DocumentConverter.h"
// Delimiter for metadata in the .txt file that stores eBook contents
const char DELIM = '|';
eBook::eBook() {
}
// Filename constructor
// Loads all appropriate information from the file
eBook::eBook(const std::string & fn) {
filename = fn;
loadEbookFromFile(fn);
}
// Attribute constructor
// Allows an ebook object to be created directly from attributes passed to the constructor
eBook::eBook(const std::string & n, const std::string & o, const std::string & d, const bool & p) {
name = n;
owner = o;
description = d;
isPublic = p;
setID();
setFilename();
}
void eBook::updateDescription(const std::string & d) {
description = d;
}
void eBook::setID() {
ID = fh.getLastIndex() + 1;
}
void eBook::setOwner(const std::string & o) {
owner = o;
}
// Changing the name involves renaming the file
// Filename format is ID_booktitle.txt
void eBook::setName(const std::string & n) {
std::string oldname = getFilename();
std::string newname = std::to_string(ID) + "_" + n;
fh.renameFile(oldname, newname);
name = n;
}
// Populates the attributes of the eBook from the meta data in the .txt file
// First 2 lines of the .txt file contain the metadata
// Format:
// ID|Title|Owner
// Description
void eBook::loadEbookFromFile(const std::string & fn) {
// Load the contents of file fn into a vector of strings
std::vector<std::string> data = fh.loadFile(fn);
// The first line contains ID|Title|Owner metadata
std::string metadata = data.at(0);
size_t pos;
// The second line contains the description
description = data.at(1);
// Make sure the content vector is empty and ready to load the text of the eBook
content.clear();
// Starting at the 3rd (index: 2) line of the vector, add every remaining line from the file input vector
// Into the eBook content vector
for (int x = 2; x < data.size(); x++) {
content.push_back(data.at(x));
}
// Split up the metadata string into the individual attributes
pos = metadata.find(DELIM);
ID = stoi(metadata.substr(0, pos));
metadata = metadata.substr(pos+1);
pos = metadata.find(DELIM);
name = metadata.substr(0, pos);
owner = metadata.substr(pos+1);
// Record the filename that was loaded
filename = fn;
}
// Sets the filename using the appropriate ID_booktitle.txt format
void eBook::setFilename() {
filename = std::to_string(ID) + "_" + name + ".txt";
}
void eBook::updateContent(const std::vector<std::string> & c) {
content = c;
}
// Public methods which return class attributes
int eBook::getID() {
return ID;
}
std::vector<std::string> eBook::getContent() {
return content;
}
std::string eBook::getOwner() {
return owner;
}
std::string eBook::getDescription() {
return description;
}
std::string eBook::getFilename() {
return filename;
}
std::string eBook::getName() {
return name;
}
// End attibute retrieval methods
// Writes the contents of the eBook to a text file
void eBook::writeEbook() {
std::vector<std::string> data;
std::string metadata = std::to_string(ID) + DELIM + name + DELIM + owner;
data.push_back(metadata);
data.push_back(description);
for (int x = 0; x < getContent().size(); x++) {
data.push_back(getContent().at(x));
}
std::cout << getFilename() << std::endl;
fh.saveToFile(getFilename(), data);
}
// Deletes the eBook file from disk
// This is a DANGEROUS method there is no kind of confirmation
// Make sure to build in any necessary sanity checks to the functions that use this method
void eBook::deleteEbook() {
fh.deleteFile(filename);
}
// Sets the eBook to public status
void eBook::setPublic() {
isPublic = true;
}
// Sets the eBook to private status
void eBook::setPrivate() {
isPublic = false;
}
// ************************************************************************
// *** DISABLE THIS METHOD IF YOU ARE DEBUGGING WITHOUT THE PDF LIBRARY ***
// ************************************************************************
// Converts the .txt eBook file into a .pdf document
void eBook::publish() {
DocumentConverter dc;
std::string fn = filename.substr(0, filename.length() - 4) + ".pdf";
dc.writeOutputContent(content, fn);
}
// Uncomment this stub instead
/*void eBook::publish() {
}*/
|
// avvinci - summers 18
// #include"prettyprint.hpp"
#include<bits/stdc++.h>
using namespace std;
typedef pair<long long,long long > P;
#define mod 1000000007
#define pb emplace_back
#define fs first
#define sc second
#define ll long long
#define fr(it,st,en) for(it=st;it<en;it++)
#define all(container) container.begin(),container.end()
#define INP ios_base::sync_with_stdio(false);cin.tie(NULL);
#define ws(x) cout << #x << " = " << x << endl;
#define N 1000004
const long long infl = 1e18+5;
ll n,m,k,q,x,y,f,val,t,i,j;
ll ind,cnt,sz,sm,ans,mx,mn;
ll a[N] ;
int main(){
INP
if (fopen("inp.txt", "r")) {
freopen("myfile.txt","w",stdout);
freopen("inp.txt", "r", stdin);
}
cin>>n;
fr(i,0,n){
cin>>a[i] ;
}
stack<ll > st ;
ans =0 ;
fr(i,0,n){
while(!st.empty() && st.top() < a[i]){
ans = max(ans , st.top() ^ a[i]) ;
st.pop() ;
}
if(!st.empty())
ans = max(ans , st.top() ^ a[i]) ;
st.push(a[i]) ;
}
// ws(ans);
// while(!st.empty()) st.pop() ;
// fr(i,0,n){
// while(!st.empty() && st.top() > a[i]){
// ans = max(ans , st.top() ^ a[i]) ;
// st.pop() ;
// }
// if(!st.empty())
// ans = max(ans , st.top() ^ a[i]) ;
// st.push(a[i]) ;
// }
cout<<ans;
return 0 ;
}
|
/*******************************************************************************
* Cristian Alexandrescu *
* 2163013577ba2bc237f22b3f4d006856 *
* 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 *
* bc9a53289baf23d369484f5343ed5d6c *
*******************************************************************************/
/* Problem 10534 - Wavio Sequence */
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <memory>
using namespace std;
/* LIS v1.2 */
/*************************************************************/
template <typename IT, typename T, typename Comparator>
void LIS(const IT &roBegin, const IT &roEnd, vector<T> &roVecNumbersOut, const Comparator &roComp, const unique_ptr<vector<size_t>> &roVecLengths = nullptr) {
const size_t MYINFINITY = static_cast<size_t>(~0);
vector<size_t> oVecLISIndex;
oVecLISIndex.push_back(MYINFINITY);
oVecLISIndex.push_back(0);
size_t nSize = roEnd - roBegin;
if (roVecLengths != nullptr) {
roVecLengths->reserve(nSize);
roVecLengths->push_back(1);
}
vector<size_t> oVecILisPrevIndex;
oVecILisPrevIndex.reserve(nSize);
oVecILisPrevIndex.push_back(MYINFINITY);
for (auto oIt = roBegin + 1; oIt != roEnd; oIt++) {
auto oItPos = lower_bound(oVecLISIndex.begin() + 1, oVecLISIndex.end(), *oIt, [&roBegin, &roComp](const size_t nLHS, const T &roValue) { return roComp(*(roBegin + nLHS), roValue); });
if (roVecLengths != nullptr)
roVecLengths->push_back(oItPos - oVecLISIndex.begin());
oVecILisPrevIndex.push_back(*(oItPos - 1));
if (oItPos != oVecLISIndex.end())
*oItPos = oIt - roBegin;
else
oVecLISIndex.push_back(oIt - roBegin);
}
vector<T> oVecResult;
for (size_t nIndex = oVecLISIndex[oVecLISIndex.size() - 1]; nIndex != MYINFINITY; nIndex = oVecILisPrevIndex[nIndex])
oVecResult.push_back(*(roBegin + nIndex));
roVecNumbersOut = move(oVecResult);
reverse(roVecNumbersOut.begin(), roVecNumbersOut.end());
}
template <typename IT, typename T>
void LIS(const IT &roBegin, const IT &roEnd, vector<T> &roVecNumbersOut) {
LIS(roBegin, roEnd, roVecNumbersOut, std::less<T>());
}
/*************************************************************/
int main() {
while (true) {
int nNoInts;
if (!(cin >> nNoInts))
return 0;
vector<int> oVecNumbers;
while (nNoInts--) {
int nN;
cin >> nN;
oVecNumbers.push_back(nN);
}
vector<int> oVecLIS;
// unique_ptr<vector<size_t>> oVecLISSizeInc = make_unique<vector<size_t>>();
// unique_ptr<vector<size_t>> oVecLISSizeDec = make_unique<vector<size_t>>();
unique_ptr<vector<size_t>> oVecLISSizeInc(new vector<size_t>());
unique_ptr<vector<size_t>> oVecLISSizeDec(new vector<size_t>());
LIS(oVecNumbers.begin(), oVecNumbers.end(), oVecLIS, std::less<int>(), oVecLISSizeInc);
LIS(oVecNumbers.rbegin(), oVecNumbers.rend(), oVecLIS, std::less<int>(), oVecLISSizeDec);
size_t nMax = 0;
transform(oVecLISSizeDec->rbegin(), oVecLISSizeDec->rend(), oVecLISSizeInc->begin(), oVecLISSizeInc->begin(), [](size_t nLHS, size_t nRHS) { return min(nLHS, nRHS) * 2 - 1; } );
nMax = *(max_element(oVecLISSizeInc->cbegin(), oVecLISSizeInc->cend()));
cout << nMax << endl;
}
return 0;
}
|
#include <whiskey/Parsing/ParserRule.hpp>
#include <whiskey/Core/Verbose.hpp>
#include <whiskey/Parsing/ParserResult.hpp>
#include <whiskey/Parsing/ParserContext.hpp>
namespace whiskey {
ParserRule::ParserRule(std::string name, std::string expected) : name(name), expected(expected) {}
std::string &ParserRule::getName() {
return name;
}
const std::string &ParserRule::getName() const {
return name;
}
void ParserRule::setName(std::string value) {
name = value;
}
std::string &ParserRule::getExpected() {
return expected;
}
const std::string &ParserRule::getExpected() const {
return expected;
}
void ParserRule::setExpected(std::string value) {
expected = value;
}
ParserResult ParserRule::parse(const ParserGrammar &grammar, ParserContext &ctx, MessageContext &msgs) const {
W_VERBOSE("parsing " << name);
ParserContext save = ctx;
ParserResult res = onParse(grammar, ctx, msgs);
if (!res.isGood()) {
res.setNode(Node());
ctx = save;
W_VERBOSE("failed " << name);
} else {
W_VERBOSE("parsed " << name);
W_VERBOSE("ast " << res.getNode());
}
return res;
}
}
|
// simple countdown from user input
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter an integer between 1 and 100:";
cin >> n;
while (n > 0)
{
cout << n << ", ";
--n;
}
cout << "BOOM \n";
return 0;
}
|
//---------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit3.h"
#include "Unit1.h"
//---------------------------------------------------------------------
#pragma resource "*.dfm"
TAboutBox *AboutBox;
//---------------------------------------------------------------------
__fastcall TAboutBox::TAboutBox(TComponent* AOwner)
: TForm(AOwner)
{
}
//---------------------------------------------------------------------
void __fastcall TAboutBox::OKButtonClick(TObject *Sender)
{
Close();
}
//---------------------------------------------------------------------------
void __fastcall TAboutBox::FormClose(TObject *Sender, TCloseAction &Action)
{
Home->GroupBox1->Enabled = true ;
}
//---------------------------------------------------------------------------
|
#include <cstdio>
int main() {
char str[100];
int i = 0, count = 0,
pos[80] = {-1};
// init
pos[count++] = 0;
while(scanf("%c", str+i) != EOF) {
if(str[i] == ' ') {
pos[count++] = i+1;
// printf("--%d--\n", i-1);
}
i++;
}
int tmp = 0;
// printf("==Count: %d==\n", count-1);
for(int j = count-1; j > -1; j--) {
tmp = pos[j];
// printf("==%d==\n", tmp);
while(str[tmp] != ' ' && str[tmp] != '\n') {
printf("%c", str[tmp++]);
}
if(j > 0) printf(" ");
}
return 0;
}
|
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXTYPE = 2000;
typedef struct{
double remain; // WARNING: 审题不仔细
double profit; // **$/T
double total_val;
} Cake;
bool cmp (Cake a, Cake b);
int main() {
int cnum, demand;
double tmp, wealth = 0;
Cake cakes[MAXTYPE];
scanf("%d %d", &cnum, &demand);
for(int i = 0; i < cnum; i++) {
scanf("%lf", &tmp);
cakes[i].remain = tmp;
}
for(int i = 0; i < cnum; i++) {
scanf("%lf", &tmp);
cakes[i].total_val = tmp;
cakes[i].profit = tmp / (double)cakes[i].remain;
}
sort(cakes, cakes+cnum, cmp);
// calculation
for(int i = 0; i < cnum; i++) {
if(demand >= cakes[i].remain) {
demand -= cakes[i].remain;
wealth += cakes[i].total_val;
if(demand == 0)
break;
} else {
wealth += demand * cakes[i].profit;
break;
}
}
printf("%.2f", wealth);
return 0;
}
bool cmp (Cake a, Cake b) {
return a.profit > b.profit;
}
|
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
void sortColors(vector<int> &nums)
{
map<int, int> m;
for (int a : nums)
m[a]++;
nums.clear();
for (auto item : m)
{
int k = item.second;
while (k--)
nums.push_back(item.first);
}
}
};
|
/******************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt PDF Module.
**
** $QT_BEGIN_LICENSE:COMM$
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** $QT_END_LICENSE$
**
******************************************************************************/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(lcExample)
namespace Ui {
class MainWindow;
}
class QLineEdit;
class SequentialPageWidget;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void open(const QUrl &docLocation);
private slots:
void showingPageRange(int start, int end);
void zoomChanged(qreal factor);
void zoomEdited();
// action handlers
void on_actionOpen_triggered();
void on_actionQuit_triggered();
void on_actionAbout_triggered();
void on_actionAbout_Qt_triggered();
void on_actionZoom_In_triggered();
void on_actionZoom_Out_triggered();
void on_actionGo_triggered();
void on_actionPrevious_Page_triggered();
void on_actionNext_Page_triggered();
private:
Ui::MainWindow *ui;
SequentialPageWidget *m_pageWidget;
QLineEdit *m_zoomEdit;
QLineEdit *m_pageEdit;
};
#endif // MAINWINDOW_H
|
#include <iostream>
int main() // int : 결과의 자료형; main : 함수의 이름; () : 인수
{
// 표준 출력 스트림으로 문장을 출력함
int a;
std::cout << "나의 첫 번째 C++프로그램" << std::endl; //문장의끝은 ;(세미콜론)
std::cin >> a;
std::cout << a << "가 입력되었습니다." << std::endl;
return 0; // 0이 리턴되면 정상적인 종료로 보통 판단
}
|
/*
* ConfigTranslator.cpp
*
* Created on: 24 Mar 2011
* Author: "SevenMachines <SevenMachines@yahoo.co.uk>"
*/
//#define CONFIGTRANSLATOR_DEBUG
#include "ConfigTranslator.h"
namespace cryomesh {
namespace config {
ConfigTranslator::ConfigTranslator(std::istream & is) : entries() {
// open file
this->readRawEntries(is);
}
ConfigTranslator::ConfigTranslator(const std::string & filename) : entries() {
// open file
std::ifstream ifs(filename.c_str());
if (ifs.is_open() == true) {
this->readRawEntries(ifs);
ifs.close();
} else {
std::cout << "ConfigTranslator::~ConfigTranslator: " << "ERROR: File " << "'" << filename << "'"
<< "could not be opened... " << std::endl;
}
}
ConfigTranslator::~ConfigTranslator() {
}
ConfigEntry ConfigTranslator::getConfigEntryByCommand(const std::string & com) const {
std::list<ConfigEntry>::const_iterator it_entries = entries.begin();
const std::list<ConfigEntry>::const_iterator it_entries_end = entries.end();
while (it_entries != it_entries_end) {
if (it_entries->getCommand() == com) {
return *it_entries;
}
++it_entries;
}
ConfigEntry tempent("");
return tempent;
}
void ConfigTranslator::readRawEntries(std::istream & fs) {
std::string line;
while (fs.good() == true) {
getline(fs, line);
#ifdef CONFIGTRANSLATOR_DEBUG
std::cout << "ConfigTranslator::readRawEntries: " << line << std::endl;
#endif
// ignore comment lines
size_t first_char_pos = line.find_first_not_of(' ');
if (first_char_pos != std::string::npos) {
std::string first_char = line.substr(first_char_pos, 1);
if (first_char != "#") {
entries.push_back(ConfigEntry(line));
}
}
}
}
std::ostream & ConfigTranslator::writeRawEntries(std::ostream & os) {
// forall in entries
{
std::list<ConfigEntry>::const_iterator it_entries = entries.begin();
const std::list<ConfigEntry>::const_iterator it_entries_end = entries.end();
while (it_entries != it_entries_end) {
os << *it_entries;
if (it_entries != it_entries_end) {
os << std::endl;
}
++it_entries;
}
}
return os;
}
const std::list<ConfigEntry> & ConfigTranslator::getEntries() const {
return entries;
}
std::ostream& operator<<(std::ostream & os, const ConfigTranslator & obj) {
// forall in entries
{
std::list<ConfigEntry>::const_iterator it_entries = obj.getEntries().begin();
const std::list<ConfigEntry>::const_iterator it_entries_end = obj.getEntries().end();
while (it_entries != it_entries_end) {
os << *it_entries << std::endl;
++it_entries;
}
}
return os;
}
} //NAMESPACE
} //NAMESPACE
|
//! Bismillahi-Rahamanirahim.
/** ========================================**
** @Author: Md. Abu Farhad ( RUET, CSE'15)
** @Category:
/** ========================================**/
#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
#define ll long long
#define scl(n) scanf("%lld", &n)
int main()
{
ll m,n,i,j;
cin>>i;
while(i--)
{
scl(m), scl(n);
if(m%2==0 and n%2==0)cout<<"YES"<<endl;
else if ((m%2==1 and n%2==0 ) ||( m%2==0 and n%2==1))
{
if( m-n >=2)cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
else cout<<"YES"<<endl;
}
}
|
/*
Copyright (c) 2011 Andrew Wall
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef TESTMETHODTIMERS_H_5119E4AA_7A61_49FF_80C1_048CC165F549
#define TESTMETHODTIMERS_H_5119E4AA_7A61_49FF_80C1_048CC165F549
#include "src\MethodTimer.h"
#include "src\MethodCaller.h"
#include "src\TimeReport.h"
#include "AutoRun.h"
#include <sstream>
namespace TestMethodTimers{
class MethodTimerTestHelper: public Auto::TestCase, gppUnit::MethodCaller, gppUnit::TimeReport{
gppUnit::MethodTimer* aTimer;
protected:
bool methodCalled;
bool timeReported;
double runtimeReport;
std::stringstream methodCallLog;
void forward();
void reportTime(double run_time);
void givenTimer(gppUnit::MethodTimer& given);
void whenCalled();
void thenMethodCalled();
};
}
#endif // TESTMETHODTIMERS_H_5119E4AA_7A61_49FF_80C1_048CC165F549
|
/*************************************************
* Publicly released by Rhoban System, August 2012
* www.rhoban-system.fr
*
* Freely usable for non-commercial purposes
*
* Licence Creative Commons *CC BY-NC-SA
* http://creativecommons.org/licenses/by-nc-sa/3.0
*************************************************/
#include <vector>
#include <iostream>
#include <sstream>
#include <cmath>
#include <string.h>
#include <logging/log.h>
#include "TestCase.h"
using namespace std;
double TestCase::deltaDouble = 0.000001;
TestCase::TestCase() : assertions(0), assertionsPassed(0)
{
}
void TestCase::run()
{
assertions = 0;
assertionsPassed = 0;
_run();
cout << endl;
cout << "-------------------------------" << endl;
#ifdef HAVE_COLORS
if (assertionsPassed == assertions) {
cout << T_COLOR_GREEN;
} else {
cout << T_COLOR_RED;
}
#endif
cout << "Ended, " << assertionsPassed << "/" << assertions << " assertions passed" << endl << endl;
#ifdef HAVE_COLORS
cout << T_COLOR_RESET;
#endif
}
void TestCase::setPlace(string file, int line, string function)
{
ostringstream oss;
oss << file << ":" << line << " in " << function;
place = oss.str();
}
void TestCase::error(string error)
{
assertions++;
cout << "!FAIL " << place << " " << current << ": " << error << endl;
}
void TestCase::pass()
{
assertions++;
assertionsPassed++;
cout << "." << flush;
}
void TestCase::_assertTrue(bool expression)
{
if (!expression) {
error("Expression is false");
} else {
pass();
}
}
void TestCase::_assertFalse(bool expression)
{
if (expression) {
error("Expression is true");
} else {
pass();
}
}
void TestCase::_assertEquals(string str1, string str2, bool neg)
{
if ((str1 != str2) ^ neg) {
if (neg) {
error("String are equals (" + str1 + " == " + str2 + ")");
} else {
error("String differs (" + str1 + " != " + str2 + ")");
}
} else {
pass();
}
}
void TestCase::_assertEquals(char *char1, char *char2, int size)
{
if (char1 == NULL || char2 == NULL) {
error("Null pointer");
return;
}
if (memcmp(char1, char2, size) != 0) {
error("Char* differs");
} else {
pass();
}
}
void TestCase::_assertEquals(int int1, int int2, bool neg)
{
if ((int1 != int2) ^ neg) {
ostringstream oss;
if (neg) {
oss << "Int are equals (" << int1 << " == " << int2 << ")";
} else {
oss << "Int differs (" << int1 << " != " << int2 << ")";
}
error(oss.str());
} else {
pass();
}
}
void TestCase::_assertEquals(char char1, char char2, bool neg)
{
if ((char1 != char2) ^ neg) {
ostringstream oss;
if (neg) {
oss << "Char are equals (" << char1 << " == " << char2 << ")";
} else {
oss << "Char differs (" << char1 << " != " << char2 << ")";
}
error(oss.str());
} else {
pass();
}
}
void TestCase::_assertEqualsDelta(float f1, float f2, float delta)
{
if (abs(f1-f2) > delta) {
ostringstream oss;
oss << "Numbers differs (" << f1 << ", " << f2 << ")";
error(oss.str());
} else {
pass();
}
}
void TestCase::_assertEqualsDelta(double f1, double f2, double delta)
{
if (abs(f1-f2) > delta) {
ostringstream oss;
oss << "Numbers differs (" << f1 << ", " << f2 << ")";
error(oss.str());
} else {
pass();
}
}
|
/* THIS CODE IS FOR CALIBRATION OF SOIL MOISTURE SENSOR
*
* 1. Open the serial port monitor and set the baud rate to 9600
* 2. Record the sensor value when the probe is exposed to the air
* as "Value 1". This is the boundary value of dry soil “Humidity: 0%RH”
* 3. Take a cup of water and insert the probe into it
* no further than the red line in the diagram
* 4. Record the sensor value when the probe is exposed to the water
* as "Value 2". This is the boundary value of moist soil “Humidity: 100%RH”
*/
void setup() {
Serial.begin(9600); // open serial port, set the baud rate as 9600 bps
}
void loop() {
int val;
val = analogRead(0); //connect sensor to Analog 0
Serial.print(val); //print the value to serial port
delay(100);
}
|
#include <stdio.h>
#include <iostream>
using namespace std;
typedef int Element;
const int PRIME_BASE = 29;
const int MAXTAM = 100000;
void Reverse(string* str){
int n = (*str).size() - 1;
for(int i = 0; i < (*str).size() / 2; i++){
swap( (*str)[i], (*str)[n] );
n--;
}
}
string IntToString(int number){
string new_string = "";
while(number != 0){
new_string += char( (number % 10) + '0');
number /= 10;
}
Reverse(&new_string);
return new_string;
}
unsigned int Pow(int value, int power){
unsigned int new_value = 1;
for(int i = 0; i < power; i++){
new_value *= value;
}
return new_value;
}
struct HashTable{
HashTable(int size): size_of(size) { table = new int[size]; Clear(); }
void Destroy(){
delete table;
}
void Clear(){
for(int i = 0; i < size_of; i++){
table[i] = 0;
}
}
int Hash(int value){
int power = 0;
unsigned int new_value = 0;
string value_str = IntToString(value);
for(int i = value_str.size() - 1; i >= 0; i--){
new_value += Pow(PRIME_BASE, power) * int(value_str[i]);
power++;
}
return new_value % size_of;
}
bool Find(Element value){
if(table[Hash(value)] == 0)
return true;
return false;
}
void InsertElement(Element value){
table[Hash(value)] += 1;
}
int* table;
int size_of;
};
struct Node {
Node(const Element& _value)
: next(nullptr), value(_value) {}
Node* next;
Element value;
};
struct LinkedList {
LinkedList() : size_of(0), head(nullptr), tail(nullptr) {}
const int Size(){
return size_of;
}
bool IsEmpty() const {
return head == nullptr;
}
void Append(const Element& value) {
Node* node = new Node(value);
if (IsEmpty()) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
size_of++;
}
void DeleteElement(Node* pointer){
Node* to_delete = pointer;
Node* next_element = pointer->next;
pointer->value = next_element->value;
pointer->next = next_element->next;
delete to_delete;
}
//Exercise
void RemoveDuplicates(){
HashTable hash_table(MAXTAM);
Node* last_node = head;
Node* actual_node = head;
while(actual_node != nullptr){
Node* copy = actual_node;
if(hash_table.Find(actual_node->value)){
hash_table.InsertElement(actual_node->value);
actual_node = actual_node->next;
} else {
if(actual_node->next == tail){
tail = last_node;
tail->next = nullptr;
break;
}
DeleteElement(actual_node);
}
last_node = copy;
}
hash_table.Destroy();
}
int size_of;
Node* head, *tail;
};
int main() {
LinkedList list;
list.Append(1);
list.Append(2);
list.Append(3);
list.Append(1);
list.Append(4);
list.Append(3);
list.Append(1);
list.RemoveDuplicates();
return 0;
}
|
#pragma once
#include <cstdint>
#include "asylo/platform/primitives/primitives.h"
namespace asylo {
namespace primitives {
static constexpr uint64_t keat_goldEnclaveSelector = kSelectorUser + 6
static constexpr uint64_t kcollisionEnclaveSelector = kSelectorUser + 5
static constexpr uint64_t kcollide_objectEnclaveSelector = kSelectorUser + 4
static constexpr uint64_t kshow_scoreEnclaveSelector = kSelectorUser + 1
static constexpr uint64_t kmoveEnclaveSelector = kSelectorUser + 3
static constexpr uint64_t ksetup_levelEnclaveSelector = kSelectorUser + 2
static constexpr uint64_t kAbortEnclaveSelector = kSelectorUser6
static constexpr uint64_t kdraw_lineOCallHandler = kSelectorUser + 6
static constexpr uint64_t ktimeOCallHandler = kSelectorUser + 5
static constexpr uint64_t ksrandOCallHandler = kSelectorUser + 4
static constexpr uint64_t krandOCallHandler = kSelectorUser + 3
static constexpr uint64_t kprintfOCallHandler = kSelectorUser + 0
static constexpr uint64_t kputsOCallHandler = kSelectorUser + 2
} // namespace primitives
} // namespace asylo
|
//--------------------------------------------------------------
//--------------------------------------------------------------
//
// AngraConstantMgr implementation file
//
// Authors: P.Chimenti
//
// 25-3-2010, v0.01
//
//--------------------------------------------------------------
//--------------------------------------------------------------
//==============================================================
//In this file is the class responsible for logging the simulation
//results
//==============================================================
#include "AngraConstantMgr.hh"
#include <climits>
using namespace std;
bool AngraConstantMgr::setup=false;
bool AngraConstantMgr::Init()
{
inFile = new std::ifstream();
// inFile->open("constantsCopia.dat");
inFile->open("constants.dat");
std::string key;
float value;
(*inFile) >> key;
while(key.length()>0){
(*inFile) >> value;
constants[key]=value;
(*inFile).ignore(INT_MAX, '\n');
key.clear();
(*inFile) >> key;
}
return true;
}
float AngraConstantMgr::GetValue(std::string key)
{
return constants[key];
}
|
#include "EvenElevator.h"
bool EvenElevator::availableInFloor(int floor) {
return floor > 0 && floor <= this->maxFloor && (floor == 1 || !(floor & 1));
}
std::string EvenElevator::type() const {
return "EvenElevator";
}
void EvenElevator::outputPosition(std::ofstream& fout) const {
fout << "EvenElevator\t\t" << this->currentFloor;
}
|
// This file is subject to the terms and conditions defined in 'LICENSE' in the source code package
#ifndef JACTORIO_INCLUDE_GAME_PLAYER_PLAYER_ACTION_H
#define JACTORIO_INCLUDE_GAME_PLAYER_PLAYER_ACTION_H
#pragma once
#include <array>
#include <functional>
#include "jactorio.h"
namespace jactorio::render
{
class RenderController;
}
namespace jactorio::game
{
class GameController;
/// Associates enum key (action) with method (executor)
/// \remark Do NOT reorder as order here is referenced by localized names in local files
#define J_PLAYER_ACTIONS \
J_CREATE_ACTION(player_move_up, PlayerMoveUp) \
J_CREATE_ACTION(player_move_right, PlayerMoveRight) \
J_CREATE_ACTION(player_move_down, PlayerMoveDown) \
J_CREATE_ACTION(player_move_left, PlayerMoveLeft) \
\
J_CREATE_ACTION(deselect_held_item, DeselectHeldItem) \
\
J_CREATE_ACTION(place_entity, PlaceEntity) \
J_CREATE_ACTION(activate_layer, ActivateTile) \
J_CREATE_ACTION(pickup_or_mine_entity, PickupOrMineEntity) \
\
J_CREATE_ACTION(rotate_entity_clockwise, RotateEntityClockwise) \
J_CREATE_ACTION(rotate_entity_counter_clockwise, RotateEntityCounterClockwise) \
\
J_CREATE_ACTION(toggle_main_menu, ToggleMainMenu) \
J_CREATE_ACTION(toggle_debug_menu, ToggleDebugMenu) \
J_CREATE_ACTION(toggle_character_menu, ToggleCharacterMenu) \
\
J_CREATE_ACTION(test, ActionTest)
struct PlayerAction
{
struct Context
{
std::reference_wrapper<GameController> gameController;
/// Handle to renderer, since initialization of the renderer is delayed
render::RenderController** hRenderController = nullptr;
// Hide implementation details on how the members are obtained
// Cannot be called GameController on GCC since that is already a class name
J_NODISCARD GameController& GController() const noexcept {
return gameController.get();
}
J_NODISCARD render::RenderController& RController() const noexcept {
assert(hRenderController != nullptr);
assert(*hRenderController != nullptr);
return **hRenderController;
}
};
using Executor = void (*)(const Context& c);
#define J_CREATE_ACTION(enum_name__, executor__) enum_name__,
enum class Type
{
J_PLAYER_ACTIONS
count_
};
#undef J_CREATE_ACTION
static constexpr auto kActionCount_ = static_cast<int>(Type::count_);
/// \return Function which performs (executes) given PlayerAction::Type
J_NODISCARD static Executor& GetExecutor(Type type);
private:
// Executors for the actions
static void PlayerMoveUp(const Context& c);
static void PlayerMoveRight(const Context& c);
static void PlayerMoveDown(const Context& c);
static void PlayerMoveLeft(const Context& c);
static void DeselectHeldItem(const Context& c);
static void PlaceEntity(const Context& c);
static void ActivateTile(const Context& c);
static void PickupOrMineEntity(const Context& c);
static void RotateEntityClockwise(const Context& c);
static void RotateEntityCounterClockwise(const Context& c);
static void ToggleMainMenu(const Context& c);
static void ToggleDebugMenu(const Context& c);
static void ToggleCharacterMenu(const Context& c);
/// For test use only, sets player position to -100, 120
static void ActionTest(const Context& c);
#define J_CREATE_ACTION(enum_name__, executor__) [](auto& game_controller) { executor__(game_controller); },
inline static std::array<Executor, kActionCount_> executors_{J_PLAYER_ACTIONS};
#undef J_CREATE_ACTION
};
#undef J_PLAYER_ACTIONS
} // namespace jactorio::game
#endif // JACTORIO_INCLUDE_GAME_PLAYER_PLAYER_ACTION_H
|
//**************************************************************************
//**
//** 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.
//**
//**************************************************************************
// HEADER FILES ------------------------------------------------------------
#include "../../qcommon.h"
#include "../../Common.h"
#include "../../endian.h"
#include "../../console_variable.h"
#include "../../content_types.h"
#include "../../md4.h"
#include "../../strings.h"
#include "local.h"
// MACROS ------------------------------------------------------------------
// TYPES -------------------------------------------------------------------
// EXTERNAL FUNCTION PROTOTYPES --------------------------------------------
// PUBLIC FUNCTION PROTOTYPES ----------------------------------------------
// PRIVATE FUNCTION PROTOTYPES ---------------------------------------------
// EXTERNAL DATA DECLARATIONS ----------------------------------------------
// PUBLIC DATA DEFINITIONS -------------------------------------------------
// PRIVATE DATA DEFINITIONS ------------------------------------------------
// CODE --------------------------------------------------------------------
//==========================================================================
//
// QClipMap38::LoadMap
//
//==========================================================================
void QClipMap38::LoadMap( const char* AName, const idList<quint8>& Buffer ) {
map_noareas = Cvar_Get( "map_noareas", "0", 0 );
if ( !AName || !AName[ 0 ] ) {
numleafs = 1;
leafs = new cleaf_t[ 1 ];
Com_Memset( leafs, 0, sizeof ( cleaf_t ) );
numclusters = 1;
numareas = 1;
areas = new carea_t[ 1 ];
Com_Memset( areas, 0, sizeof ( carea_t ) );
cmodels = new cmodel_t[ 1 ];
Com_Memset( cmodels, 0, sizeof ( cmodel_t ) );
CheckSum = 0;
CheckSum2 = 0;
return; // cinematic servers won't have anything at all
}
CheckSum = LittleLong( Com_BlockChecksum( Buffer.Ptr(), Buffer.Num() ) );
CheckSum2 = CheckSum;
bsp38_dheader_t header = *( bsp38_dheader_t* )Buffer.Ptr();
for ( int i = 0; i < ( int )sizeof ( bsp38_dheader_t ) / 4; i++ ) {
( ( int* )&header )[ i ] = LittleLong( ( ( int* )&header )[ i ] );
}
if ( header.version != BSP38_VERSION ) {
common->Error( "CMod_LoadBrushModel: %s has wrong version number (%i should be %i)",
AName, header.version, BSP38_VERSION );
}
const byte* cmod_base = Buffer.Ptr();
// load into heap
LoadSurfaces( cmod_base, &header.lumps[ BSP38LUMP_TEXINFO ] );
LoadLeafs( cmod_base, &header.lumps[ BSP38LUMP_LEAFS ] );
LoadLeafBrushes( cmod_base, &header.lumps[ BSP38LUMP_LEAFBRUSHES ] );
LoadPlanes( cmod_base, &header.lumps[ BSP38LUMP_PLANES ] );
LoadBrushes( cmod_base, &header.lumps[ BSP38LUMP_BRUSHES ] );
LoadBrushSides( cmod_base, &header.lumps[ BSP38LUMP_BRUSHSIDES ] );
LoadNodes( cmod_base, &header.lumps[ BSP38LUMP_NODES ] );
LoadAreas( cmod_base, &header.lumps[ BSP38LUMP_AREAS ] );
LoadAreaPortals( cmod_base, &header.lumps[ BSP38LUMP_AREAPORTALS ] );
LoadVisibility( cmod_base, &header.lumps[ BSP38LUMP_VISIBILITY ] );
LoadEntityString( cmod_base, &header.lumps[ BSP38LUMP_ENTITIES ] );
LoadSubmodels( cmod_base, &header.lumps[ BSP38LUMP_MODELS ] );
InitBoxHull();
ClearPortalOpen();
Name = AName;
}
//==========================================================================
//
// QClipMap38::ReloadMap
//
//==========================================================================
void QClipMap38::ReloadMap( bool ClientLoad ) {
if ( !ClientLoad ) {
ClearPortalOpen();
}
}
//==========================================================================
//
// QClipMap38::LoadSurfaces
//
//==========================================================================
void QClipMap38::LoadSurfaces( const quint8* base, const bsp_lump_t* l ) {
const bsp38_texinfo_t* in = ( const bsp38_texinfo_t* )( base + l->fileofs );
if ( l->filelen % sizeof ( *in ) ) {
common->Error( "MOD_LoadBmodel: funny lump size" );
}
int count = l->filelen / sizeof ( *in );
if ( count < 1 ) {
common->Error( "Map with no surfaces" );
}
numtexinfo = count;
surfaces = new mapsurface_t[ count ];
mapsurface_t* out = surfaces;
for ( int i = 0; i < count; i++, in++, out++ ) {
String::NCpy( out->c.name, in->texture, sizeof ( out->c.name ) - 1 );
String::NCpy( out->rname, in->texture, sizeof ( out->rname ) - 1 );
out->c.flags = LittleLong( in->flags );
out->c.value = LittleLong( in->value );
}
}
//==========================================================================
//
// QClipMap38::LoadLeafs
//
//==========================================================================
void QClipMap38::LoadLeafs( const quint8* base, const bsp_lump_t* l ) {
const bsp38_dleaf_t* in = ( const bsp38_dleaf_t* )( base + l->fileofs );
if ( l->filelen % sizeof ( *in ) ) {
common->Error( "MOD_LoadBmodel: funny lump size" );
}
int count = l->filelen / sizeof ( *in );
if ( count < 1 ) {
common->Error( "Map with no leafs" );
}
// need to save space for box planes
leafs = new cleaf_t[ count + 1 ];
numleafs = count;
numclusters = 0;
cleaf_t* out = leafs;
for ( int i = 0; i < count; i++, in++, out++ ) {
out->contents = LittleLong( in->contents );
out->cluster = LittleShort( in->cluster );
out->area = LittleShort( in->area );
out->firstleafbrush = LittleShort( in->firstleafbrush );
out->numleafbrushes = LittleShort( in->numleafbrushes );
if ( out->cluster >= numclusters ) {
numclusters = out->cluster + 1;
}
}
if ( leafs[ 0 ].contents != BSP38CONTENTS_SOLID ) {
common->Error( "Map leaf 0 is not CONTENTS_SOLID" );
}
solidleaf = 0;
emptyleaf = -1;
for ( int i = 1; i < numleafs; i++ ) {
if ( !leafs[ i ].contents ) {
emptyleaf = i;
break;
}
}
if ( emptyleaf == -1 ) {
common->Error( "Map does not have an empty leaf" );
}
}
//==========================================================================
//
// QClipMap38::LoadLeafBrushes
//
//==========================================================================
void QClipMap38::LoadLeafBrushes( const quint8* base, const bsp_lump_t* l ) {
const quint16* in = ( const quint16* )( base + l->fileofs );
if ( l->filelen % sizeof ( *in ) ) {
common->Error( "MOD_LoadBmodel: funny lump size" );
}
int count = l->filelen / sizeof ( *in );
if ( count < 1 ) {
common->Error( "Map with no leaf brushes" );
}
// need to save space for box planes
leafbrushes = new quint16[ count + 1 ];
numleafbrushes = count;
quint16* out = leafbrushes;
for ( int i = 0; i < count; i++, in++, out++ ) {
*out = LittleShort( *in );
}
}
//==========================================================================
//
// QClipMap38::LoadPlanes
//
//==========================================================================
void QClipMap38::LoadPlanes( const quint8* base, const bsp_lump_t* l ) {
const bsp38_dplane_t* in = ( const bsp38_dplane_t* )( base + l->fileofs );
if ( l->filelen % sizeof ( *in ) ) {
common->Error( "MOD_LoadBmodel: funny lump size" );
}
int count = l->filelen / sizeof ( *in );
if ( count < 1 ) {
common->Error( "Map with no planes" );
}
// need to save space for box planes
planes = new cplane_t[ count + 12 ];
Com_Memset( planes, 0, sizeof ( cplane_t ) * ( count + 12 ) );
numplanes = count;
cplane_t* out = planes;
for ( int i = 0; i < count; i++, in++, out++ ) {
for ( int j = 0; j < 3; j++ ) {
out->normal[ j ] = LittleFloat( in->normal[ j ] );
}
out->dist = LittleFloat( in->dist );
out->type = LittleLong( in->type );
SetPlaneSignbits( out );
}
}
//==========================================================================
//
// QClipMap38::LoadBrushes
//
//==========================================================================
void QClipMap38::LoadBrushes( const quint8* base, const bsp_lump_t* l ) {
const bsp38_dbrush_t* in = ( const bsp38_dbrush_t* )( base + l->fileofs );
if ( l->filelen % sizeof ( *in ) ) {
common->Error( "MOD_LoadBmodel: funny lump size" );
}
int count = l->filelen / sizeof ( *in );
brushes = new cbrush_t[ count + 1 ];
Com_Memset( brushes, 0, sizeof ( cbrush_t ) * ( count + 1 ) );
numbrushes = count;
cbrush_t* out = brushes;
for ( int i = 0; i < count; i++, out++, in++ ) {
out->firstbrushside = LittleLong( in->firstside );
out->numsides = LittleLong( in->numsides );
out->contents = LittleLong( in->contents );
}
}
//==========================================================================
//
// QClipMap38::LoadBrushSides
//
//==========================================================================
void QClipMap38::LoadBrushSides( const quint8* base, const bsp_lump_t* l ) {
const bsp38_dbrushside_t* in = ( const bsp38_dbrushside_t* )( base + l->fileofs );
if ( l->filelen % sizeof ( *in ) ) {
common->Error( "MOD_LoadBmodel: funny lump size" );
}
int count = l->filelen / sizeof ( *in );
// need to save space for box planes
brushsides = new cbrushside_t[ count + 6 ];
numbrushsides = count;
cbrushside_t* out = brushsides;
for ( int i = 0; i < count; i++, in++, out++ ) {
int num = LittleShort( in->planenum );
out->plane = &planes[ num ];
int j = LittleShort( in->texinfo );
if ( j >= numtexinfo ) {
common->Error( "Bad brushside texinfo" );
}
out->surface = &surfaces[ j ];
}
}
//==========================================================================
//
// QClipMap38::LoadNodes
//
//==========================================================================
void QClipMap38::LoadNodes( const quint8* base, const bsp_lump_t* l ) {
const bsp38_dnode_t* in = ( const bsp38_dnode_t* )( base + l->fileofs );
if ( l->filelen % sizeof ( *in ) ) {
common->Error( "MOD_LoadBmodel: funny lump size" );
}
int count = l->filelen / sizeof ( *in );
if ( count < 1 ) {
common->Error( "Map has no nodes" );
}
nodes = new cnode_t[ count + 6 ];
numnodes = count;
cnode_t* out = nodes;
for ( int i = 0; i < count; i++, out++, in++ ) {
out->plane = planes + LittleLong( in->planenum );
for ( int j = 0; j < 2; j++ ) {
int child = LittleLong( in->children[ j ] );
out->children[ j ] = child;
}
}
}
//==========================================================================
//
// QClipMap38::LoadAreas
//
//==========================================================================
void QClipMap38::LoadAreas( const quint8* base, const bsp_lump_t* l ) {
const bsp38_darea_t* in = ( const bsp38_darea_t* )( base + l->fileofs );
if ( l->filelen % sizeof ( *in ) ) {
common->Error( "MOD_LoadBmodel: funny lump size" );
}
int count = l->filelen / sizeof ( *in );
areas = new carea_t[ count ];
numareas = count;
carea_t* out = areas;
for ( int i = 0; i < count; i++, in++, out++ ) {
out->numareaportals = LittleLong( in->numareaportals );
out->firstareaportal = LittleLong( in->firstareaportal );
out->floodvalid = 0;
out->floodnum = 0;
}
}
//==========================================================================
//
// QClipMap38::LoadAreaPortals
//
//==========================================================================
void QClipMap38::LoadAreaPortals( const quint8* base, const bsp_lump_t* l ) {
const bsp38_dareaportal_t* in = ( bsp38_dareaportal_t* )( base + l->fileofs );
if ( l->filelen % sizeof ( *in ) ) {
common->Error( "MOD_LoadBmodel: funny lump size" );
}
int count = l->filelen / sizeof ( *in );
areaportals = new bsp38_dareaportal_t[ count ];
numareaportals = count;
bsp38_dareaportal_t* out = areaportals;
for ( int i = 0; i < count; i++, in++, out++ ) {
out->portalnum = LittleLong( in->portalnum );
out->otherarea = LittleLong( in->otherarea );
}
}
//==========================================================================
//
// QClipMap38::LoadVisibility
//
//==========================================================================
void QClipMap38::LoadVisibility( const quint8* base, const bsp_lump_t* l ) {
numvisibility = l->filelen;
visibility = new quint8[ l->filelen ];
Com_Memcpy( visibility, base + l->fileofs, l->filelen );
vis = ( bsp38_dvis_t* )visibility;
vis->numclusters = LittleLong( vis->numclusters );
for ( int i = 0; i < vis->numclusters; i++ ) {
vis->bitofs[ i ][ 0 ] = LittleLong( vis->bitofs[ i ][ 0 ] );
vis->bitofs[ i ][ 1 ] = LittleLong( vis->bitofs[ i ][ 1 ] );
}
}
//==========================================================================
//
// QClipMap38::LoadEntityString
//
//==========================================================================
void QClipMap38::LoadEntityString( const quint8* base, const bsp_lump_t* l ) {
numentitychars = l->filelen;
entitystring = new char[ l->filelen ];
Com_Memcpy( entitystring, base + l->fileofs, l->filelen );
}
//==========================================================================
//
// QClipMap38::LoadSubmodels
//
//==========================================================================
void QClipMap38::LoadSubmodels( const quint8* base, const bsp_lump_t* l ) {
const bsp38_dmodel_t* in = ( const bsp38_dmodel_t* )( base + l->fileofs );
if ( l->filelen % sizeof ( *in ) ) {
common->Error( "MOD_LoadBmodel: funny lump size" );
}
int count = l->filelen / sizeof ( *in );
if ( count < 1 ) {
common->Error( "Map with no models" );
}
cmodels = new cmodel_t[ count ];
numcmodels = count;
cmodel_t* out = cmodels;
for ( int i = 0; i < count; i++, in++, out++ ) {
for ( int j = 0; j < 3; j++ ) {
// spread the mins / maxs by a pixel
out->mins[ j ] = LittleFloat( in->mins[ j ] ) - 1;
out->maxs[ j ] = LittleFloat( in->maxs[ j ] ) + 1;
out->origin[ j ] = LittleFloat( in->origin[ j ] );
}
out->headnode = LittleLong( in->headnode );
}
}
|
#include <stdio.h>
#include<algorithm>
using namespace std;
#define MAXN 105
bool cmp(int a,int b){
return a>b;
}
int main(){
int K,n[MAXN];
int tag[MAXN] = {0};
scanf("%d",&K);
for(int i = 0;i<K;i++){
scanf("%d",&n[i]);
int tmp = n[i];
if(tmp%2==0) tmp/=2;
else tmp = (3*tmp+1)/2;
while(tmp!=1){
if(tmp < MAXN) // !!!!!!不加这个判断的话很可能越界!!!!
tag[tmp] = 1;
if(tmp%2==0) tmp/=2;
else tmp = (3*tmp+1)/2;
}
}
int tmp[MAXN];
int j=0;
for(int i = 0 ; i < K ; i++){
if(tag[n[i]]==0) {
tmp[j++] = n[i];
}
}
sort(tmp,tmp+j,cmp);
for(int k=0 ; k<j ; k++){
printf("%d",tmp[k]);
if(k==j-1) printf("\n");
else printf(" ");
}
return 0;
}
|
/*
// Copyright 2007 Alexandros Panagopoulos
//
// This software is distributed under the terms of the GNU Lesser General Public Licence
//
// This file is part of Be3D library.
//
// Be3D 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 3 of the License, or
// (at your option) any later version.
//
// Be3D 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 Be3D. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _TEXTURE_H45631_INCLUDED_
#define _TEXTURE_H45631_INCLUDED_
#pragma once
#include "common.h"
#include "BaseTexture.h"
class Image;
#define TEXTURE_RECTANGLE_ARB 0x84F5
#define GL_TEXTURE_CUBE_MAP_ARB 0x8513
#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x8515
#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x8516
#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x8517
#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x8518
#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x8519
#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x851A
#define GL_RGBA32F_ARB 0x8814
#define GL_RGB32F_ARB 0x8815
#define GL_ALPHA32F_ARB 0x8816
#define GL_INTENSITY32F_ARB 0x8817
#define GL_LUMINANCE32F_ARB 0x8818
#define GL_LUMINANCE_ALPHA32F_ARB 0x8819
#define GL_RGBA16F_ARB 0x881A
#define GL_RGB16F_ARB 0x881B
#define GL_ALPHA16F_ARB 0x881C
#define GL_INTENSITY16F_ARB 0x881D
#define GL_LUMINANCE16F_ARB 0x881E
#define GL_LUMINANCE_ALPHA16F_ARB 0x881F
#define WGL_TYPE_RGBA_FLOAT_ARB 0x21A0 // for wglChoosePixelFormat
#define FLOAT_RGBA16_NV 0x888A
class Texture : public BaseTexture
{
friend class TextureManager;
private:
std::vector<unsigned char> m_data;
std::vector<float> m_fData;
public:
Texture();
virtual ~Texture();
void create(int width, int height, GLenum format, unsigned char* data = 0);
void create(const Image &image, bool bResize = true);
void toImage(Image *image);
void set();
void createMipMaps();
inline int getWidth() const { return m_width; }
inline int getHeight() const { return m_height; }
bool loadMatrixFile(const std::string& filename, int sz);
bool loadMatrixFileCSV(const std::string& filename);
void convolveWithNPSF(Texture *F, double xScale, double yScale);
void multWithBeta(float beta);
void reload();
bool loadFloatRaw(const std::string& filename, int width, int height);
bool storeFloatMat(const std::string& filename); // store as matlab file
private:
double evalF(Texture *F, double x, double y, double xScale, double yScale);
};
class Texture3D : public BaseTexture
{
friend class TextureManager;
public:
Texture3D();
virtual ~Texture3D();
void create(int format, int width, int height, int depth, unsigned char* voxels);
bool load(const std::string &filename);
void set();
void createMipMaps();
inline int getWidth() const { return m_width; }
inline int getHeight() const { return m_height; }
inline int getDepth() const { return m_depth; }
inline int getMaxDim() const { int maxDim = m_width; if (maxDim < m_height) maxDim = m_height; if (maxDim < m_depth) maxDim = m_depth; return maxDim; }
};
class CubeTexture : public BaseTexture
{
friend class TextureManager;
public:
CubeTexture();
virtual ~CubeTexture();
void set();
bool loadCubePPM(const std::string (&fnames)[6]);
bool loadCubeHDR(const std::string (&fnames)[6]);
};
#endif
|
#ifndef SEARCH_ITEMS_H
#define SEARCH_ITEMS_H
#include <QDialog>
#include <QtSql>
#include<QCompleter>
#include<QMenuBar>
#include<QMenu>
#include<QDate>
#include<QSqlQuery>
#include<QMessageBox>
#include<QByteArray>
#include<QtNetwork/QNetworkInterface>
#include<QBuffer>
#include<QFile>
#include<QIODevice>
#include<QPixmap>
#include<QComboBox>
#include<QFontComboBox>
namespace Ui {
class search_items;
}
class search_items : public QDialog
{
Q_OBJECT
public:
explicit search_items(QWidget *parent = 0);
~search_items();
QString find_in;
private slots:
void on_search_in_returnPressed();
private:
Ui::search_items *ui;
QSqlDatabase db;
QSqlQueryModel *model;
QCompleter *comp;
};
#endif // SEARCH_ITEMS_H
|
#ifndef FUNC_H
#define FUNC_H
#include <iostream>
#include <cstring>
void init(unsigned char *s, unsigned char *k, const int r);
unsigned char get_gamma(unsigned char *q1, unsigned char *q2, unsigned char *s);
void encode(unsigned char *plain_text, int size, unsigned char *k, int r);
void decode(unsigned char *plain_text, int size, unsigned char *k, int r);
void gen_key(unsigned char *k, int r);
#endif // FUNC_H
|
/* EE 205 Lab 2
*
* Name: Paulo Lemus
* File: Bank.cpp
* Date: 1/19/2017
*
* Create a bank account struct with account number, name, balance.
* Create 3 basic account customers: alice, bob, charlie.
* Store them in an aarray of structs
*
*/
#include <cstdlib>
#include <iostream>
#include <ctime> // for time()
#include <limits> // for numeric_limits
#include <cstring>
#include <string>
#include <map>
#define BASIC_MAX 3
#define SAVINGS_MAX 3
using namespace std;
struct BankAccount{
public:
// Setters
void setAccountNumber(long int accountNumber){
this->accountNumber = accountNumber;
}
void setName(char name[]){
strcpy(this->name, name);
}
void setBalance(float balance){
this->balance = balance;
}
void setPin(int pin){
this->pin = pin;
}
void addBalance(float addition){
balance += addition;
}
void checkBounds(){};
// Getters
long int getAccountNumber(){
return this->accountNumber;
}
string getName(){
return string(this->name);
}
float getBalance(){
return this->balance;
}
// Print functions
void printName(){
cout << "\nName: " << this->name << endl;
}
void printAccountNumber(){
cout << "\nAccount Number: " << this->accountNumber << endl;
}
void printBalance(){
cout << "\nBalance: " << this->balance << endl;
}
protected:
long int accountNumber;
int pin;
char name[37];
float balance;
};
struct BasicAccount : public BankAccount{
public:
private:
};
struct SavingsAccount : public BankAccount{
public:
SavingsAccount(){
withdrawals = 0;
}
void initAccount(long int number, char name[], float balance){
setAccountNumber(number);
setName(name);
setBalance(balance);
}
void addBalance(float addition){
balance += addition;
withdrawals++;
}
void checkBounds(){
if(withdrawals > 2) balance -= 3;
if(balance < 100) balance -= 10;
if(balance < 0) balance = 0;
}
private:
int withdrawals;
};
void depositMoney(BankAccount* ba){
float value;
cout << "Enter amount to deposit: ";
cin >> value;
ba->addBalance(value);
ba->checkBounds();
ba->printBalance();
cout << "Press ENTER to finish";
cin.clear();
cin.ignore(10000, '\n');
getchar();
}
void withdrawMoney(BankAccount* ba){
float value;
//get value and verify here
cout << "Enter amount to draw: ";
cin >> value;
ba->addBalance(value);
ba->checkBounds();
ba->printBalance();
cin.clear();
cin.ignore(10000, '\n');
getchar();
}
void initBasicAccounts(BasicAccount* ba){
for(int i = 0; i < BASIC_MAX; i++, ba++){
char name[37];
float balance;
int newAccountNumber = rand();
cout << "\nSetting account number: " << newAccountNumber << endl;
cout << "Enter name: ";
cin >> name;
cout << "Enter balance: $";
cin >> balance;
ba->setName(name);
ba->setAccountNumber(newAccountNumber);
ba->setBalance(balance);
cout << "\n\n---------------------------------------------------------------" << endl;
cout << "-------- SUMMARY ----------------------" << endl;
ba->printAccountNumber();
ba->printName();
ba->printBalance();
cout << "---------------------------------------------------------------\n\n";
}
}
// Global variable for the endlessly incrementing account numbers
int newAccountNumber;
int main(){
srand(time(NULL));
newAccountNumber = rand();
BasicAccount basicAccounts[BASIC_MAX];
SavingsAccount savingsAccounts[SAVINGS_MAX];
initBasicAccounts(basicAccounts);
/*
// Initialize Basic accounts
for(int i = 0; i < BASIC_MAX; i++){
// Variables used to assign name and balance
char name[37];
float balance;
cout << "\nSetting account number: " << newAccountNumber << endl;
cout << "Enter name: ";
cin >> name;
cout << "Enter balance: $";
cin >> balance;
basicAccounts[i].setName(name);
basicAccounts[i].setAccountNumber(newAccountNumber);
basicAccounts[i].setBalance(balance);
newAccountNumber++;
cout << "\n\n---------------------------------------------------------------" << endl;
cout << "-------- SUMMARY ----------------------" << endl;
basicAccounts[i].printAccountNumber();
basicAccounts[i].printName();
basicAccounts[i].printBalance();
cout << "---------------------------------------------------------------\n\n";
}
*/
cout << "INITIALIZE SAVINGS ACCOUNTS\n" << endl;
cin.clear();
cin.ignore(10000, '\n');
// initialize savings accounts
for(int i = 0; i < SAVINGS_MAX; i++){
char name[37];
float balance;
cout << "Setting account number: " << newAccountNumber << endl;
cout << "Enter name: ";
cin >> name;
cout << "Enter balance: $";
cin >> balance;
savingsAccounts[i].initAccount(newAccountNumber, name, balance);
newAccountNumber++;
cout << "\n\n-------------------------------------------------------------" << endl;
cout << "-------- SUMMARY -------------------------" << endl;
savingsAccounts[i].printAccountNumber();
savingsAccounts[i].printName();
savingsAccounts[i].printBalance();
cout << "-----------------------------------------------------------------\n\n";
}
cout << "Press ENTER to continue..." << endl;
cin.clear();
cin.ignore(10000, '\n');
getchar();
/* Loop waiting for input.
* User can:
*
* Withdraw money
* Deposit money
* Shut down bank with a secret code
*/
enum Options {DEFAULT, DEPOSIT, WITHDRAW, EXIT};
map<string, Options> enumMap;
enumMap["d"] = DEPOSIT;
enumMap["w"] = WITHDRAW;
enumMap["password"] = EXIT;
bool running = true;
while(running){
cin.clear();
cin.ignore(10000, '\n');
string userChoice;
Options option;
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
cout << " ################" << endl;
cout << " # MENU #" << endl;
cout << " ################" << endl;
cout << " (w)ithdraw (d)eposit" << endl;
cout << " \n\n\n\n\n\n\n";
cin >> userChoice;
try{
option = enumMap[userChoice];
} catch(const exception& e){
option = DEFAULT;
cout << "ENTERED THE CATCH BLOCK";
}
BankAccount* baptr;
switch(option){
case DEPOSIT:
// FUNCTION TO DEPOSIT
baptr = &basicAccounts[1];
//bankAccount = findAccount(basicAccounts, savingsAccounts);
depositMoney(baptr);
break;
case WITHDRAW:
// FUNCTION TO WITHDRAW
baptr = &savingsAccounts[0];
//bankAccount = findAccount(basicAccounts, savingsAccounts);
withdrawMoney(baptr);
break;
case EXIT:
running = false;
break;
case DEFAULT:
cout << "Invalid selection, press ENTER to try again";
getchar();
break;
default:
cout << "Invalid selection, press ENTER to try again";
getchar();
break;
}
}
return 0;
}
|
#include "Block.h"
#include <iostream>
Block::Block(float x , float y)
{
position = sf::Vector2f(x , y);
}
Block::~Block() {}
bool Block::Collision(character* obj , int* result , sf::Vector2u& mySize , sf::Vector2u& objSize)
{
if (!(obj->position.x + objSize.x < position.x || //left side collision
obj->position.x > position.x + mySize.x || //right side colision
obj->position.y + objSize.y < position.y || //top down collision
obj->position.y > position.y + mySize.y)) //bottom up collision
{
if (obj->prevPosition.y + objSize.y <= position.y) { *result = 1; return true; } //top Collision
else if ((obj->prevPosition.x >= position.x + mySize.x) || (obj->prevPosition.x + objSize.x <= position.x)) { *result = 2; return true; } //side Collision
else { *result = 3; return true; } //bottom collision
}
return false;
}
void Block::update(int i , int j , float f , sf::Vector2f& v , sf::Vector2u&) {}
void Block::render(sf::RenderWindow& window , Camera& camera)
{
this->sprite.setPosition(position.x - camera.position.x, position.y - camera.position.y);
window.draw(sprite);
}
|
#include "Player2Factory.h"
Player2 *Player2Factory::choice(int choice)
{
if(choice == 2)
return new HumanPlayer(24 / 2, 80 - 3);
else if (choice == 1)
return new EasyComputer(24 / 2, 80 - 3);
else if (choice == 3)
return new HardComputer(24 / 2, 80 - 3);
else
return NULL;
}
|
#ifndef SRC_EXCEPCOES_H_
#define SRC_EXCEPCOES_H_
#include <iostream>
#include "Date.h"
using namespace std;
/*
* Excepcoes
*/
/**
* Excepçao quando um cliente ja existe
*
*/
class ClienteExistente{
string nome;
public:
ClienteExistente(string nome){ this->nome = nome;}
string getNome() const{return nome;}
};
/**
* Excepçao quando um cliente nao existe
*
*/
class ClienteInexistente{
string nome;
public:
ClienteInexistente(string nome){ this->nome = nome;}
string getNome() const{return nome;}
};
/**
* Excepçao quando um funcionário ja existe
*
*/
class FuncionarioExistente{
string nome;
public:
FuncionarioExistente(string nome){this->nome = nome;}
string getNome() const{return nome;}
};
/**
* Excepçao quando um funcionario nao existe
*
*/
class FuncionarioInexistente{
string nome;
public:
FuncionarioInexistente(string nome){this->nome = nome;}
string getNome() const{return nome;}
};
/**
* Excepçao quando um veiculo ja existe
*
*/
class VeiculoExistente{
string matricula;
public:
VeiculoExistente(string mt){ matricula= mt;}
string getMatricula() const{ return matricula;}
};
/**
* Excepçao quando um veiculo nao existe
*
*/
class VeiculoInexistente{
string matricula;
public:
VeiculoInexistente(string mt){ matricula=mt;}
string getMatricula() const{ return matricula;}
};
/**
* Excepçao quando um serviço standard ja existe na oficina
*
*/
class ServicoExistente{
string nome;
public:
ServicoExistente(string nome){this->nome=nome;}
string getNome() const{ return nome;}
};
/**
* Excepçao quando um serviço standard nao existe na oficina
*
*/
class ServicoInexistente{
string nome;
public:
ServicoInexistente(string nome){this->nome=nome;}
string getNome() const{ return nome;}
};
class ClienteInativoNaoExistente{
int id;
public:
ClienteInativoNaoExistente (int id){this->id=id;}
int getId() const {return id;}
};
class BadIterator { };
class NoMoreSpace { };
class BadPosition { };
class ErroInterno { };
class Underflow { };
class Overflow { };
class BadArgs { };
#endif /* SRC_EXCEPCOES_E_AUXILIARES_H_ */
|
//
// Created by Lennart Oymanns on 03.05.17.
//
#ifndef NumberRepr_hpp
#define NumberRepr_hpp
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <sstream>
#include <string>
#include <boost/multiprecision/cpp_int.hpp>
namespace Equation {
using Integer_t = boost::multiprecision::cpp_int;
using Rational_t = boost::multiprecision::cpp_rational;
/** NumberRepr represents an actual number.
A number is either a fraction with denominator and numerator (with arbitrary
precision) or it is a floating point number.
*/
class NumberRepr {
public:
explicit NumberRepr();
explicit NumberRepr(const std::string &s);
explicit NumberRepr(long num, long denom = 1l) { SetFromInt(num, denom); }
explicit NumberRepr(const Rational_t &rat) {
isFraction = true;
isValid = true;
rational = rat;
}
explicit NumberRepr(const Integer_t &i) {
isFraction = true;
isValid = true;
rational = i;
}
explicit NumberRepr(double l) { SetFromDouble(l); }
NumberRepr &operator*=(const NumberRepr &rhs);
NumberRepr &operator/=(const NumberRepr &rhs);
NumberRepr &operator+=(const NumberRepr &rhs);
NumberRepr &operator-=(const NumberRepr &rhs);
void SetFromInt(long num, long denom = 1l);
void SetFromDouble(double l);
bool IsValid() const { return isValid; }
/** IsFraction returns true if this number is a fraction. */
bool IsFraction() const { return isFraction; }
double Double() const;
std::string String() const;
/** Numerator returns the numerator of the fraction.
Note, the result is only useful if IsFraction() is true. */
Integer_t Numerator() const {
return boost::multiprecision::numerator(rational);
}
/** Denominator returns the denominator of the fraction.
Note, the result is only useful if IsFraction() is true. */
Integer_t Denominator() const {
return boost::multiprecision::denominator(rational);
}
bool operator==(const NumberRepr &n) const;
bool operator!=(const NumberRepr &n) const { return !(*this == n); }
bool operator<(const NumberRepr &n);
bool operator>(const NumberRepr &n);
static NumberRepr Pow(const NumberRepr &base, const NumberRepr &exp);
void ToLatex(std::ostream &s) const;
private:
double value_double; ///< if isFraction==false, the value of this number
bool isFraction = false; ///< determines if this number is a fration or not
bool isValid = true; ///< determines if the number is valid
Rational_t rational; ///< if isFraction==true, the value of this number
};
inline NumberRepr operator+(NumberRepr lhs, const NumberRepr &rhs) {
lhs += rhs;
return lhs;
}
inline NumberRepr operator*(NumberRepr lhs, const NumberRepr &rhs) {
lhs *= rhs;
return lhs;
}
inline NumberRepr operator-(NumberRepr lhs, const NumberRepr &rhs) {
lhs -= rhs;
return lhs;
}
inline NumberRepr operator/(NumberRepr lhs, const NumberRepr &rhs) {
lhs /= rhs;
return lhs;
}
} // namespace Equation
std::ostream &operator<<(std::ostream &os, const Equation::NumberRepr &obj);
#endif /* NumberRepr_hpp */
|
#pragma once
#include "CHandler.h"
#include "CShaderManager.h"
struct SDrawingInfo
{
string PolygonName;
string Program;
T4Double Global_Color;
int DrawMode;
//optional
T4Double Line_Color;
};
class CDrawing :
public CHandler
{
public:
CShaderManager* V_PSM;
SVerArray V_Array;
string V_Program; // what program should be used for this drawing
T4Double V_Color; // global color
int V_DrawMode; //0 : point, 1 : line, 2 : strip, 3 : strip + line, 4 : triangles, 5: triangles + lines
T4Double V_LineColor;
CDrawing(const SDrawingInfo& s);
void M_Draw(const glm::mat4& mat, T4Double color);
virtual ~CDrawing() {}
};
|
#pragma once
#include "process.hh"
#include <functional>
#include <mutex>
#include <thread>
#define LOCK_GUARD(X) std::lock_guard<decltype(X)> l(X)
#define DELETE_COPY_MOVE(X) \
X(X&) = delete; \
X(const X&) = delete; \
X& operator=(X&) = delete; \
X& operator=(const X&) = delete
namespace plib {
class Watcher {
public:
using callback_func = std::function<void(Process)>;
Watcher() = default;
DELETE_COPY_MOVE(Watcher);
virtual void watch() = 0;
virtual void on_update(callback_func);
virtual void watch_start();
virtual void watch_stop();
virtual void watch_toggle();
virtual void start();
virtual void join();
virtual void join() const;
protected:
mutable std::thread server;
mutable std::mutex watch_mutex;
bool watch_ = true;
callback_func notifee_ = [](const Process&) {};
};
} // namespace plib
|
#pragma once
#include<glad/glad.h>
#include<iostream>
#include<string>
#include"stb_image.h"
class CTexture
{
public:
CTexture();
~CTexture();
CTexture(const char* picPath, GLint picColorType, bool flip_vertic);
unsigned int m_TexID;
private:
};
CTexture::CTexture()
{
}
CTexture::~CTexture()
{
}
inline CTexture::CTexture(const char* picPath,GLint picColorType,bool flip_vertic)
{
if (flip_vertic)
{
stbi_set_flip_vertically_on_load(true);
}
glGenTextures(1, &m_TexID);
glBindTexture(GL_TEXTURE_2D, m_TexID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
int width, height, nrChannels;
unsigned char* data = stbi_load(picPath, &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_2D, 0, picColorType, width, height, 0, picColorType, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
std::cout << "Failed to load texture" << std::endl;
}
stbi_image_free(data);
}
|
/* Rishabh Arora
IIIT-Hyderabad */
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> II;
typedef vector<int> VI;
typedef vector<II> VII;
typedef long long int LL;
typedef unsigned long long int ULL;
#define MAXSIZE 400005
#define mod 1000000007
#define rep(i, a, b) for(i = a; i < b; i++)
#define rev(i, a, b) for(i = a; i > b; i--)
#define INF INT_MAX
#define PB push_back
#define MP make_pair
#define F first
#define S second
#define SET(a,b) memset(a, b, sizeof(a))
//debugging statements
#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
#else
#define trace(...)
#endif
struct node {
int lc, i, l, r;
bool flag;
};
int ans = 0, tim = 1, w[MAXSIZE], W[MAXSIZE], arr[2*MAXSIZE], in[MAXSIZE], out[MAXSIZE], L[MAXSIZE], par[MAXSIZE], P[MAXSIZE][20], cnt[MAXSIZE], vis[MAXSIZE], query[MAXSIZE];
bool taken[MAXSIZE];
vector<vector<int> > adj;
vector<vector<node> > Q;
map<int, int> M;
inline bool cmp(node A, node B) {
return A.r < B.r;
}
inline int read_int() {
char c;
while (c = getchar(), c < '0' || c > '9');
int t = c - '0';
while (c = getchar(), c >= '0' && c <= '9') t = t * 10 + c - '0';
return t;
}
void dfs(int v) {
taken[v] = true;
in[v] = tim++;
arr[in[v]] = v;
for(auto it : adj[v])
if(!taken[it]) {
par[it] = v;
L[it] = L[v] + 1;
dfs(it);
}
out[v] = tim++;
arr[out[v]] = v;
return;
}
inline void LCApre(int n) {
int i, j;
rep(i, 1, n+1)
P[i][0] = par[i];
rep(i, 1, n+1)
for(j = 1; 1 << j <= n; j++)
if(P[i][j-1] != -1)
P[i][j] = P[P[i][j-1]][j-1];
return;
}
inline int LCA(int a, int b) {
int i, log;
if(L[a] < L[b])
swap(a, b);
for(log = 1; 1 << log <= L[a]; log++);
log--;
rev(i, log, -1)
if(L[a] - (1 << i) >= L[b])
a = P[a][i];
if(a == b)
return a;
rev(i, log, -1)
if(P[a][i] != -1 && P[a][i] != P[b][i])
a = P[a][i], b = P[b][i];
return par[a];
}
inline void add(int x) {
vis[x] ^= 1;
int temp = w[x];
if(vis[x] == 1) {
cnt[temp]++;
if(cnt[temp] == 1)
ans++;
}
else {
cnt[temp]--;
if(cnt[temp] == 0)
ans--;
}
return;
}
inline void remove(int x) {
vis[x] ^= 1;
int temp = w[x];
if(vis[x] == 0) {
cnt[temp]--;
if(cnt[temp] == 0)
ans--;
}
else {
cnt[temp]++;
if(cnt[temp] == 1)
ans++;
}
return;
}
int extra(int x) {
if(cnt[M[W[x]]] == 0)
return 1;
return 0;
}
int main() {
int n, m;
int i, j;
int u, v;
n = read_int();
m = read_int();
adj.resize(n+1);
rep(i, 1, n+1) {
W[i] = read_int();
M[W[i]] = 0;
}
int ind = 1;
for(auto &it : M)
M[it.F] = ind++;
rep(i, 1, n+1)
w[i] = M[W[i]];
rep(i, 1, n+1)
rep(j, 0, 17)
P[i][j] = -1;
rep(i, 1, n) {
u = read_int();
v = read_int();
adj[u].PB(v);
adj[v].PB(u);
}
L[1] = 0, par[1] = -1;
dfs(1);
LCApre(n);
int sq = sqrt(2*n);
int sz = 2*n / sq + 2;
Q.resize(sz + 2);
rep(i, 1, m+1) {
node T;
u = read_int(), v = read_int();
if(in[u] > in[v])
swap(u, v);
int L = LCA(u, v);
//trace(u, v, L);
T.i = i, T.lc = L;
if(L == u)
T.l = in[u], T.r = in[v], T.flag = false;
else
T.l = out[u], T.r = in[v], T.flag = true;
if(T.l % sq == 0)
Q[T.l/sq].PB(T);
else
Q[T.l/sq + 1].PB(T);
}
for(auto &it : Q)
sort(it.begin(), it.end(), cmp);
i = 0;
// for(auto it : Q) {
// cout<<i<<"->";
// i++;
// for(auto A : it)
// cout<<A.l<<"-"<<A.r<<" ";
// cout<<endl;
// }
int f = -1;
for(auto it : Q) {
int k;
if(it.size() != 0)
rep(k, 0, n+1)
vis[k] = 0, cnt[k] = 0;
ans = 0;
int start = sq * f;
int end = start;
f++;
//trace(start);
for(auto X : it) {
int L = X.l, R = X.r;
bool flag = X.flag;
int I = X.i;
//trace(start);
while(end <= R) { if(end == 0) { end++; continue; } add(arr[end++]); }
//trace(start);
while(start < L) { if(start == 0) { start++; continue; } remove(arr[start++]); }
//trace(start);
while(start > L) { cout<<"hello"<<endl; if(start == 1) { start--; continue; } add(arr[start-1]); start--; }
query[I] = ans;
if(flag)
query[I] += extra(X.lc);
}
}
rep(i, 1, m+1)
printf("%d\n", query[i]);
return 0;
}
|
// This file has been generated by Py++.
#ifndef WidgetComponentMap_hpp__pyplusplus_wrapper
#define WidgetComponentMap_hpp__pyplusplus_wrapper
void register_WidgetComponentMap_class();
#endif//WidgetComponentMap_hpp__pyplusplus_wrapper
|
#pragma warning(disable : 4996)
#include "hashTable.h"
using namespace std;
HashTable::HashTable() {
studnum = 100;
ht = new ListHead*[studnum];
for (int i = 0; i < studnum; i++) {
ht[i] = NULL;
}
}
int HashTable::hashFunc(int key) {
return key % studnum;
}
void HashTable::insertStudent(int key, Student* student) {
int hash_v = hashFunc(key);
if (ht[hash_v] == NULL) {
cout << "i'm inserting " << student->firstname << " w key " << key << " " << hash_v << endl;
ht[hash_v] = new ListHead(key, student);
cout << "my new ht[hash_v] head is " << ht[hash_v]->student->firstname << endl;
return;
}
else {
ListHead *end = ht[hash_v];
cout << "my ht[hash_v] head is " << ht[hash_v]->student->firstname << endl;
while (end->next != NULL) {
end = end->next;
}
end->next = new ListHead(key, student);
}
return;
}
Student* HashTable::searchStudent(int key) {
int hash_v = hashFunc(key);
//if the student at the key value is null return error
if (ht[hash_v] == NULL) {
return NULL;
}
else {
ListHead *end = ht[hash_v];
while (end != NULL && end->student->id != key) {
end = end->next;
}
if (end == NULL) {
return NULL;
}
else {
return end->student;
}
}
}
void HashTable::printStudent() {
//if the student at the key value is null return error
for (int hash_v = 0; hash_v < studnum; hash_v++) {
ListHead *end = ht[hash_v];
if (end != NULL) {
cout << end->student->firstname << " " << end->student->lastname << ", " << end->student->id << ", " << end->student->gpa << endl;
end = end->next;
}
else {
end = end->next;
}
}
}
// void HashTable::printStudent() {
// int hash_v = 0;
// //if the student at the key value is null return error
// if (ht[hash_v] == NULL) {
// cout << "NULL cuz empty" << endl;
// }
// else {
// ListHead *end = ht[hash_v];
// while (end != NULL) {
// cout << end->student->firstname << " " << end->student->lastname << ", " << end->student->id << ", " << end->student->gpa << endl;
// end = end->next;
// }
// if (end == NULL) {
// cout << "NULL cuz no student" << endl;
// }
// }
// }
void HashTable::remove(int key) {
int hash_v = hashFunc(key);
if (ht[hash_v] != NULL) {
ListHead *end = ht[hash_v];
ListHead *previous = NULL;
while (end != NULL && end->student->id != key) {
previous = end;
end = end->next;
}
if (end->student->id != key) {
if (previous == NULL) {
ListHead *next= end->next;
delete end;
ht[hash_v] = next;
}
else {
ListHead *next = end->next;
delete end;
previous->next = next;
}
}
}
}
HashTable::~HashTable() {
delete[] ht;
}
//pinter to the student from the id
|
#include "particles\Singularity.Particles.h"
using namespace Singularity;
using namespace Singularity::Graphics;
using namespace Singularity::Threading;
using namespace Singularity::Components;
namespace Singularity
{
namespace Particles
{
IMPLEMENT_OBJECT_TYPE(Singularity.Particles, ParticleExtension, Extension);
#pragma region Static Variables
ParticleExtension* ParticleExtension::g_pInstance = NULL;
#pragma endregion
#pragma region Constructors and Deconstructors
ParticleExtension::ParticleExtension()
: Extension("Particle Extension"), m_pState(NULL)
{
unsigned index = 0;
this->Set_Frequency(1 / 100.0f);
for(index = 0; index < SINGULARITY_PARTICLES_MAX_SUBTASKS; ++index)
this->m_pSubTasks[index] = new ParticleSubTask();
}
#pragma endregion
#pragma region Methods
void ParticleExtension::RegisterEmitter(ParticleEmitter* emitter)
{
if(emitter == NULL)
throw SingularityException("\"particle emitter\" cannot be null or empty");
lock(this->m_kLock)
{
this->m_pEmitters.push_back(emitter);
}
}
void ParticleExtension::UnregisterEmitter(Singularity::Particles::ParticleEmitter* emitter)
{
unsigned index, count;
if(emitter == NULL)
throw SingularityException("\"particle emitter\" cannot be null or empty");
lock(this->m_kLock)
{
count = this->m_pEmitters.size();
for(index = 0; index < count; ++index)
{
if(this->m_pEmitters[index] == emitter)
{
this->m_pEmitters[index] = this->m_pEmitters[count - 1];
this->m_pEmitters.pop_back();
}
}
}
}
#pragma endregion
#pragma region Overriden Methods
void ParticleExtension::OnInitialize()
{
this->m_kTimer.Reset();
this->m_kTimer.Tick();
}
void ParticleExtension::OnExecute()
{
unsigned index, count, taskCount, emitterCount;
ParticleState* state;
#if _DEBUG
printf("Particle Call Frequency = %3.1f\n", this->Get_ActualFrequency());
#endif
if(this->m_pState == NULL)
this->m_pState = new ParticleState(0.0f);
this->m_pState->ElapsedTime = this->m_kTimer.Get_ElapsedTime();
count = this->m_pEmitters.size();
if(count > 0)
{
taskCount = max(min(count / 5, SINGULARITY_PARTICLES_MAX_SUBTASKS), 1);
emitterCount = taskCount == 0 ? 0 : count / taskCount + 1;
for(index = 0; index < taskCount; ++index)
{
this->m_pSubTasks[index]->Update(this->m_pState, index * emitterCount, min((index + 1) * emitterCount, count));
this->Spawn(this->m_pSubTasks[index]);
}
}
this->Recycle();
}
#pragma endregion
#pragma region Static Methods
ParticleExtension* ParticleExtension::Instantiate()
{
if(!ParticleExtension::g_pInstance)
ParticleExtension::g_pInstance = new ParticleExtension();
return ParticleExtension::g_pInstance;
}
#pragma endregion
}
}
|
#include"SnakeCell.h"
SnakeCell::SnakeCell(int _x, int _y) :Cell(_x, _y){}
|
#include "Model.h"
#include "ObjReader.h"
#include <iostream>
void Model::printModel()
{
std::cout << "Model stats: " << std::endl;
for (const Model::Vertex& v : this->vertexData)
{
std::cout << "vertex" << std::endl;
std::cout << "positions: " << v.posX << ' ' << v.posY << ' ' << v.posZ << std::endl;
std::cout << "normals: " << v.normX << ' ' << v.normY << ' ' << v.normZ << std::endl;
std::cout << "texture coords: " << v.teX << ' ' << v.teY << std::endl;
}
std::cout << "total vertices: " << this->vertexData.size() << std::endl;
for (unsigned int i = 0; i < this->indexData.size(); i += 3)
{
std::cout << "triangle" << std::endl;
std::cout << this->indexData[i] << ' ' << this->indexData[i + 1] << ' ' << this->indexData[i + 2] << std::endl;
}
std::cout << "total triangles: " << this->indexData.size() / 3 << std::endl;
}
void Model::loadModel(std::string sourcePath)
{
ObjReader::readVerticesObj(this, sourcePath);
loaded = true;
}
Model::Model(std::string sourcePath)
{
loadModel(sourcePath);
}
Model::Model(std::vector<Vertex>* verticesPtr)
{
}
|
/**
* Copyright (c) 2015 TheWalkingBot. For more information, see
*
* Authors : Xavier BOUVARD, Josselin Pochon, Maxime Vast
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef NAVIGATIONHANDLER_H
#define NAVIGATIONHANDLER_H
#include "BaseSensor.h"
#include "herkulex.h"
/**
* @brief The NavigationHandler class : communication with Herkulex servos
*/
class NavigationHandler : public BaseSensor
{
public:
NavigationHandler(char leftId, char rightId, PinName rx, PinName tx, double rate = 10);
virtual ~NavigationHandler();
void setPos(uint16_t leftPos, uint16_t rightPos);
void setVel(int16_t leftVel, int16_t rightVel);
int8_t getLStatus();
int8_t getRStatus();
int16_t getLPos();
int16_t getRPos();
void clear();
protected:
virtual std::string genMessage();
virtual void getData();
private:
char _leftId;
char _rightId;
int8_t _leftStatus;
int8_t _rightStatus;
int16_t _leftPos;
int16_t _rightPos;
Herkulex _herkulex;
};
#endif // NAVIGATIONHANDLER_H
|
#include <characters/warrior.h>
using namespace lab3::characters;
using namespace lab3;
Warrior::Warrior(const std::string &name, Place *place)
:Human(name, TYPE_HUMAN, place), skill_(WARRIOR_INITIAL_SKILL)
{
this->talk_msgs_ =
{
"Hi, I am a Warrior. I am here to protect the city from the animals and monsters that might"
" come and try to hurt our people"
};
}
Warrior::~Warrior()
{}
int Warrior::getStrength() const
{
return Character::getStrength() + this->skill_;
}
int Warrior::getDefense() const
{
return Character::getDefense() + this->skill_;
}
ActionResult Warrior::action(bool display_info)
{
Character*c = lookForEnemies();
if(c != nullptr && !c->isFighting()) // ** Fight to animals if they appear in the place
{
this->fight(*c);
}
else // ** Else train or talk with P =
{
// Maybe talk to player, if it's there
Character* player = this->currentPlace()->getCharacter(NAME_PLAYER);
if(player != nullptr && lab3::utils::eventHappens(1-TRAIN_PROB))
{
this->talk_to(*player);
}
else
{
this->train();
}
}
return EVENT_NULL;
}
ActionResult Warrior::train()
{
this->skill_ = std::min(this->skill_ + WARRIOR_TRAIN_INCREASE_SKILL, MAX_STRENGTH);
std::stringstream ss;
ss << this->name()<<" trains to gain experience. Now his skill level is "<<this->skill_<<" points";
lab3::utils_io::print_newline(ss.str());
return true;
}
int Warrior::getSkillPoints() const {return this->skill_;}
|
#include <eosiolib/eosio.hpp>
#include <eosiolib/print.hpp>
using namespace eosio;
class summ : public eosio::contract
{
public:
using contract::contract;
void add(uint64_t a,uint64_t b)
{
uint64_t c=a+b;
print("sum",a,b,c);
}
};
EOSIO_ABI( summ, (add))
|
#include<cstdio>
#include<iostream>
#include<queue>
#include<cmath>
using namespace std;
const int maxn = 1010;
int x[maxn],y[maxn];
priority_queue<long long> q;
int main()
{
int n,k1,k2;
while(cin >> n >> k1 >> k2)
{
while(!q.empty())
q.pop();
for(int i=0; i<n; i++)
cin >> x[i];
for(int i=0; i<n; i++)
{
cin >> y[i];
q.push(abs(x[i]-y[i]));
}
int k = k1 + k2,temp;
while(k > 0)
{
temp = q.top();
if(temp == 0) temp ++;
else temp --;
q.pop();
q.push(temp);
k--;
}
long long sum = 0;
while(!q.empty())
{
sum += q.top() * q.top();
q.pop();
}
cout << sum << endl;
}
return 0;
}
|
#include "../header/restaurant.hpp"
Restaurant::Restaurant(const string &restaurant_category)
{
this->restaurant_category = restaurant_category;
}
const string &Restaurant::get_restaurant_category() const
{
return this->restaurant_category;
}
void Restaurant::set_restaurant_category(const string &restaurant_category)
{
this->restaurant_category = restaurant_category;
}
|
#include <dsnutil/log/init.h>
#include <dsnutil/log/sinkmanager.h>
#include <dsnutil/null_deleter.h>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/formatter_parser.hpp>
/** \brief Initialize default logging environment
*
* Sets up some basic default parameters for the boost::log based logging environment and registers
* a formatter for boost::log::trivial::severity_level values.
*/
void dsn::log::init(const std::string& filename)
{
boost::log::register_simple_formatter_factory<boost::log::trivial::severity_level, char>("Severity");
boost::log::add_common_attributes();
static const std::string format{
"%TimeStamp% %Severity% (P:%ProcessID%,T:%ThreadID%) (%Class%@%This%): %Message%"
};
dsn::log::SinkManager& manager = dsn::log::SinkManager::instanceRef();
// create backend and sink for std::clog
typedef boost::log::sinks::text_ostream_backend backend_t;
boost::shared_ptr<backend_t> backend = boost::make_shared<backend_t>();
backend->add_stream(boost::shared_ptr<std::ostream>(&std::clog, dsn::null_deleter()));
backend->auto_flush(true);
typedef boost::log::sinks::synchronous_sink<backend_t> sink_t;
boost::shared_ptr<sink_t> sink(new sink_t(backend));
sink->set_formatter(boost::log::parse_formatter(format));
manager.add("std::clog", sink);
BOOST_LOG_TRIVIAL(trace) << "Initialized default console log settings (std::clog)";
if (filename.length() > 0) {
// setup backend and sink for the given logfile name, default rotation parameters are:
//
// - daily at 00:00:00
// - at 1GB size
typedef boost::log::sinks::text_file_backend backend_t;
boost::shared_ptr<backend_t> fileBackend = boost::make_shared<backend_t>(
boost::log::keywords::file_name = filename, boost::log::keywords::rotation_size = 1024 * 1024 * 1024,
boost::log::keywords::time_based_rotation = boost::log::sinks::file::rotation_at_time_point(0, 0, 0),
boost::log::keywords::format = format);
typedef boost::log::sinks::synchronous_sink<backend_t> sink_t;
boost::shared_ptr<sink_t> sink(new sink_t(fileBackend));
manager.add("file://" + filename, sink);
BOOST_LOG_TRIVIAL(trace) << "Initialized default settings for file: " << filename;
}
}
|
#ifndef NAVE_H
#define NAVE_H
#include <Entidad.h>
class Juego;
enum Movimiento
{
Izquierda,
Derecha,
Arriba,
Abajo,
NoMov
};
class Nave : public Entidad
{
public:
Nave();
void procesar_evento(sf::Event);
void accion(Juego&);
void pintar(sf::RenderWindow&);
void descontar_vidas();
int mostrar_vidas();
void descontar_salud();
int mostrar_salud();
void actualiza_puntaje();
int GetPunt(){return puntaje;};
protected:
int contador;
long puntaje;
int vidas;
int salud;
private:
bool subir;
sf::Text punt;
sf::Font fuente;
bool disparando;
Movimiento actual;
};
#endif // NAVE_H
|
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstring>
using namespace std;
int lengthOfLI(vector<int>& nums)
{
vector<int> res;
for(int i = 0; i < nums.size(); i++) {
vector<int>::iterator it = std::lower_bound(res.begin(),res.end(),nums[i]);
if(it == res.end())
res.push_back(nums[i]);
else
*it = nums[i];
}
return res.size();
}
int lengthOfLIS(vector<int>& nums)
{
int len = nums.size();
if(len < 2)
return len;
int res = 1;
int dp[len+1];
for(int i = 0; i < len; i++)
dp[i]=1;
for(int i = 1; i < len; i++) {
for(int j = 0; j < i; j++)
if(nums[j] < nums[i]) {
dp[i] = max(dp[i],dp[j]+1);
}
res = max(res,dp[i]);
}
return res;
}
int main()
{
vector<int> nums;
nums.push_back(10);
nums.push_back(9);
nums.push_back(2);
nums.push_back(5);
nums.push_back(3);
nums.push_back(7);
nums.push_back(101);
nums.push_back(18);
cout << lengthOfLI(nums) << endl;
return 0;
}
|
class Solution {
public:
unordered_map<long long, int> dict;
unordered_map<long long, int>::iterator iter;
string fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) return "0";
dict.clear();
char *result = (char*)malloc(sizeof(char)*10000);
int pos = 0;
long long a = numerator, b = denominator;
if (a < 0 ^ b < 0) result[pos++] = '-';
if (a < 0) a = -a;
if (b < 0) b = -b;
sprintf (result+pos, "%lld", a/b);
if (a % b == 0) return result;
pos = strlen(result);
result[pos++] = '.';
a %= b;
dict.insert(pair<long long, int>(a, pos));
while (a > 0)
{
a = (a*10) % b;
pos++;
iter = dict.find(a);
if (iter != dict.end())
{
int findpos = iter->second;
result[findpos] = '(';
result[pos+1] = ')';
result[pos+2] = '\0';
for (iter = dict.begin(); iter != dict.end(); iter++)
{
if (iter->second >= findpos)
{
result[iter->second+1] = iter->first*10/b+'0';
}
else
{
result[iter->second] = iter->first*10/b+'0';
}
}
return result;
}
else
{
dict.insert(pair<long long, int>(a, pos));
}
}
for (iter = dict.begin(); iter != dict.end(); iter++)
{
result[iter->second] = iter->first*10/b+'0';
}
result[pos] = '\0';
return result;
}
};
|
#include<bits/stdc++.h>
using namespace std;
int solve(int** input,int row,int col)
{
int** output = new int*[row];
for(int i=0;i<row;i++)
{
output[i]=new int[col]();
}
// first col intialized
for(int i=0;i<row;i++)
{
if(input[i][0] == 1)
{
output[i][0] = 0;
}
else if(input[i][0] == 0)
{
output[i][0] = 1;
}
}
// first row intialized
for(int i=0;i<col;i++)
{
if(input[0][i] == 1)
{
output[0][i] = 0;
}
else if(input[0][i] == 0)
{
output[0][i] = 1;
}
}
int max_ = 1;
for(int i=1;i<row;i++)
{
for(int j=1;j<col;j++)
{
if(input[i][j]==1)
{
output[i][j]=0;
}
else
{
output[i][j] = min(output[i-1][j-1],min(output[i][j-1],output[i-1][j])) + 1;
if(output[i][j] > max_)
{
max_ = output[i][j];
}
}
}
}
delete[] output;
return max_;
}
int main()
{
int m,n;
cin >> m >> n;
int** input = new int*[m];// rows
for(int i=0;i<m;i++)
{
input[i]=new int[n];
for(int j=0;j<n;j++)
{
cin >> input[i][j];
}
}
cout << solve(input,m,n) << endl;
delete[] input;
return 0;
}
|
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include "Token.h"
#ifndef __TiBasic_h_
#define __TiBasic_h_
class TiBasic {
public:
TiBasic(std::vector<std::string> programVector);
void clrhome() const;
void tiGoto(std::string label);
void disp(std::string output) const;
void prompt(char varName);
void delvar(char varName);
void runLine();
void run();
void pause() const;
private:
std::vector<std::string> fileSpace;
unsigned line;
std::map<std::string, unsigned> labels;
int vars[28];
Tokenizer parser;
};
#endif //__TiBasic_h_
|
#include <string>
#include <iostream>
#include "FileSystem.h"
#include "Commands.h"
#include "GlobalVariables.h"
using namespace std;
HistoryCommand::HistoryCommand(string args, const vector<BaseCommand *> & history):BaseCommand(args), history(history){
}
void HistoryCommand::execute(FileSystem & fs) {
if (verbose==2||verbose==3)
cout<<"history"+getArgs()<<endl;
for (int i=0;(unsigned) i<history.size(); i++) {
cout << i << " " << history.at(i)->toString() << " "<<history.at(i)->getArgs()<<endl;
}
}
string HistoryCommand::toString(){
return "history";
}
|
#include <LiquidCrystal.h>
#include "DHT.h"
////////////////////////////////////////////////////////////////////////
//Display initializing
#define LCD_LIGHT_PIN A4
const int buttonPin = 6;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int buttonState = 0;
////////////////////////////////////////////////////////////////////////
//Humidity and temperature sensor setup
#define DHTPIN 13 // data pin
//sensor type
#define DHTTYPE DHT22 // DHT 22 (AM2302)
//Humidity and temperature sensor initializing
DHT dht(DHTPIN, DHTTYPE);
////////////////////////////////////////////////////////////////////////
//Relay setup
const int pin_UV_Lamp = 7; // UV Lamp
const int pin_DAY_Lamp = 8; // Day Lamp
const int pin_NightLamp = 9; // Night Lamp
const int pinOut4 = 10;
////////////////////////////////////////////////////////////////////////
//Configuration
const int DayNightLevel = 150; //photo resistor level
const float NightLow = 25; // Night low temp
const float NightHigh = 27; // Night high temp
const float DayLow = 26; // Day low temp
const float DayHigh = 28; // Day high temp
float HighTemp;
float LowTemp;
const int CycleDelay = 1000; //Cycle delay millisecs
const int CyclesRead = 30; //Read sensor and turn on/off relays every CyclesRead cycles
const int CyclesDisplay = 10; //Display ON duration
////////////////////////////////////////////////////////////////////////
//Variables
int light;
float h;
float t;
int readcycles = 0;
int dispcycles = 0;
//int DayLampState = 0;
//int NightLampState = 0;
const int Cold = 1;
const int Hot = 2;
int ColdHot = 0; // 0 init, 1 cold, 2 hot
int IfDebug = 0;
////////////////////////////////////////////////////////////////////////
void debug(String msg) {
if (IfDebug==1)
{
Serial.println(msg);
}
}
void turn_relay_on(int pin) {
digitalWrite(pin, LOW);
}
void turn_relay_off(int pin) {
digitalWrite(pin, HIGH);
}
void setup() {
Serial.begin(9600);
debug("Start UP:");
//+Display Setup
// Setup the number of columns and rows that are available on the LCD.
lcd.begin(16, 2);
lcd.noDisplay();
// Set the button pin as an input.
pinMode(buttonPin, INPUT);
// Set the LCD display backlight pin as an output.
pinMode(LCD_LIGHT_PIN, OUTPUT);
// Turn off the LCD backlight.
lcd.display();
digitalWrite(LCD_LIGHT_PIN, HIGH);
lcd.print("Starting up...");
delay(5000);
// Turn off the LCD backlight.
//lcd.noDisplay();
digitalWrite(LCD_LIGHT_PIN, LOW);
//-Display Setup
//+Humidity and temperature sensor Setup
dht.begin();
//-Humidity and temperature sensor Setup
//+Relay Setup
pinMode(pin_UV_Lamp, OUTPUT);
//digitalWrite(pin_UV_Lamp, LOW);
turn_relay_off(pin_UV_Lamp);
pinMode(pin_DAY_Lamp, OUTPUT);
//digitalWrite(pin_DAY_Lamp, LOW);
turn_relay_off(pin_DAY_Lamp);
pinMode(pin_NightLamp, OUTPUT);
//digitalWrite(pin_NightLamp, LOW);
turn_relay_off(pin_NightLamp);
pinMode(pinOut4, OUTPUT);
//digitalWrite(pinOut4, LOW);
turn_relay_off(pinOut4);
//-Relay Setup
}
void loop() {
debug("Cycling==========================");
debug("readcycles: " + String(readcycles));
debug("dispcycles: " + String(dispcycles));
//Humidity and temperature reading
h = dht.readHumidity();
t = dht.readTemperature();
if (isnan(t) || isnan(h)) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Read error DHT ");
}
//Photo Resistor reading
light = analogRead(A0);
if (readcycles==0)
{
readcycles = CyclesRead;
debug("Readings:");
debug("humidity: " + String(h));
debug("temperature: " + String(t));
debug("light: " + String(light));
/////////////////////////////////
if (light>DayNightLevel)
{
HighTemp = DayHigh;
LowTemp = DayLow;
}
else
{
HighTemp = NightHigh;
LowTemp = NightLow;
}
debug("Limits:");
debug("HighTemp:" + String(HighTemp));
debug("LowTemp: " + String(LowTemp));
if (ColdHot==0)
{ //Init Hot/Cold status
if (t<HighTemp)
{
ColdHot = Cold;
}
else
{
ColdHot = Hot;
}
debug("Init status:");
debug("ColdHot: " + String(ColdHot));
}
else
{
if ((ColdHot==Cold)&&(t>=HighTemp))
{
ColdHot = Hot;
}
if ((ColdHot==Hot)&&(t<LowTemp))
{
ColdHot = Cold;
}
debug("Cycling status:");
debug("ColdHot: " + String(ColdHot));
}
if (light>DayNightLevel) // Day Lamp
{
turn_relay_off(pin_NightLamp);
debug("Night Lamp OFF");
turn_relay_on(pin_UV_Lamp);
debug("UV Lamp ON");
if (ColdHot==Cold)
{
//digitalWrite(pin_DAY_Lamp, HIGH); // turn it ON
turn_relay_on(pin_DAY_Lamp);
debug("Day Lamp ON");
}
if (ColdHot==Hot)
{
//digitalWrite(pin_DAY_Lamp, LOW); // turn it OFF
turn_relay_off(pin_DAY_Lamp);
debug("Day Lamp OFF");
}
}
if (light<=DayNightLevel) // Night Lamp
{
turn_relay_off(pin_DAY_Lamp);
debug("DAY Lamp OFF");
turn_relay_off(pin_UV_Lamp);
debug("UV Lamp OFF");
if (ColdHot==Cold)
{
//digitalWrite(pin_NightLamp, HIGH); // turn it ON
turn_relay_on(pin_NightLamp);
debug("Night Lamp ON");
}
if (ColdHot==Hot)
{
//digitalWrite(pin_NightLamp, LOW); // turn it OFF
turn_relay_off(pin_NightLamp);
debug("Night Lamp OFF");
}
}
//digitalWrite(pinOut4, LOW);
//digitalWrite(pinOut4, HIGH);
}
/////////////////////////////////
// Print text to the LCD.
lcd.clear();
lcd.print("Light Humid Temp");
lcd.setCursor(0, 1);
lcd.print(light);
lcd.setCursor(5, 1);
lcd.print(h);
lcd.setCursor(11, 1);
lcd.print(t);
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH)
{
dispcycles = CyclesDisplay;
// Turn the backlight on.
digitalWrite(LCD_LIGHT_PIN, HIGH);
// Display the text on the LCD.
//lcd.display();
debug("Light display........................");
}
if(dispcycles>0)
{
// if (dispcycles % 3 == 0)
// {
//
// }
if (dispcycles==1)
{
//lcd.noDisplay();
digitalWrite(LCD_LIGHT_PIN, LOW);
debug("Stop display........................");
}
dispcycles = dispcycles - 1;
debug("dispcycles2: " + String(dispcycles));
}
readcycles = readcycles - 1;
delay(CycleDelay);
}
|
#include <cmath>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <set>
#include <stack>
#include <sstream>
#include <string>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/* Solution */
const int MOD = 1000000007;
// If we can make first x values, and we have another coin y s.t. y <= x + 1
// then we can also make first x + y values
class Solution {
public:
int getMaximumConsecutive(vector<int>& coins)
{
sort(coins.begin(), coins.end());
int sum = 0;
for (int c : coins)
{
if (c <= sum + 1) sum += c;
else break;
}
return sum + 1;
}
};
int main()
{
Solution sol;
// vector<int> coins = {1, 3};
// vector<int> coins = {1,1,1,4};
vector<int> coins = {1,4,10,3,1};
cout << sol.getMaximumConsecutive(coins) << endl;
}
|
#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <regex>
using namespace std;
using namespace cv;
int main(int argc, char** argv) {
// [1]载入原始图和Mat变量定义
Mat srcImage = imread("jianzhu.png");
Mat midImage, dstImage; // 临时变量和目标图的定义
// [2]进行边缘检测和转化为灰度图
Canny(srcImage, midImage, 50, 200, 3); // 进行一次canny边缘检测
cvtColor(midImage, dstImage, CV_GRAY2BGR); // 转化边缘检测后的图为灰度图
// [3]进行霍夫线变换
vector<Vec2f> lines; // 定义一个矢量结构lines用于存放得到的线段矢量集合
HoughLines(midImage, lines, 1, CV_PI/180, 150, 0, 0);
// [4]依次在图中绘制出每条线段
for (size_t i=0; i < lines.size(); i++) {
float rho = lines[i][0], theta = lines[i][1];
Point pt1, pt2;
double a = cos(theta), b = sin(theta);
double x0 = a*rho, y0 = b*rho;
pt1.x = cvRound(x0 + 1000*(-b));
pt1.y = cvRound(y0 + 1000*(a));
pt2.x = cvRound(x0 - 1000*(-b));
pt2.y = cvRound(y0 - 1000*(a));
line(dstImage, pt1, pt2, Scalar(55, 100, 195), 1, LINE_AA);
}
// [5]显示原始图
imshow("[原始图]", srcImage);
// [6]边缘检测后的图
imshow("[边缘检测后的图]", midImage);
// [7]显示效果图
imshow("[效果图]", dstImage);
waitKey(0);
return 0;
}
|
#ifndef INC_MismatchedCharException_hpp__
#define INC_MismatchedCharException_hpp__
/**
* <b>SOFTWARE RIGHTS</b>
* <p>
* ANTLR 2.6.0 MageLang Insitute, 1999
* <p>
* We reserve no legal rights to the ANTLR--it is fully in the
* public domain. An individual or company may do whatever
* they wish with source code distributed with ANTLR or the
* code generated by ANTLR, including the incorporation of
* ANTLR, or its output, into commerical software.
* <p>
* We encourage users to develop software with ANTLR. However,
* we do ask that credit is given to us for developing
* ANTLR. By "credit", we mean that if you use ANTLR or
* incorporate any source code into one of your programs
* (commercial product, research project, or otherwise) that
* you acknowledge this fact somewhere in the documentation,
* research report, etc... If you like ANTLR and have
* developed a nice tool with the output, please mention that
* you developed it using ANTLR. In addition, we ask that the
* headers remain intact in our source code. As long as these
* guidelines are kept, we expect to continue enhancing this
* system and expect to make other tools available as they are
* completed.
* <p>
* The ANTLR gang:
* @version ANTLR 2.6.0 MageLang Insitute, 1999
* @author Terence Parr, <a href=http://www.MageLang.com>MageLang Institute</a>
* @author <br>John Lilley, <a href=http://www.Empathy.com>Empathy Software</a>
* @author <br><a href="mailto:pete@yamuna.demon.co.uk">Pete Wells</a>
*/
#include "antlr/config.hpp"
#include "antlr/RecognitionException.hpp"
#include "antlr/BitSet.hpp"
#include "antlr/CharScanner.hpp"
ANTLR_BEGIN_NAMESPACE(antlr)
class MismatchedCharException : public RecognitionException {
public:
// Types of chars
#ifndef NO_STATIC_CONSTS
static const int CHAR = 1;
static const int NOT_CHAR = 2;
static const int RANGE = 3;
static const int NOT_RANGE = 4;
static const int SET = 5;
static const int NOT_SET = 6;
#else
enum {
CHAR = 1,
NOT_CHAR = 2,
RANGE = 3,
NOT_RANGE = 4,
SET = 5,
NOT_SET = 6
};
#endif
public:
// One of the above
int mismatchType;
// what was found on the input stream
int foundChar;
// For CHAR/NOT_CHAR and RANGE/NOT_RANGE
int expecting;
// For RANGE/NOT_RANGE (expecting is lower bound of range)
int upper;
// For SET/NOT_SET
BitSet set;
protected:
// who knows...they may want to ask scanner questions
CharScanner* scanner;
public:
MismatchedCharException();
// Expected range / not range
MismatchedCharException(
int c,
int lower,
int upper_,
bool matchNot,
CharScanner* scanner_
);
// Expected token / not token
MismatchedCharException(
int c,
int expecting_,
bool matchNot,
CharScanner* scanner_
);
// Expected BitSet / not BitSet
MismatchedCharException(
int c,
BitSet set_,
bool matchNot,
CharScanner* scanner_
);
MismatchedCharException(
const ANTLR_USE_NAMESPACE(std)string& s,
int line
);
~MismatchedCharException() throw() {}
/**
* Returns the error message that happened on the line/col given.
* Copied from toString().
*/
ANTLR_USE_NAMESPACE(std)string getMessage() const;
};
ANTLR_END_NAMESPACE
#endif //INC_MismatchedCharException_hpp__
|
#include "easytf/operators/op_reverse.h"
#include "easytf/easytf_assert.h"
#include "easytf/easytf_logger.h"
//meta string
const std::string easytf::OP_Reverse::meta_unit_dim = "reverse_unit_dim";
easytf::OP_Reverse::OP_Reverse(const uint32_t unit_dim)
{
Param param;
param.put_item(meta_unit_dim, Any(unit_dim));
init(param);
}
//init
void easytf::OP_Reverse::init(const Param& param)
{
this->unit_dim = param.get_item(meta_unit_dim).as_int32();
}
//forward
void easytf::OP_Reverse::forward(const std::map<std::string, std::shared_ptr<Entity>>& bottom, std::map<std::string, std::shared_ptr<Entity>>& top)
{
easyAssert(bottom.size() == 1 && top.size() == 1, "size of bottom and top must be 1.");
auto bottom_iter = bottom.begin();
auto top_iter = top.begin();
//check
const int32_t bottom_size = bottom_iter->second->get_shape().get_full_size();
const float32_t* bottom_data = bottom_iter->second->get_data().as_float32_array();
const int32_t top_size = top_iter->second->get_shape().get_full_size();
float32_t* top_data = top_iter->second->get_data().as_float32_array();
easyAssert(bottom_size == top_size, "top_size must be equals with bottom_size.");
easyAssert(bottom_data && top_data, "bottom_data and top_data can't be empty.");
naive_implement(bottom_data, top_data, unit_dim, bottom_size / unit_dim);
}
void easytf::OP_Reverse::naive_implement(const float32_t* src, float32_t* dst, const int32_t unit_dim, const int32_t count)
{
//unit_0 unit_1 unit_2 ... unit_N
//unit_N unit_N-1 unit_N-2 ... unit_0
for (int32_t i = 0; i < count; i++)
{
const float32_t* src_unit = src + i*unit_dim;
float32_t* dst_unit = dst + (count - 1 - i)*unit_dim;
memcpy(dst_unit, src_unit, unit_dim*sizeof(float32_t));
}
}
|
#ifndef __Boids_Replay_h_
#define __Boids_Replay_h_
#include <vector>
#include <map>
#include <string>
#include "cocos2d.h"
#include <cstdint>
class SnapshotUnit : public cocos2d::Point
{
public:
double hp;
SnapshotUnit(const cocos2d::Point& pt) : cocos2d::Point(pt), hp(-1.0)
{
}
SnapshotUnit()
{
}
};
class Snapshot : public std::map<uint16_t, SnapshotUnit>
{
public:
unsigned random_i;
std::vector<std::string> logs;
};
typedef std::tuple<uint32_t, double, double> tJoystick;
typedef std::tuple<uint32_t, uint16_t, double, double, double> tSkill;
class ReplayData
{
public:
unsigned _frameRate, _snapshotInterval, _finishFrame;
std::string _terrainHashHex;
std::vector<tJoystick> joysticks;
std::vector<tSkill> skills;
std::vector<Snapshot*> snapshots;
void resetData();
};
#define _REPLAY_FRAME_RATE (1)
#define _REPLAY_TERRAIN_HASH_HEX (2)
#define _REPLAY_SNAPSHOT_INTERVAL (3)
#define _REPLAY_FINISH_FRAME (4)
#define _REPLAY_META_DATA_COUNT (4)
class ReplayToSave : protected ReplayData
{
friend class Utils;
private:
unsigned _currentFrame;
FILE* f;
void saveMetaInt(uint16_t meta_key, uint32_t meta_value);
void saveMetaString(uint16_t meta_key, const std::string& meta_value);
void saveMetaValues();
void log(const std::string& s);
void saveSnapshot();
std::vector<std::string> _logs_to_save;
public:
ReplayToSave(int frame_rate, int snapshot_interval);
void reset();
void updateFrame();
void setJoystick(double x, double y);
void setSkill(int unit_id, double dir_x, double dir_y, double range);
void setUnitHpToSnapshot(int unit_id, double hp);
void save(std::string replay_name = "");
};
class ReplayToPlay : private ReplayData
{
friend class Utils;
friend class ReplayComparer;
private:
bool _checkSnapshot;
unsigned _currentFrame;
FILE* f;
unsigned readMetaInt();
void readMetaString(std::string& str);
void readMetaValues();
std::vector<tJoystick>::const_iterator joysticks_iter;
std::vector<tSkill>::const_iterator skills_iter;
std::vector<Snapshot*>::const_iterator snapshots_iter;
void log(const std::string& s);
void compareSnapshot();
std::map<int, double> _units_hp_to_check;
std::vector<std::string> _logs_to_check;
public:
ReplayToPlay(std::string replay_path, bool check_snapshot);
void reset();
void updateFrame();
int getFrameRate();
double getJoystickX();
double getJoystickY();
int getSkillPlayer();
double getSkillDirX();
double getSkillDirY();
double getSkillRange();
void checkUnitHpWithSnapshot(int unit_id, double hp);
};
#endif
|
/*!
* \file TFeedBackForm.cpp
* \author GoZone
* \date
* \brief UI: 用户反馈
*
* \ref CopyRight
* =======================================================================<br>
* Copyright ? 2010-2012 GOZONE <br>
* All Rights Reserved.<br>
* The file is generated by Kaixin_Component Wizard for Tranzda Mobile Platform <br>
* =======================================================================<br>
*/
#include "KaiXinAPICommon.h"
/* 调用例子:
TApplication *pApp = GetApplication();
if(papp)
{
TFeedBackForm *pWin = new TFeedBackForm(papp);
if (pWin)
{
papp->SetActiveWindow(pWin);
}
else
{
papp->SendStopEvent();
}
}
*/
TFeedBackForm::TFeedBackForm(TApplication * pApp):TWindow(pApp)
{
Create(APP_KA_ID_FeedBackForm);
}
TFeedBackForm::~TFeedBackForm()
{
}
/*响应窗口创建事件*/
void TFeedBackForm::OnWinCreate(void)
{
TFont objFontType;
objFontType.Create(FONT_CONTENT, FONT_CONTENT);
m_BackBtn = SetAppBackButton(this);
SetAppTilte(this, APP_KA_ID_STRING_UserFeedback);
//Open Input Method
ImeOpenIme( IME_MODE_VOLITANT, IME_CLASS_CHINESE);
//提交按钮
TButton* pPublishBtn =new TButton ;
TRectangle obBtnRec(0,0,0,0); //初始(left, top, w, h)
TFont tFont;
obBtnRec.SetRect(BUTTON_X, BUTTON_Y, BUTTON_W, BUTTON_H);
const TBitmap * pNormalBmp = TResource::LoadConstBitmap(APP_KA_ID_BITMAP_button53);
const TBitmap * pOverBmp = TResource::LoadConstBitmap(APP_KA_ID_BITMAP_button53_over);
if(pPublishBtn->Create(this))
{
pPublishBtn->SetBounds(&obBtnRec);
m_nPublishBtnID= pPublishBtn->GetId();//Save Publish Button ID.
pPublishBtn->SetCaption(TResource::LoadConstString(APP_KA_ID_STRING_PostFeedback),TRUE);
tFont = pPublishBtn->GetFont();
tFont.Create(FONT_LARGE_BUTTON_CAPTION, FONT_LARGE_BUTTON_CAPTION);
pPublishBtn->SetFont(tFont);
pPublishBtn->SetStyles(BTN_STYLES_GRAPGICS);
pPublishBtn->SetColor(CTL_COLOR_TYPE_FORE,RGB_COLOR_WHITE);
pPublishBtn->SetColor(CTL_COLOR_TYPE_BACK,RGB_COLOR_WHITE);
pPublishBtn->SetColor(CTL_COLOR_TYPE_FOCUS_FORE,RGB_COLOR_WHITE);
pPublishBtn->SetColor(CTL_COLOR_TYPE_FOCUS_BACK,RGB_COLOR_WHITE);
pPublishBtn->SetImage(pNormalBmp,0);
pPublishBtn->SetImage(pOverBmp,1);
pPublishBtn->Show(TRUE);
}
TRichView *pFeedBakNoteRichView = static_cast<TRichView*>(GetControlPtr(APP_KA_ID_FeedBackForm_FeedBakNoteRichView));
if(pFeedBakNoteRichView)
{
pFeedBakNoteRichView->SetFont(objFontType);
pFeedBakNoteRichView->SetMaxVisibleLines(pFeedBakNoteRichView->GetLinesCount(), TRUE);
}
TLabel *pFeedBackContentLabel = static_cast<TLabel*>(GetControlPtr(APP_KA_ID_FeedBackForm_FeedBackContentLabel));
if(pFeedBackContentLabel)
{
pFeedBackContentLabel->SetFont(objFontType);
}
TEdit *pFeedBackContentField = static_cast<TEdit*>(GetControlPtr(APP_KA_ID_FeedBackForm_FeedBackContentField));
if(pFeedBackContentField)
{
pFeedBackContentField->SetFont(objFontType);
}
}
//1991, SubmitButton - "提交"
Boolean TFeedBackForm::OnSubmitButtonClick(TCtrl *Sender,EventType * eventP)
{
return FALSE;
}
/*响应菜单弹出前事件*/
void TFeedBackForm::OnBeforeMenuOpen(void)
{
return ;
}
/*响应控件上下文菜单弹出事件*/
Boolean TFeedBackForm::OnCtlContextMenu(EventType* eventP)
{
return FALSE;
}
/*响应窗口关闭前事件 - 决定是否可以关闭窗口*/
void TFeedBackForm::OnCloseQuery(VAR Boolean &CanClose)
{
return ;
}
/*响应窗口关闭事件 - 仅仅是响应而已*/
void TFeedBackForm::OnClosed()
{
// Stop the application if the main form(current form) has been closed
// GetApplication()->SendStopEvent();
}
/*响应主菜单项点击*/
Boolean TFeedBackForm::OnMenuSelect(Int32 MenuItemResID)
{
return FALSE;
}
/*响应弹出菜单项点击事件*/
Boolean TFeedBackForm::OnPopMenuSelect(Int32 MenuItemResID)
{
return FALSE;
}
/*响应控件点击事件*/
Boolean TFeedBackForm::OnCtlSelect(TApplication* pApp, EventType * eventP)
{
if(eventP->sParam1 == m_nPublishBtnID )
{
TEdit* tContentEdit =static_cast< TEdit* >(GetControlPtr(APP_KA_ID_FeedBackForm_FeedBackContentField));
if(TUString::StrLen(tContentEdit->GetCaption()) > 0)
{
pApp->MessageBox(TResource::LoadConstString(APP_KA_ID_STRING_Success),TResource::LoadConstString(APP_KA_ID_STRING_PostFeedback),WMB_OK);
this->CloseWindow();
}
else
{
pApp->MessageBox(TResource::LoadConstString(APP_KA_ID_STRING_ContentShouldNotBeEmpty),TResource::LoadConstString(APP_KA_ID_STRING_PostFeedback),WMB_OK);
}
return TRUE;
}
else if(eventP->sParam1 == m_BackBtn)
{
this->CloseWindow();
return TRUE;
}
#if 0
switch(eventP->sParam1)
{
}
#endif
return FALSE;
}
Boolean TFeedBackForm::EventHandler(TApplication * pApp, EventType * eventP)
{
Boolean handled = FALSE;
switch(eventP->eType)
{
case EVENT_CtrlSelect:
handled = OnCtlSelect(pApp,eventP);
break;
case EVENT_WinInit:
{
OnWinCreate();
}
break;
case EVENT_WinClose:
{
handled = TRUE;
OnClosed();
if(handled)
handled = FALSE;
else
handled = TRUE;
}
break;
case EVENT_CtrlSetFocus:
{
handled = _OnCtrlSetFocusEvent(pApp, eventP);
break;
}
case EVENT_CtrlKillFocus:
{
handled = _OnCtrlKillFocusEvent(pApp, eventP);
break;
}
case EVENT_WinEraseClient:
{
TDC dc(this);
WinEraseClientEventType *pEraseEvent = reinterpret_cast< WinEraseClientEventType* >( eventP );
TRectangle rc(pEraseEvent->rc);
TRectangle rcBack(5, 142, 310, 314);
this->GetBounds(&rcBack);
// 刷主窗口背景色
dc.SetBackColor(RGB_COLOR_WHITE);
// 擦除
dc.EraseRectangle(&rc, 0);
dc.DrawBitmapsH(TResource::LoadConstBitmap(APP_KA_ID_BITMAP_title_bg), 0, 0, SCR_W, GUI_API_STYLE_ALIGNMENT_LEFT);
//dc.DrawBitmapsH(TResource::LoadConstBitmap(APP_KA_ID_BITMAP_bottom_bg), 0, rcBack.Bottom()-68,
//320, GUI_API_STYLE_ALIGNMENT_LEFT|GUI_API_STYLE_ALIGNMENT_TOP);
pEraseEvent->result = 1;
handled = TRUE;
}
break;
case EVENT_KeyCommand:
{
// 抓取右软键事件
if (eventP->sParam1 == SYS_KEY_SOFTKEY_RIGHT_UP
|| eventP->sParam1 == SYS_KEY_SOFTKEY_RIGHT_LONG)
{
// 模拟退出按钮选中消息
HitControl(m_BackBtn);
handled = TRUE;
}
}
break;
}
if (handled == FALSE)
return TWindow::EventHandler(pApp,eventP);
return handled;
}
Boolean TFeedBackForm::_OnCtrlSetFocusEvent(TApplication * pApp, EventType * pEvent)
{
Boolean bHandled = FALSE;
#if 0
Int32 CtrlID = pEvent->sParam1;
if(CtrlID == APP_KA_ID_FeedBackForm_FeedBackContentField)
{
ImeOpenIme( IME_MODE_VOLITANT, IME_CLASS_CHINESE);
bHandled = TRUE;
}
#endif
return bHandled;
}
Boolean TFeedBackForm::_OnCtrlKillFocusEvent(TApplication * pApp, EventType * pEvent)
{
Boolean bHandled = FALSE;
#if 0
Int32 CtrlID = pEvent->sParam1;
if(CtrlID == APP_KA_ID_FeedBackForm_FeedBackContentField)
{
//close input method
ImeCloseIme();
bHandled = TRUE;
}
#endif
return bHandled;
}
|
//===--- TypeCheckRequests.cpp - Type Checking Requests ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "TypeChecker.h"
#include "TypeCheckType.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/Decl.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/TypeLoc.h"
#include "swift/AST/Types.h"
#include "swift/Subsystems.h"
using namespace swift;
llvm::Expected<Type>
InheritedTypeRequest::evaluate(
Evaluator &evaluator, llvm::PointerUnion<TypeDecl *, ExtensionDecl *> decl,
unsigned index,
TypeResolutionStage stage) const {
// Figure out how to resolve types.
TypeResolutionOptions options = None;
DeclContext *dc;
if (auto typeDecl = decl.dyn_cast<TypeDecl *>()) {
if (auto nominal = dyn_cast<NominalTypeDecl>(typeDecl)) {
dc = nominal;
options |= TypeResolutionFlags::AllowUnavailableProtocol;
} else {
dc = typeDecl->getDeclContext();
}
} else {
auto ext = decl.get<ExtensionDecl *>();
dc = ext;
options |= TypeResolutionFlags::AllowUnavailableProtocol;
}
Optional<TypeResolution> resolution;
switch (stage) {
case TypeResolutionStage::Structural:
resolution = TypeResolution::forStructural(dc);
break;
case TypeResolutionStage::Interface:
resolution = TypeResolution::forInterface(dc);
break;
case TypeResolutionStage::Contextual: {
// Compute the contextual type by mapping the interface type into context.
auto result =
evaluator(InheritedTypeRequest{decl, index,
TypeResolutionStage::Interface});
if (!result)
return result;
return dc->mapTypeIntoContext(*result);
}
}
TypeLoc &typeLoc = getTypeLoc(decl, index);
Type inheritedType;
if (typeLoc.getTypeRepr())
inheritedType = resolution->resolveType(typeLoc.getTypeRepr(), options);
else
inheritedType = typeLoc.getType();
return inheritedType ? inheritedType : ErrorType::get(dc->getASTContext());
}
llvm::Expected<Type>
SuperclassTypeRequest::evaluate(Evaluator &evaluator,
NominalTypeDecl *nominalDecl,
TypeResolutionStage stage) const {
assert(isa<ClassDecl>(nominalDecl) || isa<ProtocolDecl>(nominalDecl));
for (unsigned int idx : indices(nominalDecl->getInherited())) {
auto result = evaluator(InheritedTypeRequest{nominalDecl, idx, stage});
if (auto err = result.takeError()) {
// FIXME: Should this just return once a cycle is detected?
llvm::handleAllErrors(std::move(err),
[](const CyclicalRequestError<InheritedTypeRequest> &E) {
/* cycle detected */
});
continue;
}
Type inheritedType = *result;
if (!inheritedType) continue;
// If we found a class, return it.
if (inheritedType->getClassOrBoundGenericClass()) {
return inheritedType;
}
// If we found an existential with a superclass bound, return it.
if (inheritedType->isExistentialType()) {
if (auto superclassType =
inheritedType->getExistentialLayout().explicitSuperclass) {
if (superclassType->getClassOrBoundGenericClass()) {
return superclassType;
}
}
}
}
// No superclass.
return Type();
}
llvm::Expected<Type>
EnumRawTypeRequest::evaluate(Evaluator &evaluator, EnumDecl *enumDecl,
TypeResolutionStage stage) const {
for (unsigned int idx : indices(enumDecl->getInherited())) {
auto inheritedTypeResult =
evaluator(InheritedTypeRequest{enumDecl, idx, stage});
if (auto err = inheritedTypeResult.takeError()) {
llvm::handleAllErrors(std::move(err),
[](const CyclicalRequestError<InheritedTypeRequest> &E) {
// cycle detected
});
continue;
}
auto &inheritedType = *inheritedTypeResult;
if (!inheritedType) continue;
// Skip existential types.
if (inheritedType->isExistentialType()) continue;
// We found a raw type; return it.
return inheritedType;
}
// No raw type.
return Type();
}
// Define request evaluation functions for each of the type checker requests.
static AbstractRequestFunction *typeCheckerRequestFunctions[] = {
#define SWIFT_TYPEID(Name) \
reinterpret_cast<AbstractRequestFunction *>(&Name::evaluateRequest),
#include "swift/AST/TypeCheckerTypeIDZone.def"
#undef SWIFT_TYPEID
};
void swift::registerTypeCheckerRequestFunctions(Evaluator &evaluator) {
evaluator.registerRequestFunctions(SWIFT_TYPE_CHECKER_REQUESTS_TYPEID_ZONE,
typeCheckerRequestFunctions);
}
|
// Player.cpp
#include <iostream>
#include "Player.h"
#include "Random.h"
#include <string>
using namespace std;
// Default Constructor
// Initialises the data members to default values
Player::Player()
{
mName = "Default";
mClassName = "Default";
mAccuracy = 0;
mHitPoints = 0;
mMaxHitPoints = 0;
mExpPoints = 0;
mNextLevelExp = 0;
mLevel = 0;
mArmor = 0;
mGold = 0;
mWeapon.mName = "Default Weapon Name";
mWeapon.mDamageRange.mLow = 0;
mWeapon.mDamageRange.mHigh = 0;
}
// returns true if the player is dead, otherwise returns false
// (player is defined dead if hp <= 0)
bool Player::isDead()
{
return mHitPoints <= 0;
}
// accessor method, returns a copy of the mArmor data member
int Player::getArmor()
{
return mArmor;
}
// called when a monster hits a player
// The param specifies the amount of damage for which the player was hit, this indicates
// how many hit points should be subtracted from the player
void Player::takeDamage(int damage)
{
mHitPoints -= damage;
}
// This method is used to execute code that performs the character generation process.
// It 1st asks the user to enter a name for their character, then to select the class that player will be,
// then based on the class chosen, the properties of the player are filled out accordingly
void Player::createClass()
{
cout << "CHARACTER CLASS GENERATION" << endl;
cout << "==========================" << endl;
// Input character's name.
cout << "Enter your character's name: ";
getline(cin, mName);
// Character selection, the player will choose the race they wish to be
cout << "Please select a character class number..."<< endl;
cout << "[1] Elf, [2] Human, [3] Dwarf, [4] Halfling : ";
// create an int variable to store the users character race choice
int characterRaceNum = 1;
cin >> characterRaceNum;
/*
// TODO - Add message for invalid choice, repeat loop until valid choice is selected.
else
{
cout << "Sorry invalid choice, Please try again.." << endl;
// Some call to restart loop
}
*/
// here we just do a series of checks, depending on what number the player chose (what race)
// we output the appropriate selections based on the race choice..
// if player chose race 1
if (characterRaceNum == 1)
{
// output specific race selections
cout << "[1]Elf Fighter, [2]Elf Wizard, [3]Elf Cleric, [4]Elf Thief : ";
}
// if player chose race 2
else if (characterRaceNum == 2)
{
// output specific race selections
cout << "[1]Human Fighter, [2]Human Wizard, [3]Human Cleric, [4]Human Thief : ";
}
// if player chose race 3
else if (characterRaceNum == 3)
{
// output specific race selections
cout << "[1]Dwarf Fighter, [2]Dwarf Wizard, [3]Dwarf Cleric, [4]Dwarf Thief : ";
}
// if player chose race 4
else if (characterRaceNum == 4)
{
// output specific race selections
cout << "[1]Halfling Fighter, [2]Halfling Wizard, [3]Halfling Cleric, [4]Halfling Thief : ";
}
/*
// TODO - Add message for invalid choice, repeat loop until valid choice is selected.
else
{
cout << "Sorry invalid choice, Please try again.." << endl;
// Some call to restart loop
}
*/
// create another int variable to store the second choice
// e.g if the player chose elf, then their second choice may be elf fighter [1]
int characterNum = 1;
cin >> characterNum;
// same idea as a bove but a bit cleaner in a switch statement
// here we basically set the stats to the player depending on what choice they made
// e.g fighter, thief, cleric, wizard
// if character race is equal to 1 (elf)
if (characterRaceNum == 1)
{
// check which selection the user has made (e.g fighter, wizard, etc..)
switch (characterNum)
{
case 1: // Elf Fighter
mClassName = "Elf Fighter";
mAccuracy = 12;
mHitPoints = 25;
mMaxHitPoints = 34;
mExpPoints = 0;
mNextLevelExp = 1200;
mLevel = 1;
mArmor = 8;
mGold = 64;
mWeapon.mName = "Elf Long Sword";
mWeapon.mDamageRange.mLow = 2;
mWeapon.mDamageRange.mHigh = 13;
break;
case 2: // Elf Wizard
mClassName = "Elf Wizard";
mAccuracy = 8;
mHitPoints = 22;
mMaxHitPoints = 28;
mExpPoints = 0;
mNextLevelExp = 800;
mLevel = 1;
mArmor = 2;
mGold = 46;
mWeapon.mName = "Elf Wizard Staff";
mWeapon.mDamageRange.mLow = 3;
mWeapon.mDamageRange.mHigh = 5;
break;
case 3: // Elf Cleric
mClassName = "Elf Cleric";
mAccuracy = 6;
mHitPoints = 16;
mMaxHitPoints = 21;
mExpPoints = 0;
mNextLevelExp = 1350;
mLevel = 1;
mArmor = 3;
mGold = 28;
mWeapon.mName = "Elf Flail";
mWeapon.mDamageRange.mLow = 3;
mWeapon.mDamageRange.mHigh = 9;
break;
default: // Elf Thief
mClassName = "Elf Thief";
mAccuracy = 7;
mHitPoints = 18;
mMaxHitPoints = 26;
mExpPoints = 0;
mNextLevelExp = 1425;
mLevel = 1;
mArmor = 3;
mGold = 54;
mWeapon.mName = "Elf Short Sword";
mWeapon.mDamageRange.mLow = 3;
mWeapon.mDamageRange.mHigh = 7;
break;
}
}
// if character race is equal to 2 (Human)
else if (characterRaceNum == 2)
{
switch (characterNum)
{
case 1: // Human Fighter
mClassName = "Human Fighter";
mAccuracy = 10;
mHitPoints = 20;
mMaxHitPoints = 20;
mExpPoints = 0;
mNextLevelExp = 1000;
mLevel = 1;
mArmor = 4;
mGold = 50;
mWeapon.mName = "Long Sword";
mWeapon.mDamageRange.mLow = 1;
mWeapon.mDamageRange.mHigh = 8;
break;
case 2: // Human Wizard
mClassName = "Human Wizard";
mAccuracy = 5;
mHitPoints = 10;
mMaxHitPoints = 10;
mExpPoints = 0;
mNextLevelExp = 1000;
mLevel = 1;
mArmor = 1;
mGold = 26;
mWeapon.mName = "Human Staff";
mWeapon.mDamageRange.mLow = 1;
mWeapon.mDamageRange.mHigh = 4;
break;
case 3: // Human Cleric
mClassName = "Human Cleric";
mAccuracy = 8;
mHitPoints = 15;
mMaxHitPoints = 15;
mExpPoints = 0;
mNextLevelExp = 1000;
mLevel = 1;
mArmor = 3;
mGold = 18;
mWeapon.mName = "Flail";
mWeapon.mDamageRange.mLow = 1;
mWeapon.mDamageRange.mHigh = 6;
break;
default: // Human Thief
mClassName = "Human Thief";
mAccuracy = 7;
mHitPoints = 12;
mMaxHitPoints = 12;
mExpPoints = 0;
mNextLevelExp = 1000;
mLevel = 1;
mArmor = 2;
mGold = 38;
mWeapon.mName = "Short Sword";
mWeapon.mDamageRange.mLow = 1;
mWeapon.mDamageRange.mHigh = 6;
break;
}
}
// if character race is equal to 3 (Dwarf)
else if (characterRaceNum == 3)
{
switch (characterNum)
{
case 1: // Dwarf Fighter
mClassName = "Dwarf Fighter";
mAccuracy = 8;
mHitPoints = 24;
mMaxHitPoints = 26;
mExpPoints = 0;
mNextLevelExp = 950;
mLevel = 1;
mArmor = 5;
mGold = 62;
mWeapon.mName = "Long Sword";
mWeapon.mDamageRange.mLow = 1;
mWeapon.mDamageRange.mHigh = 10;
break;
case 2: // Dwarf Wizard
mClassName = "Dwarf Wizard";
mAccuracy = 3;
mHitPoints = 17;
mMaxHitPoints = 22;
mExpPoints = 0;
mNextLevelExp = 850;
mLevel = 1;
mArmor = 3;
mGold = 43;
mWeapon.mName = "Staff";
mWeapon.mDamageRange.mLow = 1;
mWeapon.mDamageRange.mHigh = 6;
break;
case 3: // Dwarf Cleric
mClassName = "Dwarf Cleric";
mAccuracy = 4;
mHitPoints = 26;
mMaxHitPoints = 30;
mExpPoints = 0;
mNextLevelExp = 1225;
mLevel = 1;
mArmor = 4;
mGold = 18;
mWeapon.mName = "Flail";
mWeapon.mDamageRange.mLow = 1;
mWeapon.mDamageRange.mHigh = 9;
break;
default: // Dwarf Thief
mClassName = "Dwarf Thief";
mAccuracy = 3;
mHitPoints = 15;
mMaxHitPoints = 18;
mExpPoints = 0;
mNextLevelExp = 650;
mLevel = 1;
mArmor = 4;
mGold = 54;
mWeapon.mName = "Short Sword";
mWeapon.mDamageRange.mLow = 1;
mWeapon.mDamageRange.mHigh = 4;
break;
}
}
// if character race is equal to 4 (Halfling)
else if (characterRaceNum == 4)
{
switch (characterNum)
{
case 1: // Halfling Fighter
mClassName = "Halfling Fighter";
mAccuracy = 11;
mHitPoints = 16;
mMaxHitPoints = 16;
mExpPoints = 0;
mNextLevelExp = 1525;
mLevel = 1;
mArmor = 8;
mGold = 150;
mWeapon.mName = "Long Sword";
mWeapon.mDamageRange.mLow = 2;
mWeapon.mDamageRange.mHigh = 7;
break;
case 2: // Halfling Wizard
mClassName = "Halfling Wizard";
mAccuracy = 2;
mHitPoints = 12;
mMaxHitPoints = 14;
mExpPoints = 0;
mNextLevelExp = 675;
mLevel = 1;
mArmor = 1;
mGold = 26;
mWeapon.mName = "Staff";
mWeapon.mDamageRange.mLow = 1;
mWeapon.mDamageRange.mHigh = 5;
break;
case 3: // Halfling Cleric
mClassName = "Halfling Cleric";
mAccuracy = 6;
mHitPoints = 15;
mMaxHitPoints = 20;
mExpPoints = 0;
mNextLevelExp = 1050;
mLevel = 1;
mArmor = 4;
mGold = 18;
mWeapon.mName = "Flail";
mWeapon.mDamageRange.mLow = 1;
mWeapon.mDamageRange.mHigh = 7;
break;
default: // Halfling Thief
mClassName = "Halfling Thief";
mAccuracy = 5;
mHitPoints = 12;
mMaxHitPoints = 18;
mExpPoints = 0;
mNextLevelExp = 755;
mLevel = 1;
mArmor = 4;
mGold = 86;
mWeapon.mName = "Short Sword";
mWeapon.mDamageRange.mLow = 1;
mWeapon.mDamageRange.mHigh = 9;
break;
}
}
/*
// TODO - Add message for invalid choice, repeat loop until valid choice is selected.
else
{
cout << "Sorry invalid choice, Please try again.." << endl;
// Some call to restart loop
}
*/
}
// essentially the same as the monster attack method, but has one IMPORTANT difference, that is
// we give the player an option of what to do on his attack turn (e.g Stay and fight .. ? or run, can also be extended..)
bool Player::attack(Monster& monster)
{
// Combat is turned based: display an options menu. You can,
// of course, extend this to let the player use an item,
// cast a spell, and so on.
int selection = 1;
cout << "1) Attack, 2) Run: ";
cin >> selection;
cout << endl;
switch( selection )
{
case 1:
cout << "You attack an " << monster.getName()
<< " with a " << mWeapon.mName << endl;
if( Random(0, 20) < mAccuracy )
{
int damage = Random(mWeapon.mDamageRange);
int totalDamage = damage - monster.getArmor();
if( totalDamage <= 0 )
{
cout << "Your attack failed to penetrate "
<< "the armor." << endl;
}
else
{
cout << "You attack for " << totalDamage
<< " damage!" << endl;
// Subtract from monster's hitpoints.
monster.takeDamage(totalDamage);
}
}
else
{
cout << "You miss!" << endl;
}
cout << endl;
break;
case 2:
// 25 % chance of being able to run.
int roll = Random(1, 4);
if( roll == 1 )
{
cout << "You run away!" << endl;
return true;//<--Return out of the function.
}
else
{
cout << "You could not escape!" << endl;
break;
}
}
return false;
}
// tests whether or not the player has acquired enough xp points to level up.
// called after every battle (to check xp points), if the player has gained enough, then
// some of the players stats (i.e hit points and accuracy) are randomly increased.
void Player::levelUp()
{
if( mExpPoints >= mNextLevelExp )
{
cout << "You gained a level!" << endl;
// Increment level.
mLevel++;
// Set experience points required for next level.
mNextLevelExp = mLevel * mLevel * 1000;
// Increase stats randomly.
mAccuracy += Random(1, 3);
mMaxHitPoints += Random(2, 6);
mArmor += Random(1, 2);
// Give player full hitpoints when they level up.
mLevel = mMaxHitPoints;
}
}
// called when the player chooses to rest, currently it increases the players hit points to maximum (useful for after a battle),
// can add the possibility of random enemy encounters during rest or other events if you wish!!...
void Player::rest()
{
cout << "Resting..." << endl;
mHitPoints = mMaxHitPoints;
// TODO: Modify function so that random enemy encounters
// are possible when resting.
}
// display the players stats
void Player::viewStats()
{
cout << "PLAYER STATS" << endl;
cout << "============" << endl;
cout << endl;
cout << "Name = " << mName << endl;
cout << "Class = " << mClassName << endl;
cout << "Accuracy = " << mAccuracy << endl;
cout << "Hitpoints = " << mHitPoints << endl;
cout << "MaxHitpoints = " << mMaxHitPoints << endl;
cout << "XP = " << mExpPoints << endl;
cout << "XP for Next Lvl = " << mNextLevelExp << endl;
cout << "Level = " << mLevel << endl;
cout << "Armor = " << mArmor << endl;
cout << "Gold = " << mGold << endl;
cout << "Weapon Name = " << mWeapon.mName << endl;
cout << "Weapon Damage = " << mWeapon.mDamageRange.mLow << "-" <<
mWeapon.mDamageRange.mHigh << endl;
cout << endl;
cout << "END PLAYER STATS" << endl;
cout << "================" << endl;
cout << endl;
}
// displayed after a player wins battle, a victory message is displayed and gives the player an xp point reward
void Player::victory(int xp, int gold)
{
cout << "You won the battle!" << endl;
cout << "You win " << xp << " experience points!" << endl;
cout << "you win " << gold << " gold coins!" << endl << endl;
mExpPoints += xp;
mGold += gold;
}
// called if the player died in battle, displays a "Game Over" message and asks the user to press 'q' to quit the game
void Player::gameover()
{
cout << "You died in battle..." << endl;
cout << endl;
cout << "================================" << endl;
cout << "GAME OVER!" << endl;
cout << "================================" << endl;
cout << "Press 'q' to quit: ";
char q = 'q';
cin >> q;
cout << endl;
}
// outputs the player's hit points to the console, used in game during battles, this is so the player may see how many hit points are remaining
void Player::displayHitPoints()
{
cout << mName << "'s hitpoints = " << mHitPoints << endl;
}
|
#include "OrderService.h"
OrderService::OrderService()
{
//ctor
}
void OrderService::viewOrderList(){
char selection;
while(selection != '4'){
service_header();
cout << "1. Edit last order" << endl;
cout << "2. View orders" << endl;
cout << "\n4. Back" << endl;
cin >>selection;
if(selection == '1'){
cout <<"Almost here..." << endl;
system("pause");
}
if(selection == '2'){
int select = orderRepo.readOrderList();
cout <<"Selected object: " << select << endl;
system("pause");
}
}
}
void OrderService::service_header(){
system("CLS");
cout << "-----------------------" << endl;
cout << " Order operations " << endl;
cout << "-----------------------" << endl;
}
|
#ifndef DeviceDisplayBinary_h
#define DeviceDisplayBinary_h
#include "Arduino.h"
namespace ART
{
class DeviceDisplay;
class DeviceDisplayBinary
{
public:
DeviceDisplayBinary(DeviceDisplay* deviceDisplay);
~DeviceDisplayBinary();
static void create(DeviceDisplayBinary* (&deviceDisplayBinary), DeviceDisplay* deviceDisplay);
private:
DeviceDisplay * _deviceDisplay;
};
}
#endif
|
#include "graph/from_node.hpp"
#include <string>
#include "graph/node.hpp"
#include "graph/unary_node.hpp"
namespace flow {
FromNode::FromNode(const std::string &name,
NodePtr input)
: UnaryNode(name),
m_input(input) {
}
}
|
/***********************************************
*
* DESCRIPTION: Atomic Model User Equipment (UE)
*
* AUTHOR: Misagh Tavanpour
*
* DATE: 19/09/2014
*
***********************************************/
#include "UE.h"
#include "message.h" // InternalMessage ....
UE::UE( const std::string &name ) : Atomic( name )
, In(addInputPort( "In" ))
, Out(addOutputPort( "Out" ))
, ProcessTime (00,00,00,20)
//, ProcessTime2 (00,00,00,10)
{
}
Model &UE::initFunction()
{
cout << "UE initFunction()" << endl;
packetNumber = 0;
state = idle;
lastSentPacketAcked = 0;
permissionToSend = 0;
holdIn(Atomic::active, 0);
return *this ;
}
/*********************************************************/
Model &UE::externalFunction( const ExternalMessage &msg )
{
cout << "UE externalFunction() at " << msg.time() << endl;
if (msg.port() == In ){
cout << " I received ACK for packet " << msg.value() << " at " << msg.time() << endl;
ackValue = msg.value();
state = rcvAck;
lastSentPacketAcked = 1;
holdIn(Atomic::active, Time(00,00,00,10));
}
return *this;
}
/*********************************************************/
Model &UE::internalFunction( const InternalMessage & )
{
cout << "UE internalFunction()" << endl;
if (state == 0 ) cout << " The input state is idle" << endl;
if (state == 1 ) cout << " The input state is sendPack" << endl;
if (state == 2 ) cout << " The input state is rcvAck" << endl;
switch (state){
case idle:
if (packetNumber == 0){
state = sendPack;
}
else {
passivate();
}
break;
case sendPack:
if (packetNumber > 9){
state = idle;
}else {
if (lastSentPacketAcked == 1 || packetNumber == 0){
packetNumber ++;
permissionToSend = 1;
cout << " packetNumber " << packetNumber << endl;
holdIn(Atomic::active, ProcessTime);
}else {
state = idle;
}
}
break;
case rcvAck:
state = sendPack;
permissionToSend = 0;
break;
}
if (state == 0 ) cout << " The Output state is idle" << endl;
if (state == 1 ) cout << " The Output state is sendPack" << endl;
if (state == 2 ) cout << " The Output state is rcvAck" << endl;
return *this;
}
/*********************************************************/
Model &UE::outputFunction( const InternalMessage &msg )
{
cout << "UE outputFunction() at " << msg.time() << endl;
if (state == sendPack && packetNumber > 0 && permissionToSend == 1){
sendOutput( msg.time(), Out, packetNumber) ;
lastSentPacketAcked = 0;
cout << " I sent packet number " << packetNumber << " at " << msg.time() << endl;
}
if (state == rcvAck){
cout << " I finished processing of received ACK for packet number " << ackValue << " at " << msg.time() << endl;
}
return *this ;
}
/*********************************************************/
UE::~UE()
{
}
|
/// Copyright (c) Vito Domenico Tagliente
#pragma once
#include <map>
#include <string>
#include <vector>
#include "builder.h"
#include "common.h"
#include "fsm.h"
#include "node.h"
|
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("robots.in");
ofstream fout("robots.out");
int **matrice,Lungime_Stack = 20,Pozitie_Stack = 0;
int *nrBoxes;
struct deque{
char CommandType[11];
int Line,Column,Boxes,ID,Timee;
deque *next,*back;
}**roboti;
struct last_executed_command{
char CommandType[11];
int RobotId,Line,Column,Boxes;
int ExecuteOrAdd,Timee;
}*LastExecuted;
void RESIZE(last_executed_command* &a){
last_executed_command *b;
Lungime_Stack *= 2;
b = new last_executed_command[Lungime_Stack]();
for(int i = 0 ; i < Lungime_Stack/2 ; i++)
b[i] = a[i];
delete[] a;
a = b;
}
void add_que(deque *&p,int newID,char newCommandType[5],int newLine,int newColumn,int newBoxes,bool priority){
deque *q;
if(p == NULL){
p = new deque;
p -> ID = newID;
p -> next = NULL;
p -> back = NULL;
p -> Timee = 1;
strcpy(p -> CommandType , newCommandType);
p -> Boxes = newBoxes;
p -> Line = newLine;
p -> Column = newColumn;
}
else if(priority == 0){
p -> back = new deque;
p -> back -> back = NULL;
p -> back -> next = p;
p = p -> back;
p -> Timee = 1;
strcpy(p -> CommandType , newCommandType);
p -> Boxes = newBoxes;
p -> Line = newLine;
p -> Column = newColumn;
p -> ID = newID;
}
else if(priority == 1){
q = p;
while(q -> next != NULL)
q = q -> next;
q -> next = new deque;
q -> next -> back = q;
q -> next -> next = NULL;
q = q -> next;
q-> Timee = 1;
strcpy(q -> CommandType , newCommandType);
q -> Boxes = newBoxes;
q -> Line = newLine;
q -> Column = newColumn;
}
if(Pozitie_Stack < Lungime_Stack){
LastExecuted[Pozitie_Stack].Boxes = newBoxes;
LastExecuted[Pozitie_Stack].Line = newLine;
LastExecuted[Pozitie_Stack].Column = newColumn;
LastExecuted[Pozitie_Stack].RobotId = newID;
strcpy(LastExecuted[Pozitie_Stack].CommandType , newCommandType);
LastExecuted[Pozitie_Stack].ExecuteOrAdd = 0;
Pozitie_Stack++;
}
else if(Pozitie_Stack == Lungime_Stack){
RESIZE(LastExecuted);
LastExecuted[Pozitie_Stack].Boxes = newBoxes;
LastExecuted[Pozitie_Stack].Line = newLine;
LastExecuted[Pozitie_Stack].Column = newColumn;
LastExecuted[Pozitie_Stack].RobotId = newID;
strcpy(LastExecuted[Pozitie_Stack].CommandType , newCommandType);
LastExecuted[Pozitie_Stack].ExecuteOrAdd = 0;
Pozitie_Stack++;
}
}
void HOW_MUCH_TIME(){
int x = Pozitie_Stack-2;
if(LastExecuted[Pozitie_Stack-1].ExecuteOrAdd==1){
fout<<LastExecuted[Pozitie_Stack-1].Timee<<'\n';
}
else{
while(x >= 0){
if(LastExecuted[x].ExecuteOrAdd == 1){
fout<<LastExecuted[x].Timee<<'\n';
break;
}
x--;
}
if(x == -1)
fout<<"No command was executed\n";
}
}
void add_que1(deque *&p,int newID,char newCommandType[5],int newLine,int newColumn,int newBoxes,bool priority){
deque *q;
if(p == NULL){
p = new deque;
p -> ID = newID;
p -> next = NULL;
p -> back = NULL;
p -> Timee = 1;
strcpy(p -> CommandType , newCommandType);
p -> Boxes = newBoxes;
p -> Line = newLine;
p -> Column = newColumn;
}
else if(priority == 0){
p -> back = new deque;
p -> back -> back = NULL;
p -> back -> next = p;
p = p -> back;
p -> Timee = 1;
strcpy(p -> CommandType , newCommandType);
p -> Boxes = newBoxes;
p -> Line = newLine;
p -> Column = newColumn;
p -> ID = newID;
}
else if(priority == 1){
q = p;
while(q -> next != NULL)
q = q -> next;
q -> next = new deque;
q -> next -> back = q;
q -> next -> next = NULL;
q = q -> next;
q-> Timee = 1;
strcpy(q -> CommandType , newCommandType);
q -> Boxes = newBoxes;
q -> Line = newLine;
q -> Column = newColumn;
}
}
void UNDO(){
if(Pozitie_Stack == 0)
fout<<"UNDO: No History\n";
else if(Pozitie_Stack >= 1 && LastExecuted[Pozitie_Stack-1].ExecuteOrAdd == 0){
deque *q = roboti[LastExecuted[Pozitie_Stack-1].RobotId];
if(q!=NULL && q -> Boxes == LastExecuted[Pozitie_Stack-1].Boxes && q -> Line == LastExecuted[Pozitie_Stack-1].Line && q -> Column == LastExecuted[Pozitie_Stack-1].Column && strcmp(q -> CommandType , LastExecuted[Pozitie_Stack-1].CommandType) == 0){
if(q -> next != NULL){
roboti[LastExecuted[Pozitie_Stack-1].RobotId] = roboti[LastExecuted[Pozitie_Stack-1].RobotId] -> next;
roboti[LastExecuted[Pozitie_Stack-1].RobotId] -> back = NULL;
delete q;
}
else if(q -> next == NULL){
delete q;
roboti[LastExecuted[Pozitie_Stack-1].RobotId] = NULL;
}
}
else{
if(q != NULL && q -> next != NULL && q -> next -> next != NULL){
while(q -> next -> next != NULL)
q = q -> next;
deque *q1 = q -> next;
q -> next = NULL;
delete q1;
}
else if(q != NULL && q -> next != NULL && q -> next -> next == NULL){
deque *q1 = q -> next;
q -> next = NULL;
delete q1;
}
}
}
else if(Pozitie_Stack >= 1 && LastExecuted[Pozitie_Stack-1].ExecuteOrAdd == 1){
if(strcmp(LastExecuted[Pozitie_Stack-1].CommandType , "GET") == 0){
matrice[LastExecuted[Pozitie_Stack-1].Line][LastExecuted[Pozitie_Stack-1].Column] += LastExecuted[Pozitie_Stack-1].Boxes;
nrBoxes[LastExecuted[Pozitie_Stack-1].RobotId] -= LastExecuted[Pozitie_Stack-1].Boxes;
}
else if(strcmp(LastExecuted[Pozitie_Stack-1].CommandType , "DROP") == 0){
matrice[LastExecuted[Pozitie_Stack-1].Line][LastExecuted[Pozitie_Stack-1].Column] -= LastExecuted[Pozitie_Stack-1].Boxes;
nrBoxes[LastExecuted[Pozitie_Stack-1].RobotId] += LastExecuted[Pozitie_Stack-1].Boxes;
}
add_que1(roboti[LastExecuted[Pozitie_Stack-1].RobotId],LastExecuted[Pozitie_Stack-1].RobotId,LastExecuted[Pozitie_Stack-1].CommandType,LastExecuted[Pozitie_Stack-1].Line,LastExecuted[Pozitie_Stack-1].Column,LastExecuted[Pozitie_Stack-1].Boxes,0);
}
if(Pozitie_Stack >= 1){
Pozitie_Stack--;
LastExecuted[Pozitie_Stack].Boxes = 0;
LastExecuted[Pozitie_Stack].Column = 0;
LastExecuted[Pozitie_Stack].Line = 0;
LastExecuted[Pozitie_Stack].ExecuteOrAdd = 2;
LastExecuted[Pozitie_Stack].RobotId = 0;
strcpy(LastExecuted[Pozitie_Stack].CommandType , "");
}
}
void EXECUTE(deque *&p){
deque *q = p;
if(q == NULL)
fout << "EXECUTE: No command to execute\n";
if(q != NULL && strcmp(q -> CommandType , "GET") == 0){
if(matrice[q -> Line][q -> Column] >= q -> Boxes){
matrice[q -> Line][q -> Column] -= q -> Boxes;
nrBoxes[q -> ID] += q -> Boxes;
if(Pozitie_Stack < Lungime_Stack){
LastExecuted[Pozitie_Stack].Boxes = q -> Boxes;
LastExecuted[Pozitie_Stack].Line = q -> Line;
LastExecuted[Pozitie_Stack].Column = q -> Column;
LastExecuted[Pozitie_Stack].RobotId = q -> ID;
LastExecuted[Pozitie_Stack].Timee = q -> Timee;
strcpy(LastExecuted[Pozitie_Stack].CommandType , q -> CommandType);
LastExecuted[Pozitie_Stack].ExecuteOrAdd = 1;
Pozitie_Stack++;
}
else if(Pozitie_Stack == Lungime_Stack){
RESIZE(LastExecuted);
LastExecuted[Pozitie_Stack].Boxes = q -> Boxes;
LastExecuted[Pozitie_Stack].Line = q -> Line;
LastExecuted[Pozitie_Stack].Column = q -> Column;
LastExecuted[Pozitie_Stack].RobotId = q -> ID;
LastExecuted[Pozitie_Stack].Timee = q -> Timee;
strcpy(LastExecuted[Pozitie_Stack].CommandType , q -> CommandType);
LastExecuted[Pozitie_Stack].ExecuteOrAdd = 1;
Pozitie_Stack++;
}
}
else if(matrice[q -> Line][q -> Column] < q-> Boxes){
nrBoxes[q -> ID] += matrice[q -> Line][q -> Column];
if(Pozitie_Stack < Lungime_Stack){
LastExecuted[Pozitie_Stack].Boxes = matrice[q -> Line][q -> Column];
LastExecuted[Pozitie_Stack].Line = q -> Line;
LastExecuted[Pozitie_Stack].Column = q -> Column;
LastExecuted[Pozitie_Stack].RobotId = q -> ID;
LastExecuted[Pozitie_Stack].Timee = q -> Timee;
strcpy(LastExecuted[Pozitie_Stack].CommandType , q -> CommandType);
LastExecuted[Pozitie_Stack].ExecuteOrAdd = 1;
Pozitie_Stack++;
}
else if(Pozitie_Stack == Lungime_Stack){
RESIZE(LastExecuted);
LastExecuted[Pozitie_Stack].Boxes = matrice[q -> Line][q -> Column];
LastExecuted[Pozitie_Stack].Line = q -> Line;
LastExecuted[Pozitie_Stack].Column = q -> Column;
LastExecuted[Pozitie_Stack].RobotId = q -> ID;
LastExecuted[Pozitie_Stack].Timee = q -> Timee;
strcpy(LastExecuted[Pozitie_Stack].CommandType , q -> CommandType);
LastExecuted[Pozitie_Stack].ExecuteOrAdd = 1;
Pozitie_Stack++;
}
matrice[q -> Line][q -> Column] = 0;
}
}
if(q != NULL && strcmp(q -> CommandType , "DROP") == 0){
if(nrBoxes[q -> ID] >= q -> Boxes){
matrice[q -> Line][q -> Column] += q -> Boxes;
nrBoxes[q -> ID] -= q -> Boxes;
if(Pozitie_Stack < Lungime_Stack){
LastExecuted[Pozitie_Stack].Boxes = q -> Boxes;
LastExecuted[Pozitie_Stack].Line = q -> Line;
LastExecuted[Pozitie_Stack].Column = q -> Column;
LastExecuted[Pozitie_Stack].RobotId = q -> ID;
LastExecuted[Pozitie_Stack].Timee = q -> Timee;
strcpy(LastExecuted[Pozitie_Stack].CommandType , q -> CommandType);
LastExecuted[Pozitie_Stack].ExecuteOrAdd = 1;
Pozitie_Stack++;
}
else if(Pozitie_Stack == Lungime_Stack){
RESIZE(LastExecuted);
LastExecuted[Pozitie_Stack].Boxes = q -> Boxes;
LastExecuted[Pozitie_Stack].Line = q -> Line;
LastExecuted[Pozitie_Stack].Column = q -> Column;
LastExecuted[Pozitie_Stack].RobotId = q -> ID;
LastExecuted[Pozitie_Stack].Timee = q -> Timee;
strcpy(LastExecuted[Pozitie_Stack].CommandType , q -> CommandType);
LastExecuted[Pozitie_Stack].ExecuteOrAdd = 1;
Pozitie_Stack++;
}
}
else if(nrBoxes[q -> ID] < q-> Boxes){
matrice[q -> Line][q -> Column] += nrBoxes[q -> ID];
if(Pozitie_Stack < Lungime_Stack){
LastExecuted[Pozitie_Stack].Boxes = nrBoxes[q -> ID];
LastExecuted[Pozitie_Stack].Line = q -> Line;
LastExecuted[Pozitie_Stack].Column = q -> Column;
LastExecuted[Pozitie_Stack].RobotId = q -> ID;
LastExecuted[Pozitie_Stack].Timee = q -> Timee;
strcpy(LastExecuted[Pozitie_Stack].CommandType , q -> CommandType);
LastExecuted[Pozitie_Stack].ExecuteOrAdd = 1;
Pozitie_Stack++;
}
else if(Pozitie_Stack == Lungime_Stack){
RESIZE(LastExecuted);
LastExecuted[Pozitie_Stack].Boxes = nrBoxes[q -> ID];
LastExecuted[Pozitie_Stack].Line = q -> Line;
LastExecuted[Pozitie_Stack].Column = q -> Column;
LastExecuted[Pozitie_Stack].RobotId = q -> ID;
LastExecuted[Pozitie_Stack].Timee = q -> Timee;
strcpy(LastExecuted[Pozitie_Stack].CommandType , q -> CommandType);
LastExecuted[Pozitie_Stack].ExecuteOrAdd = 1;
Pozitie_Stack++;
}
nrBoxes[q -> ID] = 0;
}
}
if(q != NULL && q -> next != NULL){
q -> next -> ID = q -> ID;
p = p -> next;
p -> back = NULL;
delete q;
}
else if(q != NULL && q -> next == NULL){
delete q;
p=NULL;
}
}
void PRINT_COMMANDS(deque *&p){
if(p == NULL)
fout<<"No command found\n";
else{
fout<<p -> ID<<":"<<' ';
deque *q=p;
while(q!=NULL){
fout<<q -> CommandType<<' '<<q -> Line<<' '<<q -> Column<<' '<<q -> Boxes;
if(q -> next != NULL)
fout<<"; ";
q = q -> next;
}
fout<<'\n';
}
}
void HOW_MANY_BOXES(int ID){
fout<<nrBoxes[ID]<<'\n';
}
int main()
{
int numarul_de_roboti,lines,columns,x,Linie,Coloana,IdRobot,Cutii,Priorietate;
char comanda[50];
fin >> numarul_de_roboti;
roboti = new deque*[numarul_de_roboti]();
fin >> lines >> columns;
matrice = new int*[lines]();
for(int i = 0 ; i < lines ; i++)
matrice[i] = new int[columns]();
for(int i = 0 ; i < lines ; i++)
for(int j = 0 ; j < columns ; j++){
fin >> x;
matrice[i][j] = x;
}
nrBoxes= new int[numarul_de_roboti]();
LastExecuted=new last_executed_command[Lungime_Stack]();
while(fin>>comanda){
if(strcmp(comanda , "ADD_GET_BOX") == 0){
for(int i = 0 ; i < numarul_de_roboti ; i++){
deque *q = roboti[i];
while(q!=NULL){
q -> Timee++;
q = q -> next;
}
}
fin>>IdRobot>>Linie>>Coloana>>Cutii>>Priorietate;
add_que(roboti[IdRobot],IdRobot,"GET",Linie,Coloana,Cutii,Priorietate);
}
else if(strcmp(comanda , "ADD_DROP_BOX") == 0){
for(int i = 0 ; i < numarul_de_roboti ; i++){
deque *q = roboti[i];
while(q!=NULL){
q -> Timee++;
q = q -> next;
}
}
fin>>IdRobot>>Linie>>Coloana>>Cutii>>Priorietate;
add_que(roboti[IdRobot],IdRobot,"DROP",Linie,Coloana,Cutii,Priorietate);
}
else if(strcmp(comanda , "EXECUTE") == 0){
fin>>IdRobot;
EXECUTE(roboti[IdRobot]);
for(int i = 0 ; i < numarul_de_roboti ; i++){
deque *q = roboti[i];
while(q!=NULL){
q -> Timee++;
q = q -> next;
}
}
}
else if(strcmp(comanda , "PRINT_COMMANDS") == 0){
fout<<"PRINT_COMMANDS: ";
for(int i = 0 ; i < numarul_de_roboti ; i++){
deque *q = roboti[i];
while(q!=NULL){
q -> Timee++;
q = q -> next;
}
}
fin>>IdRobot;
PRINT_COMMANDS(roboti[IdRobot]);
}
else if(strcmp(comanda , "LAST_EXECUTED_COMMAND") == 0){
fout<<"LAST_EXECUTED_COMMAND: ";
for(int i = 0 ; i < numarul_de_roboti ; i++){
deque *q = roboti[i];
while(q!=NULL){
q -> Timee++;
q = q -> next;
}
}
int x = Pozitie_Stack-2;
if(LastExecuted[Pozitie_Stack-1].ExecuteOrAdd==1){
fout<<LastExecuted[Pozitie_Stack-1].RobotId<<":"<<' '<<LastExecuted[Pozitie_Stack-1].CommandType<<' ';
fout<<LastExecuted[Pozitie_Stack-1].Line<<' '<<LastExecuted[Pozitie_Stack-1].Column<<' '<<LastExecuted[Pozitie_Stack-1].Boxes<<'\n';
}
else{
while(x >= 0){
if(LastExecuted[x].ExecuteOrAdd == 1){
fout<<LastExecuted[x].RobotId<<":"<<' '<<LastExecuted[x].CommandType<<' ';
fout<<LastExecuted[x].Line<<' '<<LastExecuted[x].Column<<' '<<LastExecuted[x].Boxes<<'\n';
break;
}
x--;
}
if(x == -1)
fout<<"No command was executed\n";
}
}
else if(strcmp(comanda , "UNDO") == 0){
for(int i = 0 ; i < numarul_de_roboti ; i++){
deque *q = roboti[i];
while(q!=NULL){
q -> Timee++;
q = q -> next;
}
}
UNDO();
}
else if(strcmp(comanda , "HOW_MANY_BOXES") == 0){
fout<<"HOW_MANY_BOXES: ";
for(int i = 0 ; i < numarul_de_roboti ; i++){
deque *q = roboti[i];
while(q!=NULL){
q -> Timee++;
q = q -> next;
}
}
fin>>IdRobot;
HOW_MANY_BOXES(IdRobot);
}
else if(strcmp(comanda , "HOW_MUCH_TIME") == 0){
fout<<"HOW_MUCH_TIME: ";
for(int i = 0 ; i < numarul_de_roboti ; i++){
deque *q = roboti[i];
while(q!=NULL){
q -> Timee++;
q = q -> next;
}
}
HOW_MUCH_TIME();
}
}
for(int i = 0 ; i < numarul_de_roboti ; i++){
deque *q = roboti[i];
deque *q1 = roboti[i];
while(q1!=NULL){
q = q1;
q1 = q1 -> next;
delete q;
}
}
delete[] roboti;
for(int i = 0 ; i < lines ; i++)
delete[] matrice[i];
delete[] matrice;
delete[] nrBoxes;
delete[] LastExecuted;
return 0;
}
|
#include"main.h"
#include"physics.h"
#include <iostream>
using namespace std;
#include<math.h>
void ball_collision(float cmi[3][50],float veli[3][50], float cmj[3][50],float velj[3][50],int i,int k)
{ //cout<<"abhi";
//cout<<veli[2]<<endl;
//cout<<velj[2]<<endl;
//float r=0.2;
float radial_vec_x =cmj[0][k]-cmi[0][i];
float radial_vec_y =cmj[1][k]-cmi[1][i];
float radial_vec_z =cmj[2][k]-cmi[2][i];
//cout<<radial_vec_z<<endl;
float radial_mod = ((radial_vec_x*radial_vec_x) + (radial_vec_y*radial_vec_y) + (radial_vec_z*radial_vec_z));
//if(radial_mod<=(4*r*r));
float dot_x=veli[0][i]*radial_vec_x;
float dot_y=veli[1][i]*radial_vec_y;
float dot_z=veli[2][i]*radial_vec_z;
float dot_res = (dot_x+dot_y+dot_z)/(radial_mod);
//cout<<dot_z<<endl;
float axial_veli_x = dot_res*radial_vec_x;
float axial_veli_y = dot_res*radial_vec_y;
float axial_veli_z = dot_res*radial_vec_z;
//cout<<axial_veli_z<<endl;
float eq_vel_x = veli[0][i] - axial_veli_x;
float eq_vel_y = veli[1][i] - axial_veli_y;
float eq_vel_z = veli[2][i] - axial_veli_z;
//cout<<eq_vel_z<<endl;
float dotj_x=velj[0][k]*radial_vec_x;
float dotj_y=velj[1][k]*radial_vec_y;
float dotj_z=velj[2][k]*radial_vec_z;
float dotj_resj = (dotj_x+dotj_y+dotj_z)/(radial_mod);
//cout<<dotj_z<<endl;
float axial_velj_x = dotj_resj*radial_vec_x;
float axial_velj_y = dotj_resj*radial_vec_y;
float axial_velj_z = dotj_resj*radial_vec_z;
//cout<<axial_velj_z<<endl;
float eq_vel_xj = velj[0][k] - axial_velj_x;
float eq_vel_yj = velj[1][k] - axial_velj_y;
float eq_vel_zj = velj[2][k] - axial_velj_z;
///cout<<eq_vel_zj<<endl;
veli[0][i] = eq_vel_x + axial_velj_x;
veli[1][i] = eq_vel_y + axial_velj_y;
veli[2][i] = eq_vel_z + axial_velj_z;
velj[0][k] = eq_vel_xj + axial_veli_x;
velj[1][k] = eq_vel_yj + axial_veli_y;
velj[2][k] = eq_vel_zj + axial_veli_z;
// cout<< veli[0]<<" "<<veli[1]<<" "<<veli[2]<<endl;
// cout<< velj[0]<<" "<<velj[1]<<" "<<velj[2]<<endl;
}
void overlap(float cm[3][50],int i,int k,float r1,float r2)
{
float distance;
distance= ((cm[0][i]-cm[0][k])*(cm[0][i]-cm[0][k])) + ((cm[1][i]-cm[1][k])*(cm[1][i]-cm[1][k])) + ((cm[2][i]-cm[2][k])*(cm[2][i]-cm[2][k]));
float r;
if(r2>=r1)
r=r2;
else
r=r1;
if(distance<=(4*r1*r2))
{
cm[0][i] = cm[0][i] -0.01*(cm[0][k] - cm[0][i]);
cm[1][i] = cm[1][i] -0.01*(cm[1][k] - cm[1][i]);
cm[2][i] = cm[2][i] -0.01*(cm[2][k] - cm[2][i]);
}
}
void col2 (float cmi[3][50],float veli[3][50], float cmj[3],float velj[3],int i)
{
float radial_vec_x =cmj[0]-cmi[0][i];
float radial_vec_y =cmj[1]-cmi[1][i];
float radial_vec_z =cmj[2]-cmi[2][i];
//cout<<radial_vec_z<<endl;
float radial_mod = ((radial_vec_x*radial_vec_x) + (radial_vec_y*radial_vec_y) + (radial_vec_z*radial_vec_z));
//if(radial_mod<=(4*r*r));
veli[0][i] = veli[0][i] - velj[0];
veli[1][i] = veli[1][i] - velj[1];
veli[2][i] = veli[2][i] - velj[2];
float dot_x=veli[0][i]*radial_vec_x;
float dot_y=veli[1][i]*radial_vec_y;
float dot_z=veli[2][i]*radial_vec_z;
float dot_res = (dot_x+dot_y+dot_z)/(radial_mod);
//cout<<dot_z<<endl;
float axial_veli_x = dot_res*radial_vec_x;
float axial_veli_y = dot_res*radial_vec_y;
float axial_veli_z = dot_res*radial_vec_z;
//cout<<axial_veli_z<<endl;
veli[0][i] = veli[0][i] - 2*axial_veli_x;
veli[1][i] = veli[1][i] - 2*axial_veli_y;
veli[2][i] = veli[2][i] - 2*axial_veli_z;
//cout<<eq_vel_z<<endl;
}
void overlap_static_terrain(float cm[3][50],int i,float cmj[3],float r1,float r2)
{
float distance;
distance= ((cm[0][i]-cmj[0])*(cm[0][i]-cmj[0])) + ((cm[1][i]-cmj[1])*(cm[1][i]-cmj[1])) + ((cm[2][i]-cmj[2])*(cm[2][i]-cmj[2]));
float r;
if(distance<=(0.49))
{
cm[0][i] = cm[0][i] +0.01*(cm[0][i] - cmj[0]);
cm[1][i] = cm[1][i] +0.01*(cm[1][i] - cmj[1]);
cm[2][i] = cm[2][i] +0.01*(cm[2][i] - cmj[2]);
}
}
|
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
if (int(nums.size()) == 0 || r * c != int(nums.size()) * int(nums[0].size())) {
return nums;
}
else {
// initialize 2 d vector, otherwise there will be a bad access
vector<vector<int>> result(r, vector<int>(c, 0));
// count how many number so far, transfer to 1d array
int count = 0;
// loop through the nums and transfer it to 1d array
for (int i = 0; i < int(nums.size()); ++i) {
for (int j = 0; j < int(nums[0].size()); ++j) {
result[count / c][count % c] = nums[i][j];
// 1d array match the nums
count++;
}
}
return result;
}
}
};
|
class Solution {
public:
int myAtoi(string str) {
long res = 0;
int negative_sign = 1;
int cur = 0;
bool has_number = true;
while(cur < str.length())
{
if(str[cur] == ' ' || str[cur] - '0' == 0)
{
cur++;
continue;
}
else if(str[cur] == '-' || str[cur] == '+' || (str[cur] - '0' < 10 && str[cur] - '0' > 0))
{
negative_sign = (str[cur] == '-')? -1 : 1;
if(str[cur] - '0' < 10 && str[cur] - '0' > 0)
res += str[cur] - '0';
cur++;
while(cur < str.length() && str[cur] - '0' < 10 && str[cur] - '0' >= 0)
{
res = res * 10 + str[cur++] - '0';
if(negative_sign * res > INT_MAX) return INT_MAX;
if(negative_sign * res < INT_MIN) return INT_MIN;
}
return int(negative_sign * res);
}
else
return 0;
}
return 0;
}
};
// Note: One solution in leetcode discuss use find_first_not_of, like int i = s.find_first_not_of(' '), the return type is size_t
|
#ifndef _BinaryCarLot_h_
#define _BinaryCarLot_h_
#include "Car.h"
struct BinaryCarLot {
private:
struct Node {
Node* parent;
Node* left;
Node* right;
Car val;
};
Node *root;
unsigned int length;
public:
BinaryCarLot(void) {
this->length = 0;
this->root = 0;
}
~BinaryCarLot(void) {
this->length = 0;
destroy(root);
}
void destroy(Node *r) {
if (!r) return;
destroy(r->left);
destroy(r->right);
delete r;
}
void add(Car v) {
Node *child = new Node;
child->val = v;
child->left = 0;
child->right = 0;
child->parent = 0;
this->length++;
if (!this->root) {
root = child;
return;
}
Node *parent = root;
while (true) {
if (v.val < parent->val.val) {
if (parent->left == 0) break;
parent = parent->left;
} else {
if (parent->right == 0) break;
parent = parent->right;
}
}
if (v.val < parent->val.val) {
parent->left = child;
} else {
parent->right = child;
}
child->parent = parent;
return;
}
Car* search(int v) {
Node *p = this->root;
while (p) {
if (p->val.val == v) { return &p->val; }
else if (v < p->val.val) {
p = p->left;
} else {
p = p->right;
}
}
return 0;
}
unsigned int size(void) {
return this->length;
}
};
#endif /* _BinaryCarLot_h_ */
|
/*
* Author:zjj
* Date:2014/11/8 10:20
* Desc:九度OJ1510,请实现一个函数,将一个字符串中的空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy
* Method:根据空格与替换字符的长度求出原串和新串的长度,从后往前替换即可
*/
#include<stdio.h>
#include<string.h>
#define MAX 1000000
void replaceSpace(char *str) {
int strLen;
int newStrLen;
char *p=NULL;
char *q=NULL;
strLen = 0;
newStrLen = 0;
p = str;
strLen = strlen(str);
while(*p) {
if(*p==' ') newStrLen += 3;
else {
newStrLen++;
}
p++;
}
p=q=str;
p = p + strLen - 1;
q = q + newStrLen - 1;
*(q+1) = '\0';
while(true) {
if(*p != ' ') {
*q-- = *p;
}else {
*q-- = '0';
*q-- = '2';
*q-- = '%';
}
p--;
if(p==q) break;
}
printf("%s\n",str);
}
int main() {
char str[MAX];
while(gets(str)){
replaceSpace(str);
}
return 0;
}
/*
We Are Happy
*/
|
// For a given string "ashs100shsdh200" the output should be the sum of the two numbers which is 300
#include<iostream>
#include "bits/stdc++.h"
using namespace std;
int sum(string s){
string a;
int flag = 0;
int sum = 0;
for(int i=0; i<s.size();i++){
flag = 0;
a = "";
while(s[i]>='0' && s[i]<='9'){
a = a+s[i];
i++;
flag = 1;
}
if(flag==1){
int num= stoi(a);
sum = sum+num;
}
}
return sum;
}
int main(){
string s = "ashs100shsdh200";
int ans = sum(s);
cout<<ans;
return 0;
}
|
//============================================================================
// Name : a.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include<fstream>
using namespace std;
int main() {
int n=0;
cout<<"Enter number of nodes : ";
cin>>n;
int adj[n][n];
int ch = 0;
int lines = 0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
adj[i][j]=0;
}
}
FILE *fp;
fp = fopen ("/home/pict/file.txt", "r");
while(!feof(fp))
{
ch = fgetc(fp);
if (ch == '\n')
lines++;
}
rewind(fp);
while (!feof(fp)) {
int src;
int dest;
int cost;
char c=0;
fscanf(fp, "%d,%d,%d%c", &src, &dest, &cost,&c);
adj[src-1][dest-1]=cost;
adj[dest-1][src-1]=cost;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<" "<<adj[i][j];
}
cout<<"\n";
}
}
|
#include "widimagelist.h"
#include <QStringList>
DualLabel::DualLabel(QWidget *parent)
: QWidget(parent) {
QHBoxLayout *hlayout = new QHBoxLayout();
QLabel *lab1 = new QLabel("left");
QLabel *lab2 = new QLabel("right");
lab1->setFixedSize(80, 50);
lab2->setFixedSize(80, 50);
hlayout->addWidget(lab1);
hlayout->addWidget(lab2);
hlayout->setSpacing(0);
setLayout(hlayout);
}
DualLabel::~DualLabel() {
}
WidImageList::WidImageList(QWidget *parent)
: QTableWidget(parent),activeRow(0),activeCol(0)
{
ui.setupUi(this);
setColumnCount(1);
horizontalHeader()->setStretchLastSection(true);
setEditTriggers(QAbstractItemView::NoEditTriggers);
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::NoSelection);
horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
//this->setSelectionModel()
connect(this, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(selectRowCol(int, int)));
}
WidImageList::~WidImageList()
{
}
int WidImageList::addPair(std::vector<cv::Mat> m_Mats[2]) {
int maxrow = m_Mats[0].size() > m_Mats[1].size() ? m_Mats[0].size() : m_Mats[1].size();
setRowCount(0);
for (int i = 0; i < maxrow; i++)
{
QWidget *wid = new QWidget();
QLabel *lab1 = new QLabel("");
lab1->setFixedSize(80, 50);
cv::Mat mat;
if(m_Mats[0].size()>i){
cv::cvtColor(m_Mats[0][i], mat, cv::COLOR_BGR2RGB);
lab1->setPixmap(QPixmap::fromImage(QImage(mat.data,mat.cols,mat.rows,mat.step,QImage::Format_RGB888)).scaled(lab1->size()));
}
QLabel *lab2 = new QLabel("");
lab2->setFixedSize(80, 50);
if (m_Mats[1].size()>i) {
cv::cvtColor(m_Mats[1][i], mat, cv::COLOR_BGR2RGB);
lab2->setPixmap(QPixmap::fromImage(QImage(mat.data, mat.cols, mat.rows, mat.step, QImage::Format_RGB888)).scaled(lab1->size()));
}
QHBoxLayout *hLayout = new QHBoxLayout();
hLayout->setSpacing(0);
hLayout->setMargin(0);
hLayout->setSpacing(0);
hLayout->addWidget(lab1);
hLayout->addWidget(lab2);
wid->setLayout(hLayout);
this->setRowCount(rowCount() + 1);
setCellWidget(rowCount() - 1, 0, wid);
}
resizeRowsToContents();
resizeColumnsToContents();
setFixedWidth(columnWidth(0)+50);
return 0;
}
void WidImageList::mousePressEvent(QMouseEvent *event) {
QTableWidget::mousePressEvent(event);
}
void WidImageList::selectRowCol(int row, int col) {
cellWidget(activeRow, activeCol)->setStyleSheet("");
this->resizeRowsToContents();
this->setRowHeight(row, 70);
cellWidget(row, col)->setStyleSheet("background-color:lightgreen;border:2px solid black;");
activeRow = row; activeCol = col;
}
void WidImageList::resizeEvent(QResizeEvent *event) {
resizeColumnsToContents();
}
|
/*********************************************************************
* Nixie Clock
* Author: Hamid Ebrahimi Kahaki
* Version 0.3
* *******************************************************************/
#include "i2c8Bit.h"
#include <iostream>
#include <ctime>
#include <unistd.h>
#define SADDR 0x20
#define MADDR 0x21
#define HADDR 0x22
#define IODIRA 0x00
#define IODIRB 0x01
#define GPIOA 0x12
#define GPIOB 0x13
#define OLATA 0x14
#define OLATB 0x15
using namespace std;
int main(void)
{
time_t now;
tm *ltm;
//Defining I2C objects
i2c8Bit i2c[3] =
{
i2c8Bit(SADDR,string("/dev/i2c-0")),
i2c8Bit(MADDR,string("/dev/i2c-0")),
i2c8Bit(HADDR,string("/dev/i2c-0"))
};
//Setting Port A (MCP23017) to Output
i2c[0].writeReg(IODIRA,0x00);
i2c[1].writeReg(IODIRA,0x00);
i2c[2].writeReg(IODIRA,0x00);
// Tube test
//Turn off tubes
i2c[0].writeReg(OLATA,0xFF);
i2c[1].writeReg(OLATA,0xFF);
i2c[2].writeReg(OLATA,0xFF);
for(int i=0;i<3;i++)
for(int j=0;j<10;j++)
{
i2c[i].writeReg(OLATA,j+(j<<4));
usleep(250000);
}
int lastSec=60;
while(1)
{
usleep(10000);
// Reading current time
now=time(0);
ltm=localtime(&now);
if(lastSec==ltm->tm_sec) continue;
lastSec=ltm->tm_sec;
//Updating nixie tubes
i2c[0].writeReg(OLATA,(char)(ltm->tm_sec % 10 + ((ltm->tm_sec/10)<< 4)));
i2c[1].writeReg(OLATA,(char)(ltm->tm_min % 10 + ((ltm->tm_min/10)<< 4)));
i2c[2].writeReg(OLATA,(char)(ltm->tm_hour % 10 + ((ltm->tm_hour/10)<< 4 )));
}
return 0;
}
|
#ifndef VECTOR_H
#define VECTOR_H
#include "ext_math.h"
#include "simple_math.h"
#include "defs.h"
struct Vector3: public Vector3Base
{
public:
Vector3(void);
Vector3(float x, float y, float z);
Vector3(float x);
Vector3(int x, int y, int z);
Vector3(const Vector3& v);
#ifdef _WIN32
Vector3( __m128 v4 );
#endif
float& operator()(size_t i);
const float& operator()(size_t i) const;
Vector3 operator +(const Vector3& v) const;
Vector3 operator +(float f) const;
Vector3 operator -(const Vector3& v) const;
Vector3 operator -() const;
Vector3 operator *(const Vector3& v) const;
Vector3 operator /(const Vector3& v) const;
Vector3 operator ^(const Vector3& v) const;
float operator &(const Vector3& v) const;
Vector3 operator *(const float& t) const;
Vector3 operator /(const float& t) const;
//Vector operator *( Matrix& m) const;
//void operator *=( Matrix& m );
void operator *=(float t);
void operator *=(const Vector3& t);
void operator +=(const Vector3& v);
void operator -=(const Vector3& v);
inline bool operator > (const Vector3& v) const
{
return (x > v.x && y > v.y && z > v.z);
}
inline bool operator == (const Vector3& v) const
{
return (x == v.x && y == v.y && z == v.z);
}
inline bool operator < (const Vector3& v) const
{
return (x < v.x && y < v.y && z < v.z);
}
inline bool operator >= (const Vector3& v) const
{
return (x >= v.x && y >= v.y && z >= v.z);
}
inline bool operator <= (const Vector3& v) const
{
return (x <= v.x && y <= v.y && z <= v.z);
}
inline bool isZero() const
{
return (x == 0.0f) && (y == 0.0f) && (z == 0.0f);
}
inline unsigned int ToRGB()
{
return GRGB((unsigned char)(x*255.f),(unsigned char)(y*255.f),(unsigned char)(z*255.f));
}
inline float luminance() const
{
return (x+y+z) / 3.f;
}
inline float contrast(const Vector3& v) const
{
return fabsf(x - v.x) + fabsf(y - v.y) + fabsf(z - v.z);
}
inline bool almostEqual(const Vector3 &v1, float epsilon = 0.00001f) const
{
return ((*this - v1).LengthSquared() < epsilon);
}
// this must me normalized!
void rotateRandomly(float angle);
const float LengthSquared() const;
const float length() const;
void Normalize();
};
#include "Vector3.ipp"
#endif //VECTOR_H
|
/*************************************************************
Author : qmeng
MailTo : qmeng1128@163.com
QQ : 1163306125
Blog : http://blog.csdn.net/Mq_Go/
Create : 2018-03-15 21:19:35
Version: 1.0
**************************************************************/
#include <cstdio>
#include <iostream>
#include <vector>
//#include <map>
using namespace std;
struct node{
int in;
int pro;
};
node no;
int st,n,key;
int map1[100000] = {0};
int map2[100000] = {0};
vector<node> v;
vector<node> v2;
//map<int,int> m;
int main(){
scanf("%d %d %d",&st,&n,&key);
int temp1,temp2,temp;
for(int i = 0 ; i < n ; i++){
scanf("%d %d %d",&temp1,&temp,&temp2);
map1[temp1] = temp;
map2[temp1] = temp2;
}
no.pro = st;
no.in = map1[st];
v.push_back(no);
while(v.size()!=n){
int k = v[v.size()-1].pro;
no.pro = map2[k];
no.in = map1[no.pro];
v.push_back(no);
}
for(int i = 0 ; i < n ; i++)
if(v[i].in<0)v2.push_back(v[i]);
int k2 = -1;
for(int i = 0 ; i < n ; i++){
if(v[i].in<key&&v[i].in>=0)v2.push_back(v[i]);
if(v[i].in==key)k2 = i;
}
if(k2!=-1)v2.push_back(v[k2]);
for(int i = 0 ; i < n ; i++){
if(v[i].in>key)v2.push_back(v[i]);
}
cout << endl;
for(int i = 0 ; i < n-1 ; i++){
printf("%05d %d %05d\n",v2[i].pro,v2[i].in,v2[i+1].pro);
}
printf("%05d %d -1\n",v2[n-1].pro,v2[n-1].in);
return 0;
}
|
void setup() {
Serial.begin(9600);
pinMode(9, INPUT);
pinMode(10, OUTPUT);
}
void loop() {
analogWrite(10, map(pulseIn(9, HIGH), 1100, 1900, 0, 255));
delay(20);
}
|
#include "vista_automapa.h"
using namespace App_Juego_Automapa;
Vista_automapa::Vista_automapa(int pw, int ph)
:w_vista(pw), h_vista(ph),
margen_w(w_vista/2), margen_h(h_vista/2)
{
if(! (w_vista % 2) || !(h_vista % 2))
{
throw new std::runtime_error("La vista de automapa debe inicializarse con valores impares");
}
}
/**
* @param int px: posición x del automapa.
* @param int py: posición y del automapa.
* @param int pdim: dimensión de la celda.
*/
std::vector<const App_Interfaces::Representable_I *> Vista_automapa::obtener_vista(int px, int py, int pdim) const
{
std::vector<const App_Interfaces::Representable_I *> res;
auto &v=vista.front();
v.pos_x_automapa=px;
v.pos_y_automapa=py;
v.dim_celda_automapa=pdim;
for(auto& v : vista) res.push_back(&v);
return res;
}
void Vista_automapa::refrescar_vista(const Automapa& am,int px, int py)
{
vista.clear();
//Calcular los límites...
int ini_x=px-margen_w;
int fin_x=ini_x + w_vista-1;
int ini_y=py-margen_h;
int fin_y=ini_y+h_vista-1;
int vx=0, vy=0;
int x_jugador=am.acc_x_jugador();
int y_jugador=am.acc_y_jugador();
for(int y=ini_y; y <= fin_y; ++y, ++vy)
{
vx=0;
for(int x=ini_x; x <=fin_x; ++x, ++vx)
{
Vista_unidad_automapa vum(am.copia_unidad(x, y), vx, vy);
vum.actual=vum.x==x_jugador && vum.y==y_jugador;
vista.push_back(vum);
}
}
}
|
#include "energyOptimal.h"
#include <unsupported/Eigen/MatrixFunctions>
void energyOptimalWps(Eigen::Matrix3Xd& control, const Waypoint* wps, const double* times, const int len, const OrbitalParams& p){
}
//Given multiple waypoints "" "", genereate the optimal interim velocities
void optimalVelocityAlg(Eigen::Matrix3Xd& control, const Waypoint* wps, const int len, const OrbitalParams& p){
}
//Given two waypoints with start and end velocities, generate the optimal trajectory.
void energyOptimal(Eigen::MatrixXd& control, const Waypoint& start, const Waypoint& end, const int& intervals, const OrbitalParams& p){
double t0 = start.t;
double tf = end.t;
double tspan = tf-t0;
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(6,6);
A << 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 1,
3*p.n*p.n, 0, 0, 0, 2*p.n, 0,
0, 0, 0, -2*p.n, 0, 0,
0, 0, -p.n*p.n, 0, 0, 0;
Eigen::MatrixXd B = Eigen::MatrixXd::Zero(6,6);
B.block(3,3,3,3) = Eigen::MatrixXd::Identity(3,3)*( p.F*p.tau*p.tau/p.m/p.nu);
double dt = tspan/intervals;
Eigen::MatrixXd W = Eigen::MatrixXd::Identity(6,6); //Controllability Gramian
integrateGramian(W,A,B,t0,tf,intervals);
Eigen::MatrixXd Winv = W.inverse();
Eigen::MatrixXd stm = (A*dt).exp();
Eigen::MatrixXd stm_tf = (A*tspan).exp();
Eigen::MatrixXd stm_i = Eigen::MatrixXd::Identity(stm.rows(),stm.cols());
Eigen::VectorXd x0 = Eigen::VectorXd::Zero(6);
x0.head(3) << start.r;
x0.tail(3) << start.v;
Eigen::VectorXd xf = Eigen::VectorXd::Zero(6);
xf.head(3) << end.r;
xf.tail(3) << end.v;
for(int i=0;i<intervals;i++){ //Quadrature, I'm lazy
stm_i *= stm;
control.block(0,i,6,1) << B.transpose()*stm_i.transpose()*Winv*(stm_tf*xf - x0);
}
}
void integrateGramian(Eigen::MatrixXd& W, const Eigen::MatrixXd& A, const Eigen::MatrixXd& B, const double& t0, const double& tf, const int& intervals){
double dt = (tf-t0)/(intervals);
Eigen::MatrixXd stm = (A*dt).exp();
Eigen::MatrixXd stm_i = Eigen::MatrixXd::Identity(stm.rows(),stm.cols());
Eigen::MatrixXd sum = Eigen::MatrixXd::Zero(stm.rows(),stm.cols());
for(int i=0;i<intervals;i++){ //Quadrature, I'm lazy
Eigen::MatrixXd rect;
stm_i *= stm;
sum += stm_i*B*B.transpose()*stm_i.transpose()*dt;
}
W << sum;//Return this, essentially
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Character.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: eyohn <sopka13@mail.ru> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/08 16:50:52 by eyohn #+# #+# */
/* Updated: 2021/07/08 22:00:54 by eyohn ### ########.fr */
/* */
/* ************************************************************************** */
#pragma once
#ifndef _CHARACTER_HPP_
#define _CHARACTER_HPP_
#include "ICharacter.hpp"
#include "AMateria.hpp"
#define MAX_INV 4
class Character : public ICharacter
{
private:
AMateria *m_inventory[MAX_INV];
std::string m_name;
public:
Character();
Character(std::string name);
Character(const Character &other);
~Character();
Character &operator= (const Character &fix);
std::string const & getName() const;// override;
void equip(AMateria* m);// override;
void unequip(int idx);// override;
void use(int idx, ICharacter& target);// override;
void free_character();
void bzero_character();
};
#endif
|
// Copyright Marc Bodmer 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include "detail/constants.hpp"
#include "detail/types.hpp"
#include "detail/exceptions.hpp"
#include "detail/encoder.hpp"
#include "detail/decoder.hpp"
#include "detail/operators.hpp"
|
//frien class example accessing private variable
#include<iostream>
using namespace std;
class B;
class A{
private:
int meter;
public:
A():meter(5)
{
cout<<"constructor called from A : \n";
}
friend int func(A a1,B b1);
};
class B{
private:
int meter;
public:
B():meter(10)
{
cout<<"Constructor of b and i am called : "<<endl;
}
friend int func(A a1,B b1);
};
int func(A a1,B b1){
a1.meter = 100;
b1.meter = 10;
cout<<a1.meter<<"\n"<<b1.meter;
}
int main ()
{
A a;
B b;
func(a,b);
return 0;
}
|
#include <iostream>
using namespace std;
int main() {
int t;
cin>>t;
while(t--)
{
int a;
cin>>a;
int i=2048,menus = 0;
while(i>0)
{
if(a>=i)
{
menus++;
a = a - i;
}
else
i = i/2;
}
cout<<menus<<endl;
}
return 0;
}
|
/*
* SPDX-FileCopyrightText: (C) 2017-2022 Matthias Fehring <mf@huessenbergnetz.de>
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef CUTELYSTVALIDATORREGEX_P_H
#define CUTELYSTVALIDATORREGEX_P_H
#include "validatorregularexpression.h"
#include "validatorrule_p.h"
namespace Cutelyst {
class ValidatorRegularExpressionPrivate : public ValidatorRulePrivate
{
public:
ValidatorRegularExpressionPrivate(const QString &f, const QRegularExpression &r, const ValidatorMessages &m, const QString &dvk)
: ValidatorRulePrivate(f, m, dvk)
, regex(r)
{
}
QRegularExpression regex;
};
} // namespace Cutelyst
#endif // CUTELYSTVALIDATORREGEX_P_H
|
/// \file This is a implementation file for diff_drive.hpp
#include<rigid2d/diff_drive.hpp>
#include<stdexcept>
#include<iostream>
namespace rigid2d
{
DiffDrive ::DiffDrive()
{
// initial params
theta = 0.0;
x = 0.0;
y = 0.0;
// fixed geometry from nuturtle_description config
wheel_base = 0.16;
wheel_radius = 0.033;
// set wheel encoder angles
left_cur = 0.0;
right_cur = 0.0;
// assume robot starts still
u_left = 0.0;
u_right = 0.0;
// assume timestep = 1.0
dt = 1.0;
}
DiffDrive::DiffDrive(const Pose2D & pose, double wheel_base, double wheel_radius)
{
this->theta = pose.theta;
this->x = pose.x;
this->y = pose.y;
this->wheel_base = wheel_base;
this->wheel_radius = wheel_radius;
// wheel encoders
left_cur = 0.0;
right_cur = 0.0;
// assume robot starts still
u_left = 0.0;
u_right = 0.0;
// assuem dt = 1.0
dt = 1.0;
}
WheelVelocities DiffDrive::twistToWheels(const Twist2D & twist) const
{
double d = wheel_base / 2;
// use Eq 1 from the diff_drive derivation file in doc
WheelVelocities vels;
vels.u_left = (1 / wheel_radius) * (-d*twist.w + 1.0*twist.vx);
vels.u_right = (1 / wheel_radius) * (d*twist.w + 1.0*twist.vx);
// throw exception
if (twist.vy != 0)
{
throw std::invalid_argument("Twist cannot have y velocity component!");
}
return vels;
}
Twist2D DiffDrive::wheelsToTwist(const WheelVelocities & vels) const
{
// use Eq 2 from the diff_drive derivation file in doc
Twist2D twist;
twist.w = wheel_radius * (-vels.u_left + vels.u_right) / wheel_base;
twist.vx = wheel_radius * (vels.u_left + vels.u_right) / 2;
twist.vy = 0.0;
return twist;
}
WheelVelocities DiffDrive::updateOdom(double left, double right)
{
WheelVelocities vels;
// wheel velocities change in wheel angles
vels.u_left = normalize_angle(left - left_cur);
vels.u_right = normalize_angle(right - right_cur);
// update wheel velocities
this->u_left = vels.u_left;
this->u_right = vels.u_right;
// update wheel angles
left_cur = normalize_angle(left);
right_cur = normalize_angle(right);
// body frame twist given wheel velocities
Twist2D Vb = wheelsToTwist(vels);
// integrate twist Tb -> Tb_bprime
Transform2D Tb_bprime;
Tb_bprime = Tb_bprime.integrateTwist(Vb);
// pose is transfrom form world to b prime;
Vector2D v;
v.x = this->x;
v.y = this->y;
Transform2D Twb(v,this->theta);
// update pose to b prime
Transform2D Tw_bprime;
Tw_bprime = Twb * Tb_bprime;
// world to robot
TransformData2D Twr;
Twr = Tw_bprime.displacement();
// update pose
this->theta = normalize_angle(Twr.theta);
this->x = Twr.x;
this->y = Twr.y;
return vels;
}
void DiffDrive::feedforward(const Twist2D & cmd)
{
// wheel velocities to achieve the cmd
WheelVelocities vel = twistToWheels(cmd);
// update wheel velocities
u_left = normalize_angle(vel.u_left);
u_right = normalize_angle(vel.u_right);
// update encoder readings
left_cur = normalize_angle(left_cur + vel.u_left);
right_cur = normalize_angle(right_cur + vel.u_right);
// integrate twist
Transform2D Tb_bprime;
Tb_bprime = Tb_bprime.integrateTwist(cmd);
// pose is transform form world to b prime
Vector2D v;
v.x = this->x;
v.y = this->y;
Transform2D Twb(v, this->theta);
// update pose to b prime
Transform2D Tw_bprime = Twb * Tb_bprime;
// world to robot
TransformData2D Twr = Tw_bprime.displacement();
// update pose
this->theta = Twr.theta;
this->x = Twr.x;
this->y = Twr.y;
}
Pose2D DiffDrive::pose() const
{
Pose2D pose;
pose.theta = normalize_angle(this->theta);
pose.x = this->x;
pose.y = this->y;
return pose;
}
WheelVelocities DiffDrive::wheelVelocities() const
{
WheelVelocities vels;
vels.u_left = this->u_left;
vels.u_right = this->u_right;
return vels;
}
void DiffDrive::reset(Pose2D pose)
{
theta = pose.theta;
x = pose.x;
y = pose.y;
}
WheelEncoders DiffDrive::getEncoders() const
{
WheelEncoders enc;
enc.left = this->left_cur;
enc.right = this->right_cur;
return enc;
}
}
// end file
|
/*
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.
*/
#include "AbstractHdf5Converter.hpp"
#include "Version.hpp"
/*
* Operator function to be called by H5Literate [HDF5 1.8.x] or H5Giterate [HDF5 1.6.x] (in TestListingDatasetsInAnHdf5File).
*/
herr_t op_func (hid_t loc_id,
const char *name,
const H5L_info_t *info,
void *operator_data);
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
AbstractHdf5Converter<ELEMENT_DIM, SPACE_DIM>::AbstractHdf5Converter(const FileFinder& rInputDirectory,
const std::string& rFileBaseName,
AbstractTetrahedralMesh<ELEMENT_DIM, SPACE_DIM>* pMesh,
const std::string& rSubdirectoryName,
unsigned precision)
: mrH5Folder(rInputDirectory),
mFileBaseName(rFileBaseName),
mOpenDatasetIndex(UNSIGNED_UNSET),
mpMesh(pMesh),
mRelativeSubdirectory(rSubdirectoryName),
mPrecision(precision)
{
GenerateListOfDatasets(mrH5Folder, mFileBaseName);
// Create new directory in which to store everything
FileFinder sub_directory(mRelativeSubdirectory, mrH5Folder);
mpOutputFileHandler = new OutputFileHandler(sub_directory, false);
MoveOntoNextDataset();
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractHdf5Converter<ELEMENT_DIM, SPACE_DIM>::WriteInfoFile()
{
// Note that we don't want the child processes to write info files
if (PetscTools::AmMaster())
{
std::string time_info_filename;
// If the dataset is just "Data" then we will leave the original filename as it is (to avoid confusion!)
// If the dataset is a new variant like "Postprocessing" then we will put the dataset name in the output.
if (mDatasetNames[mOpenDatasetIndex]=="Data")
{
time_info_filename = mFileBaseName + "_times.info";
}
else
{
time_info_filename = mDatasetNames[mOpenDatasetIndex] + "_times.info";
}
out_stream p_file = mpOutputFileHandler->OpenOutputFile(time_info_filename);
std::vector<double> time_values = mpReader->GetUnlimitedDimensionValues();
unsigned num_timesteps = time_values.size();
double first_timestep = time_values.front();
double last_timestep = time_values.back();
double timestep = num_timesteps > 1 ? time_values[1] - time_values[0] : DOUBLE_UNSET;
*p_file << "Number of timesteps " << num_timesteps << std::endl;
*p_file << "timestep " << timestep << std::endl;
*p_file << "First timestep " << first_timestep << std::endl;
*p_file << "Last timestep " << last_timestep << std::endl;
*p_file << ChasteBuildInfo::GetProvenanceString();
p_file->close();
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
AbstractHdf5Converter<ELEMENT_DIM,SPACE_DIM>::~AbstractHdf5Converter()
{
delete mpOutputFileHandler;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
std::string AbstractHdf5Converter<ELEMENT_DIM,SPACE_DIM>::GetSubdirectory()
{
return mRelativeSubdirectory;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
bool AbstractHdf5Converter<ELEMENT_DIM,SPACE_DIM>::MoveOntoNextDataset()
{
// If we are already at the end just return false.
if (mDatasetNames.size() == mOpenDatasetIndex+1u)
{
return false;
}
// If we haven't read anything yet, start at the beginning, otherwise increment by one.
if (mOpenDatasetIndex==UNSIGNED_UNSET)
{
mOpenDatasetIndex = 0u;
}
else
{
mOpenDatasetIndex++;
}
// Store directory, mesh and filenames and create the reader
mpReader.reset(new Hdf5DataReader(mrH5Folder, mFileBaseName, mDatasetNames[mOpenDatasetIndex]));
// Check the data file for basic validity
std::vector<std::string> variable_names = mpReader->GetVariableNames();
mNumVariables = variable_names.size();
if (mpReader->GetNumberOfRows() != mpMesh->GetNumNodes())
{
delete mpOutputFileHandler;
EXCEPTION("Mesh and HDF5 file have a different number of nodes");
}
WriteInfoFile();
return true;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractHdf5Converter<ELEMENT_DIM,SPACE_DIM>::GenerateListOfDatasets(const FileFinder& rH5Folder,
const std::string& rFileName)
{
/*
* Open file.
*/
std::string file_name = rH5Folder.GetAbsolutePath() + rFileName + ".h5";
hid_t file = H5Fopen(file_name.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
/*
* Begin HDF5 iteration, calls a method that populates mDatasetNames.
*/
H5Literate(file, H5_INDEX_NAME, H5_ITER_NATIVE, nullptr, op_func, &mDatasetNames);
H5Fclose(file);
// Remove datasets that end in "_Unlimited", as these are paired up with other ones!
std::string ending = "_Unlimited";
// Strip off the independent variables from the list
std::vector<std::string>::iterator iter;
for (iter = mDatasetNames.begin(); iter != mDatasetNames.end(); )
{
// If the dataset name is "Time" OR ...
// it is longer than the ending we are looking for ("_Unlimited") ...
// ... AND it ends with the string we are looking for,
// then erase it.
if ((*(iter) == "Time") ||
((iter->length() > ending.length()) &&
(0 == iter->compare(iter->length() - ending.length(), ending.length(), ending))))
{
iter = mDatasetNames.erase(iter);
}
else
{
++iter;
}
}
}
/*
* HDF5 Operator function.
*
* Puts the name of the objects (in this case 'datasets')
* in an HDF5 file into a std::vector for us to use for
* iterating over the file.
*
* This was based on a couple of HDF5 example files.
*/
herr_t op_func (hid_t loc_id, const char *name,
const H5L_info_t *info,
void *operator_data)
{
std::vector<std::string>* p_dataset_names = static_cast<std::vector< std::string > * >(operator_data);
/*
* Get type of the object and display its name and type.
* The name of the object is passed to this function by
* the Library.
*/
H5O_info_t infobuf;
H5Oget_info_by_name (loc_id, name, &infobuf, H5P_DEFAULT);
switch (infobuf.type)
{
// case H5O_TYPE_GROUP:
// printf (" Group: %s\n", name);
// break;
case H5O_TYPE_DATASET:
p_dataset_names->push_back(name);
break;
// case H5O_TYPE_NAMED_DATATYPE:
// printf (" Datatype: %s\n", name);
// break;
default:
NEVER_REACHED;
// If you ever do reach here, it means that an HDF5 file you are trying to convert contains
// something other than a 'Dataset', which is the usual data structure we write out in Chaste.
// The above commented out lines should help you figure out what it is, and how it got there.
}
return 0;
}
// Explicit instantiation
template class AbstractHdf5Converter<1,1>;
template class AbstractHdf5Converter<1,2>;
template class AbstractHdf5Converter<2,2>;
template class AbstractHdf5Converter<1,3>;
template class AbstractHdf5Converter<2,3>;
template class AbstractHdf5Converter<3,3>;
|
/* NO WARRANTY
*
* BECAUSE THE PROGRAM IS IN THE PUBLIC DOMAIN, THERE IS NO
* WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
* LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE AUTHORS
* AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
* WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO
* THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD
* THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
* NECESSARY SERVICING, REPAIR OR CORRECTION.
*
* IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
* WRITING WILL ANY AUTHOR, OR ANY OTHER PARTY WHO MAY MODIFY
* AND/OR REDISTRIBUTE THE PROGRAM, BE LIABLE TO YOU FOR DAMAGES,
* INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
* DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM
* (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
* RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES
* OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
* PROGRAMS), EVEN IF SUCH AUTHOR OR OTHER PARTY HAS BEEN ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGES.
*/
#if !defined(AFX_DRAGDROPCURSORMANAGER_H__BB5C5B92_2814_11D4_B599_004F49031E0C__INCLUDED_)
#define AFX_DRAGDROPCURSORMANAGER_H__BB5C5B92_2814_11D4_B599_004F49031E0C__INCLUDED_
#pragma warning(disable : 4786)
#include <map>
//using namespace std ;
typedef std::map<int, HCURSOR> CursorMap;
class DragDropCursorManager {
public:
enum Type {
ARROW = IDC_ARROW,
IBEAM = IDC_IBEAM,
WAIT = IDC_WAIT,
CROSS = IDC_CROSS,
UPARROW = IDC_UPARROW,
SIZE = IDC_SIZEALL,
ICON = IDC_ARROW,
SIZENWSE= IDC_SIZENWSE,
SIZENESW= IDC_SIZENESW,
SIZEWE = IDC_SIZEWE,
SIZENS = IDC_SIZENS,
NODROP = IDC_NO,
};
static void set(DragDropCursorManager::Type );
protected:
static CursorMap m_cursors;
};
typedef DragDropCursorManager CM;
#endif // !defined(AFX_DRAGDROPCURSORMANAGER_H__BB5C5B92_2814_11D4_B599_004F49031E0C__INCLUDED_)
|
#include "stdafx.h"
#include "NormalRenderItem.h"
#include "ImmutableMeshGeometry.h"
#include "SubmeshGeometry.h"
using namespace GraphicsEngine;
void NormalRenderItem::Render(ID3D11DeviceContext* deviceContext) const
{
SetInputAssemblerData(deviceContext);
const auto& submesh = GetSubmesh();
deviceContext->DrawIndexedInstanced(submesh.IndexCount, static_cast<UINT>(m_visibleInstanceCount), submesh.StartIndexLocation, submesh.BaseVertexLocation, 0);
}
void NormalRenderItem::RenderNonInstanced(ID3D11DeviceContext* deviceContext) const
{
SetInputAssemblerData(deviceContext);
const auto& submesh = GetSubmesh();
deviceContext->DrawIndexed(submesh.IndexCount, submesh.StartIndexLocation, submesh.BaseVertexLocation);
}
void NormalRenderItem::AddInstance(const ShaderBufferTypes::InstanceData& instanceData)
{
//m_colliders.push_back(OctreeCollider(this, static_cast<uint32_t>(this->InstancesData.size())));
m_instancesData.push_back(instanceData);
}
void NormalRenderItem::SetInstance(size_t instanceID, const ShaderBufferTypes::InstanceData& instanceData)
{
m_instancesData[instanceID] = instanceData;
}
const ShaderBufferTypes::InstanceData& NormalRenderItem::GetInstance(size_t instanceID)
{
return m_instancesData[instanceID];
}
void NormalRenderItem::RemoveLastInstance()
{
if (!m_instancesData.empty())
m_instancesData.pop_back();
}
void NormalRenderItem::InscreaseInstancesCapacity(size_t aditionalCapacity)
{
m_instancesData.reserve(m_instancesData.capacity() + aditionalCapacity);
}
void NormalRenderItem::InsertVisibleInstance(size_t instanceID)
{
m_visibleInstances.insert(static_cast<uint32_t>(instanceID));
}
void NormalRenderItem::ClearVisibleInstances()
{
m_visibleInstances.clear();
}
ImmutableMeshGeometry* NormalRenderItem::GetMesh() const
{
return m_mesh;
}
void NormalRenderItem::SetMesh(ImmutableMeshGeometry* mesh, const std::string& submeshName)
{
m_mesh = mesh;
m_submeshName = submeshName;
}
const SubmeshGeometry& NormalRenderItem::GetSubmesh() const
{
return m_mesh->GetSubmesh(m_submeshName);
}
const std::vector<ShaderBufferTypes::InstanceData>& NormalRenderItem::GetInstancesData() const
{
return m_instancesData;
}
const std::vector<OctreeCollider>& NormalRenderItem::GetColliders() const
{
return m_colliders;
}
std::vector<OctreeCollider>& NormalRenderItem::GetColliders()
{
return m_colliders;
}
size_t NormalRenderItem::GetVisibleInstanceCount() const
{
return m_visibleInstanceCount;
}
void NormalRenderItem::SetVisibleInstanceCount(size_t visibleInstanceCount)
{
m_visibleInstanceCount = visibleInstanceCount;
}
const std::unordered_set<uint32_t>& NormalRenderItem::GetVisibleInstances() const
{
return m_visibleInstances;
}
void NormalRenderItem::SetInputAssemblerData(ID3D11DeviceContext* deviceContext) const
{
std::array<ID3D11Buffer*, 1> vertexBuffers = { m_mesh->GetVertexBuffer() };
std::array<UINT, 1> strides = { m_mesh->GetStride() };
std::array<UINT, 1> offsets = { m_mesh->GetOffset() };
deviceContext->IASetVertexBuffers(0, 1, vertexBuffers.data(), strides.data(), offsets.data());
deviceContext->IASetIndexBuffer(m_mesh->GetIndexBuffer(), m_mesh->GetIndexFormat(), 0);
deviceContext->IASetPrimitiveTopology(m_mesh->GetPrimitiveType());
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.