text
stringlengths 8
6.88M
|
|---|
#include "stdio.h"
#include "conio.h"
void main(){
clrscr();
int c=49;
for(int i=0; i<2; i++){
for(int j=0; j<3; j++){
printf("%c\t",c);
c++;
}
printf("\n");
}
getch();
}
|
/*
* Copyright (c) 2016-2021 Morwenn
* SPDX-License-Identifier: MIT
*/
#ifndef CPPSORT_DETAIL_SWAP_RANGES_H_
#define CPPSORT_DETAIL_SWAP_RANGES_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <cstddef>
#include <iterator>
#include <type_traits>
#include <cpp-sort/utility/iter_move.h>
#include "config.h"
#include "move.h"
#include "type_traits.h"
namespace cppsort
{
namespace detail
{
////////////////////////////////////////////////////////////
// swap_ranges_overlap
//
// Most basic swap_ranges implementation, somehow tolerates
// overlapping ranges - at least enough to get some of the
// library's algorithms to work
template<typename ForwardIterator1, typename ForwardIterator2>
auto swap_ranges_overlap(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2)
-> ForwardIterator2
{
while (first1 != last1) {
using utility::iter_swap;
iter_swap(first1, first2);
++first1;
++first2;
}
return first2;
}
////////////////////////////////////////////////////////////
// swap_ranges_inner
//
// swap_ranges flavor to use when two ranges belong to the
// same collection but can not overlap, might also provide
// additional diagnostics when the precondition is violated
template<typename ForwardIterator>
auto swap_ranges_inner_impl(std::forward_iterator_tag,
ForwardIterator first1, ForwardIterator last1,
ForwardIterator first2)
-> ForwardIterator
{
#ifdef CPPSORT_ENABLE_AUDITS
bool ranges_overlap = false;
// This check assumes that first1 <= last1
auto last2 = std::next(first2, std::distance(first1, last1));
for (auto it = first1 ; it != last1 ; ++it) {
if (it == first2) {
ranges_overlap = true;
}
if (it == last2 && it != first1) {
ranges_overlap = true;
}
}
CPPSORT_AUDIT(not ranges_overlap);
#endif
return swap_ranges_overlap(first1, last1, first2);
}
template<typename RandomAccessIterator>
auto swap_ranges_inner_impl(std::random_access_iterator_tag,
RandomAccessIterator first1, RandomAccessIterator last1,
RandomAccessIterator first2)
-> RandomAccessIterator
{
CPPSORT_ASSERT(first1 <= last1);
auto last2 = first2 + (last1 - first1);
(void)last2;
CPPSORT_ASSERT(not (first2 >= first1 && first2 < last1));
CPPSORT_ASSERT(not (last2 > first1 && last2 <= last1));
return detail::swap_ranges_overlap(first1, last1, first2);
}
template<typename ForwardIterator>
auto swap_ranges_inner(ForwardIterator first1, ForwardIterator last1, ForwardIterator first2)
-> ForwardIterator
{
using category = iterator_category_t<ForwardIterator>;
return swap_ranges_inner_impl(category{}, first1, last1, first2);
}
}}
#endif // CPPSORT_DETAIL_SWAP_RANGES_H_
|
#include "accel.h"
SimpleAccelSensor::SimpleAccelSensor() {
}
void SimpleAccelSensor::initialize() {
sensor.initialize();
}
void SimpleAccelSensor::get_accel_gyro(Vector *accel, Vector *gyro) {
int16_t ax, ay ,az;
int16_t gx, gy, gz;
sensor.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
accel->x = (double)ax;
accel->y = (double)ay;
accel->z = (double)az;
gyro->x = (double)gx;
gyro->y = (double)gy;
gyro->z = (double)gz;
}
void SimpleAccelSensor::get_accel(Vector *accel) {
int16_t ax, ay ,az;
int16_t gx, gy, gz;
sensor.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
accel->x = (double)ax;
accel->y = (double)ay;
accel->z = (double)az;
}
SmoothedAccelSensor::SmoothedAccelSensor() : SimpleAccelSensor() {
}
void SmoothedAccelSensor::get_accel_gyro(Vector *accel, Vector *gyro) {
// TODO: smoothed accel gyro sensor data
// use `base::get_accel_gyro` to AccelSensor's method
}
void SmoothedAccelSensor::get_accel(Vector *accel) {
// TODO: smoothed accel gyro sensor data
// use `base::get_accel_gyro` to AccelSensor's method
}
|
#include "testlib.h"
using namespace std;
int main(int argc, char *argv[]) {
registerGen(argc, argv, 1);
int n=rnd.next(1,100);
println(n);
for(int i=1;i<=n;i++){
cout<<rnd.next(1,10)<<" ";
}
cout<<endl;
}
|
/*
输入:
4
20 35 23 40
输出:
2
输入第二行是4个题目对应的rating值,每场考试要求三道题的rating满足a<=b<=c,b-a<=10,c-b<=10,目的是最少添加多少道题能让已有的题目全部应用到考试里。
*/
#include <bitset>
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdio.h>
using namespace std;
int main()
{
int n;
vector<int> data;
data.reserve(100010);
int tmp;
long long res = 0;
scanf("%d\n", &n);
for (int i = 0; i != n; ++i)
{
scanf("%d", &tmp);
data.push_back(tmp);
}
sort(data.begin(), data.end());
tmp = 0;
for (int i = 0; i < n; ++i)
{
if (tmp == 0)
{
++tmp;
continue;
}
if (data[i] - data[i - 1] <= 10)
{
++tmp;
if (tmp == 3)
{
tmp = 0;
//++ i;
}
}
else
{
if (tmp == 2)
{
++res;
tmp = 1;
//++i;
}
else if (tmp == 1)
{
if (data[i] - data[i - 1] <= 20)
{
++res;
tmp = 0;
//++i;
}
else
{
res += 2;
tmp = 1;
--i;
}
}
}
}
//std::cout << tmp << endl;
std::cout << (res + 3 - tmp) << endl;
}
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rep1(i, n) for(int i = 1; i <= (int)(n); i++)
#define showmap(is, js, x) {rep(i, is){rep(j, js){cout << x[i][j] << " ";}cout << endl;}}
#define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;}
#define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;}
typedef long long ll;
typedef pair<int, int> P;
typedef pair<ll, ll> llP;
ll gcd(int x, int y){ return y?gcd(y, x%y):x;}
ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);}
int main()
{
int n; ll k;
cin >> n >> k;
vector<ll> a;
rep(i, n){ ll tmp; cin >> tmp; a.push_back(tmp);}
const int maxbit = 42;
vector<int> bit(maxbit);
vector<int> biton(maxbit, 0);
rep(i, n){
ll tmp = a[i];
int itr = 0;
while(tmp != 0 && itr < maxbit){
bit[itr] += tmp&1ll;
tmp >>= 1;
itr++;
}
}
rep(i, maxbit){
if (bit[i] <= ((n+1)/2) - 1){
biton[i] = 1;
}
}
ll ans = 0;
for (int i = maxbit-1; i >= 0; i--)
{
if (biton[i] == 1 && ans+(1ll<<i) <= k) ans += 1ll<<i;
}
//cout << ans << endl;
ll sum = 0;
rep(i, n) sum += ans^a[i];
cout << sum << endl;
}
|
#ifndef __MP4FILE_H__
#define __MP4FILE_H__
#ifdef __cplusplus
extern "C" {
#endif
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#ifdef __cplusplus
}
#endif
#include "common.h"
////////////////////////////////////////////////////////////////////////////////
class CMp4file
{
public:
CMp4file(const char *path, int vcodecid, int acodecid);
virtual ~CMp4file();
public:
int Start();
int Write(AVMediaType type, AVPacket *pPacket);
AVCodecContext *GetCodecContext(unsigned int index) const { return m_stream[index]==0? 0:m_stream[index]->codec;}
int64_t Get(int64_t pts) { if( m_ref ==-1 ) m_ref = pts; return pts - m_ref;}
private:
AVFormatContext *m_fmtctx;
AVStream *m_stream[2]; //0-video 1-audio
int64_t m_ref;
CLASS_LOG_DECLARE(CMp4file);
};
#endif
|
#ifndef CONFD_H
#define CONFD_H
#include <eeprom_cli.h>
/*
#define KEY_SAVED_FLAF_ADDR (KEY_ADDR + KEY_SIZE)
#define KEY_SAVED_FLAG_VAL 0xAA
#define FIRST_RUN_ADDR (KEY_SAVED_FLAF_ADDR + 1)
#define FIRST_RUN_VAL 0xBB
*/
#define START_ADDRESS 0x0000
#define SENSOR_ADDR_START (START_ADDRESS + 10)
#define SENSOR_AMOUNT 10
#define WIFI_NAME_ADDR_START (SENSOR_ADDR_START + SENSOR_AMOUNT + 1)
#define WIFI_NAME_ADDR_SIZE 33
#define WIFI_PW_ADDR_START (WIFI_NAME_ADDR_START + WIFI_NAME_ADDR_SIZE + 1)
#define WIFI_PW_ADDR_SIZE 17
enum WifiModeEnum {
na_mode = 0, // Not available status
sta_mode, // Connect to router
ap_mode // Create access point
};
union WifiMode {
WifiModeEnum mode;
uint8_t mode_array[4];
};
#define WIFI_MODE_ADDR_START (WIFI_PW_ADDR_START + WIFI_PW_ADDR_SIZE + 1)
#define WIFI_MODE_ADDR_SIZE 4
enum WifiStateEnum {
Wifi_Off = 0,
Wifi_On
};
union WifiState {
WifiStateEnum state;
uint8_t state_array[4];
};
#define WIFI_STATE_ADDR_START (WIFI_MODE_ADDR_START + WIFI_MODE_ADDR_SIZE + 1)
#define WIFI_STATE_ADDR_SIZE 4
#define WEB_ADMIN_USER_ADDR_START (WIFI_STATE_ADDR_START + WIFI_STATE_ADDR_SIZE + 1)
#define WEB_ADMIN_USER_ADDR_SIZE 10
#define WEB_ADMIN_PW_ADDR_START (WEB_ADMIN_USER_ADDR_START + WEB_ADMIN_USER_ADDR_SIZE +1)
#define WEB_ADMIN_PW_ADDR_SIZE 16
class Confd
{
public:
Confd(EepromCli &eeprom);
uint8_t read_sensors(uint8_t *all_sensorst);
uint8_t store_sensors(uint8_t *all_sensorst);
uint8_t read_wifi_name(uint8_t *name);
uint8_t store_wifi_name(uint8_t *name);
uint8_t read_wifi_pw(uint8_t *pw);
uint8_t store_wifi_pw(uint8_t *pw);
uint8_t read_wifi_mode(WifiMode *mode);
uint8_t store_wifi_mode(WifiMode *mode);
uint8_t read_wifi_state(WifiState *state);
uint8_t store_wifi_state(WifiState *state);
uint8_t read_web_admin_user(uint8_t *user);
uint8_t store_web_admin_user(uint8_t *user);
uint8_t read_web_admin_pw(uint8_t *pw);
uint8_t store_web_admin_pw(uint8_t *pw);
private:
EepromCli& _eeprom;
};
#endif
|
/*
Copyright (c) 2016, Los Alamos National Security, LLC
All rights reserved.
Copyright 2016. Los Alamos National Security, LLC. This software was produced under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National Laboratory (LANL), which is operated by Los Alamos National Security, LLC for the U.S. Department of Energy. The U.S. Government has rights to use, reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified to produce derivative works, such modified software should be clearly marked, so as not to confuse it with the version available from LANL.
Additionally, redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of Los Alamos National Security, LLC, Los Alamos National Laboratory, LANL, the U.S. Government, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY LOS ALAMOS NATIONAL SECURITY, LLC AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LOS ALAMOS NATIONAL SECURITY, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TADEngine_h
#define TADEngine_h
#include "AbstractEngine.hpp"
#include "SystemModifier.hpp"
#include "TammberTypes.hpp"
#include "Task.hpp"
#include "Log.hpp"
#include "Graph.hpp"
#include "MDEngine.hpp"
#include "TransitionFilter.hpp"
#include <map>
#include <string>
#include <boost/optional.hpp>
#include <boost/functional/hash/hash.hpp>
#include <random>
#include <Eigen/Dense> // For Supercell and Hessian
#include <Eigen/Eigenvalues> // Hessian
/*
TADTaskMapper class for TADEngine inherited from MDTaskMapper
*/
class TADTaskMapper : public MDTaskMapper {
public:
TADTaskMapper() : MDTaskMapper() {
MDTaskMapper::AbstractTaskMapper::insert("TASK_NEB");
};
};
/*
TADEngine class inherited from MDEngine
*/
template <class System, class EngineTaskMapper>
class TADEngine : public MDEngine<System,EngineTaskMapper> {
public:
//typedef AbstractEngine<EngineTaskMapper> BaseEngine; // as per MDEngine
typedef MDEngine<System,EngineTaskMapper> BaseMDEngine; // req. for taskParameters, defaultFlavor, labeler
typedef typename BaseMDEngine::BaseEngine BaseEngine; // req. for mapper, impls (could use this-> ....)
TADEngine(boost::property_tree::ptree &config, MPI_Comm localComm_, int seed_) : BaseMDEngine(config, localComm_, seed_) {
BaseEngine::impls["TASK_SEGMENT"] = TADEngine::segment_impl; // overwriting
BaseEngine::impls["TASK_LABEL"] = TADEngine::label_impl; // overwriting
BaseEngine::impls["TASK_REMAP"] = TADEngine::remap_impl; // overwriting
BaseEngine::impls["TASK_INIT_MIN"] = TADEngine::init_min_impl; // overwriting
BaseEngine::impls["TASK_NEB"] = TADEngine::neb_impl; // new task
};
/**
* Implement segment generation in terms of other more basic tasks. Can be overridden in derived classes if the engine can generate segments internally.
*
* This expects:
* inputData: Minimum
* inputData: QSD (optional)
* argument: TADSegment
*/
std::function<void(GenericTask&)> segment_impl = [this](GenericTask &task) {
std::unordered_map<std::string,std::string> parameters =
extractParameters(task.type,task.flavor,BaseMDEngine::defaultFlavor,BaseMDEngine::taskParameters);
//read parameters from the tasks
double preCorrelationTime=safe_extractor<double>(parameters,"PreCorrelationTime",1.0);
double minimumSegmentLength=safe_extractor<double>(parameters,"MinimumSegmentLength",1.0);
double BlockTime=safe_extractor<double>(parameters,"BlockTime",1.0);
double annealingTime=safe_extractor<double>(parameters,"AnnealingTime",0.25);
double annealingTemperature=safe_extractor<double>(parameters,"AnnealingTemperature",0.25);
int nDephasingTrialsMax=safe_extractor<int>(parameters,"MaximumDephasingTrials",3);
bool reportIntermediates=safe_extractor<bool>(parameters,"ReportIntermediates",false);
int segmentFlavor=(BaseMDEngine::taskParameters.count(std::make_pair(task.type,task.flavor))>0 ? task.flavor : BaseMDEngine::defaultFlavor);
int maximumSegmentLength = safe_extractor<int>(parameters,"MaximumSegmentLength",25*minimumSegmentLength);
//create tasks
GenericTask md,min,label,carve,initVelocities,filter,write;
write.type = BaseEngine::mapper.type("TASK_WRITE_TO_FILE");
write.flavor = task.flavor;
md.type=BaseEngine::mapper.type("TASK_MD");
md.flavor=task.flavor;
min.type=BaseEngine::mapper.type("TASK_MIN");
min.flavor=task.flavor;
label.type=BaseEngine::mapper.type("TASK_LABEL");
label.flavor=task.flavor;
carve.type=BaseEngine::mapper.type("TASK_CARVE");
carve.flavor=task.flavor;
initVelocities.type=BaseEngine::mapper.type("TASK_INIT_VELOCITIES");
initVelocities.flavor=task.flavor;
filter.type=BaseEngine::mapper.type("TASK_FILTER_TRANSITION");
filter.flavor=task.flavor;
// in input and output data here
TADSegment segment;
extract("TADSegment",task.arguments,segment);
bool ProductionRun=true;
extract("ProductionRun",task.arguments,ProductionRun);
//extract the systems we were provided
System minimum, reference, qsd, initial, current, currentMin, annealingMin;
bool gotMin = extract("Minimum",task.inputData,minimum);
// to be completed
std::string qsdstr = "QSD"+std::to_string(int(segment.temperature));
bool gotQsd = extract(qsdstr,task.inputData,qsd);
if(!gotMin) {
if(gotQsd) {
insert("State",min.inputData,qsd);
BaseEngine::process(min);
gotMin = extract("State",min.outputData,minimum);
} else {
if(BaseEngine::local_rank==0) LOGGER("NO QSD OR MINIMUM! EXITING")
return ;
}
}
// segment temperature
double temperature = segment.temperature;
double inittemperature = 2.0 * temperature;
//set the initial state
if(gotQsd) initial = qsd;
else initial = minimum;
// minimize and find labels
LabelPair InitialLabels,CurrentLabels,previousLabels;
// minimize
min.clearInputs(); min.clearOutputs();
insert("State",min.inputData,minimum);
BaseEngine::process(min);
extract("State",min.outputData,minimum);
// label
label.clearInputs(); label.clearOutputs();
insert("State",label.inputData,minimum);
BaseEngine::process(label);
extract("Labels",label.returns,InitialLabels);
segment.InitialLabels = InitialLabels;
// carve
int clusters=1;
std::array<double,3> position;
carve.clearInputs(); carve.clearOutputs();
insert("State",carve.inputData,minimum);
BaseEngine::process(carve);
extract("Clusters",carve.returns,clusters);
extract("Position",carve.returns,position);
segment.initialClusters = clusters;
for(int jj=0;jj<3;jj++) segment.initialPosition[jj] = position[jj];
// ensure basin is populated
segment.BasinLabels[InitialLabels]=minimum.getEnergy();
std::map<LabelPair,double> newBasinLabels;
// transition check
bool BasinTransition = false;
bool NewBasinTransition = false;
bool Transition = false;
bool Annealed = false;
// set labels
CurrentLabels=InitialLabels;
// DEPHASING ROUTINE
// Sample velocities if required, then ensure system stays in superbasin for at least 1ps...
// current test: do not put back in but must have repeat visits within nDephasingTrials== new tau_c
// DO REMAPPING AFTER BASIN TRANSITIONS?? no; all done in MarkovModelBuilder
int nDephasingTrials = 0;
int nOverheadBlocks = 0;
double msd_thresh = 0.0;
double elapsedTime = 0.0;
segment.dephased = gotQsd; // so no need to do dephasing if we have QSD...
segment.overhead = 0;
// sample thermal velocities
if(not segment.dephased) {
initVelocities.clearInputs(); initVelocities.clearOutputs();
insert("InitTemperature",initVelocities.arguments,inittemperature);
insert("State",initVelocities.inputData,initial);
BaseEngine::process(initVelocities);
extract("State",initVelocities.outputData,initial);
}
current = initial;
reference = minimum;
while(not segment.dephased) {
elapsedTime = 0.0;
while( elapsedTime < preCorrelationTime*0.999999999 ) {
// one block of MD
md.clearInputs(); md.clearOutputs();
insert("BlockTime",md.arguments,BlockTime);
insert("Temperature",md.arguments,temperature);
insert("State",md.inputData,current);
BaseEngine::process(md);
extract("State",md.outputData,current);
elapsedTime += BlockTime;
segment.overhead++;
// minimize
min.clearInputs(); min.clearOutputs();
insert("State",min.inputData,current);
BaseEngine::process(min);
extract("State",min.outputData,currentMin);
// label
label.clearInputs(); label.clearOutputs();
insert("State",label.inputData,currentMin);
BaseEngine::process(label);
extract("Labels",label.returns,CurrentLabels);
if(ProductionRun) {
if(BaseEngine::local_rank==0) LOGGER("Dephase: REFERENCE CURRENTMIN MSD_2: "<<reference.msd(currentMin,false))
if(BaseEngine::local_rank==0) LOGGER("Dephase: REFERENCE CURRENTMIN MSD_INF: "<<reference.msd(currentMin,true))
if(BaseEngine::local_rank==0) LOGGER("Dephase: CURRENT LABEL: "<<CurrentLabels.first<<" , "<<CurrentLabels.second)
} else {
if(BaseEngine::local_rank==0) LOGGERA("Dephase: REFERENCE CURRENTMIN MSD_2: "<<reference.msd(currentMin,false))
if(BaseEngine::local_rank==0) LOGGERA("Dephase: REFERENCE CURRENTMIN MSD_INF: "<<reference.msd(currentMin,true))
if(BaseEngine::local_rank==0) LOGGERA("Dephase: CURRENT LABEL: "<<CurrentLabels.first<<" , "<<CurrentLabels.second)
}
// Current "Basin" implementation: anything below MSD thresh from reference
// check for transition out of "superbasin"
BasinTransition = bool(segment.BasinLabels.find(CurrentLabels)!=segment.BasinLabels.end());
NewBasinTransition = bool(newBasinLabels.find(CurrentLabels)!=newBasinLabels.end());
// See TASK_FILTER_TRANSITION for how "Valid" is determined
filter.clearInputs(); filter.clearOutputs();
insert("ReferenceState",filter.inputData,reference);
insert("State",filter.inputData,currentMin);
BaseEngine::process(filter);
extract("Valid",filter.returns,Transition);
// If a new state is seen it must be revisited for the basin dephased
// currently we just log the basin transitions, we do not use them
// segment.dephased = !Transition or BasinTransition or NewBasinTransition;
segment.dephased = !Transition;
if(!ProductionRun) if(BaseEngine::local_rank==0) LOGGERA("Dephased: "<<segment.dephased<<" "<<Transition<<" "<<BasinTransition<<" "<<NewBasinTransition);
if(BaseEngine::local_rank==0) LOGGER("Dephased: "<<segment.dephased<<" "<<Transition<<" "<<BasinTransition<<" "<<NewBasinTransition);
if(Transition) { // i.e. a transition. We
carve.clearInputs(); carve.clearOutputs();
insert("State",carve.inputData,currentMin);
BaseEngine::process(carve);
extract("Clusters",carve.returns,clusters);
//segment.dephased = bool(clusters==segment.initialClusters);
}
// i.e. unknown transition
if(!BasinTransition and !NewBasinTransition and !Transition) {
newBasinLabels[CurrentLabels] = currentMin.getEnergy();
if(reportIntermediates)
insert("State",CurrentLabels.first,CurrentLabels.second,LOCATION_SYSTEM_MIN,true,task.outputData,currentMin);
if(!ProductionRun) {
std::string _fn = "states/state-"+std::to_string(CurrentLabels.first)+"-"+std::to_string(CurrentLabels.second)+".dat";
write.clearInputs(); write.clearOutputs();
insert("Filename",write.arguments,_fn);
insert("State",write.inputData,currentMin);
BaseEngine::process(write);
}
}
if(!Transition) {
CurrentLabels=InitialLabels;
currentMin = initial;
}
// if the system is in a new basin state is seen, then it gets promoted to 'true' basin state....
}
nDephasingTrials++;
if(nDephasingTrials>=nDephasingTrialsMax) break;
if(!Transition) break;
}
segment.trials = nDephasingTrials;
// if we have dephased, newBasinLabels have participated in superbasin dephasing so are valid
if(segment.dephased) for(auto &nbl: newBasinLabels) segment.BasinLabels.insert(nbl);
if(segment.dephased) {
if(!ProductionRun) if(BaseEngine::local_rank==0) LOGGERA("DEPHASED WITH "<<newBasinLabels.size()<<" NEW BASIN STATES (NOT CURRENTLY USED)")
if(BaseEngine::local_rank==0) LOGGER("DEPHASED WITH "<<newBasinLabels.size()<<" NEW BASIN STATES (NOT CURRENTLY USED)")
} else {
if(!ProductionRun) if(BaseEngine::local_rank==0) LOGGERA("NOT DEPHASED; TRIED "<<newBasinLabels.size()<<" NEW FAKE BASIN STATES; EXITING")
if(BaseEngine::local_rank==0) LOGGER("NOT DEPHASED; TRIED "<<newBasinLabels.size()<<" NEW FAKE BASIN STATES; EXITING")
}
if(!segment.dephased) {
insert("TADSegment",task.returns,segment);
task.clearInputs();
return ;
}
segment.duration = 0;
segment.elapsedTime = 0.0;
bool annealing = false;
double segmentBlockTime=BlockTime;
double segmentTemperature = segment.temperature;
reference=currentMin;
qsd = current;
previousLabels = InitialLabels;
while ( segment.duration<=maximumSegmentLength ) {
if (annealing) {
segmentBlockTime = annealingTime * BlockTime;
segmentTemperature = annealingTemperature;
}
else {
segmentBlockTime = BlockTime;
segmentTemperature = segment.temperature;
}
//take a block of MD
md.clearInputs(); md.clearOutputs();
insert("BlockTime",md.arguments,segmentBlockTime);
insert("Temperature",md.arguments,segmentTemperature);
insert("State",md.inputData,current);
BaseEngine::process(md);
extract("State",md.outputData,current);
if(!annealing) {
segment.duration += 1;
segment.elapsedTime += BlockTime;
}
previousLabels=CurrentLabels;
// minimize the current state
min.clearInputs(); min.clearOutputs();
insert("State",min.inputData,current);
BaseEngine::process(min);
extract("State",min.outputData,currentMin);
if(!ProductionRun && BaseEngine::local_rank==0) LOGGERA("REFERENCE CURRENTMIN MSD_INF (1st MIN): "<<reference.msd(currentMin,true));
if(BaseEngine::local_rank==0) LOGGER("REFERENCE CURRENTMIN MSD_INF (1st MIN): "<<reference.msd(currentMin,true));
// just to avoid future issues..... count this?
min.clearInputs(); min.clearOutputs();
insert("State",min.inputData,currentMin);
BaseEngine::process(min);
extract("State",min.outputData,currentMin);
// hash the current minimized state
label.clearInputs(); label.clearOutputs();
insert("State",label.inputData,currentMin);
BaseEngine::process(label);
extract("Labels",label.returns,CurrentLabels);
// logs
msd_thresh = reference.msd(currentMin,true);
if(!ProductionRun) {
if(BaseEngine::local_rank==0) LOGGERA("REFERENCE CURRENTMIN MSD_INF (2nd MIN): "<<msd_thresh)
if(BaseEngine::local_rank==0) LOGGERA("CURRENT LABEL: "<<CurrentLabels.first<<" , "<<CurrentLabels.second)
}
if(BaseEngine::local_rank==0) LOGGER("REFERENCE CURRENTMIN MSD_INF (2nd MIN): "<<msd_thresh)
if(BaseEngine::local_rank==0) LOGGER("CURRENT LABEL: "<<CurrentLabels.first<<" , "<<CurrentLabels.second)
if(annealing) {
// check that annealing did not change the minima
filter.clearInputs(); filter.clearOutputs();
insert("ReferenceState",filter.inputData,annealingMin);
insert("State",filter.inputData,currentMin);
BaseEngine::process(filter);
extract("Valid",filter.returns,Transition);
Annealed = !Transition;
// check that the minima is not the initial minima
filter.clearInputs(); filter.clearOutputs();
insert("ReferenceState",filter.inputData,reference);
insert("State",filter.inputData,currentMin);
BaseEngine::process(filter);
extract("Valid",filter.returns,Transition);
if(Annealed and Transition) { // no transition after annealing == exit
if(!ProductionRun) if(BaseEngine::local_rank==0) LOGGERA("ANNEALED! VALID TRANSITION MADE!");
if(BaseEngine::local_rank==0) LOGGER("ANNEALED! VALID TRANSITION MADE!");
insert("FinalMinimum",CurrentLabels.first,CurrentLabels.second,LOCATION_SYSTEM_MIN,true,task.outputData,currentMin);
// carve
carve.clearInputs(); carve.clearOutputs();
insert("State",carve.inputData,currentMin);
BaseEngine::process(carve);
extract("Clusters",carve.returns,clusters);
extract("Position",carve.returns,position);
segment.initialE = reference.getEnergy();
segment.finalE = currentMin.getEnergy();
segment.OutOfBasin = true;
segment.finalClusters = clusters;
for(int jj=0;jj<3;jj++) segment.finalPosition[jj] = position[jj];
segment.transition.first = InitialLabels;
segment.transition.second = CurrentLabels;
if(!ProductionRun && BaseEngine::local_rank==0) LOGGERA("INSERTING "<<CurrentLabels.first<<","<<CurrentLabels.second<<" , E="<<currentMin.getEnergy()<<", NClust = "<<clusters<<", Position: "<<position[0]<<" "<<position[1]<<" "<<position[2])
if(BaseEngine::local_rank==0) LOGGER("INSERTING "<<CurrentLabels.first<<","<<CurrentLabels.second<<" , E="<<currentMin.getEnergy()<<", NClust = "<<clusters<<", Position: "<<position[0]<<" "<<position[1]<<" "<<position[2])
annealing = false; // not annealing any more
break;
} else { // annealing + !transition == continue
if(!ProductionRun && BaseEngine::local_rank==0) LOGGERA("NO VALID TRANSITION AFTER ANNEALING! CONTINUING")
if(BaseEngine::local_rank==0) LOGGER("NO VALID TRANSITION AFTER ANNEALING! CONTINUING")
annealing = false;
}
} else {
// transition check
//BasinTransition = bool(segment.BasinLabels.find(CurrentLabels)!=segment.BasinLabels.end());
filter.clearInputs(); filter.clearOutputs();
insert("ReferenceState",filter.inputData,reference);
insert("State",filter.inputData,currentMin);
BaseEngine::process(filter);
extract("Valid",filter.returns,Transition);
//if(Transition and (not BasinTransition) ) { // no basin labels yet
if(Transition) { // not annealing + not no transition == transition has been made
if(!ProductionRun && BaseEngine::local_rank==0) LOGGERA("TRANSITION DETECTED! ANNEALING FOR AnnealingTime BLOCKS AT AnnealingTemperature")
if(BaseEngine::local_rank==0) LOGGER("TRANSITION DETECTED! ANNEALING FOR AnnealingTime BLOCKS AT AnnealingTemperature")
segment.transition.first = InitialLabels;
annealing=true;
annealingMin = currentMin;
if(!ProductionRun) {
std::string _fn = "states/state-"+std::to_string(CurrentLabels.first)+"-"+std::to_string(CurrentLabels.second)+".dat";
write.clearInputs(); write.clearOutputs();
insert("Filename",write.arguments,_fn);
insert("State",write.inputData,currentMin);
BaseEngine::process(write);
}
} else { // no transition, continue MD
// reset labels as the only change was due to small fluctuations
if(!Transition and (CurrentLabels!=InitialLabels)) {
if(!ProductionRun && BaseEngine::local_rank==0) LOGGERA("NO TRANSITION FROM MSD CHECK");
if(BaseEngine::local_rank==0) LOGGER("NO TRANSITION FROM MSD CHECK");
CurrentLabels=InitialLabels; //
}
segment.transition.first = InitialLabels;
segment.transition.second = CurrentLabels;
}
}
if(segment.duration>=maximumSegmentLength and !annealing) {
if(!ProductionRun && BaseEngine::local_rank==0) LOGGERA("SEGMENT EXCEEDED MaximumSegmentLength BLOCKS. EXITING.")
if(BaseEngine::local_rank==0) LOGGER("SEGMENT EXCEEDED MaximumSegmentLength BLOCKS. EXITING.")
segment.initialE = reference.getEnergy();
segment.finalE = currentMin.getEnergy();
segment.OutOfBasin = false;
segment.transition.first = InitialLabels;
segment.transition.second = CurrentLabels;
break;
}
}
//if(LabelError) CurrentLabels = InitialLabels;
//segment.transition.second = CurrentLabels;
insert("TADSegment",task.returns,segment);
task.clearInputs();
return ;
};
/**
* Implement NEB routine between two states
*
* This expects:
* inputData: Initial, Final, Saddle (optional)
* arguments: pathway: [required: (InitialLabels, FinalLabels) , optional: SaddleLabels]
*
* ExistingPairs are pairs of states with the same initial and final canonical labels
* This returns
* outputData: Saddle (if converged) else FoundTransitions
* returns: pathway
*/
std::function<void(GenericTask&)> neb_impl = [this](GenericTask &task) {
task.clearOutputs(); // just in case
std::unordered_map<std::string,std::string> parameters=\
extractParameters(task.type,task.flavor,BaseMDEngine::defaultFlavor,BaseMDEngine::taskParameters);
//read parameters from the task
double dt=safe_extractor<double>(parameters,"NEBTimestep",0.001);
double WellDepth=safe_extractor<double>(parameters,"WellDepth",0.5);
int nImages=safe_extractor<int>(parameters,"Images",11);
int maxiter=safe_extractor<int>(parameters,"MaxIterations",1000);
double spring=safe_extractor<double>(parameters,"Spring",1.0);
double ftol=safe_extractor<double>(parameters,"ForceTolerance",0.01);
bool doClimb=safe_extractor<bool>(parameters,"Climbing",false);
bool writeFiles=safe_extractor<bool>(parameters,"WriteFiles",false);
int clust_thresh=safe_extractor<int>(parameters,"NEBClusterThresh",-1);
bool CalculatePrefactor=safe_extractor<bool>(parameters,"CalculatePrefactor",false);
bool IntermediateMinima=safe_extractor<bool>(parameters,"IntermediateMinima",false);
double ThresholdBarrier=safe_extractor<double>(parameters,"ThresholdBarrier",1.0);
// GenericTasks
GenericTask label;
label.type=BaseEngine::mapper.type("TASK_LABEL");
label.flavor=task.flavor;
GenericTask min;
min.type=BaseEngine::mapper.type("TASK_MIN");
min.flavor=task.flavor;
GenericTask carve;
carve.type=BaseEngine::mapper.type("TASK_CARVE");
carve.flavor = task.flavor;
GenericTask symmetry;
symmetry.type=BaseEngine::mapper.type("TASK_SYMMETRY");
symmetry.flavor=task.flavor;
GenericTask write;
write.type=BaseEngine::mapper.type("TASK_WRITE_TO_FILE");
write.flavor=task.flavor;
std::string filename;
//Extract Systems
System initial, final, saddle;
std::list<System> ExistingPairs;
LabelPair InitialLabels, FinalLabels, saddle_labels;
//std::list<LabelPair> ExistingPair_labels;
NEBPathway pathway; // home of all non-configuration return data;
bool success, reset, have_saddle, have_pairs, have_pathway,fsuccess;
int InitialClusters=1,FinalClusters=1;
have_pathway = extract("NEBPathway",task.arguments,pathway);
std::list<TransitionSymmetry> transitions;
std::map< Label, std::set<PointShiftSymmetry> > self_symmetries;
success = extract("Initial",task.inputData,initial);
fsuccess = extract("Final",task.inputData,final);
have_saddle = extract("Saddle",task.inputData,saddle);
if(!success) if(BaseEngine::local_rank==0) LOGGERA("COULDN'T FIND INITIAL STATES! EXITING!")
if(!fsuccess) if(BaseEngine::local_rank==0) LOGGERA("COULDN'T FIND FINAL STATES! EXITING!")
if(!success || !fsuccess) {
pathway.valid=false;
pathway.saddleE = MAX_BARRIER;
pathway.SaddleLabels = pathway.InitialLabels;
insert("NEBPathway",task.returns,pathway);
return;
}
if(have_saddle) {
label.clearInputs(); label.clearOutputs();
insert("State",label.inputData,final);
BaseEngine::process(label);
extract("Labels",label.returns,saddle_labels);
pathway.SaddleLabels = saddle_labels;
}
// not implemented yet...
pathway.priornu = std::make_pair(PRIOR_NU,PRIOR_NU);
// minimize everything (found to be useful; really needed?)
min.clearOutputs(); min.clearInputs();
insert("State",min.inputData,initial);
BaseEngine::process(min);
extract("State",min.outputData,initial);
label.clearInputs(); label.clearOutputs();
insert("State",label.inputData,initial);
BaseEngine::process(label);
extract("Labels",label.returns,InitialLabels);
carve.clearInputs(); carve.clearOutputs();
insert("State",carve.inputData,initial);
BaseEngine::process(carve);
extract("Clusters",carve.returns,InitialClusters);
if(BaseEngine::local_rank==0) LOGGER("Initial E: "<<initial.getEnergy())
pathway.initialE = initial.getEnergy();
min.clearOutputs(); min.clearInputs();
insert("State",min.inputData,final);
BaseEngine::process(min);
extract("State",min.outputData,final);
label.clearInputs(); label.clearOutputs();
insert("State",label.inputData,final);
BaseEngine::process(label);
extract("Labels",label.returns,FinalLabels);
carve.clearInputs(); carve.clearOutputs();
insert("State",carve.inputData,final);
BaseEngine::process(carve);
extract("Clusters",carve.returns,FinalClusters);
if(BaseEngine::local_rank==0) LOGGER("Final E: "<<final.getEnergy())
pathway.finalE = final.getEnergy();
pathway.mismatch = false;
if(have_pathway and (pathway.InitialLabels!=InitialLabels or pathway.FinalLabels != FinalLabels)) {
if(pathway.InitialLabels!=InitialLabels) {
if(BaseEngine::local_rank==0) LOGGER("INITIAL LABEL MISMATCH: "<<pathway.InitialLabels.first<<","<<pathway.InitialLabels.second<<" != "<<InitialLabels.first<<","<<InitialLabels.second)
} else {
if(BaseEngine::local_rank==0) LOGGER("INITIAL LABEL MATCH: "<<pathway.InitialLabels.first<<","<<pathway.InitialLabels.second<<" == "<<InitialLabels.first<<","<<InitialLabels.second)
}
if(pathway.FinalLabels != FinalLabels) {
if(BaseEngine::local_rank==0) LOGGER("FINAL LABEL MISMATCH: "<<pathway.FinalLabels.first<<","<<pathway.FinalLabels.second<<" != "<<FinalLabels.first<<","<<FinalLabels.second)
} else {
if(BaseEngine::local_rank==0) LOGGER("FINAL LABEL MATCH: "<<pathway.FinalLabels.first<<","<<pathway.FinalLabels.second<<" == "<<FinalLabels.first<<","<<FinalLabels.second)
}
InitialLabels = pathway.InitialLabels;
FinalLabels = pathway.FinalLabels;
if((pathway.InitialLabels==FinalLabels) and (pathway.FinalLabels==InitialLabels)) {
if(BaseEngine::local_rank==0) LOGGER("STRANGE SWAPPING BUG IN std::list<System>. SWAPPING BACK")
System temp_S = initial;
initial = final;
final = temp_S;
InitialLabels = pathway.InitialLabels;
FinalLabels = pathway.FinalLabels;
pathway.initialE = initial.getEnergy();
pathway.finalE = final.getEnergy();
} else {
pathway.mismatch = true;
pathway.MMInitialLabels = InitialLabels;
pathway.MMFinalLabels = FinalLabels;
if(BaseEngine::local_rank==0) LOGGER("STRANGE MISMATCH BUG IN DB. EXITING AND TRYING AGAIN....")
pathway.valid=false;
pathway.saddleE = MAX_BARRIER + std::max(pathway.initialE,pathway.finalE);
insert("NEBPathway",task.returns,pathway);
return;
}
}
pathway.valid=true; // innocent until proven guilty...
if(BaseEngine::local_rank==0) LOGGER("InitialClusters: "<<InitialClusters<<" FinalClusters: "<<FinalClusters)
if(clust_thresh>0 and std::max(InitialClusters,FinalClusters)>clust_thresh) {
pathway.valid=false; // innocent until proven guilty...
pathway.saddleE = pathway.initialE + MAX_BARRIER;
insert("NEBPathway",task.returns,pathway);
if(BaseEngine::local_rank==0) LOGGERA("TOO MANY CLUSTERS; EXITING")
return;
}
if(BaseEngine::local_rank==0) LOGGER("CANONICAL TRANSITION: "<<InitialLabels.first<<" -> "<<FinalLabels.first)
// add initial and final states to symmetry
symmetry.clearInputs();
#ifdef ISOMORPHIC
for(auto ss: pathway.InitialSymmetries) self_symmetries[pathway.InitialLabels.first].insert(ss);
for(auto ss: pathway.FinalSymmetries) self_symmetries[pathway.FinalLabels.first].insert(ss);
insert("Targets",InitialLabels.first,InitialLabels.second,0,false,symmetry.inputData,initial);
insert("Targets",FinalLabels.first,FinalLabels.second,0,false,symmetry.inputData,final);
insert("SelfSymmetries",symmetry.arguments,self_symmetries);
// minimize all ExistingPairs then compare transitions
extract("ExistingPairs",task.inputData,ExistingPairs);
have_pairs = (ExistingPairs.size()>0) and (ExistingPairs.size()%2==0);
if (have_pairs) {
if(BaseEngine::local_rank==0) LOGGER("Found "<<ExistingPairs.size()/2<<" pairs")
auto sys_ep = ExistingPairs.begin();
LabelPair labels;
while(sys_ep!=ExistingPairs.end()) {
min.clearOutputs(); min.clearInputs();
insert("State",min.inputData,*sys_ep);
BaseEngine::process(min);
extract("State",min.outputData,*sys_ep);
// better to check?
label.clearOutputs(); label.clearInputs();
insert("State",label.inputData,*sys_ep);
BaseEngine::process(label);
extract("Labels",label.returns,labels);
insert("Candidates",labels.first,labels.second,0,false,symmetry.inputData,*sys_ep);
if(BaseEngine::local_rank==0) LOGGER("Adding ExistingPairs: ("<<labels.first<<","<<labels.second<<")")
sys_ep = ExistingPairs.erase(sys_ep); // delete from master; added to symmetry
//labels = std::next(labels);
}
}
BaseEngine::process(symmetry);
// extract symmetry returns
extract("SelfTransitions",symmetry.returns,pathway.self_transitions);
extract("StateIsomorphisms",symmetry.returns,pathway.equivalent_states);
extract("TransitionIsomorphisms",symmetry.returns,pathway.equivalent_transitions);
self_symmetries.clear();
extract("SelfSymmetries",symmetry.returns,self_symmetries);
for(auto ss: self_symmetries) {
if(ss.first==pathway.InitialLabels.first)
for(auto sss: ss.second) pathway.InitialSymmetries.insert(sss);
if(ss.first==pathway.FinalLabels.first)
for(auto sss: ss.second) pathway.FinalSymmetries.insert(sss);
}
if (pathway.equivalent_transitions.size() > 0) {
pathway.duplicate = true;
if(BaseEngine::local_rank==0) LOGGER("Matches found, exiting NEB")
task.clearInputs();
insert("NEBPathway",task.returns,pathway);
if(writeFiles) {
if(BaseEngine::local_rank==0) LOGGER("Writing Initial and Final states")
// write initial and final states....
write.clearInputs(); write.clearOutputs();
filename="states/state-"+std::to_string(pathway.InitialLabels.first)+"-"+std::to_string(pathway.InitialLabels.second)+".dat";
insert("Filename",write.arguments,filename);
insert("State",write.inputData,initial);
BaseEngine::process(write);
write.clearInputs(); write.clearOutputs();
filename="states/state-"+std::to_string(pathway.FinalLabels.first)+"-"+std::to_string(pathway.FinalLabels.second)+".dat";
insert("Filename",write.arguments,filename);
insert("State",write.inputData,final);
BaseEngine::process(write);
}
return;
} else {
if(BaseEngine::local_rank==0) LOGGER("No matches found, Starting NEB")
pathway.duplicate = false;
}
#endif
// NEB routine proper
// wrap final to initial
initial.minimumImage(final); // final -> initial + minimumImageVector(final-initial)
pathway.dXmax = initial.msd(final,true);
pathway.dX = initial.msd(final,false);
if(BaseEngine::local_rank==0) LOGGER("dXThresh: "<<pathway.dXmax<<" "<<pathway.dX)
// if gap too large return with MAX_BARRIER
if (pathway.dXmax>10.0) {
pathway.valid=false;
if(BaseEngine::local_rank==0) LOGGER("max|dX| > 10A!!")
pathway.SaddleLabels = pathway.InitialLabels;
pathway.saddleE = pathway.initialE + 2.0 * MAX_BARRIER;
pathway.Ftol = 100.0;
task.clearInputs();
insert("NEBPathway",task.returns,pathway);
if(writeFiles) {
if(BaseEngine::local_rank==0) LOGGER("Writing Initial and Final states")
// write initial and final states....
write.clearInputs(); write.clearOutputs();
filename="states/state-"+std::to_string(pathway.InitialLabels.first)+"-"+std::to_string(pathway.InitialLabels.second)+".dat";
insert("Filename",write.arguments,filename);
insert("State",write.inputData,initial);
BaseEngine::process(write);
write.clearInputs(); write.clearOutputs();
filename="states/state-"+std::to_string(pathway.FinalLabels.first)+"-"+std::to_string(pathway.FinalLabels.second)+".dat";
insert("Filename",write.arguments,filename);
insert("State",write.inputData,final);
BaseEngine::process(write);
}
return;
}
// if gap too small return with MIN_BARRIER ??
// initialize f and set v=0
const int nAtoms = initial.getNAtoms();
initial.fflag = 1; final.fflag = 1;
initial.resize(nAtoms); final.resize(nAtoms);
for(int i=0;i<NDIM*nAtoms;i++) initial.v[i] = 0.0;
for(int i=0;i<NDIM*nAtoms;i++) final.v[i] = 0.0;
ExecutionTimer timer;
std::vector<System> neb_systems;
std::vector<double> energies;
energies.push_back(initial.getEnergy());
if(have_saddle) {
energies.push_back(saddle.getEnergy());
neb_systems.push_back(saddle);
}
energies.push_back(final.getEnergy());
if(!have_saddle) interpolate(neb_systems,initial,final,0,nImages-2,energies);
else {
interpolate(neb_systems,initial,final,1,nImages/2-1,energies);
interpolate(neb_systems,initial,final,0,nImages-2-nImages/2,energies);
}
neb_forces(neb_systems,initial,final,energies); // no projection here
int i=0;
if(BaseEngine::local_rank==0) for( auto E: energies) LOGGER(i++<<" "<<E-initial.getEnergy())
// Initializations for FIRE
bool rcNN = true; // recompute nn list etc
bool Climbing = false;
bool Extended = false;
bool ReDiscretize = false;
int ClimbingImage = nImages / 2;
std::list<int> InterMinImages;
int MinImage = 0;
double c_v,c_f,v_n,f_n,x_at,v_at,f_at,vdotf,f_ratio=1.0;
// FIRE parameters- TMAX=20 quite aggressive but seems OK
const double AL_ST = 0.1, AL_SHR = 0.99, DT_SHR = 0.5, DT_GR = 1.3, TMAX = 100.;
const int DELAYSTEP = 5;
const double dtmax = TMAX * dt;
//std::vector<double> dt_a(nImages,dt), alpha(nImages,AL_ST);
//std::vector<int> last_negative(nImages,0);
int lnt=0;
double dt_at=dt,alt=AL_ST;
double max_x_disp=0.0,max_x_c_disp=0.0;
double max_f_at_sq = 10.0 * ftol * ftol;
timer.start("NEB_ROUTINE");
if(BaseEngine::local_rank==0) LOGGERA("NEB STEP: MinImage ClimbingImage InterMinImages? E[ClimbingImage]-E[0] E[MinImage]-E[0] sqrt(max_f_at_sq) sqrt(max_x_c_disp) dt")
pathway.FoundTransitions.clear();
for(int iter = 0; iter < maxiter; iter++) {
timer.start("NEB_ITERATION");
if(max_x_c_disp>.1*.1 || max_f_at_sq>1.0*1.0) { // skin depth is 2A, so 1A conservative....
if(BaseEngine::local_rank==0) LOGGER("Relisting neighbors due to drift: |dX|_inf="<<sqrt(max_x_c_disp)<<", |F|_inf="<<sqrt(max_f_at_sq))
rcNN=true;
max_x_c_disp=0.0;
if(max_f_at_sq>50.0*50.0) {
if(BaseEngine::local_rank==0) LOGGER("Fmax is very large! Quitting this NEB routine and flagging for restart!")
if(BaseEngine::local_rank==0) LOGGERA("eV/A -> EXIT NEB")
pathway.valid=false;
pathway.SaddleLabels = pathway.InitialLabels;
pathway.saddleE = pathway.initialE + 2.0 * MAX_BARRIER;
pathway.Ftol = 100.0;
task.clearInputs();
insert("NEBPathway",task.returns,pathway);
return;
}
} else rcNN=bool(iter%20==0); // always every 20 steps in either case
rcNN=true; // safer for now...
neb_forces(neb_systems,initial,final,energies,false,true,spring,ClimbingImage,Climbing,rcNN); // no reset this time, but projection
path_analysis(neb_systems,initial,final,energies,MinImage,ClimbingImage,InterMinImages,WellDepth,IntermediateMinima);
// we have intermediate minima...
if ((InterMinImages.size()>0) && ((max_f_at_sq<4.0*ftol*ftol)||(iter==maxiter-1))) {
ReDiscretize = true; // only happens once..
if(BaseEngine::local_rank==0) LOGGERA("NEB "<<iter<<": "<<MinImage<<" "<<ClimbingImage<<" "<<bool(InterMinImages.size()>0)<<" "<<energies[ClimbingImage]-energies[0]<<" "<<energies[MinImage]-energies[0]<<" "<<sqrt(max_f_at_sq)<<" "<<sqrt(max_x_c_disp))
if(BaseEngine::local_rank==0) LOGGERA("InterMinImage(s) detected! Profile: E[0]="<<energies[0])
double dE = energies[ClimbingImage]-energies[0];
// max res: 20 spaces
int min_im=0;
for(int im=1;im<nImages;im++) if(energies[im]<energies[min_im]) min_im=im;
for(int im=0;im<nImages;im++) {
std::string res = "\t";
for(int ss=0;ss<int(20.0*(energies[im]-energies[min_im])/dE);ss++) res+=" ";
res += "| "+std::to_string(energies[im]-energies[min_im]);
for(auto InterMinImage: InterMinImages) if(im==InterMinImage) res+=" InterMinImage";
if(BaseEngine::local_rank==0) LOGGERA(res)
}
Transition ntrans;
ntrans.first = pathway.InitialLabels;
for(auto InterMinImage: InterMinImages) {
min.clearOutputs();
min.clearInputs();
insert("State",min.inputData,neb_systems[InterMinImage-1]);
BaseEngine::process(min);
extract("State",min.outputData,saddle);
label.clearOutputs();
label.clearInputs();
insert("State",label.inputData,saddle);
BaseEngine::process(label);
extract("Labels",label.returns,ntrans.second);
pathway.FoundTransitions.push_back(ntrans);
if(BaseEngine::local_rank==0) LOGGER("INSERTING "<<ntrans.second.first<<","<<ntrans.second.second)
insert("State",ntrans.second.first,ntrans.second.second,LOCATION_SYSTEM_MIN,true,task.outputData,saddle);
if(writeFiles) {
if(BaseEngine::local_rank==0) LOGGER("Writing Intermediate states")
// write initial and final states....
write.clearInputs(); write.clearOutputs();
filename="states/state-"+std::to_string(ntrans.second.first)+"-"+std::to_string(ntrans.second.second)+".dat";
insert("Filename",write.arguments,filename);
insert("State",write.inputData,neb_systems[InterMinImage-1]);
BaseEngine::process(write);
}
ntrans.first = ntrans.second;
}
ntrans.second = pathway.FinalLabels;
pathway.FoundTransitions.push_back(ntrans);
pathway.valid=false;
pathway.saddleE = energies[ClimbingImage];
pathway.energies = energies;
pathway.Ftol = 100.0;//sqrt(max_f_at_sq);
insert("NEBPathway",task.returns,pathway);
if(BaseEngine::local_rank==0) LOGGER("Exiting NEB!")
if(writeFiles) {
if(BaseEngine::local_rank==0)
LOGGER("Writing Initial and Final states")
// write initial and final states....
write.clearInputs(); write.clearOutputs();
filename="states/state-"+std::to_string(pathway.InitialLabels.first)+"-"+std::to_string(pathway.InitialLabels.second)+".dat";
insert("Filename",write.arguments,filename);
insert("State",write.inputData,initial);
BaseEngine::process(write);
write.clearInputs(); write.clearOutputs();
filename="states/state-"+std::to_string(pathway.FinalLabels.first)+"-"+std::to_string(pathway.FinalLabels.second)+".dat";
insert("Filename",write.arguments,filename);
insert("State",write.inputData,final);
BaseEngine::process(write);
}
return;
}
if(iter%10==0 && BaseEngine::local_rank==0)
LOGGERA("NEB "<<iter<<": "<<MinImage<<" "<<ClimbingImage<<" "<<bool(InterMinImages.size()>0)<<" "<<energies[ClimbingImage]-energies[0]<<" "<<energies[MinImage]-energies[0]<<" "<<sqrt(max_f_at_sq)<<" "<<sqrt(max_x_c_disp))
max_f_at_sq = 0.0; vdotf=0.0; f_n=0.0; v_n=0.0; f_ratio=1.0;
//for(int l=0;l<nImages-2;l++)
for(int i=0;i<nAtoms*NDIM;i++) {
f_at = neb_systems[std::max(ClimbingImage-1,0)].getForce(i/NDIM,i%NDIM);
if(f_at*f_at>max_f_at_sq) max_f_at_sq = f_at*f_at;
}
// conditioning for minimization
if(max_f_at_sq > 2.0*2.0) f_ratio = 2.0/sqrt(max_f_at_sq);
for(int l=0;l<nImages-2;l++) for(int i=0;i<nAtoms*NDIM;i++) {
x_at = neb_systems[l].getPosition(i/NDIM,i%NDIM);
v_at = neb_systems[l].getVelocity(i/NDIM,i%NDIM);
f_at = neb_systems[l].getForce(i/NDIM,i%NDIM) * f_ratio;
if(f_at*f_at>max_f_at_sq) max_f_at_sq = f_at*f_at;
f_n += f_at * f_at;
v_n += v_at * v_at;
vdotf += v_at * f_at;
}
f_n = sqrt(f_n);
v_n = sqrt(v_n);
if ( vdotf > 0.0) {
// if (v dot f) > 0:
// v = (1-alpha) v + alpha |v| Fhat
// |v| = length of v, Fhat = unit f
// no verlet here, simple to implement though
c_v = -alt;
if (f_n == 0.0) c_f = 0.0;
else c_f = alt * v_n/f_n;
max_x_disp=0.0;
for(int l=0;l<nImages-2;l++) for(int i=0;i<nAtoms*NDIM;i++) {
x_at = neb_systems[l].getPosition(i/NDIM,i%NDIM);
v_at = neb_systems[l].getVelocity(i/NDIM,i%NDIM);
f_at = neb_systems[l].getForce(i/NDIM,i%NDIM);
neb_systems[l].setVelocity(i/NDIM,i%NDIM,v_at + c_v*v_at + c_f*f_at);
neb_systems[l].setPosition(i/NDIM,i%NDIM,x_at + v_at * dt_at);
max_x_disp = std::max(max_x_disp,v_at * dt_at * v_at * dt_at);
}
max_x_c_disp += max_x_disp;
// if more than DELAYSTEP since v dot f was negative:
// increase timestep and decrease alpha
if(iter - lnt > DELAYSTEP) {
dt_at = std::min(dtmax,dt_at*DT_GR);
alt *= AL_SHR;
}
} else {
// else (v dot f) <= 0:
// decrease timestep, reset alpha, set v = dt * f
// FIRE says v=0 but this gets stuck
lnt = iter;
dt_at *= DT_SHR;
alt = AL_ST;
for(int l=0;l<nImages-2;l++) for(int i=0;i<nAtoms*NDIM;i++)
neb_systems[l].v[i] = dt_at * neb_systems[l].f[i];
}
if (max_f_at_sq < 4.0 * ftol * ftol) {
if (!Climbing and doClimb) {
if(BaseEngine::local_rank==0) LOGGER("CLIMBING"<<std::endl)
Climbing = true;
} else if(max_f_at_sq<ftol*ftol) break;
}
timer.stop("NEB_ITERATION");
}
timer.stop("NEB_ROUTINE");
i=0;
if(BaseEngine::local_rank==0) {
for( auto E: energies) LOGGERA("E["<<i++<<"]-E[0]="<<E-initial.getEnergy())
LOGGERA(energies[ClimbingImage]-energies[0]<<" "<<neb_systems.size()<<" "<<ClimbingImage)
}
// Add saddle to system
if(ClimbingImage>=neb_systems.size()) ClimbingImage = neb_systems.size()-1;
if(ClimbingImage<0) ClimbingImage = 0;
saddle = neb_systems[ClimbingImage];
label.clearInputs(); label.clearOutputs();
insert("State",label.inputData,saddle);
BaseEngine::process(label);
extract("Labels",label.returns,pathway.SaddleLabels);
insert("State",pathway.SaddleLabels.first,pathway.SaddleLabels.second,LOCATION_SYSTEM_SADDLE,true,task.outputData,saddle);
pathway.saddleE = energies[ClimbingImage];
pathway.energies = energies;
pathway.Ftol = sqrt(std::fabs(max_f_at_sq));
insert("NEBPathway",task.returns,pathway);
task.clearInputs();
timer.report();
if(writeFiles) {
if(BaseEngine::local_rank==0) LOGGER("Writing Initial, Final and Saddle states")
// write initial and final states....
write.clearInputs(); write.clearOutputs();
filename="states/state-"+std::to_string(pathway.InitialLabels.first)+"-"+std::to_string(pathway.InitialLabels.second)+".dat";
insert("Filename",write.arguments,filename);
insert("State",write.inputData,initial);
BaseEngine::process(write);
write.clearInputs(); write.clearOutputs();
filename="states/state-"+std::to_string(pathway.SaddleLabels.first)+"-"+std::to_string(pathway.SaddleLabels.second)+".dat";
insert("Filename",write.arguments,filename);
insert("State",write.inputData,saddle);
BaseEngine::process(write);
write.clearInputs(); write.clearOutputs();
filename="states/state-"+std::to_string(pathway.FinalLabels.first)+"-"+std::to_string(pathway.FinalLabels.second)+".dat";
insert("Filename",write.arguments,filename);
insert("State",write.inputData,final);
BaseEngine::process(write);
}
return;
};
/**
* read a configuration from a file, minimize, and label it.
*
* This expects:
*
* arguments: Filename
*
* This returns
* returns: Labels, Clusters, Position, SelfSymmetries
* outputData State
*/
std::function<void(GenericTask&)> init_min_impl = [this](GenericTask &task) {
task.clearOutputs();
LabelPair labels;
GenericTask t;
t.clearOutputs();
t.arguments=task.arguments;
System s;
t.flavor=task.flavor;
//read the file
t.type=BaseEngine::mapper.type("TASK_INIT_FROM_FILE");
BaseEngine::process(t);
extract("State",t.outputData,s);
// minimize
t.clear();
t.type=BaseEngine::mapper.type("TASK_MIN");
insert("State",t.inputData,s);
BaseEngine::process(t);
extract("State",t.outputData,s);
double energy = s.getEnergy();
//extract("Energy",t.returns,energy);
insert("Energy",task.returns,energy);
// label it
t.clear();
t.type=BaseEngine::mapper.type("TASK_LABEL");
insert("State",t.inputData,s);
BaseEngine::process(t);
extract("State",t.outputData,s);
extract("Labels",t.returns,labels);
insert("Labels",task.returns,labels);
// carve it
t.clear();
t.type=BaseEngine::mapper.type("TASK_CARVE");
insert("State",t.inputData,s);
BaseEngine::process(t);
// dump it
int clusters=1;
std::array<double,3> position={0.,0.,0.};
extract("Clusters",t.returns,clusters);
extract("Position",t.returns,position);
insert("Clusters",task.returns,clusters);
insert("Position",task.returns,position);
#ifdef ISOMORPHIC
std::unordered_map<std::string,std::string> parameters =
extractParameters(BaseEngine::mapper.type("TASK_NEB"),task.flavor,
BaseMDEngine::defaultFlavor,BaseMDEngine::taskParameters);
std::map<Label,std::set<PointShiftSymmetry>> self_symmetries;
t.clear();
t.type=BaseEngine::mapper.type("TASK_SYMMETRY");
insert("Targets",labels.first, labels.second,0,false,t.inputData,s);
BaseEngine::process(t);
extract("SelfSymmetries",t.returns,self_symmetries);
if(self_symmetries.find(labels.first) != self_symmetries.end()) {
insert("SelfSymmetries",task.returns,self_symmetries[labels.first]);
}
#endif
insert("State",labels.first, labels.second, LOCATION_SYSTEM_MIN, true, task.outputData, s);
};
std::function<void(GenericTask&)> label_impl = [this](GenericTask &task) {
bool canonical=false;
System s;
extract("State",task.inputData,s);
LabelPair labels;
labels.first = BaseMDEngine::labeler->hash(s,true);
labels.second = BaseMDEngine::labeler->hash(s,false);
if(BaseEngine::local_rank==0)
LOGGER("TADEngine::label_impl: "<<labels.first<<" "<<labels.second)
insert("State",labels.first,labels.second,0,false,task.outputData,s);
insert("Labels",task.returns,labels);
insert("Label",task.returns,labels.second);
insert("CanonicalLabel",task.returns,labels.first);
};
//joint remapping of a number of states. This assumes that all systems in the task correspond to the same state. The first state is used as a reference
std::function<void(GenericTask&)> remap_impl = [this](GenericTask &task){
System csys,sys;
std::map<int,int> canonicalMap;
LabelPair labs;
Label clab;
extract("State",task.inputData,sys);
if (extract("State",task.inputData,csys)) {
labs.first = BaseMDEngine::labeler->hash(sys,false);
BaseMDEngine::labeler->canonicalMap(csys,canonicalMap,labs.second);
csys.remap(canonicalMap);
clab = BaseMDEngine::labeler->hash(csys,false);
insert("Labels",task.returns,labs);
insert("State",labs.first,labs.second,LOCATION_SYSTEM_MIN,false,task.outputData,sys);
insert("CanonState",clab,labs.second,LOCATION_SYSTEM_MIN,false,task.outputData,csys);
}
};
/* HELPER FUNCTIONS */
/*
If final derived engine has singleForceEnergyCall(..) this is overwritten
Bit of a hack but stable
*/
virtual void singleForceEnergyCall(System &s, bool noforce=false,bool prepost=true) {
GenericTask forces;
forces.type = BaseEngine::mapper.type("TASK_FORCES");
bool reset = false;
insert("Reset",forces.arguments,reset);
insert("State",forces.inputData,s);
BaseEngine::process(forces);
extract("State",forces.outputData,s);
};
void neb_forces(std::vector<System> &nsv, System &initial, System &final, std::vector<double> &ev, bool reset=true, bool project=false, double spring=1.0, int ClimbingImage=1, bool Climbing=false, bool prepost=true) {
/* if(fc) {
GenericTask forces;
forces.type = BaseEngine::mapper.type("TASK_FORCES");
insert("Reset",forces.arguments,reset);
insert("PrePost",forces.arguments,prepost);
for(auto &ns: nsv) insert("State",forces.inputData,ns);
BaseEngine::process(forces);
std::list<System> nsl;
extract("State",forces.outputData,nsl);
std::swap_ranges(nsl.begin(), nsl.end(), nsv.begin());
} else */
for(auto &ns: nsv) singleForceEnergyCall(ns,false,prepost); // now robust (see above)
int ei=1;
for(auto sit=nsv.begin();sit!=nsv.end();sit++,ei++) ev[ei] = sit->getEnergy();
// do the NEB projection. Following Henkelman et al JCP 2000
if (project) {
Cell bc = initial.getCell();
int nImages=ev.size(), nAtoms=initial.getNAtoms();
System *sysp;
std::vector<double> ft(NDIM*nAtoms,0.0), bt(NDIM*nAtoms,0.0);
double ft_n,bt_n,t_n,mm,ediff[2],tmix[2],tdotf;
for(int l=0;l<nImages-2;l++) {
// FT = (X_i+1 - X_i) , |X_i+1 - X_i|
sysp = ( l==nImages-3 ? &final : &nsv[l+1] );
bc.minimumImageVector(nsv[l].x,sysp->x,ft,ft_n,mm); ft_n = sqrt(ft_n);
// BT = (X_i - X_i-1) , |X_i - X_i-1|
sysp = ( l==0 ? &initial : &nsv[l-1] );
bc.minimumImageVector(sysp->x,nsv[l].x,bt,bt_n,mm); bt_n = sqrt(bt_n);
// ft will become true tangent vector
t_n = ft_n;
// look at curvature
ediff[0] = ev[l]-ev[l-1];
ediff[1] = ev[l+1]-ev[l];
if(ediff[0]<0.0 and ediff[1]<0.0) { // i.e. both same sign => not at saddle but -ve slope
t_n = bt_n;
ft = bt;
} else { // at 'saddle' so mix
tmix[0] = (ediff[1]+ediff[0]>0.0 ? std::min(fabs(ediff[0]),fabs(ediff[1])) : std::max(fabs(ediff[0]),fabs(ediff[1])));
tmix[1] = (ediff[1]+ediff[0]>0.0 ? std::max(fabs(ediff[0]),fabs(ediff[1])) : std::min(fabs(ediff[0]),fabs(ediff[1])));
t_n = 0.0;
for(int i=0; i<nAtoms*NDIM; i++) {
ft[i] = ft[i]*tmix[0] + bt[i]*tmix[1];
t_n += ft[i] * ft[i];
}
t_n = sqrt(t_n);
}
for(int i=0; i<nAtoms*NDIM; i++) ft[i] /= t_n; // normalize for projection
// F_i . T_i
tdotf = 0.0; for(int i=0; i<nAtoms*NDIM; i++) tdotf += nsv[l].f[i] * ft[i];
// Climbing: F_i = F_i - 2T_i x [ (F_i.T_i) ]
// Regular: F_i = F_i - T_i x [ (F_i.T_i) - K (|R_{i+1}-R_i| - |R_i-R_{i-1}|) ]
if(l==ClimbingImage and Climbing) for(int i=0; i<nAtoms*NDIM; i++) nsv[l].f[i] -= 2.0 * ft[i] * tdotf;
else for(int i=0; i<nAtoms*NDIM; i++) nsv[l].f[i] -= ft[i] * ( tdotf - spring * ( ft_n - bt_n ) );
}
}
};
/* inserts nImages Systems from index start-1 of neb_systems. ie start=0 implies index */
virtual void interpolate(std::vector<System> &nsv,System &initial,System &final, unsigned int start,unsigned int nImages,std::vector<double> &energies) {
double r=0.0, dr=1.0/(double)(nImages+1);
int n = initial.getNAtoms();
std::vector<double> dx;
Cell bc = initial.getCell(); // assumes constant over path
if(start>nsv.size()) start = nsv.size();
auto eit = std::next(energies.begin(),start+1); // always shifted by one more
double refe = energies[start], drefe=energies[start+1]-energies[start]; // always possible
auto it = std::next(nsv.begin(),start);
System *a = (start==0 ? &initial : &nsv[start-1]);
System *b = (start==nsv.size() ? &final : &nsv[start]);
//a->minimumImage(*b);
bc.minimumImageVector(a->x,b->x,dx);
for(int j=0;j<NDIM*n;j++) b->x[j] = a->x[j] + dx[j];
for(int imi=0;imi<nImages;imi++,it++,eit++) {
r = dr * (imi+1);
it = nsv.insert(it,*a);
eit = energies.insert(eit, refe + r * drefe);
for(int j=0;j<NDIM*n;j++) it->x[j] += dx[j] * r;
}
};
/* finds minImage and either one or (if minImage not at an end) two climbing images */
virtual void path_analysis(std::vector<System> &systems,System &initial,System &final,std::vector<double> &energies,int &MinImage,\
int &ClimbingImage, std::list<int> &InterMinImages, double e_thresh, bool IntermediateMinima) {
// Finds minimia and climbing image of an energy path
int lastimg = energies.size()-1;
double tempE = energies[0];
// MinImage that is not 0
tempE = energies[0];
MinImage = 0;
for (int l=1;l<=lastimg;l++) if (energies[l] < tempE) {
tempE = energies[l];
MinImage = l;
}
// Climbing Image
tempE = energies[0];
for (int l=1;l<=lastimg;l++) if(energies[l] > tempE) {
tempE = energies[l];
ClimbingImage = l;
}
// InterMinImages
InterMinImages.clear();
// intermediate minima at least e_thresh deep
if(IntermediateMinima) {
double relE;
bool msdc;
for (int l=1;l<lastimg;l++) {
relE = energies[l]+e_thresh;
if((relE<energies[l+1]) && (relE<energies[l-1])) {
if(InterMinImages.size()==0) msdc = bool(initial.msd(systems[l-1],false)>MSD_THRESH);
else msdc = bool(systems[*(std::prev(InterMinImages.end()))-1].msd(systems[l-1],false)>MSD_THRESH);
if(msdc) InterMinImages.push_back(l);
}
}
}
};
};
#endif
|
#pragma once
#include "Observer.h"
#include "Observable.h"
#include <string>
// PhaseObserver is a concrete Observer that will observe be updated when game changes
class PhaseObserver : public Observer
{
private:
// we need the game as a subject so when it notifies the PhaseObserver of a change
// the phase observer will call gmae.getState() and display the changes.
static Observable* observableGameplayState;
std::string currentStatus; // Stores the current game status
public:
PhaseObserver();
PhaseObserver(Observable* gameplayState); // the passed game will set the subject data member
~PhaseObserver();
void setObservableGameplayState(Observable* gameplayState);
void update();
std::string getStatus() { return currentStatus; }; // Display the current changes in the UI
};
// StatsObserver is a concrete Observer that will observe be updated when player stats change
class StatsObserver : public Observer
{
private:
// we need the game as a subject so when it notifies the StatsObserver of a change
// the StatsObserver will call gmae.getState() and display the changes.
static Observable* observableGameplayState;
std::string statistics; // Stores all the game statistics
public:
StatsObserver();
StatsObserver(Observable* gameplayState); // the passed game will set the subject data member
~StatsObserver();
void setObservableGameplayState(Observable* gameplayState);
void update();
std::string getStatistics() { return statistics; }; // Display the current changes in the UI
};
|
#include "Semaphore.h"
#include <assert.h>
#define INCREMENT_AMOUT 1
#ifdef _MSC_VER
#include <Windows.h>
#endif // _MSC_VER
#ifndef NULL
#define NULL 0
#endif // !NULL
#ifndef LONG_MAX
#define LONG_MAX 2147483647l /* maxinum (signed) ling value*/
#endif // !LONG_MAX
struct Semaphore::SemaphoreInternal
{
void* handle;
};
Semaphore::Semaphore(int initialCount)
{
m_internal = new SemaphoreInternal;
m_internal->handle = CreateSemaphore(NULL,initialCount,LONG_MAX,NULL);
assert(m_internal->handle);
}
Semaphore::~Semaphore(void)
{
CloseHandle(m_internal->handle);
delete m_internal;
}
int Semaphore::pend()
{
assert(m_internal->handle);
return WaitForSingleObject(m_internal->handle,INFINITE);
}
int Semaphore::pend(unsigned long timeout)
{
assert(m_internal->handle);
DWORD ret = WaitForSingleObject(m_internal->handle,timeout);
if (ret == WAIT_OBJECT_0)
return 0;
return -1;
}
int Semaphore::post()
{
LONG cnt = 0;
// 获取当前信号量被使用的数量
return ReleaseSemaphore(m_internal->handle,INCREMENT_AMOUT,&cnt);
}
|
#include<bits/stdc++.h>
#define maxn 3000010
using namespace std;
using ll=long long;
int phi[maxn];
void getphi() {
phi[1]=1;
for(int i=2; i<maxn; i++)
phi[i]=i;
for(int i=2; i<maxn; i++)
if(i==phi[i])
for(int j=i; j<maxn; j+=i)
phi[j]=phi[j]/i*(i-1);
}
int main() {
// ios::sync_with_stdio(false);
// cin.tie(0);
int a,b;
ll ans;
getphi();
while(cin>>a>>b) {
ans=0;
for(int i=a; i<=b; i++)
ans+=phi[i];
cout<<ans<<"\n";
}
return 0;
}
|
// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <functional>
#include "Batcher.h"
#include "Params.h"
#include "PickingManager.h"
#include "TextBox.h"
class GlCanvas;
class GlSlider : public Pickable, public std::enable_shared_from_this<GlSlider> {
public:
GlSlider();
~GlSlider(){};
[[nodiscard]] bool Draggable() override { return true; }
void SetCanvas(GlCanvas* canvas) { canvas_ = canvas; }
void SetSliderRatio(float start); // [0,1]
void SetSliderWidthRatio(float ratio); // [0,1]
[[nodiscard]] Color GetBarColor() const { return slider_color_; }
void SetPixelHeight(float height) { pixel_height_ = height; }
[[nodiscard]] float GetPixelHeight() const { return pixel_height_; }
void SetOrthogonalSliderSize(float size) { orthogonal_slider_size_ = size; }
[[nodiscard]] float GetOrthogonalSliderSize() { return orthogonal_slider_size_; }
typedef std::function<void(float)> DragCallback;
void SetDragCallback(DragCallback callback) { drag_callback_ = callback; }
protected:
static Color GetLighterColor(const Color& color);
static Color GetDarkerColor(const Color& color);
void DrawBackground(GlCanvas* canvas, float x, float y, float width, float height);
void DrawSlider(GlCanvas* canvas, float x, float y, float width, float height,
ShadingDirection shading_direction);
protected:
static const float kGradientFactor;
GlCanvas* canvas_;
float ratio_;
float length_;
float picking_ratio_;
DragCallback drag_callback_;
Color selected_color_;
Color slider_color_;
Color bar_color_;
float min_slider_pixel_width_;
float pixel_height_;
float orthogonal_slider_size_;
};
class GlVerticalSlider : public GlSlider {
public:
GlVerticalSlider() : GlSlider(){};
~GlVerticalSlider(){};
void OnPick(int x, int y) override;
void OnDrag(int x, int y) override;
void Draw(GlCanvas* canvas, PickingMode picking_mode) override;
};
class GlHorizontalSlider : public GlSlider {
public:
GlHorizontalSlider() : GlSlider(){};
~GlHorizontalSlider(){};
void OnPick(int x, int y) override;
void OnDrag(int x, int y) override;
void Draw(GlCanvas* canvas, PickingMode picking_mode) override;
};
|
/**
* @file UserWidget.h
* @brief 用于定义UserWidget类的头文件
*/
#ifndef USERWIDGET_H
#define USERWIDGET_H
#include <qwidget.h>
#include <OgreCamera.h>
#include <OgreFrameListener.h>
#include <OgreRenderWindow.h>
#include <OgreSceneManager.h>
#include <OgreRoot.h>
#include "State.h"
class MainWindow;
class QTextEdit;
class QPushButton;
class QLabel;
class QStackedWidget;
class QVBoxLayout;
class QHBoxLayout;
class SceneWidget;
/**
* @class UserWidget UserWidget.h
* @brief 继承自QWidget类.
* 用于显示界面右边的信息栏,包括一些物体参数和场景状态信息
*/
class UserWidget: public QWidget {
Q_OBJECT
MainWindow *m_spMainWindow; ///<主界面
QVBoxLayout *userLayout; ///<垂直布局管理器
QStackedWidget* m_pStackWidget; ///<堆栈窗体
QWidget* m_pManualView; ///<手动漫游时的窗口部件
QWidget* m_pAutoView; ///<自动漫游时的窗口部件
QWidget* m_pModelEdit; ///<模型编辑时的窗口部件
QWidget* m_pRouteEdit; ///<路线编辑时的窗口部件
///模型的相关参数
QLabel *para_; ///<运动参数
QLabel *pos_; ///<当前位置
QLabel *name_; ///<选中实体名称
QLabel *box_; ///<包围盒
///路线的相关参数
QLabel *post_num_; ///<路线上的节点数目
///鼠标的相关参数-
QLabel *m_pMousePos; ///<鼠标位置
//enum SceneState{ EditModel, EditRoute, ManualRoam, AutoRoam };
signals:
void Interface(int state); ///<界面
public:
UserWidget(int state = ManualRoam, MainWindow *mainwindow = 0);
~UserWidget ();
void Initialize (int state); ///<初始化
void Clear(); ///<清屏
public slots:
void Switch(int state); ///<模式和状态选择
void OnUpdateMousePosition (Ogre::Real x, Ogre::Real y, Ogre::Real z); ///<更新鼠标位置
void OnUpdateCurrentObject (Ogre::SceneNode *obj); ///<更新当前对象位置
void OnUpdatePara (Ogre::Real speed, Ogre::Real angle, Ogre::Real ratio); ///<更新参数
void OnUpdatePostNumber (int num); ///<更新节点数目
void OnUpdateBoxInfo(int num); ///<更新盒子信息
};
#endif
|
/*
* Time.cpp
*
* Created on: 07-Apr-2015
* Author: kishor
*/
#include "Time.h"
#include <iostream>
Time::Time() {
m_hour = 0;
m_minutes = 0;
}
Time::Time(const int hour, const int minutes=0)
{
m_hour = hour;
m_minutes = minutes;
}
void Time::addHour(const int hour) {
m_hour += hour;
}
void Time::addMinutes(const int minutes) {
m_minutes += minutes;
m_minutes %= 60;
m_hour = int(minutes/60);
}
Time Time::operator + (const Time & t) {
int tot_hours = m_hour + t.m_hour;
int tot_minutes = m_minutes + t.m_minutes;
tot_hours += int(tot_minutes)/60;
tot_minutes %= 60;
return Time(tot_hours, tot_minutes);
}
Time Time::operator - (const Time & t) {
int t_tot_minutes = t.m_hour * 60 + t.m_minutes;
int tot_minutes = m_hour * 60 + m_minutes;
int diff = tot_minutes - t_tot_minutes;
return Time(int(diff/60), diff%60);
}
Time Time::operator * (const int fact) {
m_hour *= fact;
m_minutes *= fact;
int hours = m_hour + int(m_minutes / 60);
return Time(hours, m_minutes%60);
}
void Time::show() const {
std::cout << " Hours = " << m_hour << std::endl;
std::cout << " Minutes = " << m_minutes << std::endl;
}
Time::operator int() {
return m_hour*60 + m_minutes;
}
std::ostream& operator << (std::ostream& out, const Time & t) {
out << t.m_hour << " hours, " << t.m_minutes << " minutes" << std::endl;
return out;
}
|
// Sharna Hossain
// CSC111
// percentages.cpp
#include <iostream>
using namespace std;
void get_percent(int num, double percent)
{
double res = num * percent;
int percentage = percent * 100;
cout << percentage << " percent of " << num << " is " << res << endl;
}
int main()
{
int num1, num2, num3;
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
cout << "Enter the third number: ";
cin >> num3;
get_percent(num1, .10);
get_percent(num2, .20);
get_percent(num3, .30);
return 0;
}
|
#pragma once
class Station;
class Location;
class QsoItem;
class QsoTokenType;
class QsoError;
class QsoInfo;
class AllLocations;
class Contest;
class DxccCountryManager;
enum HamBand { eUnknownBand=-100, eAnyBand=-10,
e160m=0, e80m=1, e40m=2, e20m=3, e15m=4, e10m=5, e6m=6, e2m=7, e440=8, eHamBandSize=11};
enum QsoMode { eUnknownMode, eAnyMode, eModePhone, eModeCw, eModeDigital};
#include "Freq.h"
#include "Mode.h"
#include "Date.h"
#include "QsoTime.h"
#include "QsoName.h"
#include "Callsign.h"
#include "Rst.h"
#include "SerialNumber.h"
class Qso
{
public:
Qso();
virtual ~Qso();
// Copy constructor
Qso(const Qso& qso);
// C++ Assignment operator
Qso& operator=(const Qso& qso);
string OriginalText() const { return m_orig; }
void Process(const string& line, vector<QsoTokenType*>& tokenTypes);
const Freq& GetFreq() const { return m_freq; }
const Mode& GetMode() const { return m_mode; }
const Date& GetDate() const { return m_date; }
const QsoTime& GetTime() const { return m_time; }
const Callsign& GetMyCallsign() const { return m_myCall; }
const Rst& GetMyRst() const { return m_myRst; }
const QsoName& GetQsoName() const { return m_myName; }
const SerialNumber& GetMySerialNumber() const { return m_mySerialNumber; }
const Location *GetMyLocation() const { return m_myLocation; }
const Callsign& GetTheirCallsign() const { return m_theirCall; }
const Rst& GetTheirRst() const { return m_theirRst; }
const QsoName& GetTheirName() const { return m_theirName; }
const SerialNumber& GetTheirSerialNumber() const { return m_theirSerialNumber; }
const Location *GetTheirLocation() const { return m_theirLocation; }
// Return the 'qso' minute since Jan 1 2000
int GetQsoTime() const;
void SetStation(Station *station) { m_station = station; }
Station *GetStation() const { return m_station; }
static double m_dtorTime;
int GetNumber() const { return m_number; }
void SetNumber(int num) { m_number = num; }
bool IsDuplicate() const { return m_dupeNumber > 0; }
int GetDuplicateNumber() const { return m_dupeNumber; }
void SetDuplicateNumber(const int x) { m_dupeNumber = x; }
bool GetQsoErrors(list<string>& errors);
void AddQsoError(QsoError* error);
bool GetQsoInfos(list<string>& infos);
void AddQsoInfo(QsoInfo* info);
// Remove all the qso error objects
void ClearQsoErrors();
bool ValidQso() const { return m_qsoErrors.empty(); }
int ErrorCount() const { return (int)m_qsoErrors.size(); }
// Return the nth qso error
QsoError *GetQsoError(const int num);
// RefQsoNumber is the qso number for the station worked for the matching qso
int GetRefQsoNumber() const { return m_refQsoNumber; }
void SetRefQsoNumber(int x) { m_refQsoNumber = x; }
// Validate this qso
bool Validate(Contest *contest);
// Return true if the qso arg is a duplicate
bool IsDuplicateQso(Qso* qso, bool cwAndDigitalAreTheSameMode);
bool Match(HamBand band, QsoMode mode, const string& callsign, const string& myLocation, const string& theirLocation);
// Copy the freq/mode/date/time data and also copy the call/rst/sn/location data, flipping the source and target
// This is used when creating missing log files
bool CopyAndFlip(Qso* source);
// Get the created text for missing qso's
string GetCreatedText(vector<QsoTokenType*>& qsoTokenTypes);
static string GetHamBandString(const HamBand band);
bool OtherStationMissing() const { return m_otherStationMissing; }
void SetIgnore(const bool b) { m_ignore = b; }
bool IsIgnored() const { return m_ignore; }
private:
Station *m_station;
Station *m_otherStation;
bool m_alive; // true -> set true in ctor, false in dtor
// if a station mode is ssb and they have a cw qso, the cw qso
// is ignored for scoring
bool m_ignore; // ignore the qso for scoring
string m_orig; // original qso from cab file
string m_origLow; // lower case verson of m_orig
int m_number; // qso number (order in log file): 1, 2, 3...
// Created text for missing qso's
string m_createdText;
// Reference qso number of the station worked
int m_refQsoNumber;
// Duplicate Qso Number: -1 duplicate not checked, =0 no duplicate found, >0 duplicate qso number
int m_dupeNumber;
list<string> m_tokens;
list<QsoError*> m_qsoErrors;
list<QsoInfo*> m_qsoInfos;
// frequency, mode, date, time QsoItem map
map<string, QsoItem*> m_freqMap;
// qso data map; callsign, rst, serial number, location
map<string, QsoItem*> m_myQsoMap;
map<string, QsoItem*> m_theirQsoMap;
// true -> the station worked in the qso did not submit a log
bool m_otherStationMissing;
// string line("QSO: 3541 CW 2014-04-06 0109 AI4WW 599 0001 FL N0H 599 0616 GAS ");
Freq m_freq;
Mode m_mode;
Date m_date;
QsoTime m_time;
Callsign m_myCall;
Rst m_myRst;
QsoName m_myName;
SerialNumber m_mySerialNumber;
Location *m_myLocation;
Callsign m_theirCall;
Rst m_theirRst;
QsoName m_theirName;
SerialNumber m_theirSerialNumber;
Location *m_theirLocation;
private:
void Process2( list<string>::iterator& iter,
vector<QsoTokenType*>& tokenTypes,
map<string, QsoItem*>& qsoItemMap,
int& tokenCount, int& errorCount);
bool CheckInStateLocation(Location *location, const set<string>& locationAbbrevs);
bool CheckAllLocations(Location *location, AllLocations *allLocations, const set<string>& countyAbbrevs, bool checkCounties, DxccCountryManager *dxccCountryMgr);
// extract 'my' qso data to the map
bool GetMyQsoData(map<string, string>& qsoData);
// extract 'their' qso data to the map
bool GetTheirQsoData(map<string, string>& qsoData);
};
|
#include <cassert>
namespace techniques {
template<bool>
struct CompileTimeChecker {
CompileTimeChecker(...);
};
template<>
struct CompileTimeChecker<false> {};
#define STATIC_CHECK_1(expr, msg)\
{\
class ERROR_##msg {};\
(void)sizeof(CompileTimeChecker<(expr) != 0>((ERROR_##msg{})));\
}
template<bool> struct CompileTimeError;
template<> struct CompileTimeError<true> {};
#define STATIC_CHECK(expr) { char unnamed[(expr) ? 1 : -1]; }
#define STATIC_CHECK(expr)\
(CompileTimeError<(expr) != 0>{})
template<class To, class From>
To safe_reinterpret_cast(From from) {
// assert(sizeof(From) <= sizeof(To));
// STATIC_CHECK(sizeof(From) <= sizeof(To));
STATIC_CHECK_1(sizeof(From) <= sizeof(To), Destionation_Type_Too_Narrow);
// static_assert(sizeof(From) <= sizeof(To));
return To{};
// return reinterpret_cast<To>(from);
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
**
*/
#include "core/pch.h"
#include "modules/url/url2.h"
URL_InUse::~URL_InUse()
{
UnsetURL();
}
/*
void URL_InUse::SetURL(URL_InUse &old)
{
if(&old == this)
return; // No action needed
UnsetURL();
if(old.url.IsValid())
{
url = old.url;
url.IncUsed();
TRACER_INUSE_SETTRACKER(url);
}
}
*/
void URL_InUse::SetURL(URL &p_url)
{
if(p_url == url)
return; // No action needed
UnsetURL();
if(p_url.IsValid())
{
url = p_url;
url.IncUsed();
TRACER_INUSE_SETTRACKER(url);
}
}
void URL_InUse::SetURL(const URL &p_url)
{
if(p_url == url)
return; // No action needed
UnsetURL();
if(p_url.IsValid())
{
url = p_url;
url.IncUsed();
TRACER_INUSE_SETTRACKER(url);
}
}
void URL_InUse::UnsetURL()
{
if(url.IsValid())
{
url.DecUsed();
url = URL();
}
TRACER_RELEASE();
}
|
// Copyright 2015 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sharer_sender.h"
#include "base/logger.h"
#include "base/ptr_utils.h"
#include "sender/video_sender.h"
#include <string>
namespace sharer {
SharerSender::SharerSender(pp::Instance* instance, int id)
: instance_(instance),
sender_id_(id),
clock_(make_unique<base::DefaultTickClock>()),
initialized_video_(false),
/* initialized_audio_(false), */
initialized_cb_(nullptr),
pauseID(0) {}
SharerSender::~SharerSender() { DINF() << "Destroying SharerSender."; }
void SharerSender::Initialize(const SenderConfig& config,
SharerSenderInitializedCb cb) {
initialized_cb_ = cb;
auto transport_cb =
[this](bool result) { this->InitializedTransport(result); };
transport_ = make_unique<TransportSender>(instance_, clock_.get(), config,
transport_cb);
auto video_cb = [this](bool result) { this->InitializedVideo(result); };
auto playout_changed_cb = [this](const base::TimeDelta& playout_delay) {
this->SetTargetPlayoutDelay(playout_delay);
};
video_sender_ =
make_unique<VideoSender>(instance_, clock_.get(), transport_.get(),
config, video_cb, playout_changed_cb);
}
bool SharerSender::SetTracks(const pp::MediaStreamVideoTrack& video_track,
const SharerSuccessCb& cb) {
DINF() << "Setting audio and video tracks.";
video_sender_->StartSending(video_track, cb);
return true;
}
bool SharerSender::StopTracks(const SharerSuccessCb& cb) {
DINF() << "Stop sendng.";
video_sender_->StopSending(cb);
return true;
}
void SharerSender::ChangeEncoding(const SenderConfig& config) {
DINF() << "Changing encoding parameters";
video_sender_->ChangeEncoding(config);
return;
}
void SharerSender::InitializedVideo(bool success) {
if (!success) {
ERR() << "Failed to initialize video.";
initialized_cb_(id(), SharerSender::INIT_FAILED_VIDEO);
return;
}
initialized_video_ = true;
INF() << "Successfully initialized video.";
CheckInitialized();
}
void SharerSender::InitializedTransport(bool success) {
if (!success) {
ERR() << "Failed to initialize transport.";
initialized_cb_(id(), SharerSender::INIT_FAILED_TRANSPORT);
return;
}
initialized_transport_ = true;
INF() << "Successfully initialized transport.";
CheckInitialized();
}
void SharerSender::CheckInitialized() {
if (initialized_video_ && initialized_transport_) {
if (initialized_cb_) {
initialized_cb_(id(), SharerSender::INIT_SUCCESS);
initialized_cb_ = nullptr;
}
}
}
void SharerSender::SetTargetPlayoutDelay(const base::TimeDelta& playout_delay) {
if (video_sender_) {
video_sender_->SetTargetPlayoutDelay(playout_delay);
}
}
} // namespace sharer
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
int a[600][600];
int main() {
int n;
scanf("%d",&n);
a[1][1] = 1;
for (int k = 0;k < n; k++) {
int d = 1 << k;
for (int i = 1;i <= d; i++)
for (int j = 1;j <= d; j++) {
a[d+i][j] = a[i][j];a[i][d+j] = a[i][j];
a[d+i][d+j] = -a[i][j];
}
}
int k = 1 << n;
for (int i = 1;i <= k; i++) {
for (int j = 1;j <= k; j++)
if (a[i][j] == 1) putchar('+');
else putchar('*');
puts("");
}
return 0;
}
|
#include "stdafx.h"
#include "boneSphere.h"
boneSphere::boneSphere()
{
}
boneSphere::boneSphere(bone* b)
{
originBone = b;
}
boneSphere::boneSphere(boneSphere *b)
{
*this = *b;
}
boneSphere::~boneSphere()
{
}
|
// --- This file is distributed under the MIT Open Source License, as detailed
// by the file "LICENSE.TXT" in the root of this repository ---
#ifndef HURCHALLA_UTIL_EXTENSIBLE_MAKE_SIGNED_H_INCLUDED
#define HURCHALLA_UTIL_EXTENSIBLE_MAKE_SIGNED_H_INCLUDED
#include "hurchalla/util/compiler_macros.h"
#include <type_traits>
namespace hurchalla { namespace util {
// primary template
template <typename T>
struct extensible_make_signed {
static_assert(std::is_integral<T>::value,
"You'll need to specialize extensible_make_signed for your type T");
using type = typename std::make_signed<T>::type;
};
// ---Specializations---
//
// You can use the following as an example of how to specialize for a particular
// integer type you wish to use.
//
// ** If you specialize this type, you should probably also specialize
// extensible_make_unsigned (in extensible_make_unsigned.h) **
#if (HURCHALLA_COMPILER_HAS_UINT128_T())
// explicit specializations for __int128_t
template<>
struct extensible_make_signed<__int128_t> {
using type = __int128_t;
};
template<>
struct extensible_make_signed<const __int128_t> {
using type = const __int128_t;
};
template<>
struct extensible_make_signed<volatile __int128_t> {
using type = volatile __int128_t;
};
template<>
struct extensible_make_signed<const volatile __int128_t> {
using type = const volatile __int128_t;
};
// explicit specializations for __uint128_t
template<>
struct extensible_make_signed<__uint128_t> {
using type = __int128_t;
};
template<>
struct extensible_make_signed<const __uint128_t> {
using type = const __int128_t;
};
template<>
struct extensible_make_signed<volatile __uint128_t> {
using type = volatile __int128_t;
};
template<>
struct extensible_make_signed<const volatile __uint128_t> {
using type = const volatile __int128_t;
};
#endif
}} // end namespace
#endif
|
#ifndef KWIK_LEXER_H
#define KWIK_LEXER_H
#include <string>
#include <memory>
#include "utf8cpp/utf8.h"
#include "parser.h"
#include "token.h"
#include "io.h"
namespace kwik {
class Lexer {
public:
Lexer(ParseState& s);
Token get_token();
private:
SourceRef getref(size_t line, size_t col);
void throw_unexpected_char(uint32_t c, size_t line, size_t col);
Token lex_num();
Token lex_ident();
ParseState& s;
size_t line, col;
utf8::unchecked::iterator<const char*> it;
};
}
#endif
|
// Created on: 1996-01-29
// Created by: Jean Yves LEBEY
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TopOpeBRepBuild_WireToFace_HeaderFile
#define _TopOpeBRepBuild_WireToFace_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <TopTools_ListOfShape.hxx>
class TopoDS_Wire;
class TopoDS_Face;
//! This class builds faces from a set of wires SW and a face F.
//! The face must have and underlying surface, say S.
//! All of the edges of all of the wires must have a 2d representation
//! on surface S (except if S is planar)
class TopOpeBRepBuild_WireToFace
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT TopOpeBRepBuild_WireToFace();
Standard_EXPORT void Init();
Standard_EXPORT void AddWire (const TopoDS_Wire& W);
Standard_EXPORT void MakeFaces (const TopoDS_Face& F, TopTools_ListOfShape& LF);
protected:
private:
TopTools_ListOfShape myLW;
};
#endif // _TopOpeBRepBuild_WireToFace_HeaderFile
|
#pragma once
#include "ReiaEngine/Scene.h"
#include "ReiaEngine/UI.h"
class MainScene : public Scene
{
public:
MainScene() {
points.Anchor = TOP_LEFT;
points.Position.X = 10;
points.Position.Y = 10;
Renderer.AddObject(&points);
}
private:
Text points;
};
|
// BEGIN CUT HERE
// PROBLEM STATEMENT
// A non-negative integer n is said to be a sum of two
// perfect powers if there exist two non-negative integers a
// and b such that am + bk = n for some positive integers m
// and k, both greater than 1. Given two non-negative
// integers lowerBound and upperBound, return the number of
// integers between lowerBound and upperBound, inclusive,
// that are sums of two perfect powers.
//
// DEFINITION
// Class:SumsOfPerfectPowers
// Method:howMany
// Parameters:int, int
// Returns:int
// Method signature:int howMany(int lowerBound, int upperBound)
//
//
// CONSTRAINTS
// -lowerBound will be between 0 and 5000000, inclusive.
// -upperBound will be between lowerBound and 5000000,
// inclusive.
//
//
// EXAMPLES
//
// 0)
// 0
// 1
//
// Returns: 2
//
// 0 and 1 are both sums of two perfect powers since 0 = 0 +
// 0 and 1 = 12 + 02.
//
// 1)
// 5
// 6
//
// Returns: 1
//
// 5 is a sum of two perfect powers since 5 = 22 + 12 while 6
// is not.
//
// 2)
// 25
// 30
//
// Returns: 5
//
// Only 30 is not a sum of two perfect powers.
//
// 3)
// 103
// 103
//
// Returns: 0
//
// There may be no desired integers in the range.
//
// 4)
// 1
// 100000
//
// Returns: 33604
//
//
//
// END CUT HERE
#line 71 "SumsOfPerfectPowers.cpp"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include <set>
#include <cassert>
#include <list>
#include <deque>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
using namespace std;
#define fi(n) for(int i=0;i<(n);i++)
#define fj(n) for(int j=0;j<(n);j++)
#define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
typedef vector <int> VI;
typedef vector <string> VS;
typedef vector <VI> VVI;
class SumsOfPerfectPowers
{
public:
int get(int no) {
set<int> pow;
for (int i = 0; i * i <= no; ++i) {
if (pow.find(i) != pow.end()) {
continue;
}
for(int j = 0; ;j++) {
if (pow
}
}
}
int howMany(int lb, int ub)
{
return get(ub) - get(lb-1);
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 0; int Arg1 = 1; int Arg2 = 2; verify_case(0, Arg2, howMany(Arg0, Arg1)); }
void test_case_1() { int Arg0 = 5; int Arg1 = 6; int Arg2 = 1; verify_case(1, Arg2, howMany(Arg0, Arg1)); }
void test_case_2() { int Arg0 = 25; int Arg1 = 30; int Arg2 = 5; verify_case(2, Arg2, howMany(Arg0, Arg1)); }
void test_case_3() { int Arg0 = 103; int Arg1 = 103; int Arg2 = 0; verify_case(3, Arg2, howMany(Arg0, Arg1)); }
void test_case_4() { int Arg0 = 1; int Arg1 = 100000; int Arg2 = 33604; verify_case(4, Arg2, howMany(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
SumsOfPerfectPowers ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include "Battipaglia.h"
#include "MyBattipagliaProjectile.h"
#include "GameFramework/ProjectileMovementComponent.h"
AMyBattipagliaProjectile::AMyBattipagliaProjectile(const class FObjectInitializer& PCIP)
:
Super(PCIP),
acceleration(100.0f),
velocity(0.0f)
{
PrimaryActorTick.bCanEverTick = true;
}
void AMyBattipagliaProjectile::Tick(float dt)
{
velocity += acceleration * dt;
RootComponent->MoveComponent(FVector(0, velocity, 0), FRotator::ZeroRotator, false);
Super::Tick(dt);
}
|
/*
题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
思路:左子树的左孩子和右子树的右孩子相等,左子树的右孩子和右子树的左孩子相等,符合这两个条件就是对称
*/
#include<iostream>
using namespace std;
#include<vector>
#include<map>
#include<algorithm>
#include<deque>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > res;
if (!pRoot) return res;
deque<TreeNode*> mydeq;
TreeNode* endnode = pRoot, * p;
mydeq.push_back(pRoot);
bool tag = 0;
vector<int> temp;
while (!mydeq.empty()) {
if (tag == 0) {
p = mydeq.front();
mydeq.pop_front();
if(p->left) mydeq.push_back(p->left);
if (p->right) mydeq.push_back(p->right);
temp.push_back(p->val);
}
else
{
p = mydeq.back();
mydeq.pop_back();
if (p->right) mydeq.push_front(p->right);
if (p->left) mydeq.push_front(p->left);
temp.push_back(p->val);
}
if (p == endnode) {
if (!tag) endnode = mydeq.front();
else endnode = mydeq.back();
tag = !tag;
res.push_back(temp);
temp.clear();
}
}
return res;
}
};
void f(){}
int main() {
return 0;
}
|
// Copyright (c) 2020 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TDataStd_GenericExtString_HeaderFile
#define _TDataStd_GenericExtString_HeaderFile
#include <TDF_DerivedAttribute.hxx>
#include <TCollection_ExtendedString.hxx>
#include <Standard_GUID.hxx>
class TDF_RelocationTable;
class TDataStd_GenericExtString;
DEFINE_STANDARD_HANDLE(TDataStd_GenericExtString, TDF_Attribute)
//! An ancestor attribute for all attributes which have TCollection_ExtendedString field.
//! If an attribute inherits this one it should not have drivers for persistence.
//! Also this attribute provides functionality to have on the same label same attributes with different IDs.
class TDataStd_GenericExtString : public TDF_Attribute
{
public:
//! Sets <S> as name. Raises if <S> is not a valid name.
Standard_EXPORT virtual void Set (const TCollection_ExtendedString& S);
//! Sets the explicit user defined GUID to the attribute.
Standard_EXPORT void SetID (const Standard_GUID& guid) Standard_OVERRIDE;
//! Returns the name contained in this name attribute.
Standard_EXPORT virtual const TCollection_ExtendedString& Get() const;
//! Returns the ID of the attribute.
Standard_EXPORT const Standard_GUID& ID() const Standard_OVERRIDE;
Standard_EXPORT void Restore (const Handle(TDF_Attribute)& with) Standard_OVERRIDE;
Standard_EXPORT void Paste (const Handle(TDF_Attribute)& into, const Handle(TDF_RelocationTable)& RT) const Standard_OVERRIDE;
//! Dumps the content of me into the stream
Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(TDataStd_GenericExtString,TDF_Attribute)
protected:
//! A string field of the attribute, participated in persistence.
TCollection_ExtendedString myString;
//! A private GUID of the attribute.
Standard_GUID myID;
};
#endif // _TDataStd_GenericExtString_HeaderFile
|
#ifndef LEARNING_CADDON
#define LEARNING_CADDON
#include <math.h>
class MyPoint
{
public:
MyPoint() : x(0), y(0){};
// MyPoint(MyPoint sp) { x = sp.x, y = sp.y; }
/* 构造函数不能引用构造本类作为参数:印象中是可以的,不知错哪了? */
MyPoint(double x0, double y0) { x = x0, y = y0; };
void Set(double x0, double y0) { x = x0, y = y0; }
void SetX(double x0) { x = x0; }
void SetY(double y0) { y = y0; }
void Get(double &x0, double &y0) const { x0 = x, y0 = y; }
double GetX() const { return x; }
double GetY() const { return y; }
~MyPoint(void){};
MyPoint Move(double x1, double y1)
{
x += x1;
y += y1;
return *this;
}
double Distance(MyPoint p)
{
double dx = x - p.x;
double dy = y - p.y;
return sqrt(dx * dx + dy * dy);
}
double Distance(double x1, double y1)
{
double dx = x - x1;
double dy = y - y1;
return sqrt(dx * dx + dy * dy);
}
private:
double x;
double y;
};
#endif // LEARNING_CADDON
|
#include "Core/Core.h"
DWORD WINAPI MainThread(LPVOID lpParam)
{
g_Core.Load();
while (!g_Core.ShouldUnload())
Sleep(100);
g_Core.Unload();
FreeLibraryAndExitThread(static_cast<HMODULE>(lpParam), EXIT_SUCCESS);
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
{
DisableThreadLibraryCalls(hinstDLL);
if (fdwReason == DLL_PROCESS_ATTACH)
{
if (HANDLE hMainThread = CreateThread(0, 0, MainThread, hinstDLL, 0, 0))
CloseHandle(hMainThread);
}
return TRUE;
}
|
//everytime char goes to " " space, goes to next line
#include<iostream>
#include "showWords.h"
void showWords(string st) {
for (int i = 0; i < st.length() i++) {
}
}
|
#include <iostream>
#include <string>
#include <string.h>
int main(int argc, char* argv[]){
{
// copy from string to char array
char* charArray = (char*)malloc(sizeof(char) * 1024);
memset(charArray, 'A', 1024);
std::string strTemp;
strTemp.resize(strlen(charArray));
std::cout << "before: " << strTemp[0] << std::endl;
memcpy(&strTemp[0], charArray, strlen(charArray));
std::cout << "after: " << strTemp[0] << std::endl;
}
{
// free memory
char* charArray = NULL;
std::cout << "before free" << std::endl;
if (charArray != NULL){
free(charArray);
}
std::cout << "after free" << std::endl;
}
return 0;
}
|
#ifndef SPHPARTICLEPROPEPRTY_H
#define SPHPARTICLEPROPEPRTY_H
#include <cuda_runtime.h>
//--------------------------------------------------------------------------------------------------------------
/// @author Idris Miles
/// @version 1.0
/// @date 01/06/2017
//--------------------------------------------------------------------------------------------------------------
/// @class SphParticleProperty
/// @brief This class holds the properties of the BaseSphParticle
class SphParticleProperty
{
public:
/// @brief constructor
SphParticleProperty(unsigned int _numParticles = 8000,
float _particleMass = 1.0f,
float _particleRadius = 0.2f,
float _restDensity = 998.36f,
float _smoothingLength = 1.2f,
float3 _gravity = make_float3(0.0f, -9.8f, 0.0f)):
numParticles(_numParticles),
particleMass(_particleMass),
particleRadius(_particleRadius),
restDensity(_restDensity),
smoothingLength(_smoothingLength),
gravity(_gravity)
{
float dia = 2.0f * particleRadius;
particleMass = restDensity * (dia * dia * dia);
}
/// @brief destructor
~SphParticleProperty(){}
unsigned int numParticles;
float particleMass;
float particleRadius;
float restDensity;
float smoothingLength;
float3 gravity;
};
//--------------------------------------------------------------------------------------------------------------
#include "json/src/json.hpp"
using json = nlohmann::json;
void to_json(json& j, const SphParticleProperty& p);
void from_json(const json& j, SphParticleProperty& p);
#endif // SPHPARTICLEPROPEPRTY_H
|
// EMERGENT GAME TECHNOLOGIES PROPRIETARY INFORMATION
//
// This software is supplied under the terms of a license agreement or
// nondisclosure agreement with Emergent Game Technologies and may not
// be copied or disclosed except in accordance with the terms of that
// agreement.
//
// Copyright (c) 1996-2008 Emergent Game Technologies.
// All Rights Reserved.
//
// Emergent Game Technologies, Chapel Hill, North Carolina 27517
// http://www.emergent.net
#ifndef NIUISLOT_H
#define NIUISLOT_H
#include <GnTSet.h>
class GnSignal0;
template <typename Arg1Type>
class GnSignal1;
template <typename Arg1Type, typename Arg2Type>
class GnSignal2;
class GnBaseSlot0 : public GnMemoryObject
{
public:
GnBaseSlot0();
virtual ~GnBaseSlot0();
virtual void ReceiveSignal() const = 0;
void Subscribe(GnSignal0* pkSignal);
void Unsubscribe(GnSignal0* pkSignal);
bool IsSubscribed(GnSignal0* pkSignal) const;
unsigned int NumSubscribed() const;
protected:
GnTPrimitiveSet <GnSignal0*> m_pkSignals;
};
// These two classes only add the function callback pointer and the class
// instance pointer (where needed) to the above Base class
class GnStaticSlot0 : public GnBaseSlot0
{
public:
GnStaticSlot0();
GnStaticSlot0(void (*pfnCallback)());
void Initialize(void (*pfnCallback)());
virtual ~GnStaticSlot0();
virtual void ReceiveSignal() const;
protected:
void (*m_pfnCallback)();
};
template <typename ClassType>
class GnMemberSlot0 : public GnBaseSlot0
{
public:
GnMemberSlot0();
GnMemberSlot0(ClassType* pkInstance, void (ClassType::*pfnCallback)());
void Initialize(ClassType* pkInstance, void (ClassType::*pfnCallback)());
virtual ~GnMemberSlot0();
virtual void ReceiveSignal() const;
protected:
ClassType* m_pkInstance;
void (ClassType::*m_pfnCallback)();
};
// All one parameter slots must inherit from GnBaseSlot1. This allows for
// a single signal to emit to slots which call member functions as well as
// non-member or static member functions.
template <typename Arg1Type>
class GnBaseSlot1 : public GnMemoryObject
{
public:
GnBaseSlot1();
virtual ~GnBaseSlot1();
virtual void ReceiveSignal(Arg1Type Arg1) const = 0;
void Subscribe(GnSignal1<Arg1Type>* pkSignal);
void Unsubscribe(GnSignal1<Arg1Type>* pkSignal);
bool IsSubscribed(GnSignal1<Arg1Type>* pkSignal) const;
unsigned int NumSubscribed() const;
protected:
GnTPrimitiveSet <GnSignal1<Arg1Type>*> m_pkSignals;
};
// These two classes only add the function callback pointer and the class
// instance pointer (where needed) to the above Base class
template <typename Arg1Type>
class GnStaticSlot1 : public GnBaseSlot1<Arg1Type>
{
public:
GnStaticSlot1();
GnStaticSlot1(void (*pfnCallback)(Arg1Type));
void Initialize(void (*pfnCallback)(Arg1Type));
virtual ~GnStaticSlot1();
virtual void ReceiveSignal(Arg1Type Arg1) const;
protected:
void (*m_pfnCallback)(Arg1Type);
};
template <typename ClassType, typename Arg1Type>
class GnMemberSlot1 : public GnBaseSlot1<Arg1Type>
{
public:
GnMemberSlot1();
GnMemberSlot1(ClassType* pkInstance,
void (ClassType::*pfnCallback)(Arg1Type));
void Initialize(ClassType* pkInstance,
void (ClassType::*pfnCallback)(Arg1Type));
virtual ~GnMemberSlot1();
virtual void ReceiveSignal(Arg1Type Arg1) const;
protected:
ClassType* m_pkInstance;
void (ClassType::*m_pfnCallback)(Arg1Type);
};
// All two parameter slots must inherit from GnBaseSlot2. This allows for
// a single signal to emit to slots which call member functions as well as
// non-member or static member functions.
template <typename Arg1Type, typename Arg2Type>
class GnBaseSlot2 : public GnMemoryObject
{
public:
GnBaseSlot2();
virtual ~GnBaseSlot2();
virtual void ReceiveSignal(Arg1Type Arg1, Arg2Type Arg2) const = 0;
void Subscribe(GnSignal2<Arg1Type, Arg2Type>* pkSignal);
void Unsubscribe(GnSignal2<Arg1Type, Arg2Type>* pkSignal);
bool IsSubscribed(GnSignal2<Arg1Type, Arg2Type>* pkSignal) const;
unsigned int NumSubscribed() const;
protected:
GnTPrimitiveSet <GnSignal2<Arg1Type, Arg2Type>*> m_pkSignals;
};
// These two classes only add the function callback pointer and the class
// instance pointer (where needed) to the above Base class
template <typename Arg1Type, typename Arg2Type>
class GnStaticSlot2 : public GnBaseSlot2<Arg1Type, Arg2Type>
{
public:
GnStaticSlot2();
GnStaticSlot2(void (*pfnCallback)(Arg1Type, Arg2Type));
void Initialize(void (*pfnCallback)(Arg1Type, Arg2Type));
virtual ~GnStaticSlot2();
virtual void ReceiveSignal(Arg1Type Arg1, Arg2Type Arg2) const;
protected:
void (*m_pfnCallback)(Arg1Type, Arg2Type);
};
template <typename ClassType, typename Arg1Type, typename Arg2Type>
class GnMemberSlot2 : public GnBaseSlot2<Arg1Type, Arg2Type>
{
public:
GnMemberSlot2();
GnMemberSlot2(ClassType* pkInstance,
void (ClassType::*pfnCallback)(Arg1Type, Arg2Type));
void Initialize(ClassType* pkInstance,
void (ClassType::*pfnCallback)(Arg1Type, Arg2Type));
virtual ~GnMemberSlot2();
virtual void ReceiveSignal(Arg1Type Arg1, Arg2Type Arg2) const;
protected:
ClassType* m_pkInstance;
void (ClassType::*m_pfnCallback)(Arg1Type, Arg2Type);
};
#include "GnSignalSlotMacros.h"
#include "GnSignal.h"
inline GnBaseSlot0::GnBaseSlot0()
{
}
inline GnBaseSlot0::~GnBaseSlot0()
{
GnUnsubscribeFromAll(m_pkSignals);
}
inline void GnBaseSlot0::Subscribe(GnSignal0* pkSignal)
{
GnSubscribeToMe(m_pkSignals, pkSignal);
}
inline void GnBaseSlot0::Unsubscribe(GnSignal0* pkSignal)
{
GnUnsubscribeToMe(m_pkSignals, pkSignal);
}
inline bool GnBaseSlot0::IsSubscribed(GnSignal0* pkSignal) const
{
return GnIsElementInGroup(m_pkSignals, pkSignal);
}
inline unsigned int GnBaseSlot0::NumSubscribed() const
{
return GnNumElements(m_pkSignals);
}
inline GnStaticSlot0::GnStaticSlot0() : GnBaseSlot0(), m_pfnCallback(NULL)
{
}
inline GnStaticSlot0::GnStaticSlot0(void (*pfnCallback)()) : GnBaseSlot0(), m_pfnCallback(pfnCallback)
{
GnAssert(pfnCallback != NULL);
}
inline void GnStaticSlot0::Initialize(void (*pfnCallback)())
{
GnAssert(pfnCallback != NULL);
m_pfnCallback = pfnCallback;
}
inline GnStaticSlot0::~GnStaticSlot0()
{
// Note: None of the pointers in any of these destructors is owned by
// this instance: Therefore, it should not delete them
m_pfnCallback = NULL;
}
inline void GnStaticSlot0::ReceiveSignal() const
{
GnAssert(m_pfnCallback != NULL);
(*m_pfnCallback)();
}
template <typename ClassType> inline
GnMemberSlot0<ClassType>::GnMemberSlot0() : m_pkInstance(NULL), m_pfnCallback(NULL)
{
}
template <typename ClassType> inline
GnMemberSlot0<ClassType>::GnMemberSlot0(ClassType* pkInstance, void (ClassType::*pfnCallback)())
: m_pkInstance(pkInstance), m_pfnCallback(pfnCallback)
{
GnAssert(pkInstance != NULL);
GnAssert(pfnCallback != NULL);
}
template <typename ClassType> inline
void GnMemberSlot0<ClassType>::Initialize(ClassType* pkInstance, void (ClassType::*pfnCallback)())
{
GnAssert(pkInstance != NULL);
GnAssert(pfnCallback != NULL);
m_pkInstance = pkInstance,
m_pfnCallback = pfnCallback;
}
template <typename ClassType> inline
GnMemberSlot0<ClassType>::~GnMemberSlot0()
{
// Note: None of the pointers in any of these destructors is owned by
// this instance: Therefore, it should not delete them
m_pkInstance = NULL;
m_pfnCallback = NULL;
}
template <typename ClassType> inline
void GnMemberSlot0<ClassType>::ReceiveSignal() const
{
GnAssert(m_pkInstance != NULL);
GnAssert(m_pfnCallback != NULL);
(m_pkInstance->*m_pfnCallback)();
}
template <typename Arg1Type> inline
GnBaseSlot1<Arg1Type>::GnBaseSlot1()
{
}
template <typename Arg1Type> inline GnBaseSlot1<Arg1Type>::~GnBaseSlot1()
{
GnUnsubscribeFromAll(m_pkSignals);
}
template <typename Arg1Type> inline
void GnBaseSlot1<Arg1Type>::Subscribe(GnSignal1<Arg1Type>* pkSignal)
{
GnSubscribeToMe(m_pkSignals, pkSignal);
}
template <typename Arg1Type> inline
void GnBaseSlot1<Arg1Type>::Unsubscribe(GnSignal1<Arg1Type>* pkSignal)
{
GnUnsubscribeToMe(m_pkSignals, pkSignal);
}
template <typename Arg1Type> inline
bool GnBaseSlot1<Arg1Type>::IsSubscribed(GnSignal1<Arg1Type>* pkSignal)
const
{
return GnIsElementInGroup(m_pkSignals, pkSignal);
}
template <typename Arg1Type> inline unsigned int GnBaseSlot1<Arg1Type>::NumSubscribed() const
{
return GnNumElements(m_pkSignals);
}
template <typename Arg1Type>
inline GnStaticSlot1<Arg1Type>::GnStaticSlot1() : GnBaseSlot1<Arg1Type>(), m_pfnCallback(NULL)
{
}
template <typename Arg1Type> inline GnStaticSlot1<Arg1Type>::GnStaticSlot1(
void (*pfnCallback)(Arg1Type)) : GnBaseSlot1<Arg1Type>(), m_pfnCallback(pfnCallback)
{
GnAssert(pfnCallback != NULL);
}
template <typename Arg1Type> inline
void GnStaticSlot1<Arg1Type>::Initialize(void (*pfnCallback)(Arg1Type))
{
GnAssert(pfnCallback != NULL);
m_pfnCallback = pfnCallback;
}
template <typename Arg1Type> inline
GnStaticSlot1<Arg1Type>::~GnStaticSlot1()
{
// Note: None of the pointers in any of these destructors is owned by
// this instance: Therefore, it should not delete them
m_pfnCallback = NULL;
}
template <typename Arg1Type> inline
void GnStaticSlot1<Arg1Type>::ReceiveSignal(Arg1Type Arg1) const
{
GnAssert(m_pfnCallback != NULL);
(*m_pfnCallback)(Arg1);
}
template <typename ClassType, typename Arg1Type> inline
GnMemberSlot1<ClassType, Arg1Type>::GnMemberSlot1() : GnBaseSlot1<Arg1Type>()
, m_pkInstance(NULL), m_pfnCallback(NULL)
{
}
template <typename ClassType, typename Arg1Type> inline
GnMemberSlot1<ClassType, Arg1Type>::GnMemberSlot1(ClassType* pkInstance,
void (ClassType::*pfnCallback)(Arg1Type)) : GnBaseSlot1<Arg1Type>(), m_pkInstance(pkInstance)
, m_pfnCallback(pfnCallback)
{
GnAssert(pkInstance != NULL);
GnAssert(pfnCallback != NULL);
}
template <typename ClassType, typename Arg1Type> inline
void GnMemberSlot1<ClassType, Arg1Type>::Initialize(ClassType* pkInstance,
void (ClassType::*pfnCallback)(Arg1Type))
{
GnAssert(pkInstance != NULL);
GnAssert(pfnCallback != NULL);
m_pkInstance = pkInstance;
m_pfnCallback = pfnCallback;
}
template <typename ClassType, typename Arg1Type> inline
GnMemberSlot1<ClassType, Arg1Type>::~GnMemberSlot1()
{
// Note: None of the pointers in any of these destructors is owned by
// this instance: Therefore, it should not delete them
m_pkInstance = NULL;
m_pfnCallback = NULL;
}
template <typename ClassType, typename Arg1Type> inline
void GnMemberSlot1<ClassType, Arg1Type>::ReceiveSignal(Arg1Type Arg1) const
{
GnAssert(m_pkInstance != NULL);
GnAssert(m_pfnCallback != NULL);
(m_pkInstance->*m_pfnCallback)(Arg1);
}
template <typename Arg1Type, typename Arg2Type> inline
GnBaseSlot2<Arg1Type, Arg2Type>::GnBaseSlot2()
{
}
// All code in GnUIBaseSlot* methods are implemented in the macros defined in
// GnUISignalSlotMacros.h.
template <typename Arg1Type, typename Arg2Type> inline
GnBaseSlot2<Arg1Type, Arg2Type>::~GnBaseSlot2()
{
// Note: None of the pointers in any of these destructors is owned by
// this instance: Therefore, it should not delete them
GnUnsubscribeFromAll(m_pkSignals);
}
template <typename Arg1Type, typename Arg2Type> inline
void GnBaseSlot2<Arg1Type, Arg2Type>::Subscribe(GnSignal2<Arg1Type, Arg2Type>* pkSignal)
{
GnSubscribeToMe(m_pkSignals, pkSignal);
}
template <typename Arg1Type, typename Arg2Type> inline
void GnBaseSlot2<Arg1Type, Arg2Type>::Unsubscribe(GnSignal2<Arg1Type, Arg2Type>* pkSignal)
{
GnUnsubscribeToMe(m_pkSignals, pkSignal);
}
template <typename Arg1Type, typename Arg2Type>
inline bool GnBaseSlot2<Arg1Type, Arg2Type>::IsSubscribed(GnSignal2<Arg1Type, Arg2Type>* pkSignal) const
{
return GnIsElementInGroup(m_pkSignals, pkSignal);
}
template <typename Arg1Type, typename Arg2Type>
inline unsigned int GnBaseSlot2<Arg1Type, Arg2Type>::NumSubscribed() const
{
return GnNumElements(m_pkSignals);
}
template <typename Arg1Type, typename Arg2Type>
inline GnStaticSlot2<Arg1Type, Arg2Type>::GnStaticSlot2() : GnBaseSlot2<Arg1Type, Arg2Type>()
, m_pfnCallback(NULL)
{
}
template <typename Arg1Type, typename Arg2Type> inline
GnStaticSlot2<Arg1Type, Arg2Type>::GnStaticSlot2(void (*pfnCallback)(Arg1Type, Arg2Type))
: GnBaseSlot2<Arg1Type, Arg2Type>(), m_pfnCallback(pfnCallback)
{
GnAssert(pfnCallback != NULL);
}
template <typename Arg1Type, typename Arg2Type> inline
void GnStaticSlot2<Arg1Type, Arg2Type>::Initialize(void (*pfnCallback)(Arg1Type, Arg2Type))
{
GnAssert(pfnCallback != NULL);
m_pfnCallback = pfnCallback;
}
template <typename Arg1Type, typename Arg2Type> inline
GnStaticSlot2<Arg1Type, Arg2Type>::~GnStaticSlot2()
{
// Note: None of the pointers in any of these destructors is owned by
// this instance: Therefore, it should not delete them
m_pfnCallback = NULL;
}
template <typename Arg1Type, typename Arg2Type>
inline void GnStaticSlot2<Arg1Type, Arg2Type>::ReceiveSignal(Arg1Type Arg1, Arg2Type Arg2) const
{
GnAssert(m_pfnCallback != NULL);
(*m_pfnCallback)(Arg1, Arg2);
}
template <typename ClassType, typename Arg1Type, typename Arg2Type>
inline GnMemberSlot2<ClassType, Arg1Type, Arg2Type>::GnMemberSlot2()
: GnBaseSlot2<Arg1Type, Arg2Type>(), m_pkInstance(NULL), m_pfnCallback(NULL)
{
}
template <typename ClassType, typename Arg1Type, typename Arg2Type>
inline GnMemberSlot2<ClassType, Arg1Type, Arg2Type>::GnMemberSlot2(ClassType* pkInstance
, void (ClassType::*pfnCallback)(Arg1Type, Arg2Type)) : GnBaseSlot2<Arg1Type, Arg2Type>(),
m_pkInstance(pkInstance), m_pfnCallback(pfnCallback)
{
GnAssert(m_pkInstance != NULL);
GnAssert(m_pfnCallback != NULL);
}
template <typename ClassType, typename Arg1Type, typename Arg2Type> inline
void GnMemberSlot2<ClassType, Arg1Type, Arg2Type>::Initialize(ClassType* pkInstance
, void (ClassType::*pfnCallback)(Arg1Type, Arg2Type))
{
GnAssert(pkInstance != NULL);
GnAssert(pfnCallback != NULL);
m_pkInstance = pkInstance;
m_pfnCallback = pfnCallback;
}
template <typename ClassType, typename Arg1Type, typename Arg2Type> inline
GnMemberSlot2<ClassType, Arg1Type, Arg2Type>::~GnMemberSlot2()
{
m_pkInstance = NULL;
m_pfnCallback = NULL;
}
template <typename ClassType, typename Arg1Type, typename Arg2Type> inline
void GnMemberSlot2<ClassType, Arg1Type, Arg2Type>::ReceiveSignal(Arg1Type Arg1, Arg2Type Arg2) const
{
GnAssert(m_pkInstance != NULL);
GnAssert(m_pfnCallback != NULL);
(m_pkInstance->*m_pfnCallback)(Arg1, Arg2);
}
#endif // NIUISLOT_H
|
class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
unordered_set<string> beginSet({beginWord}), endSet({endWord});
int transLen = 2;
while(!beginSet.empty() && !endSet.empty()){
if(beginSet.size() > endSet.size()){
swap(beginSet, endSet);
}
unordered_set<string> midSet;
for(string s: beginSet){
for(int i = 0; i < s.size(); ++i){
char letter = s[i];
for(char c = 'a'; c <= 'z'; ++c){
s[i] = c;
if(endSet.count(s)) return transLen;
if(wordList.count(s)){
midSet.insert(s);
wordList.erase(s);
}
}
s[i] = letter;
}
}
swap(beginSet, midSet);
++transLen;
}
return 0;
}
};
|
// ----------------------------------------------------------------------------
// Copyright (C) 2002-2006 Marcin Kalicinski
//
// 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)
//
// For more information, see www.boost.org
// ----------------------------------------------------------------------------
#ifndef LIBLAS_BOOST_PROPERTY_TREE_DETAIL_JSON_PARSER_WRITE_HPP_INCLUDED
#define LIBLAS_BOOST_PROPERTY_TREE_DETAIL_JSON_PARSER_WRITE_HPP_INCLUDED
#include <liblas/external/property_tree/ptree.hpp>
#include <boost/next_prior.hpp>
#include <boost/type_traits/make_unsigned.hpp>
#include <string>
#include <ostream>
#include <iomanip>
namespace liblas { namespace property_tree { namespace json_parser
{
// Create necessary escape sequences from illegal characters
template<class Ch>
std::basic_string<Ch> create_escapes(const std::basic_string<Ch> &s)
{
std::basic_string<Ch> result;
typename std::basic_string<Ch>::const_iterator b = s.begin();
typename std::basic_string<Ch>::const_iterator e = s.end();
while (b != e)
{
// This assumes an ASCII superset. But so does everything in PTree.
// We escape everything outside ASCII, because this code can't
// handle high unicode characters.
if (*b == 0x20 || *b == 0x21 || (*b >= 0x23 && *b <= 0x2E) ||
(*b >= 0x30 && *b <= 0x5B) || (*b >= 0x5D && *b <= 0xFF))
result += *b;
else if (*b == Ch('\b')) result += Ch('\\'), result += Ch('b');
else if (*b == Ch('\f')) result += Ch('\\'), result += Ch('f');
else if (*b == Ch('\n')) result += Ch('\\'), result += Ch('n');
else if (*b == Ch('\r')) result += Ch('\\'), result += Ch('r');
else if (*b == Ch('/')) result += Ch('\\'), result += Ch('/');
else if (*b == Ch('"')) result += Ch('\\'), result += Ch('"');
else if (*b == Ch('\\')) result += Ch('\\'), result += Ch('\\');
else
{
const char *hexdigits = "0123456789ABCDEF";
typedef typename make_unsigned<Ch>::type UCh;
unsigned long u = (std::min)(static_cast<unsigned long>(
static_cast<UCh>(*b)),
0xFFFFul);
int d1 = u / 4096; u -= d1 * 4096;
int d2 = u / 256; u -= d2 * 256;
int d3 = u / 16; u -= d3 * 16;
int d4 = u;
result += Ch('\\'); result += Ch('u');
result += Ch(hexdigits[d1]); result += Ch(hexdigits[d2]);
result += Ch(hexdigits[d3]); result += Ch(hexdigits[d4]);
}
++b;
}
return result;
}
template<class Ptree>
void write_json_helper(std::basic_ostream<typename Ptree::key_type::value_type> &stream,
const Ptree &pt,
int indent, bool pretty)
{
typedef typename Ptree::key_type::value_type Ch;
typedef typename std::basic_string<Ch> Str;
// Value or object or array
if (indent > 0 && pt.empty())
{
// Write value
Str data = create_escapes(pt.template get_value<Str>());
stream << Ch('"') << data << Ch('"');
}
else if (indent > 0 && pt.count(Str()) == pt.size())
{
// Write array
stream << Ch('[');
if (pretty) stream << Ch('\n');
typename Ptree::const_iterator it = pt.begin();
for (; it != pt.end(); ++it)
{
if (pretty) stream << Str(4 * (indent + 1), Ch(' '));
write_json_helper(stream, it->second, indent + 1, pretty);
if (boost::next(it) != pt.end())
stream << Ch(',');
if (pretty) stream << Ch('\n');
}
stream << Str(4 * indent, Ch(' ')) << Ch(']');
}
else
{
// Write object
stream << Ch('{');
if (pretty) stream << Ch('\n');
typename Ptree::const_iterator it = pt.begin();
for (; it != pt.end(); ++it)
{
if (pretty) stream << Str(4 * (indent + 1), Ch(' '));
stream << Ch('"') << create_escapes(it->first) << Ch('"') << Ch(':');
if (pretty) {
if (it->second.empty())
stream << Ch(' ');
else
stream << Ch('\n') << Str(4 * (indent + 1), Ch(' '));
}
write_json_helper(stream, it->second, indent + 1, pretty);
if (boost::next(it) != pt.end())
stream << Ch(',');
if (pretty) stream << Ch('\n');
}
if (pretty) stream << Str(4 * indent, Ch(' '));
stream << Ch('}');
}
}
// Verify if ptree does not contain information that cannot be written to json
template<class Ptree>
bool verify_json(const Ptree &pt, int depth)
{
typedef typename Ptree::key_type::value_type Ch;
typedef typename std::basic_string<Ch> Str;
// Root ptree cannot have data
if (depth == 0 && !pt.template get_value<Str>().empty())
return false;
// Ptree cannot have both children and data
if (!pt.template get_value<Str>().empty() && !pt.empty())
return false;
// Check children
typename Ptree::const_iterator it = pt.begin();
for (; it != pt.end(); ++it)
if (!verify_json(it->second, depth + 1))
return false;
// Success
return true;
}
// Write ptree to json stream
template<class Ptree>
void write_json_internal(std::basic_ostream<typename Ptree::key_type::value_type> &stream,
const Ptree &pt,
const std::string &filename,
bool pretty)
{
if (!verify_json(pt, 0))
BOOST_PROPERTY_TREE_THROW(json_parser_error("ptree contains data that cannot be represented in JSON format", filename, 0));
write_json_helper(stream, pt, 0, pretty);
stream << std::endl;
if (!stream.good())
BOOST_PROPERTY_TREE_THROW(json_parser_error("write error", filename, 0));
}
} } }
#endif
|
#include "Physics.h"
Physics::Physics(pos_t pos /*0, 0*/, pos_t vel /*0, 0*/, pos_t acc /*0, 0*/)
{
position = pos;
velocity = vel;
acceleration = acc;
}
void Physics::move(int dt, bool resistance /*false*/)
{
double acc_sd = 0.930001;
double vel_sd = 0.92043;
if (resistance) acceleration = acceleration * acc_sd;
velocity = (velocity + acceleration * dt);
if (resistance) velocity = velocity * vel_sd;
position = position + velocity * dt + acceleration * dt * dt * 0.5;
}
Physics::~Physics()
{
}
|
#include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i=0;i<(n);i++)
#define for1(i,n) for(int i=1;i<=n;i++)
#define FOR(i,a,b) for(int i=(a);i<=(b);i++)
#define FORD(i,a,b) for(int i=(a);i>=(b);i--)
const int INF = 1<<29;
const int MOD=1000000007;
#define pp pair<ll,ll>
typedef long long int ll;
bool isPowerOfTwo (ll x)
{
return x && (!(x&(x-1)));
}
void fastio()
{
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
}
long long binpow(long long a, long long b) {
long long res = 1;
while (b > 0) {
if (b & 1)
res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
const int dx[] = {1,0,-1,0,1,1,-1,-1};
const int dy[] = {0,-1,0,1,1,-1,-1,1};
////////////////////////////////////////////////////////////////////
vector<int> v[(int)1e5 + 6];
int main()
{
fastio();
int t=1;
//cin>>t;
while(t--)
{
int n;
cin>>n;
int x;
int mx=INT32_MIN;
REP(i,n)
{
cin>>x;
v[x].push_back(i);
mx=max(mx,x);
}
vector<pp> res;
for1(i,mx)
{
if(v[i].size()==0)continue;
if(v[i].size()==1)
{
res.push_back({i,0});
continue;
}
else if(v[i].size()==2)
{
res.push_back({i,v[i][1]-v[i][0]});
continue;
}
x=v[i][1]-v[i][0];
for(int j=1;j<v[i].size()-1;j++)
{
if(v[i][j+1]-v[i][j] !=x)goto done;
}
res.push_back({i,x});
done:
;
}
cout<<res.size()<<"\n";
for(auto i:res)
{
cout<<i.first<<" "<<i.second<<"\n";
}
}
return 0;
//Read the stuff at the bottom
}
/* Look for:
* the exact constraints (multiple sets are too slow for n=10^6 :( )
* special cases (n=1?)
* 1LL<<i and not 1<<i
* overflow (int vs ll?)
* array bounds
* if you have no idea just guess the appropriate well-known algo instead of doing nothing :/
*/
/*lcm(gcd(N1, M), gcd(N2, M), ..., gcd(Nk, M)) = gcd(lcm(N1, ..., Nk), M)
gcd(lcm(N1, M), lcm(N2, M), ..., lcm(Nk, M)) = lcm(gcd(N1, ..., Nk), M).
If gcd(N1, N2) = 1, then
gcd(N1·N2, M) = gcd(N1, M)·gcd(N2, M)
lcm(N1·N2, M) = lcm(N1, M)·lcm(N2, M)/M.
lcm(M, N, P) · gcd(M, N) · gcd(N, P) · gcd(P, M) = NMP · gcd(N, M, P).
*/
|
#include <bits/stdc++.h>
using namespace std;
#define prev PREEVEV
const int N = 35000 + 10;
const int oo = 0x3f3f3f3f;
struct Node;
void modify(Node *nd, int lf, int rg, int L, int R, int delta);
struct Node {
int vmax;
int flag;
Node *ls, *rs;
void update() {
vmax = max(ls->vmax, rs->vmax);
}
void pushdown(int lf, int rg) {
if(flag) {
int mid = (lf + rg) >> 1;
modify(ls,lf,mid,lf,mid,flag);
modify(rs,mid+1,rg,mid+1,rg,flag);
flag = 0;
}
}
}pool[N*2], *tail, *root;
int n, m;
int aa[N], pos[N], prev[N];
int dp[2][N];
int cur = 1, prv = 0;
Node *build(int lf, int rg) {
Node *nd = ++tail;
nd->vmax = nd->flag = 0;
if(lf == rg) {
nd->vmax = dp[prv][lf];
} else {
int mid = (lf + rg) >> 1;
nd->ls = build(lf, mid);
nd->rs = build(mid+1, rg);
nd->update();
}
return nd;
}
void modify(Node *nd, int lf, int rg, int L, int R, int delta) {
if(L <= lf && rg <= R) {
nd->vmax += delta;
nd->flag += delta;
return;
}
int mid = (lf + rg)>>1;
nd->pushdown(lf,rg);
if( L <= mid )
modify(nd->ls, lf, mid, L, R, delta);
if( R > mid )
modify(nd->rs, mid+1, rg, L, R, delta);
nd->update();
}
int query(Node *nd, int lf, int rg, int L, int R) {
if(L <= lf && rg <= R)
return nd->vmax;
int mid = (lf + rg) >> 1;
nd->pushdown(lf,rg);
int rt = -oo;
if( L <= mid )
rt = max( rt, query(nd->ls, lf, mid, L, R) );
if( R > mid )
rt = max( rt, query(nd->rs,mid+1,rg,L,R) );
return rt;
}
int main() {
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++)
scanf("%d", aa + i);
for(int i = 1; i <= n; i++) {
prev[i] = pos[aa[i]];
pos[aa[i]] = i;
}
for(int i = 1; i <= n; i++)
dp[prv][i] = dp[prv][i-1] + (prev[i] == 0);
for(int k = 2; k <= m; k++) {
tail = pool;
root = build(1, n);
for(int i = 1; i <= n; i++) {
if(i < k )
dp[cur][i] = -oo;
else {
modify(root, 1, n, max(prev[i],1), i - 1, +1);
dp[cur][i] = query(root, 1, n, 1, i - 1);
}
}
swap(prv, cur);
}
printf("%d\n", dp[prv][n]);
}
|
#include "../include/mirrordialog.h"
#include "ui_mirrordialog.h"
MirrorDialog::MirrorDialog(QWidget *parent) : QDialog(parent), ui(new Ui::MirrorDialog),
horizontal(false), vertical(false) {
ui->setupUi(this);
connect(ui->checkBoxHor, SIGNAL(stateChanged(int)), this, SLOT(setHorizontal(int)));
connect(ui->checkBoxVer, SIGNAL(stateChanged(int)), this, SLOT(setVertical(int)));
}
MirrorDialog::~MirrorDialog() {
delete ui;
}
void MirrorDialog::setHorizontal(int state) {
horizontal = (state == Qt::Checked);
}
void MirrorDialog::setVertical(int state) {
vertical = (state == Qt::Checked);
}
int MirrorDialog::getMirrorPara(QWidget *parent) {
MirrorDialog dialog(parent);
if (dialog.exec() == QDialog::Accepted) {
if (dialog.horizontal && dialog.vertical) {
return HORANDVER;
}
else if (dialog.horizontal) {
return HORIZONTAL;
}
else if (dialog.vertical) {
return VERTICAL;
} else {
return NONE;
}
}
return NONE;
}
|
//float unit_cost=5.5;// per unit cost 5.5 tk
// this code will be uploaded on esp8266-12E
#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP8266.h>
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
char ssid[] = "IoTCodeLab";//ssid
char wifiPassword[] = "@IoTCodeLab";//password
// Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char username[] = "3e72ac20-2fda-11ea-8221-599f77add412";
char password[] = "eae77232abd1253b73d71fe288af32330089f050";
char clientID[] = "9c05e730-2fda-11ea-84bb-8f71124cfdfb";
void setup()
{
pinMode(2, OUTPUT);
Serial.begin(9600);
Cayenne.begin(username, password, clientID, ssid, wifiPassword);
}
void loop()
{
Cayenne.loop();
handleIndex();
delay(2000);
}
void handleIndex()
{
// Send a JSON-formatted request with key "type" and value "request"
// then parse the JSON-formatted response with keys "gas" and "distance"
DynamicJsonDocument doc(1024);//allocate 256 if not working then allocate 1024 or 2048 and more if not working.
//but remamber them more you allocate the more space then the flash memory then it willl create problem ( ArduinoJson version 6+)
double cur = 0, unit = 0,tk=0;
// Sending the request
doc["type"] = "request";
serializeJson(doc,Serial);
// Reading the response
boolean messageReady = false;
String message = "";
while(messageReady == false) { // blocking but that's ok
if(Serial.available()) {
message = Serial.readString();
//Serial.println(message);
messageReady = true;
}
}
// Attempt to deserialize the JSON-formatted message
DeserializationError error = deserializeJson(doc,message);
if(error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return;
}
cur = doc["cur"];
unit = doc["unit"];
tk = doc["tk"];
//Decrypted
int bill=round(tk);
float fine=(tk-bill)*1000;
/// ADC0 - CHANNEL 2
Cayenne.virtualWrite(2, cur);
delay(100);
/// ADC0 - CHANNEL 3
Cayenne.virtualWrite(3, unit);
delay(100);
/// ADC0 - CHANNEL 4
Cayenne.virtualWrite(4,bill);
delay(100);
/// ADC0 - CHANNEL 5
Cayenne.virtualWrite(5,fine);
delay(100);
Serial.println(cur);
Serial.println(unit);
Serial.println(tk);
}
CAYENNE_IN_DEFAULT()
{
CAYENNE_LOG("CAYENNE_IN_DEFAULT(%u) - %s, %s", request.channel, getValue.getId(), getValue.asString());
//Process message here. If there is an error set an error message using getValue.setError(), e.g getValue.setError("Error message");
int i = getValue.asInt();
digitalWrite(2, i);
}
|
// system includes
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
// project includes
#include "Polymorphic.h"
#include "CRect.h"
#include "CPolyLine.h"
#include "xmlParser.h"
// global namespace declaration
using namespace std;
CShape::CreationMapType CShape::gCreateFromXmlMap;
// --------------------------------------------------------------------------
// ReadXml_
// --------------------------------------------------------------------------
list< CShape* >
ReadXml_()
{
bool success = false;
XMLNode xMainNode = XMLNode::openFileHelper( "input.xml" );
XMLNode xNode = xMainNode.getChildNode();
string theName = xNode.getName();
list< CShape* > outShapes;
CShape::gCreateFromXmlMap[ "Point" ] = CPoint::CreateFromXml;
CShape::gCreateFromXmlMap[ "PolyLine" ] = CPolyLine::CreateFromXml;
CShape::gCreateFromXmlMap[ "Rect" ] = CRect::CreateFromXml;
if ( theName != "Geometries" )
cout << "Unknown format" << endl;
else
{
int count = xNode.nChildNode();
XMLNode currNode;
CShape::CreationMapIter myIter;
for ( int i=0; i<count; ++i)
{
currNode = xNode.getChildNode(i);
theName = currNode.getName();
myIter = CShape::gCreateFromXmlMap.find( theName.c_str() );
if ( myIter != CShape::gCreateFromXmlMap.end() )
{
CreateFromXmlType currFunction = myIter->second;
CShape* ptr = currFunction( currNode );
outShapes.push_back( ptr );
}
else
cout << theName << ": unknow geometry type" << endl;
}
}
return outShapes;
}
// --------------------------------------------------------------------------
// Poly2
// --------------------------------------------------------------------------
bool
Poly2()
{
list< CShape* > outShapes;
ReadXml( outShapes );
list< CShape* >::iterator shapeIter;
CPoint* p = new CPoint(9,29);
shapeIter=outShapes.begin();
if ( outShapes.size() > 1 )
{
++shapeIter;
outShapes.insert( shapeIter, p );
}
XMLNode node = XMLNode::createXMLTopNode( "Geometries" );
cout << "Drawing <Shapes>" << endl << endl;
for( shapeIter=outShapes.begin() ; shapeIter != outShapes.end() ; ++ shapeIter)
{
(*(shapeIter))->Draw();
(*(shapeIter))->SaveXml( node );
cout << "\n";
delete(*(shapeIter));
}
node.writeToFile( "pippo.xml" );
return true;
}
// --------------------------------------------------------------------------
// Poly1
// --------------------------------------------------------------------------
//bool
//Poly1()
//{
// CPoint* ptrPoint = new CPoint(8,8);
// CRect* ptrRect = new CRect( CPoint(0,1), CPoint(19,20) );
//
// ptrPoint->Draw();
//
// cout << "\n\nrect" << endl;
// ptrRect->Draw();
//
// // polyline
// CPolyLine* ptrPoly = new CPolyLine();
// ptrPoly->AddPoint( CPoint(0,1) );
// ptrPoly->AddPoint( CPoint(19,20) );
//
// cout << "\n\nPoly" << endl;
// ptrPoly->Draw();
//
// // shapes
// vector< CShape* > shpVec;
//
// shpVec.push_back( ptrPoint );
// shpVec.push_back( ptrRect );
// shpVec.push_back( ptrPoly );
//
// cout << "\n\nDraw shapes" << endl;
//
// for ( size_t i=0; i<shpVec.size(); ++i)
// {
// shpVec[i]->Draw();
// cout << "\n";
// }
//
// cout << "\nCreatedShapes: " << CShape::CreatedShapes() << endl;
//
//
// ReadXml che restituisce un vector di shape
//
// XMLNode node = createXMLTopNode( "Geometries" );
// .. shpVec[i]->SaveXml(node);
//
// CPoint::SaveXml( XMLNode parent )
// {
// XMLNode io = parent->addChild( "Point" );
// io->addAttribute( "x", converto in stringa(mX) );
// io->addAttribute( "y", converto in stringa(mY) );
// }
//
//
// node.writeToFile( "pippo.xml" );
//
//
// for ( size_t i=0; i<shpVec.size(); ++i)
// delete shpVec[i];
//
// return true;
//}
// --------------------------------------------------------------------------
// ReadXmlPolymorphic
// --------------------------------------------------------------------------
bool
ReadXml ( list< CShape* >& outShapes )
{
bool success = false;
XMLNode xMainNode = XMLNode::openFileHelper( "input.xml" );
XMLNode xNode = xMainNode.getChildNode();
string theName = xNode.getName();
if ( theName != "Geometries" )
cout << "Unknown format" << endl;
else
{
int count = xNode.nChildNode();
XMLNode currNode;
for ( int i=0; i<count; ++i)
{
currNode = xNode.getChildNode(i);
theName = currNode.getName();
if ( theName == "Point" )
{
CShape* p= CPoint::CreateFromXml( currNode );
outShapes.push_back( p );
}
else if ( theName == "PolyLine" )
{
CShape* myPL = CPolyLine::CreateFromXml( currNode );
outShapes.push_back( myPL );
}
else if ( theName == "Rect" )
{
CShape* myRect = CRect::CreateFromXml( currNode );
outShapes.push_back( myRect );
}
else
{
cout << theName << ": unknow geometry type" << endl;
}
}
success = true;
}
return success;
}
// --------------------------------------------------------------------------
// Poly3
// --------------------------------------------------------------------------
bool
Poly3()
{
list< CShape* > outShapes;
outShapes = ReadXml_();
list< CShape* >::iterator shapeIter;
//CPoint* p = new CPoint(9,29);
//shapeIter=outShapes.begin();
//if ( outShapes.size() > 1 )
//{
// ++shapeIter;
// outShapes.insert( shapeIter, p );
//}
//
XMLNode node = XMLNode::createXMLTopNode( "Geometries" );
cout << "Drawing <Shapes>" << endl << endl;
for( shapeIter=outShapes.begin() ; shapeIter != outShapes.end() ; ++ shapeIter)
{
(*(shapeIter))->Draw();
(*(shapeIter))->SaveXml( node );
cout << "\n";
delete(*(shapeIter));
}
node.writeToFile( "pluto.xml" );
return true;
}
|
#include<bits/stdc++.h>
using namespace std;
bool Parenthesis(string str);
int main()
{
string str = "{()}[{}]";
if (Parenthesis(str)) { cout <<"true";}
else { cout<<"false";}
return 0;
}
bool Parenthesis(string str)
{
if (str.length() & 1) {
return false;
}
stack<char> stack;
for (char ch: str){
if (ch == '(' || ch == '{' || ch == '['){
stack.push(ch);
}
if (ch == ')' || ch == '}' || ch == ']'){
if (stack.empty()) {
return false;
}
char top = stack.top();
stack.pop();
if ((top == '(' && ch != ')') || (top == '{' && ch != '}') || (top == '[' && ch != ']')){
return false;
}
}
}
return stack.empty();
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
**
*/
#include "core/pch.h"
#if defined(_NATIVE_SSL_SUPPORT_)
#include "modules/libssl/sslbase.h"
#include "modules/libssl/ssl_api.h"
#include "modules/libssl/methods/sslphash.h"
#include "modules/libssl/methods/sslnull.h"
void Cleanup_HashPointer()
{
OP_DELETE(g_SSL_Hash_Pointer_NullHash);
g_SSL_Hash_Pointer_NullHash = NULL;
}
void SSL_Hash_Pointer::Init()
{
hash = NULL;
if (g_SSL_Hash_Pointer_NullHash==NULL)
{
g_SSL_Hash_Pointer_NullHash = OP_NEW(SSL_Null_Hash, ());
if(g_SSL_Hash_Pointer_NullHash == NULL)
RaiseAlert(SSL_Internal, SSL_Allocation_Failure);
}
point = g_SSL_Hash_Pointer_NullHash;
}
SSL_Hash_Pointer::SSL_Hash_Pointer()
{
Init();
}
SSL_Hash_Pointer::SSL_Hash_Pointer(SSL_HashAlgorithmType alg)
: SSL_Error_Status()
{
Init();
Set(alg);
}
/*
SSL_Hash_Pointer::SSL_Hash_Pointer(const SSL_Hash_Pointer &old)
: SSL_Error_Status()
{
Init();
CreatePointer(old.hash, TRUE);
}
*/
/*
SSL_Hash_Pointer::SSL_Hash_Pointer(const SSL_Hash *old)
{
Init();
CreatePointer(old , TRUE);
}
*/
SSL_Hash_Pointer::~SSL_Hash_Pointer()
{
RemovePointer();
}
void SSL_Hash_Pointer::RemovePointer()
{
OP_DELETE(hash);
hash = NULL;
point = g_SSL_Hash_Pointer_NullHash;
}
void SSL_Hash_Pointer::Set(SSL_HashAlgorithmType alg)
{
RemovePointer();
OP_STATUS op_err = OpStatus::OK;
hash = g_ssl_api->CreateMessageDigest(alg, op_err);
if(OpStatus::IsError(op_err))
{
RaiseAlert(op_err);
return;
}
point = hash;
point->ForwardTo(this);
}
BOOL SSL_Hash_Pointer::CreatePointer(const SSL_Hash *org, BOOL fork, BOOL hmac)
{
RemovePointer();
if(org)
{
if(fork)
hash = org->Fork();
else
{
Set(org->HashID());
return !Error(); // Already configured
}
if(hash == NULL)
{
RaiseAlert(SSL_Internal,SSL_Allocation_Failure);
return FALSE;
}
else
{
point = hash;
point->ForwardTo(this);
}
}
return TRUE;
}
// Unref YNP
#if 0
BOOL SSL_Hash_Pointer::SetFork(const SSL_Hash *org)
{
return CreatePointer(org,TRUE);
}
#endif
#if 0
BOOL SSL_Hash_Pointer::SetProduce(const SSL_Hash *org)
{
return CreatePointer(org,FALSE);
}
BOOL SSL_Hash_Pointer::SetProduceHMAC(const SSL_Hash *org)
{
return CreatePointer(org,FALSE, TRUE);
}
#endif
SSL_Hash_Pointer &SSL_Hash_Pointer::operator =(const SSL_Hash_Pointer &old)
{
CreatePointer(old.hash ,TRUE);
return *this;
}
SSL_Hash_Pointer &SSL_Hash_Pointer::operator =(const SSL_Hash *org)
{
CreatePointer(org ,TRUE);
return *this;
}
BOOL SSL_Hash_Pointer::Valid(SSL_Alert *msg) const
{
if(Error(msg))
return FALSE;
if(hash != NULL)
{
return (point == hash && hash->Valid(msg));
}
else if(point != g_SSL_Hash_Pointer_NullHash || point == NULL)
{
if(msg)
msg->Set(SSL_Internal, SSL_InternalError);
return FALSE;
}
return TRUE;
}
#endif
|
//
// Created by jeremyelkayam on 10/14/20.
//
#include "special_item.hpp"
SpecialItem::SpecialItem(sf::Texture &texture, sf::SoundBuffer &used_sound_buffer, float a_appear_time) :
Entity(0.f,0.f,texture), appear_time(a_appear_time) {
consumed = false;
active = false;
age = 0;
color = sf::Color::Yellow;
used_sound.setBuffer(used_sound_buffer);
}
void SpecialItem::update(float s_elapsed) {
age += s_elapsed;
}
void SpecialItem::consume(){
assert(active);
active = false;
consumed = true;
used_sound.play();
}
void SpecialItem::spawn(float xcor, float ycor) {
assert(ready_to_spawn());
this->sprite.setPosition(xcor,ycor);
active = true;
}
void SpecialItem::draw(sf::RenderWindow &window, ColorGrid &color_grid) const {
if(active) Entity::draw(window, color_grid);
}
|
#include<due_can.h>
#include"variant.h"
CAN_FRAME msg;
void setup()
{
Serial.begin(9600);
Serial.println("---- CAN Sender ----");
}
void sender()
{
msg.id=0x5A1;
msg.extended=LOW;
msg.priority=LOW;
msg.length=8;
msg.rtr=LOW;
msg.data.byte[0]=0x0;
msg.data.byte[1]=0x1;
msg.data.byte[2]=0x2;
msg.data.byte[3]=0x3;
msg.data.byte[4]=0x4;
msg.data.byte[5]=0x5;
msg.data.byte[6]=0x6;
msg.data.byte[7]=0x7;
}
void loop()
{
Can0.begin(CAN_BPS_250K);
sender();
if(CAN.sendFrame(msg))
Serial.println("Sent...........");
else Serial.println("CAN Failed!!!!");
}
|
/*!
* @copyright © 2017 UFAM - Universidade Federal do Amazonas.
*
* @brief Interface da classe "mkl_TPMPulseWidthModulation.h".
*
* @file mkl_TPMPulseWidthModulation.h
* @version 1.0
* @date 02 Agosto 2017
*
* @section HARDWARES & SOFTWARES
* +board FRDM-KL25Z da NXP.
* +processor MKL25Z128VLK4 - ARM Cortex-M0+.
* +compiler Kinetis® Design Studio IDE.
* +manual L25P80M48SF0RM, Rev.3, September 2012.
* +revisions Versão (data): Descrição breve.
* ++ 1.0 (20 Agosto 2017): Versão inicial.
*
* @section AUTHORS & DEVELOPERS
* +institution Universidade Federal do Amazonas.
* +courses Engenharia da Computação / Engenharia Elétrica.
* +teacher Miguel Grimm <miguelgrimm@gmail.com>
* +student Versão inicial:
* ++ Hamilton Nascimento <hdan_neto@hotmail.com>
*
* @section LICENSE
*
* GNU General Public License (GNU GPL).
*
* Este programa é um software livre; Você pode redistribuí-lo
* e/ou modificá-lo de acordo com os termos do "GNU General Public
* License" como publicado pela Free Software Foundation; Seja a
* versão 3 da licença, ou qualquer versão posterior.
*
* Este programa é distribuído na esperança de que seja útil,
* mas SEM QUALQUER GARANTIA; Sem a garantia implícita de
* COMERCIALIZAÇÃO OU USO PARA UM DETERMINADO PROPÓSITO.
* Veja o site da "GNU General Public License" para mais detalhes.
*
* @htmlonly http://www.gnu.org/copyleft/gpl.html
*/
#ifndef MKL_TPMPulseWidthModulation_H
#define MKL_TPMPulseWidthModulation_H
#include <stdint.h>
#include <MKL25Z4.h>
#include "mkl_TPM.h"
/*!
* @class mkl_TPMPulseWidthModulation.
*
* @brief A classe implementa o serviço PWM do periférico TPM.
*
* @details Esta classe implementa o serviço PWM utilizando os
* periféricos TPM0, TPM1 ou TPM2 e os pinos correspondentes e
* herdando da classe mãe "mkl_TPM".
*
* @section EXAMPLES USAGE
*
* Uso dos métodos para geração de sinal PWM.
*
* +fn setFrequency(tpm_div16, 999);
* +fn setDutyCycle(750);
* +fn enableOperation();
*/
class mkl_TPMPulseWidthModulation : public mkl_TPM {
public:
/*!
* Método construtor padrão da classe.
*/
explicit mkl_TPMPulseWidthModulation(tpm_Pin pin = tpm_PTC1);
/*!
* Métodos de configuração de frequência e duty cycle do sinal.
*/
void setFrequency(tpm_Div divBase, uint16_t MODRegister);
void setDutyCycle(uint16_t CnVRegister);
/*!
* Método de habilitar a operação PWM.
*/
void enableOperation();
/*!
* Método de desabilitar a operação PWM.
*/
void disableOperation();
private:
/*!
* Método de seleção do modo de operação PWM.
*/
void setPWMOperation();
};
#endif // MKL_TPMPulseWidthModulation_H_
|
#ifndef SCENE_H
#define SCENE_H
#include <vector>
#include "GL/gl.h"
#include "GL/glext.h"
#include "../mat.h"
#include "Terrain.h"
class App;
extern App* a;
class Scene
{
public:
Scene();
virtual ~Scene();
void render();
Terrain* ter;
protected:
private:
GLuint _sp;
};
#endif // SCENE_H
|
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Select3D_SensitivePoly_HeaderFile
#define _Select3D_SensitivePoly_HeaderFile
#include <gp_Circ.hxx>
#include <Select3D_PointData.hxx>
#include <Select3D_SensitiveSet.hxx>
#include <Select3D_TypeOfSensitivity.hxx>
#include <TColStd_HArray1OfInteger.hxx>
#include <TColgp_HArray1OfPnt.hxx>
//! Sensitive Entity to make a face selectable.
//! In some cases this class can raise Standard_ConstructionError and
//! Standard_OutOfRange exceptions from its member Select3D_PointData
//! myPolyg.
class Select3D_SensitivePoly : public Select3D_SensitiveSet
{
DEFINE_STANDARD_RTTIEXT(Select3D_SensitivePoly, Select3D_SensitiveSet)
public:
//! Constructs a sensitive face object defined by the
//! owner OwnerId, the array of points ThePoints, and
//! the sensitivity type Sensitivity.
//! The array of points is the outer polygon of the geometric face.
Standard_EXPORT Select3D_SensitivePoly (const Handle(SelectMgr_EntityOwner)& theOwnerId,
const TColgp_Array1OfPnt& thePoints,
const Standard_Boolean theIsBVHEnabled);
//! Constructs a sensitive face object defined by the
//! owner OwnerId, the array of points ThePoints, and
//! the sensitivity type Sensitivity.
//! The array of points is the outer polygon of the geometric face.
Standard_EXPORT Select3D_SensitivePoly (const Handle(SelectMgr_EntityOwner)& theOwnerId,
const Handle(TColgp_HArray1OfPnt)& thePoints,
const Standard_Boolean theIsBVHEnabled);
//! Constructs the sensitive arc object defined by the
//! owner theOwnerId, the circle theCircle, the parameters theU1
//! and theU2, the boolean theIsFilled and the number of points theNbPnts.
//! theU1 and theU2 define the first and last points of the arc on theCircle.
Standard_EXPORT Select3D_SensitivePoly (const Handle(SelectMgr_EntityOwner)& theOwnerId,
const gp_Circ& theCircle,
const Standard_Real theU1,
const Standard_Real theU2,
const Standard_Boolean theIsFilled = Standard_False,
const Standard_Integer theNbPnts = 12);
//! Constructs a sensitive curve or arc object defined by the
//! owner theOwnerId, the theIsBVHEnabled flag, and the
//! maximum number of points on the curve: theNbPnts.
Standard_EXPORT Select3D_SensitivePoly (const Handle(SelectMgr_EntityOwner)& theOwnerId,
const Standard_Boolean theIsBVHEnabled,
const Standard_Integer theNbPnts = 6);
//! Checks whether the poly overlaps current selecting volume
Standard_EXPORT virtual Standard_Boolean Matches (SelectBasics_SelectingVolumeManager& theMgr,
SelectBasics_PickResult& thePickResult) Standard_OVERRIDE;
//! Returns the amount of segments in poly
Standard_EXPORT virtual Standard_Integer NbSubElements() const Standard_OVERRIDE;
//! Returns the 3D points of the array used at construction time.
void Points3D (Handle(TColgp_HArray1OfPnt)& theHArrayOfPnt)
{
Standard_Integer aSize = myPolyg.Size();
theHArrayOfPnt = new TColgp_HArray1OfPnt (1,aSize);
for(Standard_Integer anIndex = 1; anIndex <= aSize; anIndex++)
{
theHArrayOfPnt->SetValue (anIndex, myPolyg.Pnt (anIndex-1));
}
}
//! Return array bounds.
void ArrayBounds (Standard_Integer& theLow,
Standard_Integer& theUp) const
{
theLow = 0;
theUp = myPolyg.Size() - 1;
}
//! Return point.
gp_Pnt GetPoint3d (const Standard_Integer thePntIdx) const
{
return (thePntIdx >= 0 && thePntIdx < myPolyg.Size())
? myPolyg.Pnt (thePntIdx)
: gp_Pnt();
}
//! Returns bounding box of a polygon. If location
//! transformation is set, it will be applied
Standard_EXPORT virtual Select3D_BndBox3d BoundingBox() Standard_OVERRIDE;
//! Returns center of the point set. If location transformation
//! is set, it will be applied
Standard_EXPORT virtual gp_Pnt CenterOfGeometry() const Standard_OVERRIDE;
//! Returns the amount of segments of the poly
Standard_EXPORT virtual Standard_Integer Size() const Standard_OVERRIDE;
//! Returns bounding box of segment with index theIdx
Standard_EXPORT virtual Select3D_BndBox3d Box (const Standard_Integer theIdx) const Standard_OVERRIDE;
//! Returns geometry center of sensitive entity index theIdx in the vector along
//! the given axis theAxis
Standard_EXPORT virtual Standard_Real Center (const Standard_Integer theIdx,
const Standard_Integer theAxis) const Standard_OVERRIDE;
//! Swaps items with indexes theIdx1 and theIdx2 in the vector
Standard_EXPORT virtual void Swap (const Standard_Integer theIdx1,
const Standard_Integer theIdx2) Standard_OVERRIDE;
//! Dumps the content of me into the stream
Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE;
protected:
//! Checks whether the segment with index theIdx overlaps the current selecting volume
Standard_EXPORT virtual Standard_Boolean overlapsElement (SelectBasics_PickResult& thePickResult,
SelectBasics_SelectingVolumeManager& theMgr,
Standard_Integer theElemIdx,
Standard_Boolean theIsFullInside) Standard_OVERRIDE;
//! Checks whether the entity with index theIdx is inside the current selecting volume
Standard_EXPORT virtual Standard_Boolean elementIsInside (SelectBasics_SelectingVolumeManager& theMgr,
Standard_Integer theElemIdx,
Standard_Boolean theIsFullInside) Standard_OVERRIDE;
//! Calculates distance from the 3d projection of used-picked screen point
//! to center of the geometry
Standard_EXPORT virtual Standard_Real distanceToCOG (SelectBasics_SelectingVolumeManager& theMgr) Standard_OVERRIDE;
protected:
Select3D_PointData myPolyg; //!< Points of the poly
mutable gp_Pnt myCOG; //!< Center of the poly
Handle(TColStd_HArray1OfInteger) mySegmentIndexes; //!< Segment indexes for BVH tree build
Select3D_BndBox3d myBndBox; //!< Bounding box of the poly
Select3D_TypeOfSensitivity mySensType; //!< Type of sensitivity: boundary or interior
mutable Standard_Boolean myIsComputed; //!< Is true if all the points and data structures of polygon are initialized
};
DEFINE_STANDARD_HANDLE(Select3D_SensitivePoly, Select3D_SensitiveSet)
#endif // _Select3D_SensitivePoly_HeaderFile
|
// -*- Mode: c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
//
// Copyright (C) 2012 Opera Software ASA. All rights reserved.
//
// This file is an original work developed by Opera Software ASA
#ifdef POSIX_AUTOUPDATECHECKER_IMPLEMENTATION
#include <string.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <fstream>
#include "adjunct/autoupdate/autoupdate_checker/adaptation_layer/system_info.h"
#include "adjunct/autoupdate/autoupdate_checker/adaptation_layer/system_utils.h"
namespace opera_update_checker {
namespace system_info {
#define PACKAGE_NAME_LENGTH 32
class StringHolder {
public:
StringHolder() {
read_uname_ = (uname(&sys_info_) == 0);
read_package_name_ = false;
// Package name must be read from an ini file :-(
std::ifstream package_id_ini("/usr/share/opera/package-id.ini");
if (package_id_ini.is_open() && package_id_ini.good()) {
const char key_searched[] = "Package Type=";
char key_buffer[sizeof(key_searched) + PACKAGE_NAME_LENGTH];
// Go over the file until you've found "Package Type="
int bytes_read = 0;
while (!package_id_ini.eof()
&& !package_id_ini.fail()
&& bytes_read == 0) {
package_id_ini.getline(key_buffer, sizeof(key_buffer));
bytes_read = sscanf(key_buffer, "Package Type=%s", package_name_);
}
if (bytes_read > 0)
read_package_name_ = true;
}
}
bool read_uname_;
bool read_package_name_;
char package_name_[PACKAGE_NAME_LENGTH];
utsname sys_info_;
};
const StringHolder g_stringHolder;
/** Returns operating system's name e.g. "Windows". Never NULL. */
/*static*/
const char* SystemInfo::GetOsName() {
if (g_stringHolder.read_uname_)
return g_stringHolder.sys_info_.sysname;
else
return "Unknown OS";
}
/** Returns operating system's version e.g. "7" for Windows 7. Never NULL. */
/*static*/
const char* SystemInfo::GetOsVersion() {
if (g_stringHolder.read_uname_)
return g_stringHolder.sys_info_.release;
else
return "Unknown Version";
}
/** Returns computer's architecture e.g. "x86". Never NULL. */
/*static*/
const char* SystemInfo::GetArch() {
if (g_stringHolder.read_uname_)
return g_stringHolder.sys_info_.machine;
else
return "Unknown Architecture";
}
/** Returns expected package type e.g. "EXE". Never NULL. */
/*static*/
const char* SystemInfo::GetPackageType() {
if (g_stringHolder.read_package_name_)
return g_stringHolder.package_name_;
else
return "Unknown Package Type";
}
} // namespace system_info
namespace system_utils {
/** Sleep the calling process for the given amount of time in miliseconds. */
/*static*/
void SystemUtils::Sleep(OAUCTime time) {
usleep(time * 1000); // converting miliseconds to microseconds
}
/** Case insensitive strncmp(). */
/*static*/
int SystemUtils::strnicmp(const char* str1, const char* str2, size_t length) {
return strncasecmp(str1, str2, length);
}
} // namespace system_utils
} // namespace opera_update_checker
#endif // POSIX_AUTOUPDATECHECKER_IMPLEMENTATION
|
#include <iostream>
using namespace std;
const int money_rank1[7] = {0, 5000000, 3000000, 2000000, 500000, 300000, 100000};
const int money_rank2[6] = {0, 5120000, 2560000, 1280000, 640000, 320000};
void calculate(int rank1, int rank2){
int ch_rank1 = 0;
int ch_rank2 = 0;
if(rank1 == 0){
ch_rank1 = 0;
}else if(rank1 <= 1){
ch_rank1 = 1;
}else if(rank1 <= 3){
ch_rank1 = 2;
}else if(rank1 <= 6){
ch_rank1 = 3;
}else if(rank1 <= 10){
ch_rank1 = 4;
}else if(rank1 <= 15){
ch_rank1 = 5;
}else if(rank1 <= 21){
ch_rank1 = 6;
}else{
ch_rank1 = 0;
}
if(rank2 == 0){
ch_rank2 = 0;
}else if(rank2 <= 1){
ch_rank2 = 1;
}else if(rank2 <= 3){
ch_rank2 = 2;
}else if(rank2 <= 7){
ch_rank2 = 3;
}else if(rank2 <= 15){
ch_rank2 = 4;
}else if(rank2 <= 31){
ch_rank2 = 5;
}else{
ch_rank2 = 0;
}
cout << money_rank1[ch_rank1]+money_rank2[ch_rank2] << '\n';
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
int tc;
cin >> tc;
while(tc--){
int a, b;
cin >> a >> b;
calculate(a, b);
}
return 0;
}
|
#include <bits/stdc++.h>
#define INF 1917483645
using namespace std;
const int maxn = 20, maxm = 1010;
int n, m, dis[maxn], a[maxn][maxn];
void DFS(int u, int k, int cnt, int val) {
if (cnt == n) {
ans = min(ans, val);
return ;
}
for (int v = 1; v <= n; v++)
if (dis[u] + a[u][v] * k < dis[v]) {
dis[v] = dis[u] + a[u][v] * k;
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
a[i][j] = INF;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &x, &y, &z);
a[x][y] = min(a[x][y], z);
a[y][x] = min(a[y][x], z);
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
dis[j] = INF;
dis[i] = 0;
DFS(i, 1, 1, 0);
}
}
|
//===-- OProfileJITEventListener.cpp - Tell OProfile about JITted code ----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a JITEventListener object that uses OProfileWrapper to tell
// oprofile about JITted functions, including source line information.
//
//===----------------------------------------------------------------------===//
#include "llvm/Config/config.h"
#include "llvm/ExecutionEngine/JITEventListener.h"
#define DEBUG_TYPE "oprofile-jit-event-listener"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/ExecutionEngine/ObjectImage.h"
#include "llvm/ExecutionEngine/OProfileWrapper.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Errno.h"
#include "EventListenerCommon.h"
#include <dirent.h>
#include <fcntl.h>
using namespace llvm;
using namespace llvm::jitprofiling;
namespace {
class OProfileJITEventListener : public JITEventListener {
OProfileWrapper& Wrapper;
void initialize();
public:
OProfileJITEventListener(OProfileWrapper& LibraryWrapper)
: Wrapper(LibraryWrapper) {
initialize();
}
~OProfileJITEventListener();
virtual void NotifyFunctionEmitted(const Function &F,
void *FnStart, size_t FnSize,
const JITEvent_EmittedFunctionDetails &Details);
virtual void NotifyFreeingMachineCode(void *OldPtr);
virtual void NotifyObjectEmitted(const ObjectImage &Obj);
virtual void NotifyFreeingObject(const ObjectImage &Obj);
};
void OProfileJITEventListener::initialize() {
if (!Wrapper.op_open_agent()) {
const std::string err_str = sys::StrError();
DEBUG(dbgs() << "Failed to connect to OProfile agent: " << err_str << "\n");
} else {
DEBUG(dbgs() << "Connected to OProfile agent.\n");
}
}
OProfileJITEventListener::~OProfileJITEventListener() {
if (Wrapper.isAgentAvailable()) {
if (Wrapper.op_close_agent() == -1) {
const std::string err_str = sys::StrError();
DEBUG(dbgs() << "Failed to disconnect from OProfile agent: "
<< err_str << "\n");
} else {
DEBUG(dbgs() << "Disconnected from OProfile agent.\n");
}
}
}
static debug_line_info LineStartToOProfileFormat(
const MachineFunction &MF, FilenameCache &Filenames,
uintptr_t Address, DebugLoc Loc) {
debug_line_info Result;
Result.vma = Address;
Result.lineno = Loc.getLine();
Result.filename = Filenames.getFilename(
Loc.getScope(MF.getFunction()->getContext()));
DEBUG(dbgs() << "Mapping " << reinterpret_cast<void*>(Result.vma) << " to "
<< Result.filename << ":" << Result.lineno << "\n");
return Result;
}
// Adds the just-emitted function to the symbol table.
void OProfileJITEventListener::NotifyFunctionEmitted(
const Function &F, void *FnStart, size_t FnSize,
const JITEvent_EmittedFunctionDetails &Details) {
assert(F.hasName() && FnStart != 0 && "Bad symbol to add");
if (Wrapper.op_write_native_code(F.getName().data(),
reinterpret_cast<uint64_t>(FnStart),
FnStart, FnSize) == -1) {
DEBUG(dbgs() << "Failed to tell OProfile about native function "
<< F.getName() << " at ["
<< FnStart << "-" << ((char*)FnStart + FnSize) << "]\n");
return;
}
if (!Details.LineStarts.empty()) {
// Now we convert the line number information from the address/DebugLoc
// format in Details to the address/filename/lineno format that OProfile
// expects. Note that OProfile 0.9.4 has a bug that causes it to ignore
// line numbers for addresses above 4G.
FilenameCache Filenames;
std::vector<debug_line_info> LineInfo;
LineInfo.reserve(1 + Details.LineStarts.size());
DebugLoc FirstLoc = Details.LineStarts[0].Loc;
assert(!FirstLoc.isUnknown()
&& "LineStarts should not contain unknown DebugLocs");
MDNode *FirstLocScope = FirstLoc.getScope(F.getContext());
DISubprogram FunctionDI = getDISubprogram(FirstLocScope);
if (FunctionDI.Verify()) {
// If we have debug info for the function itself, use that as the line
// number of the first several instructions. Otherwise, after filling
// LineInfo, we'll adjust the address of the first line number to point at
// the start of the function.
debug_line_info line_info;
line_info.vma = reinterpret_cast<uintptr_t>(FnStart);
line_info.lineno = FunctionDI.getLineNumber();
line_info.filename = Filenames.getFilename(FirstLocScope);
LineInfo.push_back(line_info);
}
for (std::vector<EmittedFunctionDetails::LineStart>::const_iterator
I = Details.LineStarts.begin(), E = Details.LineStarts.end();
I != E; ++I) {
LineInfo.push_back(LineStartToOProfileFormat(
*Details.MF, Filenames, I->Address, I->Loc));
}
// In case the function didn't have line info of its own, adjust the first
// line info's address to include the start of the function.
LineInfo[0].vma = reinterpret_cast<uintptr_t>(FnStart);
if (Wrapper.op_write_debug_line_info(FnStart, LineInfo.size(),
&*LineInfo.begin()) == -1) {
DEBUG(dbgs()
<< "Failed to tell OProfile about line numbers for native function "
<< F.getName() << " at ["
<< FnStart << "-" << ((char*)FnStart + FnSize) << "]\n");
}
}
}
// Removes the being-deleted function from the symbol table.
void OProfileJITEventListener::NotifyFreeingMachineCode(void *FnStart) {
assert(FnStart && "Invalid function pointer");
if (Wrapper.op_unload_native_code(reinterpret_cast<uint64_t>(FnStart)) == -1) {
DEBUG(dbgs()
<< "Failed to tell OProfile about unload of native function at "
<< FnStart << "\n");
}
}
void OProfileJITEventListener::NotifyObjectEmitted(const ObjectImage &Obj) {
if (!Wrapper.isAgentAvailable()) {
return;
}
// Use symbol info to iterate functions in the object.
error_code ec;
for (object::symbol_iterator I = Obj.begin_symbols(),
E = Obj.end_symbols();
I != E && !ec;
I.increment(ec)) {
object::SymbolRef::Type SymType;
if (I->getType(SymType)) continue;
if (SymType == object::SymbolRef::ST_Function) {
StringRef Name;
uint64_t Addr;
uint64_t Size;
if (I->getName(Name)) continue;
if (I->getAddress(Addr)) continue;
if (I->getSize(Size)) continue;
if (Wrapper.op_write_native_code(Name.data(), Addr, (void*)Addr, Size)
== -1) {
DEBUG(dbgs() << "Failed to tell OProfile about native function "
<< Name << " at ["
<< (void*)Addr << "-" << ((char*)Addr + Size) << "]\n");
continue;
}
// TODO: support line number info (similar to IntelJITEventListener.cpp)
}
}
}
void OProfileJITEventListener::NotifyFreeingObject(const ObjectImage &Obj) {
if (!Wrapper.isAgentAvailable()) {
return;
}
// Use symbol info to iterate functions in the object.
error_code ec;
for (object::symbol_iterator I = Obj.begin_symbols(),
E = Obj.end_symbols();
I != E && !ec;
I.increment(ec)) {
object::SymbolRef::Type SymType;
if (I->getType(SymType)) continue;
if (SymType == object::SymbolRef::ST_Function) {
uint64_t Addr;
if (I->getAddress(Addr)) continue;
if (Wrapper.op_unload_native_code(Addr) == -1) {
DEBUG(dbgs()
<< "Failed to tell OProfile about unload of native function at "
<< (void*)Addr << "\n");
continue;
}
}
}
}
} // anonymous namespace.
namespace llvm {
JITEventListener *JITEventListener::createOProfileJITEventListener() {
static std::unique_ptr<OProfileWrapper> JITProfilingWrapper(
new OProfileWrapper);
return new OProfileJITEventListener(*JITProfilingWrapper);
}
// for testing
JITEventListener *JITEventListener::createOProfileJITEventListener(
OProfileWrapper* TestImpl) {
return new OProfileJITEventListener(*TestImpl);
}
} // namespace llvm
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#if !TARGET_RT_MAC_MACHO
#include <OpenTptClient.h>
#endif
#include <stdarg.h>
#include "platforms/mac/debug/log2.jens.h"
#include "platforms/mac/debug/OnScreen.h"
#ifdef _JB_DEBUG
#include DEBUG_SETTINGS
#endif
char *gSpaces = " \0";
#ifdef SPECIAL_MAC_TEST_VERSION
Log gContextLog("Context.log");
#endif
SInt32 gNotifierCount = 0;
Log::Log(char *filename)
{
#ifndef _DISABLE_LOGGING
char oldname[256];
enabled = true;
spacePtr = &gSpaces[256];
sprintf(name, ": logs:%s", filename);
sprintf(oldname, "%s.old", name);
::remove(oldname);
::rename(name, oldname);
::remove(name); // just in case the newest file could not be renamed
if(Open())
{
fprintf(fp, "\n-- New Session -------------------------------------------------------------------------------------\n");
Close();
}
currLog = 0;
notifierLog[0] = (char*)op_malloc(16384 + 1);
notifierLog[1] = (char*)op_malloc(16384 + 1);
if(NULL != notifierLog[0])
{
*notifierLog[0] = '\0';
}
else
{
DebugStr("\pCould not get buffer0 for log-file");
}
if(NULL != notifierLog[1])
{
*notifierLog[1] = '\0';
}
else
{
DebugStr("\pCould not get buffer1 for log-file");
}
#endif
}
Log::~Log()
{
#ifndef _DISABLE_LOGGING
if(NULL != fp)
{
fclose(fp);
}
if(NULL != notifierLog[0])
{
op_free(notifierLog[0]);
}
if(NULL != notifierLog[1])
{
op_free(notifierLog[1]);
}
#endif
}
void Log::PutI(int id)
{
#ifndef _DISABLE_LOGGING
if(Open())
{
fprintf(fp, "%s{%d\n", spacePtr, id);
Close();
}
#endif
}
void Log::PutO(int id)
{
#ifndef _DISABLE_LOGGING
if(Open())
{
fprintf(fp, "%s}%d\n", spacePtr, id);
Close();
}
#endif
}
void Log::Put(char *format, ...)
{
va_list marker;
char temp[1024];
char *p;
static OTTimeStamp startTime;
UInt32 mS;
static Boolean first = true;
UInt8 log;
va_start(marker, format);
#ifndef _DISABLE_LOGGING
if(first)
{
first = false;
OTGetTimeStamp(&startTime);
}
mS = OTElapsedMilliseconds(&startTime);
p = temp;
sprintf(p, " %2lu:%02lu:%02lu.%03lu ", mS / 3600000, (mS / 60000) % 60, (mS / 1000) % 60, mS % 1000);
p += OTStrLength(p);
OTStrCopy(p, spacePtr);
p += OTStrLength(p);
vsprintf(p, format, marker);
p += OTStrLength(p);
*p++ = '\n';
*p++ = '\0';
if(0 == gNotifierCount)
{
if(Open())
{
log = (~OTAtomicAdd8(1, &currLog)) & 1; // toggle currLog, get result to log
p = notifierLog[log];
if(NULL != p)
{
if(*p) // if we have something in the notifierlog
{
fprintf(fp, "%s", p); // write old log to disk
*p = '\0'; // reset buffer
}
}
fprintf(fp, "%s", temp); // write new string to disk
Close();
}
}
else
{
// Dec8OnScreen(0, 0, kOnScreenBlue, timesCalledByNotifier++);
log = currLog & 1;
p = notifierLog[log];
if(NULL != p)
{
p[10240] = '\n';
p[10241] = '{';
p[10242] = 's';
p[10243] = 'n';
p[10244] = 'i';
p[10245] = 'p';
p[10246] = '}';
p[10247] = '\n';
p[10248] = '\0'; // make sure it does not write way too much
temp[0] = '*';
OTStrCat(p, temp);
// Dec8OnScreen(0, 8, kOnScreenBlue, log);
// Dec8OnScreen(0, 16, kOnScreenBlue, OTStrLength(p));
}
// Dec8OnScreen(0, 24, kOnScreenBlue, (long) p);
}
#endif
va_end(marker);
}
int Log::Open()
{
fp = NULL;
if(enabled) // only try opening if log is enabled
{
fp = fopen(name, "at");
}
if(NULL == fp) // if we had an error opening file...
{
enabled = false; // ...give up, never try again.
}
return(NULL != fp); // return whether we opened the file or not
}
void Log::Close()
{
fclose(fp);
fp = NULL;
}
|
#include<iostream>
#include<windows.h>
using namespace std;
struct winm//winvalue array
{
int a,b,c;
};
struct aimove
{
int x;
int score;
aimove(){}
aimove(int s)
{
score=s;
x=0;
}
};
class engine
{
public:
bool gameover,check,multi;
int k,humval,comp,rv;
struct winm w[8];
int state[9],mat[5][5];
void setup()
{//writing wincheck values
char mul;
w[1]={0,3,6};
w[2]={1,4,7};
w[3]={2,5,8};
w[4]={0,4,8};
w[5]={2,4,6};
w[6]={0,1,2};
w[7]={3,4,5};
w[0]={6,7,8};
for(int i=0;i<9;i++)
{
state[i]=0;
//cout<<state[i];
}
cout<<"Multiplayer ? y or n \n ";
cin>>mul;
mul=='y' ? multi=true : multi=false;
cout<<endl;
//cout<<multi;Sleep(1000);
gameover = false;
}
void draw()
{
int j;
system("cls");
//draw engine
for(int i=1,k=0;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if(i%2==0)
{
cout<<"_";//drawing horizontal lines
}
else if(j%2==0 && j!=1)
cout<<"|";//drawing vertical lines
else//X O and spaces
{
mat[i-1][j-1]=state[(3*k)+(j/2)];
if(mat[i-1][j-1]==1)
cout<<"X";
else if(mat[i-1][j-1]==-1)
cout<<"O";
else
cout<<" ";
}
}
if(i%2==0)
k++;
cout<<endl;
}
for(int k=0;k<9;k++)
cout<<state[k]<<" ";
cout<<endl;
}
int checkwin()
{check=false;
for(int i=0;i<9;i++)
{
if(state[w[i].a]==1 && state[w[i].b]==1 && state[w[i].c]==1){
return 1;check=true;}
else if(state[w[i].a]==-1 && state[w[i].b]==-1 && state[w[i].c]==-1){
return -1;check=true;}
}bool tie=true;
for(int k=0;k<9;k++)
{
if(state[k]==0)
tie=false;
}
if(tie==true)
return 2;
if(check==false)
return 0;
}
aimove callai(int state[],int player)
{//base case check
aimove aik;int t=0;
aimove moves[20];
rv=checkwin();
if(rv==1)
return aimove(10);
else if(rv==-1)
return aimove(-10);
else if(rv==0)
return aimove(0);
//recrsive part
for(int i=0;i<9;i++)
{
if(state[i]==0)
{
aimove move;
move.x=i;
state[move.x]=player;
if(player==-1){
aik=callai(state,1);
move.score=aik.score;}
else if(player==1){
aik=callai(state,-1);
move.score=aik.score;}
moves[t++]=move;
state[i]=0;
}
}
//picking the best move
int bestmove,bestscore;
if(player==-1)
{
bestscore=-100;
for(int k=0;k<9;k++)
{
if(moves[k].score >= bestscore)
{
bestmove=k;
bestscore=moves[k].score;
}
}
}
if(player==1)
{
bestscore=100;
for(int k=0;k<9;k++)
{
if(moves[k].score <= bestscore)
{
bestmove=k;
bestscore=moves[k].score;
}
}
}
return moves[bestmove];
}
void logic()
{
if(checkwin()==1)
{draw();
if(multi==false)
cout<<"You Won!!\n";
else
cout<<"Player 1 Won!!\n";
gameover=true;
}
else if(checkwin()==-1)
{draw();
if(multi==false)
cout<<"Computer Won!!\n";
else
cout<<"Player 2 Won!!\n";
gameover=true;}
else if(checkwin()==2){draw();
cout<<"Its a Draw!!\n";gameover=true;}
}
void input()
{//Input values
if(multi==false){
aimove ai;
cout<<"Enter position\n";
cin>>humval;
if(state[humval-1]==0)
state[humval-1]=1;
else{
cout<<"Select another value\n";Sleep(1000);}
//calling AI
ai=callai(state,-1);
comp=ai.x;
state[comp]=-1;
}
else
{
int p1,p2;
cout<<"Enter player 1 : ";
cin>>p1;
if(state[p1-1]==0)
state[p1-1]=1;
else{
cout<<"Select another value\n";Sleep(1000);}
if(checkwin()!=0)
return;
draw();
cout<<"Enter player 2 : ";
cin>>p2;
if(state[p2-1]==0)
state[p2-1]=-1;
else{
cout<<"Select another value\n";Sleep(1000);}
if(checkwin()!=0)
return;
draw();
}
}
};
int main()
{
engine e;
e.setup();
//recursive function till gameover
while(!e.gameover)
{
e.draw();
e.input();
e.logic();
}
}
|
#ifndef ADJACENCIA_H
#define ADJACENCIA_H
#include<stdlib.h>
#include<iostream>
class No;
class Adjacencia
{
public:
Adjacencia(No* inicio, No* fim, int peso);
~Adjacencia();
void setProx(Adjacencia* adj);
Adjacencia* getProx();
int getPeso();
No* getNoInicio();
No* getNoFim();
protected:
private:
No* noInicio;
No* noFim;
int peso;
Adjacencia* prox;
};
#endif // ADJACENCIA_H
|
//
// Game.hpp
// MirrorChess
//
// Created by Sergio Colado on 22.04.20.
// Copyright © 2020 Sergio Colado. All rights reserved.
//
#ifndef Game_hpp
#define Game_hpp
#include <SFML/Graphics.hpp>
#include "Piece.hpp"
#include "Board.hpp"
using namespace sf;
enum class InputState
{
Pressed,
Released,
Inactive
};
class Game
{
private:
RenderWindow* windowPtr;
Board board;
Vector2i mousePos;
void render();
InputState inputState;
void update();
public:
Game();
void init();
void handleInput();
};
#endif /* Game_hpp */
|
#include "plane_parameterization.h"
PlaneParameterization::PlaneParameterization()
{
}
PlaneParameterization::~PlaneParameterization() {}
bool PlaneParameterization::Plus(const double* x,const double* delta,double* x_plus_delta) const
{
ceres::HomogeneousVectorParameterization hvp(3);
hvp.Plus(x,delta,x_plus_delta);
x_plus_delta[3] = x[3] + delta[2];
if (x_plus_delta[3] < 0 )
{
for (int i = 0; i < 4; i++)
x_plus_delta[i] *= -1;
}
return true;
}
bool PlaneParameterization::ComputeJacobian(const double* x, double* jacobian) const
{
ceres::HomogeneousVectorParameterization hvp(3);
double hvpj[6];
hvp.ComputeJacobian(x,hvpj);
for (int i = 0;i<12;i++)jacobian[i] = 0;
jacobian[0] = hvpj[0];
jacobian[1] = hvpj[1];
jacobian[3] = hvpj[2];
jacobian[4] = hvpj[3];
jacobian[6] = hvpj[4];
jacobian[7] = hvpj[5];
jacobian[11] = 1;
return true;
}
int PlaneParameterization::GlobalSize() const
{
return 4;
}
int PlaneParameterization::LocalSize() const
{
return 3;
}
|
#ifndef WARRIOR_H
#define WARRIOR_H
#include<string>
#include<sstream>
#include<random>
#include "Character.h"
#include<iostream>
#include<thread>
#include<vector>
#include "Sword.h"
#include "Axe.h"
using std::string;
using std::stringstream;
using std::cout;
using std::endl;
using std::vector;
class Warrior : public Character
{
private:
static const WeaponType types[];
public:
Warrior(string name);
virtual ~Warrior();
Warrior(const Warrior& other);
Warrior& operator=(const Warrior& other);
bool operator==(const Warrior* w)const;
Warrior* clone()const override;
void setWeapon(Weapon *weapon);
void addHealth();
void addStrength();
void addDefense();
void addSpeed();
void addResistance();
void addMagic();
void addLuck();
void addSkill();
protected:
};
#endif // WARRIOR_H
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_set>
#include <queue>
using namespace std;
int solve(string start,string end,unordered_set<string> &dict, int length){
string alphebet = "abcdefghijklmnopqrstuvwxyz";
int res =0;
for(int j=0;j<start.length();j++){
string temp = start;
for(int i=0;i<26;i++){
string rs = temp;
rs[j] = alphebet[i];
if(rs == end){
cout <<"got"<< length+1 <<endl;
return length+1;
}
if(dict.count(rs)>0){
cout <<"getget"<<endl;
cout << rs<<endl;
dict.erase(rs);
int k = solve(rs,end,dict,length+1);
if(res == 0 && k!=0) res = k;
if(k < res) res = k;
}
}
start = temp;
}
if(res !=0)return res;
return 0;
}
// Bad function
int ladderLength2(string start, string end, unordered_set<string> &dict){
if(dict.empty()) return 0;
int res = solve(start,end,dict,1);
return res;
}
int ladderLength(string start, string end, unordered_set<string> &dict){
string alphebet = "abcdefghijklmnopqrstuvwxyz";
if(dict.empty()) return 0;
int length = 1;
int onelevelnum = 0;
int lastnum =1;
queue<string> myqueue;
myqueue.push(start);
unordered_set<string> myset;
while(!myqueue.empty()){
string temp = myqueue.front();
lastnum = 1;
for(int i=0;i<start.length();i++){
for(int j=0;j<26;j++){
string rs = temp;
rs[i] = alphebet[j];
if(rs == end){
return length+1;
}
if(dict.count(rs)>0 && !myset.count(rs)>0 ){
onelevelnum++;
myqueue.push(rs);
myset.insert(rs);
}
}
temp=myqueue.front();
}
myqueue.pop();
lastnum--;
if(lastnum == 0){
lastnum = onelevelnum;
onelevelnum = 0;
length++;
}
}
return 0;
}
int main(){
string start,end;
cin >> start >> end;
string s;
unordered_set<string> dict;
while(cin >> s) dict.insert(s);
cout << "Finish Input" <<endl;
cout << start << " " << end <<endl;
for(auto &x : dict) cout << x << " ";
int res = ladderLength(start,end,dict);
cout << "Res: " <<res<<endl;
}
|
#include <Poco/Exception.h>
#include <Poco/Logger.h>
#include "loop/StopControl.h"
#include "util/Loggable.h"
using namespace std;
using namespace Poco;
using namespace BeeeOn;
StopControl::Run::Run(StopControl &control):
m_control(control)
{
m_control.clear();
}
StopControl::Run::~Run()
{
try {
m_control.clear();
}
BEEEON_CATCH_CHAIN(Loggable::forInstance(this))
}
bool StopControl::Run::waitStoppable(const Timespan &timeout)
{
return m_control.waitStoppable(timeout);
}
StopControl::Run::operator bool() const
{
return !m_control.shouldStop();
}
StopControl::StopControl():
m_stop(false)
{
}
bool StopControl::doWait(long ms)
{
if (ms < 0) {
m_condition.wait(m_lock);
return true;
}
return m_condition.tryWait(m_lock, ms);
}
bool StopControl::waitStoppable(const Timespan &timeout)
{
FastMutex::ScopedLock guard(m_lock);
if (m_stop)
return true; // we are always woken up here
if (timeout < 0)
return doWait(-1);
if (timeout < 1 * Timespan::MILLISECONDS)
return doWait(1);
return doWait(timeout.totalMilliseconds());
}
bool StopControl::shouldStop() const
{
FastMutex::ScopedLock guard(m_lock);
return m_stop;
}
void StopControl::requestStop()
{
FastMutex::ScopedLock guard(m_lock);
m_stop = true;
requestWakeup();
}
void StopControl::requestWakeup()
{
m_condition.broadcast();
}
void StopControl::clear()
{
FastMutex::ScopedLock guard(m_lock);
m_stop = false;
}
|
//Kaveh Pezeshki
//literally just turns an LED on
#include "easySamIO.h"
#include <stdio.h>
int main(void) {
samInit();
//Testing Digital I/O
/*
pinMode(10, OUTPUT);
while (1) {
digitalWrite(10, LOW);
for(int i = 0; i < 100000; i++);
digitalWrite(10, HIGH);
for(int i = 0; i < 100000; i++);
}*/
//Testing SPI and UART
unsigned short received = 0;
float voltage;
spiInit(255, 0, 0);
uartInit(4,2);
char strTransmit[5];
while (1) {
received = spiSendReceive16(0x6000);
received &= 0x03FF; //removing top 6 bits
voltage = 3.3*((float)received/1023.0);
snprintf(strTransmit, 5, "%f", voltage);
for (int charNum = 0; charNum < 5; charNum++) {
uartTx(strTransmit[charNum]);
}
}
}
|
#include"ServerSenderr.h"
HttpMessage ServerSender::makeMessage(size_t n, const std::string& body, const EndPoint& ep)
{
HttpMessage msg;
HttpMessage::Attribute attrib;
EndPoint myEndPoint = "localhost:8080"; // ToDo: make this a member of the sender
// given to its constructor.
msg.clear();
switch (n)
{
case 1:
msg.addAttribute(HttpMessage::attribute("GET", "Ack-Upload"));
break;
case 2:
msg.addAttribute(HttpMessage::attribute("GET", "Ack-Download"));
break;
case 3:
msg.addAttribute(HttpMessage::attribute("GET", "Ack-PUBLISH"));
break;
case 4:
msg.addAttribute(HttpMessage::attribute("GET", "Ack-DOWNLOAD"));
break;
case 5:
msg.addAttribute(HttpMessage::attribute("GET", "Exception"));
break;
default:
msg.clear();
msg.addAttribute(HttpMessage::attribute("Error", "unknown message type"));
}
msg.addAttribute(HttpMessage::Attribute("mode", "oneway"));
msg.addAttribute(HttpMessage::parseAttribute("toAddr:" + ep));
msg.addAttribute(HttpMessage::parseAttribute("fromAddr:" + myEndPoint));
msg.addBody(body); // the above strings are passed byte by byte through http message
if (body.size() > 0)
{
attrib = HttpMessage::attribute("content-length", Converter<size_t>::toString(body.size()));
msg.addAttribute(attrib);
}
return msg;
}
bool ServerSender::sendFile(const std::string& filename, Socket& socket)
{
// assumes that socket is connected
std::string fqname = "../ServerRepository/" + filename;
FileSystem::FileInfo fi(fqname);
size_t fileSize = fi.size(); //Size
std::string sizeString = Converter<size_t>::toString(fileSize); //convert size to string
FileSystem::File file(fqname);
file.open(FileSystem::File::in, FileSystem::File::binary);
if (!file.isGood())
return false;
HttpMessage msg = makeMessage(1, "", "localhost::8081");
msg.addAttribute(HttpMessage::Attribute("file", filename));
msg.addAttribute(HttpMessage::Attribute("content-length", sizeString));
sendMessage(msg, socket);
const size_t BlockSize = 2048;
Socket::byte buffer[BlockSize];
while (true)
{
FileSystem::Block blk = file.getBlock(BlockSize);
if (blk.size() == 0)
break;
for (size_t i = 0; i < blk.size(); ++i)
buffer[i] = blk[i];
socket.send(blk.size(), buffer);
if (!file.isGood())
break;
}
file.close();
return true;
}
//----< send message using socket >----------------------------------
void ServerSender::sendMessage(HttpMessage& msg, Socket& socket)
{
std::string msgString = msg.toString();
socket.send(msgString.size(), (Socket::byte*)msgString.c_str());
}
//----< this defines the behavior of the client >--------------------
void ServerSender::execute(const size_t TimeBetweenMessages, const size_t NumMessages)
{
// send NumMessages messages
std::cout << "Sending message from " << std::endl;
try
{
SocketSystem ss;
SocketConnecter si;
while (!si.connect("localhost", 8080)) //if the server isn't connected to the client on that port then the client sleeps
{
Show::write("\n server waiting to connect");
::Sleep(100);
}
// send a set of messages
HttpMessage msg;
std::string msgBody =
"<msg>Message # Test message from Server from Server # </msg>"; //myCounterString
msg = makeMessage(1, msgBody, "localhost:8080");
/*
* Sender class will need to accept messages from an input queue
* and examine the toAddr attribute to see if a new connection
* is needed. If so, it would either close the existing connection
* or save it in a map[url] = socket, then open a new connection.
*/
sendMessage(msg, si);
Show::write("\n\n server sent\n" + msg.toIndentedString()); //enqueqe into the blocking queue //Client Client Number sent and the messgae sent
::Sleep(TimeBetweenMessages);
// send all *.cpp files from TestFiles folder
std::vector<std::string> files = FileSystem::Directory::getFiles("../ServerRepository", "*.htm");
for (size_t i = 0; i < files.size(); ++i)
{
Show::write("\n\n sending file " + files[i]); //to blocking queue
sendFile(files[i], si);
}
// shut down server's client handler
msg = makeMessage(5, "quit", "toAddr:localhost:8080");
sendMessage(msg, si);
Show::write("\n\n server sent\n" + msg.toIndentedString());
Show::write("\n");
Show::write("\n All done folks");
}
catch (std::exception& exc)
{
Show::write("\n Exeception caught: ");
std::string exMsg = "\n " + std::string(exc.what()) + "\n\n";
Show::write(exMsg);
}
}
|
#include "dataview.h"
DataView::DataView()
: mModel{nullptr}
{
}
DataModel *DataView::model() const
{
return mModel;
}
void DataView::setModel(DataModel *model)
{
if(model && mModel != model)
{
mModel = model;
}
}
|
#include "sensorsDHT11.h"
#include "json.h"
#include "HTTPinit.h"
extern ESP8266WebServer HTTP;
#define DHTPIN 4 // GPIO4 or D2 - what digital pin we're connected to
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
// humidity => 0
// temperature => 1
void initDht(void){
HTTP.on("/sensors.json", HTTP_GET, []() {
readDht (0);
HTTP.send(200, "application/json", sensorsJson);
});
dht.begin();
// static uint16_t test = dht.getMinimumSamplingPeriod(); // Получаем минимальное значение между запросами данных с датчика
}
int16_t readDht (int8_t who) {
static int16_t t, h;
if (who == 0){
t = dht.readTemperature();
h = dht.readHumidity();
// Serial.print("termo: ");
// Serial.print(t);
jsonWrite(sensorsJson, "termo", t);
jsonWrite(sensorsJson, "humid", h);
// jsonWrite(sensorsJson, "pressure", 1008);
}
if (who == 1){ return h;}
if (who == 2){ return t;}
}
|
#pragma once
namespace arithmetic_parser
{
enum class TokenType
{
None = 0,
Number,
Variable,
BuiltinFunction,
Parentheses,
Comma,
Constant
};
}
|
#include "core/pch.h"
#include "modules/libgogi/mde.h"
// == MDE_Region ==========================================================
MDE_Region::MDE_Region()
: rects(NULL)
, num_rects(0)
, max_rects(0)
{
}
MDE_Region::~MDE_Region()
{
Reset();
}
void MDE_Region::Swap(MDE_Region *other)
{
int _max_rects = max_rects;
int _num_rects = num_rects;
MDE_RECT * _rects = rects;
max_rects = other->max_rects;
num_rects = other->num_rects;
rects = other->rects;
other->max_rects = _max_rects;
other->num_rects = _num_rects;
other->rects = _rects;
}
void MDE_Region::Offset(int dx, int dy)
{
for(int i = 0; i < num_rects; i++)
{
rects[i].x += dx;
rects[i].y += dy;
}
}
void MDE_Region::Reset(bool free_mem)
{
if (free_mem)
{
/*#ifdef _DEBUG
for(int i = 0; i < num_rects; i++)
for(int j = 0; j < num_rects; j++)
if (i != j && MDE_RectIntersects(rects[i], rects[j]))
{
MDE_ASSERT(false);
}
#endif*/
OP_DELETEA(rects);
rects = NULL;
max_rects = 0;
}
num_rects = 0;
}
bool MDE_Region::Set(MDE_RECT rect)
{
Reset();
return AddRect(rect);
}
bool MDE_Region::GrowIfNeeded()
{
if(num_rects == max_rects)
{
int new_max_rects = (max_rects == 0 ? 1 : max_rects + 4);
MDE_RECT *new_rects = OP_NEWA(MDE_RECT, new_max_rects);
if (!new_rects)
return false;
if(rects)
op_memmove(new_rects, rects, sizeof(MDE_RECT) * max_rects);
OP_DELETEA(rects);
rects = new_rects;
max_rects = new_max_rects;
}
return true;
}
bool MDE_Region::AddRect(MDE_RECT rect)
{
MDE_ASSERT(!MDE_RectIsEmpty(rect));
if (!GrowIfNeeded())
return false;
rects[num_rects++] = rect;
/*#ifdef _DEBUG
static maxcount = 0;
if (num_rects > maxcount)
{
maxcount = num_rects;
P_DEBUG_PRINTF("%d\n", maxcount);
}
#endif*/
return true;
}
void MDE_Region::RemoveRect(int index)
{
MDE_ASSERT(index >= 0 && index < num_rects);
if(index < num_rects - 1)
for(int i = index; i < num_rects - 1; i++)
rects[i] = rects[i + 1];
num_rects--;
}
bool MDE_Region::IncludeRect(MDE_RECT rect)
{
MDE_RECT r = rect;
/* Old version. Big rectangles as result.
for(int i = 0; i < num_rects; i++)
{
if (MDE_RectIntersects(r, rects[i]))
{
r = MDE_RectUnion(r, rects[i]);
RemoveRect(i);
i = -1; // 0 next loop
}
}*/
for(int i = 0; i < num_rects; i++)
{
if (MDE_RectIntersects(r, rects[i]))
{
MDE_Region r_split;
if (!r_split.ExcludeRect(r, rects[i]))
return false;
for(int j = 0; j < r_split.num_rects; j++)
{
if (!IncludeRect(r_split.rects[j]))
return false;
}
return true;
}
}
return AddRect(r);
}
bool MDE_Region::ExcludeRect(MDE_RECT rect, MDE_RECT remove)
{
MDE_ASSERT(MDE_RectIntersects(rect, remove));
remove = MDE_RectClip(remove, rect);
// Create rectangles that surround the clipped remove rect.
//
// Creating vertical slices is preferred over horizontal slices to make scrolling
// overlapped views faster vertically. This wouldn't matter if subsequent scrolls
// exclude themselves from the invalidation caused by the other scrolls.
//
// Details:
//
// Vertical slices Horizontal slices
// #################################### ####################################
// # . . # # #
// # .top . # # top #
// # . . # # #
// # !!!!!! # #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#
// # ###### # #...............######.............#
// # left # # right # # left # # right #
// # # # # #!!!!!!!!!!!!!!!# #!!!!!!!!!!!!!#
// # ###### # #...............######.............#
// # . . # # #
// # bottom # # bottom #
// # . . # # #
// #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!# #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#
// #################################### ####################################
//
// Showing the invalidated parts with "!" for vertical vs horizontal slices after a
// typical scroll.
// Since close enough invalidated areas are unioned to larger areas, the horizontal
// slices would cause many vertical scrolls to invalidate most of the screen!
// Top
if (remove.y > rect.y)
if (!AddRect(MDE_MakeRect(remove.x, rect.y, remove.w, remove.y - rect.y)))
return false;
// Left
if (remove.x > rect.x)
if (!AddRect(MDE_MakeRect(rect.x, rect.y, remove.x - rect.x, rect.h)))
return false;
// Right
if (remove.x + remove.w < rect.x + rect.w)
if (!AddRect(MDE_MakeRect(remove.x + remove.w, rect.y, rect.x + rect.w - (remove.x + remove.w), rect.h)))
return false;
// Bottom
if (remove.y + remove.h < rect.y + rect.h)
if (!AddRect(MDE_MakeRect(remove.x, remove.y + remove.h, remove.w, rect.y + rect.h - (remove.y + remove.h))))
return false;
return true;
}
bool MDE_Region::ExcludeRect(const MDE_RECT &rect)
{
// Split all intersecting rectangles
int num_to_split = num_rects;
for(int i = 0; i < num_to_split; i++)
{
if (MDE_RectIntersects(rects[i], rect))
{
if (!ExcludeRect(rects[i], rect))
return false;
RemoveRect(i);
num_to_split--;
i--;
}
}
#ifdef _DEBUG
for(int k = 0; k < num_rects; k++)
for(int m = 0; m < num_rects; m++)
if (k != m && MDE_RectIntersects(rects[k], rects[m]))
{
MDE_ASSERT(0);
}
#endif
return true;
}
void MDE_Region::CoalesceRects()
{
for(int i = 0; i < num_rects; i++)
{
for(int j = 0; j < num_rects; j++)
{
if (i == j)
continue;
if (i > num_rects - 1)
break;
if (// Vertical
(rects[i].x == rects[j].x && rects[i].w == rects[j].w &&
((rects[i].y + rects[i].h == rects[j].y) || (rects[j].y + rects[j].h == rects[i].y)))
|| // Horizontal
(rects[i].y == rects[j].y && rects[i].h == rects[j].h &&
((rects[i].x + rects[i].w == rects[j].x) || (rects[j].x + rects[j].w == rects[i].x)))
)
{
rects[i] = MDE_RectUnion(rects[i], rects[j]);
RemoveRect(j);
j--;
}
}
}
}
// == MDE_RECT ============================================================
MDE_RECT MDE_MakeRect(int x, int y, int w, int h)
{
MDE_RECT tmp = { x, y, w, h };
return tmp;
}
bool MDE_RectIntersects(const MDE_RECT &this_rect, const MDE_RECT &with_rect)
{
#ifdef MDE_PEDANTIC_ASSERTS
MDE_ASSERT(!MDE_RectIsInsideOut(this_rect));
MDE_ASSERT(!MDE_RectIsEmpty(this_rect));
MDE_ASSERT(!MDE_RectIsInsideOut(with_rect));
MDE_ASSERT(!MDE_RectIsEmpty(with_rect));
#endif
if (MDE_RectIsEmpty(this_rect) || MDE_RectIsEmpty(with_rect))
return false;
return !( (this_rect.x >= with_rect.x + with_rect.w) || (this_rect.x + this_rect.w <= with_rect.x) ||
(this_rect.y >= with_rect.y + with_rect.h) || (this_rect.y + this_rect.h <= with_rect.y) );
}
bool MDE_RectContains(const MDE_RECT &rect, int x, int y)
{
MDE_ASSERT(!MDE_RectIsInsideOut(rect));
return !( x < rect.x || (x >= rect.x + rect.w) || y < rect.y || (y >= rect.y + rect.h) );
}
bool MDE_RectContains(const MDE_RECT& container, const MDE_RECT& containee)
{
MDE_ASSERT(!MDE_RectIsInsideOut(container));
MDE_ASSERT(!MDE_RectIsInsideOut(containee));
return (containee.x >= container.x &&
containee.y >= container.y &&
containee.x + containee.w <= container.x + container.w &&
containee.y + containee.h <= container.y + container.h);
}
MDE_RECT MDE_RectClip(const MDE_RECT &this_rect, const MDE_RECT &clip_rect)
{
#ifdef MDE_PEDANTIC_ASSERTS
MDE_ASSERT(!MDE_RectIsInsideOut(this_rect));
#endif
MDE_ASSERT(!MDE_RectIsInsideOut(clip_rect));
MDE_RECT tmp = { 0, 0, 0, 0 };
if(!MDE_RectIntersects(this_rect, clip_rect))
return tmp;
int x1 = this_rect.x;
int x2 = this_rect.x + this_rect.w;
int y1 = this_rect.y;
int y2 = this_rect.y + this_rect.h;
tmp.x = MDE_MAX(x1, clip_rect.x);
tmp.y = MDE_MAX(y1, clip_rect.y);
tmp.w = MDE_MIN(x2, clip_rect.x + clip_rect.w) - tmp.x;
tmp.h = MDE_MIN(y2, clip_rect.y + clip_rect.h) - tmp.y;
return tmp;
}
MDE_RECT MDE_RectUnion(const MDE_RECT &this_rect, const MDE_RECT &and_this_rect)
{
MDE_ASSERT(!MDE_RectIsInsideOut(this_rect));
MDE_ASSERT(!MDE_RectIsInsideOut(and_this_rect));
if (MDE_RectIsEmpty(this_rect))
return and_this_rect;
if (MDE_RectIsEmpty(and_this_rect))
return this_rect;
int minx = MDE_MIN(this_rect.x, and_this_rect.x);
int miny = MDE_MIN(this_rect.y, and_this_rect.y);
int maxx = this_rect.x + this_rect.w > and_this_rect.x + and_this_rect.w ?
this_rect.x + this_rect.w : and_this_rect.x + and_this_rect.w;
int maxy = this_rect.y + this_rect.h > and_this_rect.y + and_this_rect.h ?
this_rect.y + this_rect.h : and_this_rect.y + and_this_rect.h;
MDE_RECT tmp = { minx, miny, maxx - minx, maxy - miny };
return tmp;
}
void MDE_RectReset(MDE_RECT &this_rect)
{
this_rect.x = this_rect.y = this_rect.w = this_rect.h = 0;
}
bool MDE_RectRemoveOverlap(MDE_RECT& rect, const MDE_RECT& remove_rect)
{
if (!MDE_RectIntersects(rect, remove_rect))
return true;
MDE_RECT new_rect = { 0, 0, 0, 0 };
MDE_RECT remove = MDE_RectClip(remove_rect, rect);
int piece_count = 0;
// Top
if (remove.y > rect.y)
{
new_rect = MDE_MakeRect(rect.x, rect.y, rect.w, remove.y - rect.y);
piece_count++;
}
// Left
if (remove.x > rect.x)
{
new_rect = MDE_MakeRect(rect.x, remove.y, remove.x - rect.x, remove.h);
piece_count++;
}
// Right
if (remove.x + remove.w < rect.x + rect.w)
{
new_rect = MDE_MakeRect(remove.x + remove.w, remove.y, rect.x + rect.w - (remove.x + remove.w), remove.h);
piece_count++;
}
// Bottom
if (remove.y + remove.h < rect.y + rect.h)
{
new_rect = MDE_MakeRect(rect.x, remove.y + remove.h, rect.w, rect.y + rect.h - (remove.y + remove.h));
piece_count++;
}
// Only succeed if there was 1 new slice. Otherwise we have more than 2 rectangles totally.
if (piece_count == 1)
{
rect = new_rect;
return true;
}
return false;
}
// == MDE_BUFFER ============================================================
#if !defined(MDE_SUPPORT_HW_PAINTING) || defined(MDE_HW_SOFTWARE_FALLBACK)
#ifndef MDE_SUPPORT_HW_PAINTING
#define MDE_SOFTWARE_FUNCTION(func) func
#else
#define MDE_SOFTWARE_FUNCTION(func) func ## _soft
#endif
MDE_BUFFER* MDE_SOFTWARE_FUNCTION(MDE_CreateBuffer)(int w, int h, MDE_FORMAT format, int pal_len)
{
MDE_BUFFER *buf = OP_NEW(MDE_BUFFER, ());
if (!buf)
return NULL;
MDE_InitializeBuffer(w, h, MDE_GetBytesPerPixel(format) * w, format, NULL, NULL, buf);
buf->data = OP_NEWA(char, buf->stride * h);
if (pal_len)
buf->pal = OP_NEWA(unsigned char, pal_len * 3);
if (!buf->data || (pal_len && !buf->pal))
{
MDE_DeleteBuffer(buf);
return NULL;
}
return buf;
}
void MDE_SOFTWARE_FUNCTION(MDE_DeleteBuffer)(MDE_BUFFER *&buf)
{
if (buf)
{
char* data_ptr = (char*) buf->data;
OP_DELETEA(data_ptr);
OP_DELETEA(buf->pal);
OP_DELETE(buf);
buf = NULL;
}
}
void* MDE_SOFTWARE_FUNCTION(MDE_LockBuffer)(MDE_BUFFER *buf, const MDE_RECT &rect, int &stride, bool readable)
{
stride = buf->stride;
return ((char*)buf->data) + stride*rect.y + MDE_GetBytesPerPixel(buf->format)*rect.x;
}
void MDE_SOFTWARE_FUNCTION(MDE_UnlockBuffer)(MDE_BUFFER *buf, bool changed)
{}
#endif // !MDE_SUPPORT_HW_PAINTING || MDE_HW_SOFTWARE_FALLBACK
void MDE_MakeSubsetBuffer(const MDE_RECT &rect, MDE_BUFFER *subset_buf, MDE_BUFFER *parent_buf)
{
MDE_RECT outer_clip = MDE_RectClip(rect, parent_buf->outer_clip);
outer_clip.x -= rect.x;
outer_clip.y -= rect.y;
*subset_buf = *parent_buf;
if (parent_buf->data)
subset_buf->data = ((char *)parent_buf->data) + parent_buf->stride * rect.y + rect.x * parent_buf->ps;
subset_buf->outer_clip = outer_clip;
subset_buf->w = rect.w;
subset_buf->h = rect.h;
subset_buf->ofs_x = parent_buf->ofs_x + rect.x;
subset_buf->ofs_y = parent_buf->ofs_y + rect.y;
subset_buf->user_data = parent_buf->user_data;
MDE_SetClipRect(MDE_MakeRect(0, 0, rect.w, rect.h), subset_buf);
}
void MDE_OffsetBuffer(int dx, int dy, MDE_BUFFER *buf)
{
if (buf->data)
buf->data = ((char *)buf->data) + buf->stride * (-dy) - dx * buf->ps;
buf->outer_clip.x += dx;
buf->outer_clip.y += dy;
buf->clip.x += dx;
buf->clip.y += dy;
buf->ofs_x += dx;
buf->ofs_y += dy;
}
void MDE_InitializeBuffer(int w, int h, int stride, MDE_FORMAT format, void *data, unsigned char *pal, MDE_BUFFER *buf)
{
buf->data = data;
buf->pal = pal;
buf->w = w;
buf->h = h;
buf->stride = stride;
buf->ps = MDE_GetBytesPerPixel(format);
buf->format = format;
buf->clip = MDE_MakeRect(0, 0, w, h);
buf->outer_clip = buf->clip;
buf->ofs_x = 0;
buf->ofs_y = 0;
buf->user_data = NULL;
buf->col = 0;
buf->mask = 0;
buf->method = MDE_METHOD_COPY;
#ifdef MDE_BILINEAR_BLITSTRETCH
buf->stretch_method = MDE_DEFAULT_STRETCH_METHOD;
#endif
}
// == PAINTING ================================================================
#if !defined(MDE_SUPPORT_HW_PAINTING) || defined(MDE_HW_SOFTWARE_FALLBACK)
void MDE_SOFTWARE_FUNCTION(MDE_SetColor)(unsigned int col, MDE_BUFFER *dstbuf)
{
dstbuf->col = col;
}
void MDE_SOFTWARE_FUNCTION(MDE_SetClipRect)(const MDE_RECT &rect, MDE_BUFFER *dstbuf)
{
dstbuf->clip = MDE_RectClip(rect, dstbuf->outer_clip);
}
#ifdef USE_PREMULTIPLIED_ALPHA
void SetColorMap(unsigned int* col_map, unsigned int color);
#endif // USE_PREMULTIPLIED_ALPHA
void MDE_SOFTWARE_FUNCTION(MDE_DrawBufferData)(MDE_BUFFER_DATA *srcdata, MDE_BUFFER_INFO *srcinf, int src_stride, const MDE_RECT &dst, int srcx, int srcy, MDE_BUFFER *dstbuf)
{
if (!MDE_RectIntersects(dst, dstbuf->clip))
return;
if (srcinf->method == MDE_METHOD_COLOR)
{
if (!MDE_COL_A(srcinf->col))
return;
#ifdef USE_PREMULTIPLIED_ALPHA
if (srcinf->col == MDE_RGBA(0,0,0,0xff))
g_opera->libgogi_module.m_color_lookup = g_opera->libgogi_module.m_black_lookup;
else
{
g_opera->libgogi_module.m_color_lookup = g_opera->libgogi_module.m_generic_color_lookup;
if (g_opera->libgogi_module.m_color_lookup[256] != srcinf->col)
{
SetColorMap(g_opera->libgogi_module.m_color_lookup, srcinf->col);
g_opera->libgogi_module.m_color_lookup[256] = srcinf->col;
}
}
#endif // USE_PREMULTIPLIED_ALPHA
}
MDE_RECT r = dst;
MDE_RECT clip = dstbuf->clip;
// Destclipping
if(r.x < clip.x)
{
int diff = clip.x - r.x;
srcx += diff;
r.x += diff;
r.w -= diff;
}
if(r.y < clip.y)
{
int diff = clip.y - r.y;
srcy += diff;
r.y += diff;
r.h -= diff;
}
if(r.x + r.w > clip.x + clip.w)
{
int diff = (r.x + r.w) - (clip.x + clip.w);
r.w -= diff;
}
if(r.y + r.h > clip.y + clip.h)
{
int diff = (r.y + r.h) - (clip.y + clip.h);
r.h -= diff;
}
// Extreme sourceclipping
if(srcx < - r.w)
return;
if(srcy < - r.h)
return;
if(srcx > srcdata->w)
return;
if(srcy > srcdata->h)
return;
// Sourceclipping
if(srcx < 0)
{
int diff = - srcx;
srcx += diff;
r.x += diff;
r.w -= diff;
}
if(srcy < 0)
{
int diff = - srcy;
srcy += diff;
r.y += diff;
r.h -= diff;
}
if(srcx + r.w > srcdata->w)
{
int diff = (srcx + r.w) - srcdata->w;
r.w -= diff;
}
if(srcy + r.h > srcdata->h)
{
int diff = (srcy + r.h) - srcdata->h;
r.h -= diff;
}
// Check if there is something left
if (MDE_RectIsEmpty(r))
return;
MDE_SCANLINE_BLITNORMAL scanline = MDE_GetScanline_BlitNormal(dstbuf, srcinf->format);
bool MDE_Scanline_BlitNormal_unsupported(void *dst, void *src, int len, MDE_BUFFER_INFO *srcinf, MDE_BUFFER_INFO *dstinf);
MDE_ASSERT(scanline != MDE_Scanline_BlitNormal_unsupported);
int src_ps = MDE_GetBytesPerPixel(srcinf->format);
for(int j = 0; j < r.h; j++)
{
void *dstrow = ((char*)dstbuf->data) + r.x * dstbuf->ps + (j + r.y) * dstbuf->stride;
void *srcrow = ((char*)srcdata->data) + srcx * src_ps + (j + srcy) * src_stride;
scanline(dstrow, srcrow, r.w, srcinf, dstbuf);
}
}
void MDE_SOFTWARE_FUNCTION(MDE_DrawBufferDataStretch)(MDE_BUFFER_DATA *srcdata, MDE_BUFFER_INFO *srcinf, int src_stride, const MDE_RECT &dst, const MDE_RECT &src, MDE_BUFFER *dstbuf)
{
if (MDE_RectIsEmpty(dst))
return;
if (!MDE_RectIntersects(dst, dstbuf->clip))
return;
if (src.w <= 0 || src.h <= 0)
return;
MDE_RECT r = dst;
MDE_RECT clip = dstbuf->clip;
MDE_F1616 dx = ((MDE_F1616)src.w << 16) / dst.w;
MDE_F1616 dy = ((MDE_F1616)src.h << 16) / dst.h;
MDE_F1616 sx;
MDE_F1616 sy;
// Pre clipping of source start - since we can't allow sx/sy to be negative. We need 16.16 unsigned fixedpoint.
if (src.x < 0)
{
int diff = ((MDE_F1616)(-src.x << 16) - 1) / dx + 1;
// Assert we're adjusting by the precise amount needed.
MDE_ASSERT((int)((diff - 1) * dx >> 16) < -src.x);
MDE_ASSERT((int)(diff * dx >> 16) >= -src.x);
sx = diff * dx - (-src.x << 16);
r.x += diff;
r.w -= diff;
if (r.w <= 0) return;
}
else
{
sx = ((MDE_F1616)src.x << 16);
}
if (src.y < 0)
{
int diff = ((MDE_F1616)(-src.y << 16) - 1) / dy + 1;
// Assert we're adjusting by the precise amount needed.
MDE_ASSERT((int)((diff - 1) * dy >> 16) < -src.y);
MDE_ASSERT((int)(diff * dy >> 16) >= -src.y);
sy = diff * dy - (-src.y << 16);
r.y += diff;
r.h -= diff;
if (r.h <= 0) return;
}
else
{
sy = ((MDE_F1616)src.y << 16);
}
// Destclipping
if(r.x < clip.x)
{
int diff = clip.x - r.x;
sx += diff * dx;
r.x += diff;
r.w -= diff;
if (r.w <= 0) return;
}
if(r.y < clip.y)
{
int diff = clip.y - r.y;
sy += diff * dy;
r.y += diff;
r.h -= diff;
if (r.h <= 0) return;
}
if(r.x + r.w > clip.x + clip.w)
{
int diff = (r.x + r.w) - (clip.x + clip.w);
r.w -= diff;
if (r.w <= 0) return;
}
if(r.y + r.h > clip.y + clip.h)
{
int diff = (r.y + r.h) - (clip.y + clip.h);
r.h -= diff;
if (r.h <= 0) return;
}
// Sourceclipping
if (((sx + (MDE_F1616)(r.w - 1) * dx) >> 16) >= (unsigned long)srcdata->w)
{
if ((sx >> 16) >= (unsigned long)srcdata->w)
return; // completely outside
int diff = ((sx + (MDE_F1616)(r.w - 1) * dx) - ((unsigned long)srcdata->w << 16)) / dx + 1;
// Assert we're adjusting by the precise amount needed.
MDE_ASSERT(((sx + (MDE_F1616)(r.w - diff - 1) * dx) >> 16) < (unsigned long)srcdata->w);
MDE_ASSERT(((sx + (MDE_F1616)(r.w - diff) * dx) >> 16) >= (unsigned long)srcdata->w);
r.w -= diff;
if (r.w <= 0) return;
}
if (((sy + (MDE_F1616)(r.h - 1) * dy) >> 16) >= (unsigned long)srcdata->h)
{
if ((sy >> 16) >= (unsigned long)srcdata->h)
return; // completely outside
int diff = ((sy + (MDE_F1616)(r.h - 1) * dy) - ((unsigned long)srcdata->h << 16)) / dy + 1;
// Assert we're adjusting by the precise amount needed.
MDE_ASSERT(((sy + (MDE_F1616)(r.h - diff - 1) * dy) >> 16) < (unsigned long)srcdata->h);
MDE_ASSERT(((sy + (MDE_F1616)(r.h - diff) * dy) >> 16) >= (unsigned long)srcdata->h);
r.h -= diff;
if (r.h <= 0) return;
}
MDE_ASSERT(((sx + (r.w-1) * dx) >> 16) < (unsigned long)srcdata->w);
MDE_ASSERT(((sy + (r.h-1) * dy) >> 16) < (unsigned long)srcdata->h);
// Check if there is something left
#ifdef MDE_BILINEAR_BLITSTRETCH
// if this triggers a buffer not initialized with
// MDE_InitializeBuffer doesn't set stretch_method - please
// fix
OP_ASSERT(srcinf->stretch_method == MDE_STRETCH_BILINEAR || srcinf->stretch_method == MDE_STRETCH_NEAREST);
MDE_BILINEAR_INTERPOLATION_X interpolX = MDE_GetBilinearInterpolationX(srcinf->format);
MDE_BILINEAR_INTERPOLATION_Y interpolY = MDE_GetBilinearInterpolationY(srcinf->format);
if (interpolX && interpolY && srcinf->stretch_method == MDE_STRETCH_BILINEAR)
{
MDE_SCANLINE_BLITNORMAL scanline = MDE_GetScanline_BlitNormal(dstbuf, srcinf->format);
int currentScanline[2] = {-1, -1};
// allocate 3 scanlines
int tmpstride = r.w*MDE_GetBytesPerPixel(srcinf->format);
void* tmpbuf = op_malloc(3*tmpstride);
void* scanlineBuf[2] = {tmpbuf, ((unsigned char*)tmpbuf)+tmpstride};
if (tmpbuf)
{
// for all y values,
for (int y = 0; y < r.h; ++y)
{
// calculate the two scanlines to use (or one), reuse the existing ones
// merge the two scanlines
// do a regular, non-stretched blit
int sl = sy>>16;
void *dstrow = ((char*)dstbuf->data) + r.x * dstbuf->ps + (y + r.y) * dstbuf->stride;
void *srcrow = ((char*)srcdata->data) + sl * src_stride;
if (currentScanline[0] != sl)
{
if (currentScanline[1] == sl)
{
// swap 0 and 1
void* tmp = scanlineBuf[0];
scanlineBuf[0] = scanlineBuf[1];
scanlineBuf[1] = tmp;
currentScanline[1] = -1;
}
else
interpolX(scanlineBuf[0], srcrow, r.w, srcdata->w, sx, dx);
currentScanline[0] = sl;
}
if (sy&0xffff && sl+1 < srcdata->h)
{
if (currentScanline[1] != sl+1)
{
interpolX(scanlineBuf[1], ((char*)srcrow) + src_stride, r.w, srcdata->w, sx, dx);
currentScanline[1] = sl+1;
}
interpolY(((unsigned char*)tmpbuf)+2*tmpstride, scanlineBuf[0], scanlineBuf[1], r.w, sy&0xffff);
scanline(dstrow, ((unsigned char*)tmpbuf)+2*tmpstride, r.w, srcinf, dstbuf);
}
else
scanline(dstrow, scanlineBuf[0], r.w, srcinf, dstbuf);
sy += dy;
}
op_free(tmpbuf);
return;
}
}
#endif // MDE_BILINEAR_BLITSTRETCH
MDE_SCANLINE_BLITSTRETCH scanline = MDE_GetScanline_BlitStretch(dstbuf, srcinf->format);
for(int y = 0; y < r.h; y++)
{
void *dstrow = ((char*)dstbuf->data) + r.x * dstbuf->ps + (y + r.y) * dstbuf->stride;
void *srcrow = ((char*)srcdata->data) + (sy >> 16) * src_stride;
scanline(dstrow, srcrow, r.w, sx, dx, srcinf, dstbuf);
sy += dy;
}
}
void MDE_SOFTWARE_FUNCTION(MDE_DrawBuffer)(MDE_BUFFER *srcbuf, const MDE_RECT &dst, int srcx, int srcy, MDE_BUFFER *dstbuf)
{
MDE_SOFTWARE_FUNCTION(MDE_DrawBufferData)(srcbuf, srcbuf, srcbuf->stride, dst, srcx, srcy, dstbuf);
}
void MDE_SOFTWARE_FUNCTION(MDE_DrawBufferStretch)(MDE_BUFFER *srcbuf, const MDE_RECT &dst, const MDE_RECT &src, MDE_BUFFER *dstbuf)
{
MDE_SOFTWARE_FUNCTION(MDE_DrawBufferDataStretch)(srcbuf, srcbuf, srcbuf->stride, dst, src, dstbuf);
}
void MDE_SOFTWARE_FUNCTION(MDE_DrawRect)(const MDE_RECT &rect, MDE_BUFFER *dstbuf)
{
if (MDE_RectIsEmpty(rect))
return;
MDE_SCANLINE_SETCOLOR scanline = MDE_GetScanline_SetColor(dstbuf);
int x = MDE_MAX(dstbuf->clip.x, rect.x);
int w = MDE_MIN(dstbuf->clip.x + dstbuf->clip.w, rect.x + rect.w) - x;
if (MDE_RectContains(dstbuf->clip, dstbuf->clip.x, rect.y))
scanline(((char*)dstbuf->data) + x * dstbuf->ps + (rect.y) * dstbuf->stride, w, dstbuf->col);
if (MDE_RectContains(dstbuf->clip, dstbuf->clip.x, rect.y + rect.h - 1))
scanline(((char*)dstbuf->data) + x * dstbuf->ps + (rect.y + rect.h - 1) * dstbuf->stride, w, dstbuf->col);
int y1 = MDE_MAX(rect.y + 1, dstbuf->clip.y);
int y2 = MDE_MIN(rect.y + rect.h - 1, dstbuf->clip.y + dstbuf->clip.h);
for(int y = y1; y < y2; y++)
{
if (MDE_RectContains(dstbuf->clip, rect.x, y))
scanline(((char*)dstbuf->data) + rect.x * dstbuf->ps + y * dstbuf->stride, 1, dstbuf->col);
if (MDE_RectContains(dstbuf->clip, rect.x + rect.w - 1, y))
scanline(((char*)dstbuf->data) + (rect.x + rect.w - 1) * dstbuf->ps + y * dstbuf->stride, 1, dstbuf->col);
}
}
void MDE_SOFTWARE_FUNCTION(MDE_DrawRectFill)(const MDE_RECT &rect, MDE_BUFFER *dstbuf, bool blend)
{
MDE_RECT r = MDE_RectClip(rect, dstbuf->clip);
MDE_SCANLINE_SETCOLOR scanline = MDE_GetScanline_SetColor(dstbuf, blend);
for(int y = 0; y < r.h; y++)
scanline(((char*)dstbuf->data) + r.x * dstbuf->ps + (r.y + y) * dstbuf->stride, r.w, dstbuf->col);
}
void MDE_SOFTWARE_FUNCTION(MDE_DrawRectInvert)(const MDE_RECT &rect, MDE_BUFFER *dstbuf)
{
MDE_RECT r = MDE_RectClip(rect, dstbuf->clip);
MDE_SCANLINE_SETCOLOR scanline = MDE_GetScanline_InvertColor(dstbuf);
for(int y = 0; y < r.h; y++)
scanline(((char*)dstbuf->data) + r.x * dstbuf->ps + (r.y + y) * dstbuf->stride, r.w, 0);
}
void Symmetry(int x, int y, int a, int b, MDE_SCANLINE_SETCOLOR scanline, MDE_BUFFER *dstbuf, bool fill, int linewidth, const MDE_RECT &clip, int fix_x, int fix_y)
{
if (fill)
{
int x1 = MDE_MAX(clip.x, x - a);
int x2 = MDE_MIN(clip.x + clip.w, x + a - fix_x + 1);
if (x1 <= x2)
{
int top = y - b;
int bottom = y + b - fix_y;
if (top >= clip.y && top < clip.y + clip.h)
scanline(((char*)dstbuf->data) + x1 * dstbuf->ps + top * dstbuf->stride, x2-x1, dstbuf->col);
if (top != bottom && bottom >= clip.y && bottom < clip.y + clip.h)
scanline(((char*)dstbuf->data) + x1 * dstbuf->ps + bottom * dstbuf->stride, x2-x1, dstbuf->col);
}
}
else
{
int px[4] = { x - a,
x - a,
x + a - fix_x,
x + a - fix_x };
int py[4] = { y - b,
y + b - fix_y,
y + b - fix_y,
y - b };
int on[4] = { 1, 1, 1, 1 };
if (x - a == x + a - fix_x)
{
on[2] = 0;
on[3] = 0;
}
else if (y - b == y + b - fix_y)
{
on[1] = 0;
on[2] = 0;
}
if (linewidth > 1)
{
// FIX: Can be optimized
// FIX: Always align even thickness inside or outside
int half_linewidth = (linewidth >> 1);
for(int i = 0; i < 4; i++)
if (on[i])
MDE_DrawRectFill(MDE_MakeRect(px[i] - half_linewidth, py[i] - half_linewidth, linewidth, linewidth), dstbuf);
return;
}
for(int i = 0; i < 4; i++)
if (on[i] && MDE_RectContains(clip, px[i], py[i]))
scanline(((char*)dstbuf->data) + px[i] * dstbuf->ps + py[i] * dstbuf->stride, 1, dstbuf->col);
}
}
void Bresenham_Ellipse(const MDE_RECT &rect, MDE_BUFFER *dstbuf, bool fill, int linewidth, MDE_SCANLINE_SETCOLOR scanline)
{
if (rect.w <= 2 || rect.h <= 2)
{
// The ellipsedrawing code doesn't handle 2px width or height well (displays nothing)
// Use a filled rect, since that will give the same result anyway.
MDE_DrawRectFill(rect, dstbuf);
return;
}
// Bresenham algorithm. http://xarch.tu-graz.ac.at/home/rurban/news/comp.graphics.algorithms/ellipse_bresenham.html
// Modified to handle both odd/even widths/height and be filled.
int a = rect.w >> 1, b = rect.h >> 1;
int px = rect.x + a;
int py = rect.y + b;
int x, y, a2,b2, S, T, oldy;
int fix_x = a << 1 == rect.w;
int fix_y = b << 1 == rect.h;
if (MDE_RectIsEmpty(rect))
return;
a2 = b * b;
b2 = a * a;
x = a;
y = 0;
oldy = y - 1;
S = a2 * (1 - (a << 1)) + (b2 << 1);
T = b2 - (a2 << 1) * ((a << 1) - 1);
b2 = b2 << 1;
a2 = a2 << 1;
do
{
if (S < 0)
{
S += b2 * ((y << 1) + 3);
T += (b2 << 1) * (y + 1);
y++;
}
else if (T < 0)
{
S += b2 * ((y << 1) + 3) - (a2 << 1) * (x - 1);
T += (b2 << 1) * (y + 1) - a2 * ((x << 1) - 3);
y++;
x--;
}
else
{
S -= (a2 << 1) * (x - 1);
T -= a2 * ((x << 1) - 3);
x--;
}
if (!fill || y != oldy)
{
oldy = y;
Symmetry(px, py, x, y, scanline, dstbuf, fill, linewidth, dstbuf->clip, fix_x, fix_y);
}
}
while (x > 0);
if (!fix_y)
Symmetry(px, py, a, 0, scanline, dstbuf, fill, linewidth, dstbuf->clip, fix_x, fix_y);
}
void MDE_SOFTWARE_FUNCTION(MDE_DrawEllipse)(const MDE_RECT &rect, MDE_BUFFER *dstbuf)
{
MDE_SCANLINE_SETCOLOR scanline = MDE_GetScanline_SetColor(dstbuf);
Bresenham_Ellipse(rect, dstbuf, false, 1, scanline);
}
void MDE_SOFTWARE_FUNCTION(MDE_DrawEllipseThick)(const MDE_RECT &rect, int linewidth, MDE_BUFFER *dstbuf)
{
MDE_SCANLINE_SETCOLOR scanline = MDE_GetScanline_SetColor(dstbuf);
Bresenham_Ellipse(rect, dstbuf, false, linewidth, scanline);
}
void MDE_SOFTWARE_FUNCTION(MDE_DrawEllipseInvert)(const MDE_RECT &rect, MDE_BUFFER *dstbuf)
{
MDE_SCANLINE_SETCOLOR scanline = MDE_GetScanline_InvertColor(dstbuf);
Bresenham_Ellipse(rect, dstbuf, false, 1, scanline);
}
void MDE_SOFTWARE_FUNCTION(MDE_DrawEllipseFill)(const MDE_RECT &rect, MDE_BUFFER *dstbuf)
{
MDE_SCANLINE_SETCOLOR scanline = MDE_GetScanline_SetColor(dstbuf);
Bresenham_Ellipse(rect, dstbuf, true, 1, scanline);
}
void MDE_SOFTWARE_FUNCTION(MDE_DrawEllipseInvertFill)(const MDE_RECT &rect, MDE_BUFFER *dstbuf)
{
MDE_SCANLINE_SETCOLOR scanline = MDE_GetScanline_InvertColor(dstbuf);
Bresenham_Ellipse(rect, dstbuf, true, 1, scanline);
}
void Plot(int x, int y, int linewidth, MDE_SCANLINE_SETCOLOR scanline, MDE_BUFFER *dstbuf)
{
if (linewidth > 1)
{
// FIX: Can be optimized
int half_linewidth = (linewidth >> 1);
MDE_DrawRectFill(MDE_MakeRect(x - half_linewidth, y - half_linewidth, linewidth, linewidth), dstbuf);
}
else if (MDE_RectContains(dstbuf->clip, x, y))
scanline(((char*)dstbuf->data) + x * dstbuf->ps + y * dstbuf->stride, 1, dstbuf->col);
}
void Bresenham_DrawLine(int x1, int y1, int x2, int y2, int linewidth, MDE_BUFFER *dstbuf, MDE_SCANLINE_SETCOLOR scanline)
{
int minx = MDE_MIN(x1, x2);
int miny = MDE_MIN(y1, y2);
int maxx = MDE_MAX(x1, x2);
int maxy = MDE_MAX(y1, y2);
if (!MDE_RectIntersects(MDE_MakeRect(minx, miny, maxx - minx + 1, maxy - miny + 1), dstbuf->clip))
return;
// Bresenham algorithm
// http://www.ezresult.com/article/Bresenham's_line_algorithm_C_code
int i;
int steep = 1;
int sx, sy; // step positive or negative (1 or -1)
int dx, dy; // delta (difference in X and Y between points)
int e;
int tmpswap;
Plot(x2, y2, linewidth, scanline, dstbuf);
dx = MDE_ABS(x2 - x1);
sx = ((x2 - x1) > 0) ? 1 : -1;
dy = MDE_ABS(y2 - y1);
sy = ((y2 - y1) > 0) ? 1 : -1;
if (dy > dx)
{
steep = 0;
MDE_SWAP(tmpswap, x1, y1);
MDE_SWAP(tmpswap, dx, dy);
MDE_SWAP(tmpswap, sx, sy);
}
e = (dy << 1) - dx;
for (i = 0; i < dx; i++)
{
if (steep)
Plot(x1, y1, linewidth, scanline, dstbuf);
else
Plot(y1, x1, linewidth, scanline, dstbuf);
while (e >= 0)
{
y1 += sy;
e -= (dx << 1);
}
x1 += sx;
e += (dy << 1);
}
}
void MDE_SOFTWARE_FUNCTION(MDE_DrawLine)(int x1, int y1, int x2, int y2, MDE_BUFFER *dstbuf)
{
MDE_SCANLINE_SETCOLOR scanline = MDE_GetScanline_SetColor(dstbuf);
Bresenham_DrawLine(x1, y1, x2, y2, 1, dstbuf, scanline);
}
void MDE_SOFTWARE_FUNCTION(MDE_DrawLineThick)(int x1, int y1, int x2, int y2, int linewidth, MDE_BUFFER *dstbuf)
{
MDE_SCANLINE_SETCOLOR scanline = MDE_GetScanline_SetColor(dstbuf);
Bresenham_DrawLine(x1, y1, x2, y2, linewidth, dstbuf, scanline);
}
void MDE_SOFTWARE_FUNCTION(MDE_DrawLineInvert)(int x1, int y1, int x2, int y2, MDE_BUFFER *dstbuf)
{
MDE_SCANLINE_SETCOLOR scanline = MDE_GetScanline_InvertColor(dstbuf);
Bresenham_DrawLine(x1, y1, x2, y2, 1, dstbuf, scanline);
}
#ifdef MDE_INTERNAL_MEMCPY_SCROLL
void MDE_MemCpy32(unsigned int *dst, unsigned int *src, int len)
{
switch(len & 7)
{
while(len > 0)
{
case 0: *dst++ = *src++;
case 7: *dst++ = *src++;
case 6: *dst++ = *src++;
case 5: *dst++ = *src++;
case 4: *dst++ = *src++;
case 3: *dst++ = *src++;
case 2: *dst++ = *src++;
case 1: *dst++ = *src++;
len -= 8;
}
}
}
void MDE_MemCpy16(unsigned short *dst, unsigned short *src, int len)
{
switch(len & 7)
{
while(len > 0)
{
case 0: *dst++ = *src++;
case 7: *dst++ = *src++;
case 6: *dst++ = *src++;
case 5: *dst++ = *src++;
case 4: *dst++ = *src++;
case 3: *dst++ = *src++;
case 2: *dst++ = *src++;
case 1: *dst++ = *src++;
len -= 8;
}
}
}
#endif // MDE_INTERNAL_MEMCPY_SCROLL
void MDE_SOFTWARE_FUNCTION(MDE_MoveRect)(const MDE_RECT &rect, int dx, int dy, MDE_BUFFER *dstbuf)
{
MDE_RECT r = rect;
r.x -= dx;
r.y -= dy;
r = MDE_RectClip(r, dstbuf->outer_clip);
r.x += dx;
r.y += dy;
r = MDE_RectClip(r, dstbuf->outer_clip);
if (r.w <= 0 || r.h <= 0)
return;
char* dstrow = ((char*)dstbuf->data) + r.x * dstbuf->ps + r.y * dstbuf->stride;
char* srcrow = dstrow - dx * dstbuf->ps - dy * dstbuf->stride;
#ifdef MDE_USE_MEMCPY_SCROLL
if (dx == 0)
{
#ifdef MDE_INTERNAL_MEMCPY_SCROLL
if (dstbuf->ps == 4)
{
if (dy > 0)
{
for(int y = r.h - 1; y >= 0; y--)
MDE_MemCpy32((unsigned int *)(dstrow + y * dstbuf->stride), (unsigned int *)(srcrow + y * dstbuf->stride), r.w);
}
else
{
for(int y = 0; y < r.h; y++)
MDE_MemCpy32((unsigned int *)(dstrow + y * dstbuf->stride), (unsigned int *)(srcrow + y * dstbuf->stride), r.w);
}
}
else if (dstbuf->ps == 2)
{
if (dy > 0)
{
for(int y = r.h - 1; y >= 0; y--)
MDE_MemCpy16((unsigned short *)(dstrow + y * dstbuf->stride), (unsigned short *)(srcrow + y * dstbuf->stride), r.w);
}
else
{
for(int y = 0; y < r.h; y++)
MDE_MemCpy16((unsigned short *)(dstrow + y * dstbuf->stride), (unsigned short *)(srcrow + y * dstbuf->stride), r.w);
}
}
else
#endif // MDE_INTERNAL_MEMCPY_SCROLL
{
if (dy > 0)
{
for(int y = r.h - 1; y >= 0; y--)
op_memcpy(dstrow + y * dstbuf->stride, srcrow + y * dstbuf->stride, r.w * dstbuf->ps);
}
else
{
for(int y = 0; y < r.h; y++)
op_memcpy(dstrow + y * dstbuf->stride, srcrow + y * dstbuf->stride, r.w * dstbuf->ps);
}
}
}
else
#endif // MDE_USE_MEMCPY_SCROLL
{
if ((r.w + MDE_ABS(dx)) * dstbuf->ps == dstbuf->stride)
{
const size_t n = r.h * dstbuf->stride - MDE_ABS(dx) * dstbuf->ps;
MDE_ASSERT(dstrow >= (char*)dstbuf->data && dstrow + n <= (char*)dstbuf->data + dstbuf->stride * dstbuf->h);
MDE_ASSERT(srcrow >= (char*)dstbuf->data && srcrow + n <= (char*)dstbuf->data + dstbuf->stride * dstbuf->h);
// It should be faster to do only one call than several.
MDE_GfxMove(dstrow, srcrow, n);
}
else
{
if (dy > 0)
{
for(int y = r.h - 1; y >= 0; y--)
MDE_GfxMove(dstrow + y * dstbuf->stride, srcrow + y * dstbuf->stride, r.w * dstbuf->ps);
}
else
{
for(int y = 0; y < r.h; y++)
MDE_GfxMove(dstrow + y * dstbuf->stride, srcrow + y * dstbuf->stride, r.w * dstbuf->ps);
}
}
}
}
#endif // !MDE_SUPPORT_HW_PAINTING
|
// Copyright (c) 2012-2017 The Cryptonote developers
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <thread>
#include <System/Context.h>
#include <System/Dispatcher.h>
#include <System/ContextGroup.h>
#include <System/Event.h>
#include <System/InterruptedException.h>
#include <System/Timer.h>
#include <gtest/gtest.h>
using namespace platform_system;
class TimerTests : public testing::Test {
public:
TimerTests() : contextGroup(dispatcher) {
}
Dispatcher dispatcher;
ContextGroup contextGroup;
};
TEST_F(TimerTests, timerIsWorking) {
bool done = false;
contextGroup.spawn([&]() {
done = true;
});
ASSERT_FALSE(done);
Timer(dispatcher).sleep(std::chrono::milliseconds(10));
ASSERT_TRUE(done);
}
TEST_F(TimerTests, movedTimerIsWorking) {
Timer t{Timer{dispatcher}};
bool done = false;
contextGroup.spawn([&]() {
done = true;
});
ASSERT_FALSE(done);
t.sleep(std::chrono::milliseconds(10));
ASSERT_TRUE(done);
}
TEST_F(TimerTests, movedAndStoopedTimerIsWorking) {
contextGroup.spawn([&] {
Timer src(dispatcher);
contextGroup.interrupt();
Timer t(std::move(src));
ASSERT_ANY_THROW(t.sleep(std::chrono::milliseconds(1)));
});
}
TEST_F(TimerTests, doubleTimerTest) {
auto begin = std::chrono::high_resolution_clock::now();
Event first(dispatcher);
Event second(dispatcher);
Context<> context(dispatcher, [&] {
Timer(dispatcher).sleep(std::chrono::milliseconds(100));
first.set();
});
Context<> contextSecond(dispatcher, [&] {
Timer(dispatcher).sleep(std::chrono::milliseconds(200));
second.set();
});
first.wait();
second.wait();
ASSERT_GE(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - begin).count(), 150);
ASSERT_TRUE((std::chrono::high_resolution_clock::now() - begin) < std::chrono::milliseconds(275));
}
TEST_F(TimerTests, doubleTimerTestGroup) {
auto begin = std::chrono::high_resolution_clock::now();
Event first(dispatcher);
Event second(dispatcher);
contextGroup.spawn([&] {
Timer(dispatcher).sleep(std::chrono::milliseconds(100));
first.set();
});
contextGroup.spawn([&] {
Timer(dispatcher).sleep(std::chrono::milliseconds(200));
second.set();
});
first.wait();
second.wait();
ASSERT_GE(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - begin).count(), 150);
ASSERT_TRUE((std::chrono::high_resolution_clock::now() - begin) < std::chrono::milliseconds(250));
}
TEST_F(TimerTests, doubleTimerTestGroupWait) {
auto begin = std::chrono::high_resolution_clock::now();
contextGroup.spawn([&] {
Timer(dispatcher).sleep(std::chrono::milliseconds(100));
});
contextGroup.spawn([&] {
Timer(dispatcher).sleep(std::chrono::milliseconds(200));
});
contextGroup.wait();
ASSERT_GE(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - begin).count(), 150);
ASSERT_TRUE((std::chrono::high_resolution_clock::now() - begin) < std::chrono::milliseconds(250));
}
TEST_F(TimerTests, doubleTimerTestTwoGroupsWait) {
auto begin = std::chrono::high_resolution_clock::now();
ContextGroup cg(dispatcher);
cg.spawn([&] {
Timer(dispatcher).sleep(std::chrono::milliseconds(100));
});
contextGroup.spawn([&] {
Timer(dispatcher).sleep(std::chrono::milliseconds(200));
});
contextGroup.wait();
ASSERT_GE(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - begin).count(), 150);
ASSERT_TRUE((std::chrono::high_resolution_clock::now() - begin) < std::chrono::milliseconds(275));
}
TEST_F(TimerTests, movedTimerIsWorking2) {
bool done = false;
contextGroup.spawn([&] {
Timer t(dispatcher);
t = Timer{dispatcher};
//contextGroup.spawn([&]() { done = true; });
ASSERT_FALSE(done);
t.sleep(std::chrono::milliseconds(10));
ASSERT_TRUE(done);
});
contextGroup.spawn([&]() {
done = true;
});
contextGroup.wait();
}
TEST_F(TimerTests, movedAndStoopedTimerIsWorking2) {
contextGroup.spawn([&] {
Timer src(dispatcher);
contextGroup.interrupt();
Timer t(dispatcher);
t = std::move(src);
ASSERT_ANY_THROW(t.sleep(std::chrono::milliseconds(1)));
});
}
TEST_F(TimerTests, movedTimerIsTheSame) {
contextGroup.spawn([&] {
Timer timer(dispatcher);
auto timerPtr1 = &timer;
Timer srcEvent(dispatcher);
timer = std::move(srcEvent);
auto timerPtr2 = &timer;
ASSERT_EQ(timerPtr1, timerPtr2);
});
}
TEST_F(TimerTests, timerStartIsWorking) {
contextGroup.spawn([&] {
Timer t(dispatcher);
contextGroup.interrupt();
ASSERT_ANY_THROW(t.sleep(std::chrono::milliseconds(1)));
ASSERT_NO_THROW(t.sleep(std::chrono::milliseconds(1)));
});
}
TEST_F(TimerTests, timerStopBeforeSleep) {
contextGroup.spawn([&] {
Timer t(dispatcher);
contextGroup.interrupt();
ASSERT_THROW(t.sleep(std::chrono::milliseconds(1)), InterruptedException);
contextGroup.interrupt();
ASSERT_THROW(t.sleep(std::chrono::milliseconds(1)), InterruptedException);
});
}
TEST_F(TimerTests, timerIsCancelable) {
contextGroup.spawn([&] {
Timer t(dispatcher);
ASSERT_THROW(t.sleep(std::chrono::milliseconds(100)), InterruptedException);
});
contextGroup.spawn([&]() {
contextGroup.interrupt();
});
}
// Disabled, because on OS X it is currently impossible to distinguish timer timeout and interrupt
TEST_F(TimerTests, DISABLED_sleepThrowsOnlyIfTimerIsStoppedBeforeTime1) {
contextGroup.spawn([&] {
Timer t(dispatcher);
ASSERT_NO_THROW(t.sleep(std::chrono::milliseconds(1)));
ASSERT_THROW(t.sleep(std::chrono::milliseconds(1)), InterruptedException);
});
contextGroup.spawn([&]() {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
contextGroup.interrupt();
});
}
TEST_F(TimerTests, sleepIsSleepingAtLeastTakenTime) {
auto timepoint1 = std::chrono::high_resolution_clock::now();
contextGroup.spawn([&] {
Timer(dispatcher).sleep(std::chrono::milliseconds(100));
});
contextGroup.wait();
auto timepoint2 = std::chrono::high_resolution_clock::now();
ASSERT_LE(95, std::chrono::duration_cast<std::chrono::milliseconds>(timepoint2 - timepoint1).count());
}
TEST_F(TimerTests, timerIsReusable) {
Timer t(dispatcher);
auto timepoint1 = std::chrono::high_resolution_clock::now();
contextGroup.spawn([&] {
ASSERT_NO_THROW(t.sleep(std::chrono::seconds(1)));
});
contextGroup.wait();
auto timepoint2 = std::chrono::high_resolution_clock::now();
contextGroup.spawn([&] {
ASSERT_NO_THROW(t.sleep(std::chrono::seconds(1)));
});
contextGroup.wait();
auto timepoint3 = std::chrono::high_resolution_clock::now();
ASSERT_LE(950, std::chrono::duration_cast<std::chrono::milliseconds>(timepoint2 - timepoint1).count());
ASSERT_LE(950, std::chrono::duration_cast<std::chrono::milliseconds>(timepoint3 - timepoint2).count());
}
TEST_F(TimerTests, timerIsReusableAfterInterrupt) {
contextGroup.spawn([&] {
Timer t(dispatcher);
contextGroup.interrupt();
auto timepoint1 = std::chrono::high_resolution_clock::now();
ASSERT_THROW(t.sleep(std::chrono::seconds(1)), InterruptedException);
auto timepoint2 = std::chrono::high_resolution_clock::now();
ASSERT_NO_THROW(t.sleep(std::chrono::seconds(1)));
auto timepoint3 = std::chrono::high_resolution_clock::now();
ASSERT_LE(0, std::chrono::duration_cast<std::chrono::milliseconds>(timepoint2 - timepoint1).count());
ASSERT_LE(950, std::chrono::duration_cast<std::chrono::milliseconds>(timepoint3 - timepoint2).count());
});
}
TEST_F(TimerTests, timerWithZeroTimeIsYielding) {
bool done = false;
contextGroup.spawn([&]() {
done = true;
});
ASSERT_FALSE(done);
Timer(dispatcher).sleep(std::chrono::milliseconds(0));
ASSERT_TRUE(done);
}
|
/****************************************************************
File Name: cutil.C
Author: Tian Zhang, CS Dept., Univ. of Wisconsin-Madison, 1995
Copyright(c) 1995 by Tian Zhang
All Rights Reserved
Permission to use, copy and modify this software must be granted
by the author, provided that the above copyright notice appear in
all relevant copies and that both that copyright notice and this
permission notice appear in all relevant supporting documentations.
Comments and additions may be sent the author at zhang@cs.wisc.edu.
******************************************************************/
#include "global.h"
#include "util.h"
#include "vector.h"
#include "rectangle.h"
#include "parameter.h"
#include "cfentry.h"
#include "status.h"
#include "cftree.h"
#include "cutil.h"
double distance(short dtype, const Entry &ent1, const Entry &ent2)
{
switch (dtype) {
case D0: return (ent1 || ent2);
case D1: return (ent1 ^ ent2);
case D2: return (ent1 | ent2);
case D3: return (ent1 & ent2);
case D4: return (ent1 && ent2);
default: print_error("distance","Invalid distance type"); return 0;
}
}
double fitness(short ftype, const Entry &ent1, const Entry &ent2)
{
switch (ftype) {
case AVG_DIAMETER: return (ent1 & ent2);
default: print_error("fitness","Invalid fitness type"); return 0;
}
}
void ClosestTwoOut(Entry *tmpentry, int head, int tail,
short dtype, int &i, int &j)
{
int i1,j1,imin,jmin;
double d, dmin;
if (tail-head<1)
print_error("ClosestTwoOut3","Less than 2 entries");
if (tail-head==1)
{i=head; j=tail; return;}
imin = head;
jmin = head+1;
dmin = distance(dtype,tmpentry[imin],tmpentry[jmin]);
for (i1=head;i1<tail;i1++)
for (j1=i1+1;j1<=tail;j1++) {
d = distance(dtype,tmpentry[i1],tmpentry[j1]);
if (d<dmin) {
imin = i1;
jmin = j1;
dmin = d;}
}
i=imin; j=jmin;
}
void FarthestTwoOut(Entry *tmpentry, int head, int tail,
short dtype, int &i, int &j)
{
int i1,j1,imax,jmax;
double d, dmax;
if (tail-head<1)
print_error("FarthestTwoOut3","Less than 2 entries");
if (tail-head==1)
{i=head; j=tail; return;}
imax = head;
jmax = head+1;
dmax = distance(dtype,tmpentry[imax],tmpentry[jmax]);
for (i1=head;i1<tail;i1++)
for (j1=i1+1;j1<=tail;j1++) {
d = distance(dtype,tmpentry[i1],tmpentry[j1]);
if (d>dmax) {
imax = i1;
jmax = j1;
dmax = d;}
}
i=imax; j=jmax;
}
double Quality(short qtype, const int NumCluster, const Entry *Clusters) {
switch (qtype) {
case OVERALL_AVG_DIAMETER: return Quality1(NumCluster,Clusters);
case OVERALL_AVG_RADIUS: return Quality2(NumCluster,Clusters);
default: print_error("Quality","Invalid quality type");return 0;
}
}
double Quality1(const int NumCluster, const Entry *Clusters) {
int i;
double cnt_all=0.0, sum_all=0.0, tmp0,tmp1;
for (i=0; i<NumCluster; i++) {
tmp0 = Clusters[i].n*(Clusters[i].n-1.0);
tmp1 = 2*Clusters[i].n*Clusters[i].sxx-2*(Clusters[i].sx&&Clusters[i].sx);
cnt_all += tmp0;
sum_all += tmp1;
#ifdef DEBUG
logfile << "cluster " << i << " with " << Clusters[i].n << " points\n";
if (Clusters[i].n==1) logfile << "quality: 0\n" ;
else logfile << "quality: " << sqrt(tmp1/tmp0) << endl;
#endif DEBUG
}
return(sqrt(sum_all/cnt_all));
}
double Quality2(const int NumCluster, const Entry *Clusters) {
int i;
double cnt_all=0.0, sum_all=0.0, tmp0,tmp1,tmp2;
for (i=0; i<NumCluster; i++) {
tmp1 = 0;
for (short j=0; j<Clusters[i].sx.dim; j++) {
tmp0 = Clusters[i].sx.value[j]/Clusters[i].n;
tmp1 += tmp0*tmp0;
}
tmp2 = Clusters[i].sxx - Clusters[i].n*tmp1;
cnt_all += Clusters[i].n;
sum_all += tmp2;
#ifdef DEBUG
logfile << "cluster " << i << " with " << Clusters[i].n << " points\n";
if (Clusters[i].n==1) logfile << "quality: 0\n" ;
else logfile << "quality: " << sqrt(tmp2/Clusters[i].n) << endl;
#endif DEBUG
}
return(sqrt(sum_all/cnt_all));
}
|
#include "temp_controller.h"
#include "http_request.h"
#include "screen1.h"
#include <ESP32Encoder.h>
void TempController::init()
{
// Update the encoder position based on the new set temp.
_encoder.setCount(_temp_to_count(_set_temp));
} // init()
bool TempController::update()
{
// Early return if it isn't time to do something
if ( !_upd_timer.expired() )
return false;
// Check to see if the encoder position has changed.
static unsigned long oldPosition = _encoder.getCount();
unsigned long newPosition = oldPosition;
newPosition = _encoder.getCount();
if ( newPosition != oldPosition )
{
// Detected knob movement
_position_changing = true;
_position_changing_tmr.reset();
oldPosition = newPosition;
Serial.println("Position: " + String(newPosition));
if ( _count_to_temp(newPosition) > MAX_SAFE_TEMP )
newPosition = _temp_to_count(MAX_SAFE_TEMP);
else if ( _count_to_temp(newPosition) < MIN_SAFE_TEMP )
newPosition = _temp_to_count(MIN_SAFE_TEMP);
_set_temp = _count_to_temp(newPosition);
}
else if ( _position_changing )
{
// Knob is not moving. Check to see if the movement has stopped.
if ( _position_changing_tmr.expired() )
{
_position_changing = false;
// Send updated set temperature (living_room_set_temp) to server.
send_controller_set_temp("lr_temp", _set_temp);
// Get the current temperature here. Send controller should have returned it, but
// that isn't working for some reason.
_set_temp = get_controller_set_temp("lr_temp");
_temp_srvr_req_tmr.reset();
}
}
// Retrieve the current set temperature from the server, but only if the user
// isn't actively turning the knob.
// @TODO: This will happen every 100 msec as currently written! Need to do it immediately
// after a set operation, but only once every 5 seconds or so thereafter.
if ( !_position_changing && _temp_srvr_req_tmr.expired() )
{
// Get the current temperature here.
auto set_t = get_controller_set_temp("lr_temp");
if ( set_t > 0.0 )
{
_set_temp = set_t;
}
_temp_srvr_req_tmr.reset();
}
// Update the encoder position based on the new set temp.
_encoder.setCount(_temp_to_count(_set_temp));
// Update the display with the set temp
if ( _display != nullptr )
{
_display->update(_set_temp);
}
return true;
} //update()
|
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int size, x, y, temp;
char arr[100];
cout << "Enter Array Size: ";
cin >> size;
cout << "\nEnter " << size << " characters: ";
for(x=0; x<size; x++)
{
cin >> arr[x];
}
y = x - 1;
x = 0;
while(x<y)
{
temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
x++;
y--;
}
cout<<"\nThe Reverse of the Array is : ";
for(x=0; x<size; x++)
{
cout << arr[x]<<" ";
}
getch();
return 0;
}
|
#include "utils/file/filewriter.h"
#include <iostream>
#include <fstream> // TODO: Re-implement as my own?
#include <stdio.h>
namespace utils {
namespace file {
namespace filewriter {
} // namespace filewriter
} // namespace file
} // namespace utils
|
#include "SpringObject.h"
using namespace std;
SpringObject::SpringObject():SelectGravityObject()
{
}
SpringObject::SpringObject(int weight, Vector* position, Vector* speed, Vector* acceleration, map<GravityObject*,vector<double> >* links):SelectGravityObject(weight, position, speed, acceleration), _links(links)
{
}
SpringObject::SpringObject(const SpringObject &gravObj):SelectGravityObject(static_cast<SelectGravityObject>(gravObj)), _links(gravObj.getLinks())
{
}
SpringObject::~SpringObject()
{
delete _position, _speed, _acceleration, _links;
}
map<GravityObject*,vector<double> >* SpringObject::getLinks() const
{
return _links;
}
/**
* Attractive gravitation (null if we are in the object) plus spring effect (links)
*/
Vector* SpringObject::getInfluenceFor(const GravityObject* gravObj)
{
double distance = (_position->squareDistanceTo(*(gravObj->getPosition())));
double acceleration;
if(distance<_weight/2) return new Vector();
acceleration = GravityObject::G*_weight*gravObj->getWeight()/distance;
Vector* v = new Vector(*(gravObj)->getPosition());
//NOTICE memory leak !!!!! *t+=(*_position-*v);
Vector* t = new Vector(*_position);
*t-=*v;
Vector* k = new Vector(*t);
delete v;
t->multiply(-acceleration);
if(_links!=0) {
if((*_links).find(const_cast<GravityObject*>(gravObj))!=(*_links).end())
{
vector<double> spring = (*((*_links).find(const_cast<GravityObject*>(gravObj)))).second;
k->normalize();
k->multiply(spring[0]*(sqrt(distance)-spring[1]));
// cout <<sqrt(distance)-spring[1]<<endl;
}
*t+=*k;
}
delete k;
return t;
}
void SpringObject::calculateGravityAcceleration(const vector<GravityObject*> &universe)
{
_temporaryAcceleration = new Vector();
vector<GravityObject*>::const_iterator gravObjPtr;
for (gravObjPtr = universe.begin(); gravObjPtr != universe.end(); ++gravObjPtr)
{
if ((*gravObjPtr)!=this) //TODO fusion ? //TODO pas de gravité à l'intérieur
{
if(_links!=0) {
if((*_links).find(const_cast<GravityObject*>(*gravObjPtr))!=(*_links).end())
{
Vector* t = this->getInfluenceFor(*gravObjPtr);
*_temporaryAcceleration-=*t;
delete t;
}
}
}
}
}
|
//算法:贪心
//对每个人按照接水时间升序排序, 时间相同则按照序号升序排序
//因为要让平均值最小,即使所有人等待时间之和最小
//就需要让时间小的先接完水,
//把较小的等待时间累加到需要时间较多的人身上
//排序后顺序即题目要求的接水顺序
//计算后输出即可
#include<cstdio>
#include<algorithm>
using namespace std;
struct baka//存每个人编号与时间
{
int data,bian;
}a[1010];
bool cmp(baka x,baka y)//排序比较函数
{
if(x.data==y.data)
return x.bian>y.bian;
return x.data>y.data;
}
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)//输入
{
a[i].bian=i+1;
scanf("%d",&a[i].data);
}
double ans=0;
sort(a,a+n,cmp);//排序
for(int i=0;i<n;i++)//按顺序输出,计算.
{
printf("%d ",a[n-i-1].bian);
ans+=i*a[i].data;
}
printf("\n%.2lf",ans/n);
}
|
#pragma once
#include "../nt.h"
#include "../../driver/gina.h"
#include <string>
namespace gina
{
namespace driver
{
constexpr const auto device_path = L"\\Device\\Null";
static nt::handle handle = {};
bool open();
void close();
bool opened();
bool is_present();
std::uintptr_t get_image_base(unsigned long process_id);
std::uintptr_t get_peb_address(unsigned long process_id);
bool read(unsigned long process_id, std::uintptr_t address, void* buffer, std::size_t size);
bool write(unsigned long process_id, std::uintptr_t address, void* buffer, std::size_t size);
std::uintptr_t allocate(unsigned long process_id, std::uintptr_t base_address, std::size_t size, unsigned long type, unsigned long protect);
bool free(unsigned long process_id, std::uintptr_t base_address, std::size_t size, unsigned long type);
bool remove_nx(unsigned long process_id, std::uintptr_t base_address, std::size_t size);
template <typename T>
T read(unsigned long process_id, std::uintptr_t address)
{
T buffer;
if (read(process_id, address, &buffer, sizeof(T)))
{
return buffer;
}
return {};
}
template <typename T>
void write(unsigned long process_id, std::uintptr_t address, const T& buffer)
{
write(process_id, address, &buffer, sizeof(T));
}
inline bool ioctl_present();
inline bool ioctl_unload();
inline bool ioctl_clear_unloaded(ioctl_code_clear_unloaded_parameters& parameters);
inline bool ioctl_image_base(ioctl_image_base_parameters& parameters);
inline bool ioctl_peb(ioctl_peb_parameters& paramaters);
inline bool ioctl_copy_memory(ioctl_copy_memory_parameters& parameters);
inline bool ioctl_allocate_memory(ioctl_allocate_memory_parameters& parameters);
inline bool ioctl_free_memory(ioctl_free_memory_parameters& parameters);
inline bool ioctl_remove_nx(ioctl_remove_nx_parameters& parameters);
}
}
|
#include <TinyGPS++.h>
#include "HX711.h"
TinyGPSPlus gps;
#define trigPin 12
#define echoPin 11
#define DOUT A3
#define CLK A2
HX711 scale(DOUT, CLK);
float calibration_factor = 182540;
String Message;
int d;
int duration, distance, binweight;
int MQ7map;
float flat,flon;
String lat, lon, flag;
unsigned long age;
bool newData = false;
#include <SoftwareSerial.h>
SoftwareSerial mySerial(9, 10 ); //RX, TX
SoftwareSerial myGps(3, 4); //RX, TX
void setup() {
Serial.begin(9600);
mySerial.begin(9600);
myGps.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
scale.set_scale();
scale.tare(); //Reset the scale to 0
long zero_factor = scale.read_average(); //Get a baseline reading
Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
Serial.println(zero_factor);
}
void loop() {
values();
delay(1000);
getGPSdata();
delay(1000);
sendcmd();
delay(1000);
}
void values(){
digitalWrite(trigPin, HIGH);
delay(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) * 0.0343;
Serial.print("distance=");
Serial.println(distance);
scale.set_scale(calibration_factor); //Adjust to this calibration factor
binweight=scale.get_units()*453;
Serial.print("Reading: ");
Serial.print(binweight);
Serial.println(" grams");
int MQ7=analogRead(A2);
MQ7map=map(MQ7,0,1023,0,100);
Serial.print("MQ7 Value is: ");
Serial.println(MQ7map);
}
void getGPSdata(){
flat = gps.location.lat();
lat = String(flat,6);
Serial.print("Latitude : ");
Serial.println(lat);
flon = gps.location.lng();
lon = String(flon,6);
Serial.print("Latitude : ");
Serial.println(lon);
smartDelay(1000);
if (millis() > 5000 && gps.charsProcessed() < 10)
Serial.println(F("No GPS data received: check wiring"));
}
static void smartDelay(unsigned long ms) // This custom version of delay() ensures that the gps object is being "fed".
{
unsigned long start = millis();
do
{
while (myGps.available())
gps.encode(myGps.read());
} while (millis() - start < ms);
}
void sendcmd(){
String cmd = "#&field1="+String(lat)+"&field2="+String(lon)+"&field3="+String(distance)+"&field4="+String(binweight)+"&field5="+String(MQ7map);
Serial.println(cmd);
Serial.println(cmd.length());
mySerial.println(cmd);
}
|
#ifndef CAFFE_DXY_TEMP_LAYER_HPP_
#define CAFFE_DXY_TEMP_LAYER_HPP_
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "boost/dynamic_bitset.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
using boost::dynamic_bitset;
/**
* @brief According to the First input blob , Maks the second blob .
* Output: First is the masked blob(2th) , using Threshold calculate the Ground Truth. channels -> 1
* Second is the masked blob(2th) , masked by the First input blob..
*
* TODO(dox): thorough documentation for Forward, Backward, and proto params.
*
*/
template <typename Dtype>
class DXYTempLayer : public Layer<Dtype> {
public:
explicit DXYTempLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "DXYTempLayer"; }
virtual inline int ExactNumBottomBlobs() const { return 2; }
virtual inline int ExactNumTopBlobs() const { return 2; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
//Dtype Threshold;
//Dtype Confidence_For_Test;
Dtype mask_ratio;
shared_ptr<Blob<Dtype> > sum_value;
};
} // namespace caffe
#endif // CAFFE_DXY_TEMP_LAYER_HPP_
|
//
// Created by abel_ on 29-06-2022.
//
/*
* PROBLEM LINK : https://www.codechef.com/problems/MAXORMIN
* PROBLEM CODE : MAXORMIN
*/
#include <bits/stdc++.h>
using namespace std;
int main(){
int T;
cin >> T;
while(T--){
long long int N;
cin >> N;
vector<long long int> ones;
vector<long long int> zeros;
for(long long int i = 0; i < N; i++){
long long int x;
cin >> x;
if(x == 1){
ones.push_back(x);
}
else{
zeros.push_back(x);
}
}
/* A_i = {0,1}
* Alice want to maximise , Bob minimise
* Alice will do XOR of any 2 elements of A_i
* 0 OR 0 = 0
* 0 OR 1 = 1
* 1 OR 0 = 1
* 1 OR 1 = 1
* Bob will do AND of any 2 elements of A_i
* 0 AND 0 = 0
* 0 AND 1 = 0
* 1 AND 0 = 0
* 1 AND 1 = 1
* Alice has first turn
* */
int count = 1;
while(ones.size() > 0 || zeros.size() > 0) {
if (ones.size() == 1 && zeros.size() == 0) {
cout << 1 << endl;
break;
}
if (ones.size() == 0 && zeros.size() == 1) {
cout << 0 << endl;
break;
}
if (count % 2 == 1 && zeros.size()>0) {
// remove one 0 from zeros
zeros.erase(zeros.begin());
} else {
// remove one 1 from ones
if(ones.size() > 0){
ones.erase(ones.begin());
}
}
count++;
}
}
return 0;
}
|
#define _REENTRANT
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/sem.h>
int signal = 0;
char buffer[1000];
void *function(void *args);
int main()
{
pthread_t a_thread;
int res;
res = pthread_create(&a_thread, NULL, function, NULL);
if(res != NULL)
{
printf("create thread function failed");
exit(-1);
}
while(1)
{
fflush(stdout);
if(signal)
{
printf("%s\nnext line\n", buffer);
signal = 0;
}
}
return 0;
}
void* function(void* args)
{
while(1)
{
if(scanf("%s", buffer))
signal = 1;
}
}
|
#ifndef APPLICATION_GETSERVERLOGS_H
#define APPLICATION_GETSERVERLOGS_H
#include "BaseCommand.h"
/*
* Get server logs command class
*/
class GetServerLogs: public BaseCommand {
public:
explicit GetServerLogs(boost::property_tree::ptree& params);
~GetServerLogs() override = default;
/*
* Executing a command
*/
boost::property_tree::ptree execute(std::shared_ptr<Controller> controller) override;
};
#endif //APPLICATION_GETSERVERLOGS_H
|
/*
* Copyright (C) 2013 Tom Wong. All rights reserved.
*/
#ifndef __GT_LOGIN_DIALOG_H__
#define __GT_LOGIN_DIALOG_H__
#include "gttabview.h"
#include "gtusermanager.h"
#include "ui_gtlogindialog.h"
GT_BEGIN_NAMESPACE
class GT_APP_EXPORT GtLoginDialog : public QDialog, public GtObject
{
Q_OBJECT
public:
explicit GtLoginDialog(QWidget *parent = 0);
~GtLoginDialog();
private Q_SLOTS:
void on_rememberMe_clicked(bool checked);
void on_autoLogin_clicked(bool checked);
void on_loginButton_clicked();
void accountIndexChanged(int index);
void usernameEdited(const QString &text);
void passwordEdited(const QString &text);
private:
int indexFromUsername(const QString &username);
private:
Ui_LoginDialog m_ui;
QList<GtUserManager::Account> m_accounts;
QString m_password;
};
GT_END_NAMESPACE
#endif /* __GT_LOGIN_DIALOG_H__ */
|
#pragma once
#include "../../../Toolbox/Toolbox.h"
#include "Mesh3D.h"
namespace ae
{
/// \ingroup graphics
/// <summary>
/// Simple 3D colored cube.
/// </summary>
/// <seealso cref="Mesh3D" />
/// <seealso cref="Drawable" />
class AERO_CORE_EXPORT CubeMesh : public Mesh3D
{
public:
/// <summary>Create a colored cube with a side size.</summary>
/// <param name="_Size">The size of cube side size.</param>
/// <param name="_SubdivisionWidth">Number of face along the width of the cube.</param>
/// <param name="_SubdivisionHeight">Number of face along the height of the cube.</param>
/// <param name="_SubdivisionDepth">Number of face along the depth of the cube.</param>
CubeMesh( const float _Size = 1.0f, Uint32 _SubdivisionWidth = 1, Uint32 _SubdivisionHeight = 1, Uint32 _SubdivisionDepth = 1 );
/// <summary>Set the side size of the cube.</summary>
/// <param name="_Size">The new size to apply.</param>
void SetSize( const float _Size );
/// <summary>Retrieve the size of the cube.</summary>
/// <returns>The size of the cube.</returns>
float GetSize() const;
/// <summary>Retrieve the number of the face along the width of the cube.</summary>
/// <returns>The number of face along the width of the cube.</returns>
Uint32 GetSubdivisionWidth() const;
/// <summary>Set the number of the face along the width of the cube.</summary>
/// <param name="_Subdvision">The new number of face along the width of the cube.</param>
void SetSubdivisionWidth( Uint32 _Subdvision );
/// <summary>Retrieve the number of the face along the height of the cube.</summary>
/// <returns>The number of face along the height of the cube.</returns>
Uint32 GetSubdivisionHeight() const;
/// <summary>Set the number of the face along the height of the cube.</summary>
/// <param name="_Subdvision">The new number of face along the height of the cube.</param>
void SetSubdivisionHeight( Uint32 _Subdvision );
/// <summary>Retrieve the number of the face along the height of the cube.</summary>
/// <returns>The number of face along the height of the cube.</returns>
Uint32 GetSubdivisionDepth() const;
/// <summary>Set the number of the face along the height of the cube.</summary>
/// <param name="_Subdvision">The new number of face along the height of the cube.</param>
void SetSubdivisionDepth( Uint32 _Subdvision );
/// <summary>
/// Function called by the editor.
/// It allows the class to expose some attributes for user editing.
/// Think to call all inherited class function too when overloading.
/// </summary>
virtual void ToEditor() override;
private:
/// <summary>Create the cube mesh according to the stored parameters.</summary>
void GenerateCubeMesh();
/// <summary>Create the cube mesh according to the stored parameters.</summary>
/// <param name="_Vertices">Allocated vertices array to setup.</param>
/// <param name="_Indices">Allocated indices array to setup.</param>
void SetupVerticesAndIndices( AE_InOut Vertex3DArray& _Vertices, AE_InOut IndexArray& _Indices );
/// <summary>Generate the a plane mesh for a cube side.</summary>
/// <param name="_Vertices">The vertices array containing the cube mesh to modify.</param>
/// <param name="_Indices">The indices array containing the faces to modify.</param>
/// <param name="_iTri">The index of the first free face index.</param>
/// <param name="_iVertex">The index of the free vertex.</param>
/// <param name="_ExtremePoints">The extreme points of the side plane.</param>
/// <param name="_Normal">The normal of the side.</param>
/// <param name="_WidthVerticesCount">The number of points along the width of the plane.</param>
/// <param name="_HeightVerticesCount">The number of points along the height of the plane.</param>
void SetupVerticesAndIndicesSide( AE_InOut Vertex3DArray& _Vertices, AE_InOut IndexArray& _Indices,
AE_InOut size_t& _iTri, AE_InOut size_t& _iVertex,
const Vector3 _ExtremePoints[4], const Vector3& _Normal,
size_t _WidthVerticesCount, size_t _HeightVerticesCount );
private:
/// <summary>Size of the cube.</summary>
float m_Size;
/// <summary>Number of face along the width of the cube.</summary>
Uint32 m_SubdivisionWidth;
/// <summary>Number of face along the height of the cube.</summary>
Uint32 m_SubdivisionHeight;
/// <summary>Number of face along the depth of the cube.</summary>
Uint32 m_SubdivisionDepth;
};
} // ae
|
#include <iostream>
#include <vector>
using namespace std;
#define int long long
#define pb push_back
#define endl '\n'
const int N = 1e5 + 5;
vector <int> Graph[N];
int cat[N];
int n, m;
int ans = 0;
void dfs(int src, int par, int safe) {
if (safe > m)
return ;
int valid = 1;
for (auto to : Graph[src]) {
if (to != par) {
valid = 0;
dfs(to, src, safe * cat[to] + cat[to]);
}
}
//cout<<src<<" ";
ans += valid;
}
void solve() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> cat[i];
}
int x = n;
x--;
while (x--) {
int u, v; cin >> u >> v;
Graph[u].pb(v);
Graph[v].pb(u);
}
dfs(1, 0, cat[1]);
cout << ans;
return ;
}
int32_t main() {
ios_base:: sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
// code starts
//int t;cin>>t;while(t--)
solve();
return 0;
}
|
#include "Gameboard.h"
#include "GameInterface.h"
using namespace std;
Game_specs GameInterface::reportSpecs(){
return board_specs;
}
/* Send game commands to the gameboard
* commands are 5 characters long
* Allowed commands are:
* getsq x,y - returns integer value of square x,y
* picsq x,y - picks the square at x,y coordinate
*/
double GameInterface::sendCommand(string cmd){
//cout << "GI:"<<cmd<<":\n";
string vars;
string command = cmd.substr(0,5);
int x,y;
//getsq function
if(command.compare("getsq")==0){
vars = cmd.substr(6,cmd.length());
x = atoi(vars.substr(0,vars.find_first_of(',')).c_str());
y = atoi(vars.substr(vars.find_first_of(',')+1,vars.length()).c_str());
return board->getCoordinate(x,y,'p');
}
else if(command.compare("picsq")==0){
vars = cmd.substr(7,cmd.length());
x = atoi(vars.substr(0,vars.find_first_of(',')).c_str());
y = atoi(vars.substr(vars.find_first_of(',')+1,vars.length()).c_str());
board->pickSquare(x,y);
//return the value of the square we just picked
return board->getCoordinate(x,y,'p');
}
else{
return -1;
}
}
/* The percentage of completion on this board
return - board completion percentage
*/
double GameInterface::report(){
return board->percentComplete();
}
/* Returns a true value if the current game is still being played (no win or loss conditions met)
returns false if the game has concluded
*/
bool GameInterface::report_status(){
return board->progress();
}
/* Initializes a gameboard of mine sweeper
* difficulty - the game difficulty
* seed - the random seed value
*/
void GameInterface::initGame(string difficulty="easy", int seed=-1){
if(difficulty.compare("easy")==0){
width = 9;
height = 9;
mines = 10;
}else if(difficulty.compare("intermediate")==0){
width = 16;
height = 16;
mines = 40;
}else if(difficulty.compare("hard")==0){
width = 30;
height = 16;
mines = 99;
}else{
perror("Unknown difficulty setting, shutting down");
exit(1);
}
board = new Gameboard(width, height, mines, seed);
board_specs.Height = height;
board_specs.Width = width;
board_specs.Mines = mines;
board_specs.difficulty = difficulty;
}
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/profiler/rpc/client/remote_profiler_session_manager.h"
#include <cstddef>
#include <memory>
#include "absl/memory/memory.h"
#include "absl/strings/string_view.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "tensorflow/core/platform/env_time.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/rpc/client/save_profile.h"
#include "tensorflow/core/profiler/utils/time_utils.h"
#include "tensorflow/core/protobuf/error_codes.pb.h"
namespace tensorflow {
namespace profiler {
namespace {
constexpr uint64 kMaxEvents = 1000000;
// TODO(yisitu) merge with the implementation in capture_profile.
void PopulateProfileRequest(const RemoteProfilerSessionManagerOptions& options,
absl::string_view session_id,
absl::string_view host_name,
ProfileRequest* request) {
request->set_max_events(kMaxEvents);
request->set_repository_root(options.profiler_options().repository_path());
request->set_session_id(session_id.data(), session_id.size());
request->add_tools("trace_viewer");
request->add_tools("op_profile");
request->add_tools("input_pipeline");
request->add_tools("kernel_stats");
request->add_tools("memory_viewer");
request->add_tools("memory_profile");
request->add_tools("overview_page");
request->add_tools("pod_viewer");
request->add_tools("tensorflow_stats");
request->set_host_name(host_name.data(), host_name.size());
*request->mutable_opts() = options.profiler_options();
request->set_duration_ms(options.profiler_options().duration_ms());
}
} // namespace
/*static*/ std::unique_ptr<RemoteProfilerSessionManager>
RemoteProfilerSessionManager::Create(
const RemoteProfilerSessionManagerOptions& options,
tensorflow::Status& out_status, AddressResolver resolver) {
VLOG(1) << "Creating a RemoteProfilerSessionManager.";
auto session_manager =
absl::WrapUnique(new RemoteProfilerSessionManager(options, resolver));
out_status = session_manager->Init();
if (!out_status.ok()) {
return nullptr;
}
return session_manager;
}
RemoteProfilerSessionManager::RemoteProfilerSessionManager(
RemoteProfilerSessionManagerOptions options, AddressResolver resolver)
: options_(std::move(options)) {
if (resolver) {
resolver_ = std::move(resolver);
} else {
resolver_ = [](absl::string_view addr) { return std::string(addr); };
}
}
RemoteProfilerSessionManager::~RemoteProfilerSessionManager() {
VLOG(2) << "Destroying RemoteProfilerSessionManager.";
}
Status RemoteProfilerSessionManager::Init() {
mutex_lock lock(mutex_);
VLOG(1) << "SessionManager initializing.";
// TODO(b/169482824) Move validation to call site.
Status status = ValidateOptionsLocked();
if (!status.ok()) {
LOG(ERROR) << status;
return status;
}
std::string session_id = GetCurrentTimeStampAsString();
const absl::Time session_created_ts =
absl::FromUnixNanos(options_.session_creation_timestamp_ns());
const absl::Time deadline =
session_created_ts +
absl::Milliseconds(options_.max_session_duration_ms());
LOG(INFO) << "Deadline set to " << deadline
<< " because max_session_duration_ms was "
<< options_.max_session_duration_ms()
<< " and session_creation_timestamp_ns was "
<< options_.session_creation_timestamp_ns() << " ["
<< session_created_ts << "]";
// Prepare a list of clients.
clients_.reserve(options_.service_addresses_size());
for (auto& service_addr : options_.service_addresses()) {
std::string resolved_service_addr = resolver_(service_addr);
ProfileRequest profile_request;
PopulateProfileRequest(options_, session_id, resolved_service_addr,
&profile_request);
// Creation also issues Profile RPC asynchronously.
auto client = RemoteProfilerSession::Create(
std::move(resolved_service_addr), deadline, std::move(profile_request));
clients_.push_back(std::move(client));
}
LOG(INFO) << "Issued Profile gRPC to " << clients_.size() << " clients";
return Status::OK();
}
Status RemoteProfilerSessionManager::ValidateOptionsLocked() {
if (!options_.service_addresses_size()) {
return errors::InvalidArgument("No service addresses specified.");
}
if (options_.profiler_options().duration_ms() == 0) {
if (options_.max_session_duration_ms() != 0) {
return errors::InvalidArgument(
"If local profiler duration is unbounded, profiling session duration "
"must be unbounded.");
}
}
if (options_.max_session_duration_ms() <
options_.profiler_options().duration_ms()) {
return errors::InvalidArgument(
"The maximum profiling session duration must be greater than or equal "
"to the local profiler duration.");
}
return Status::OK();
}
std::vector<RemoteProfilerSessionManager::Response>
RemoteProfilerSessionManager::WaitForCompletion() {
mutex_lock lock(mutex_);
std::vector<RemoteProfilerSessionManager::Response> remote_responses;
remote_responses.reserve(clients_.size());
for (auto& client : clients_) {
remote_responses.emplace_back();
auto* profile_response = &remote_responses.back().profile_response;
Status& status = remote_responses.back().status;
std::string* service_addr = &remote_responses.back().service_addr;
*profile_response = client->WaitForCompletion(status);
*service_addr = std::string(client->GetServiceAddress());
}
return remote_responses;
}
} // namespace profiler
} // namespace tensorflow
|
#include "SieveParAlternative2.h"
std::string SieveParAlternative2::name()
{
return "Sieve Algorith, split range array, separate dividers";
}
int* SieveParAlternative2::find(int min, int max, int* size)
{
int dividersSize = sqrt(max) + 1;
int arraySize = max - min;
// Initialize array
bool* array = new bool[arraySize];
*size = 0;
for (int i = 0; i < arraySize; i++)
{
array[i] = true;
}
#pragma omp parallel
{
bool* dividers = new bool[dividersSize];
for (int i = 0; i < dividersSize; i++)
{
dividers[i] = true;
}
// Filter non-prime dividers
for (int i = 2; i < sqrt(dividersSize); i++)
{
int j = i;
while (j + i < dividersSize)
{
j += i;
dividers[j] = false;
}
}
// Filter non-prime numbers
int maxT = omp_get_num_threads();
int t = omp_get_thread_num();
int minIndex = min + t * arraySize / maxT;
int maxIndex = min + (t + 1) * arraySize / maxT;
for (int i = 2; i < sqrt(maxIndex); i++)
{
if (dividers[i])
{
int j = i * floor((minIndex - 1) / i);
if (j < i)
{
j += i;
}
while (j + i < maxIndex)
{
j += i;
int index = j - min;
if (array[index])
{
array[index] = false;
}
}
}
}
delete[] dividers;
}
for (int i = 0; i < arraySize; i++)
{
if (array[i])
{
(*size)++;
}
}
// Insert all prime numbers into an array
int* result = new int[*size];
int j = 0;
for (int i = 0; i < arraySize; i++)
{
if (array[i])
{
result[j++] = min + i;
}
}
// Clean up
delete[] array;
return result;
}
|
#include<iostream>
using namespace std;
class node{
public:
int data;
node* next;
//Constructor
node(int d){
data = d;
next = NULL;
}
};
node* insertFront(node*& head,node *ab)
{
if(ab==NULL)
{
//head=new node(ab->data);
return head;
}
node *n = new node(ab->data);
n->next=insertFront(head,ab->next);
head=n;
return head;
}
void insertLast(node*& head,int data)
{
if(head==NULL)
{
head=new node(data);
return;
}
node *tail=head;
while(tail->next!=NULL)
{
tail=tail->next;
}
tail->next=new node(data);
return;
}
void print(node *head)
{while(head!=NULL){
cout<<head->data<<"->";
head = head->next;
}
cout<<endl;
}
int main()
{
int n,a,k;
cin>>n;
node *head=NULL;
for(int i=0;i<n;i++)
{
cin>>a;
insertLast(head,a);
}
cin>>k;
k=k%n;
node *ab=head;
for(int i=1;i<=n-k;i++)
ab=ab->next;
head=insertFront(head,ab);
int j=1;
while(j<=n)
{
cout<<head->data<<" ";
head=head->next;
j++;
}
return 0;
}
|
#ifndef AWS_NODES_PARSERNODE_H
#define AWS_NODES_PARSERNODE_H
/*
* aws/nodes/parsernode.h
* AwesomeScript Parser Node
* Author: Dominykas Djacenka
* Email: Chaosteil@gmail.com
*/
#include <ostream>
#include "nodeexception.h"
#include "translatesettings.h"
namespace AwS{
namespace Nodes{
class ParserNode{
public:
ParserNode(){}
virtual ~ParserNode(){}
virtual void translatePhp(std::ostream& output, TranslateSettings& settings) const throw(NodeException) = 0;
};
};
};
#endif
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
int a, n, b[222];
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
int T;
cin >> T;
for (int __it = 1; __it <= T; ++__it) {
cin >> a >> n;
for (int i = 0; i < n; ++i) {
cin >> b[i];
}
sort(b, b + n);
int eat = 0;
int ans = n;
int dbl = 0;
while (eat < n) {
ans = min(ans, dbl + n - eat);
if (b[eat] < a) {
a += b[eat];
++eat;
} else {
if (a == 1) break;
dbl++;
a = a + a - 1;
}
ans = min(ans, dbl + n - eat);
}
cout << "Case #" << __it << ": " << ans << endl;
}
return 0;
}
|
#pragma once
#include <map>
#include <SFML/Graphics.hpp>
namespace Sonar
{
class AssetManager
{
public:
AssetManager() = default;
~AssetManager() = default;
void LoadTexture(const std::string name, const std::string fileName);
const sf::Texture& GetTexture(const std::string& name);
void LoadFont(const std::string name, const std::string fileName);
const sf::Font& GetFont(const std::string& name);
private:
std::map<std::string, sf::Texture> _textures;
std::map<std::string, sf::Font> _fonts;
};
}
|
#include <stdio.h>
#include <sys/dir.h>
#include <maxmod9.h> // Maxmod definitions for ARM9
#include <utility>
#include <list>
#include "soundbank.h"
#include "tile.h"
#include "mirror.h"
#include "spinmirror.h"
#include "spinblocker.h"
#include "spinreflector.h"
#include "teleporter.h"
#include "laser.h"
#include "receiver.h"
#include "beam.h"
#include "spike.h"
#include "random.h"
#include "target.h"
#include "settings.h"
#include "subtile.h"
#include "subtileholder.h"
#include "gremlin.h"
#include "bar.h"
#include "level.h"
//Parses and loads a level from a text file
extern bool readLevel(FILE* input, Level* lev, Tile* (*gameMap)[TILES_X][TILES_Y], LevelParams& levParams, int tilesBgHandle, int mirrorsBgHandle);
extern bool oddFrame; //Is this an odd or even frame?
extern bool audio; //Should we try to use audio?
extern int consoleBg;
extern int bmpBg;
using namespace std;
typedef pair<coord,bool> pathPoint;
Level::Level(char* path,
int tilesBg,
int mirrorsBg,
int beamBg,
LevelParams& params) :
tilesBg(tilesBg),
mirrorsBg(mirrorsBg),
beamBg(beamBg),
mirrorsTileBase(params.mirrorsTileBase),
shipsTileBase(params.shipsTileBase),
objsTileBase(params.objsTileBase),
spinnersTileBase(params.spinnersTileBase),
toAnimate(),
targets(),
goalTiles(),
gremlins(),
beam(beamBg, 0xFFFF),
blankTile(new Tile(tilesBg, 0, 0, 0)),
complete(false),
activeMirror(NULL),
energy(BAR_MAX),
overload(0),
score(0)
{
for(int i = 0; i < TILES_X; ++i)
{
for(int j = 0; j < TILES_Y; ++j)
{
gameMap[i][j] = blankTile;
}
}
//Try and read level data from a file
FILE* test = fopen(path, "r");
if(test)
{
if(readLevel(test, this, &gameMap, params, tilesBg, mirrorsBg))
{
iprintf("Parsing level: Success\n");
}
else
{
iprintf("Parsing level: Failure");
}
}
else
{
iprintf("Parsing level: couldn't open file\n");
}
fclose(test);
}
Level::~Level()
{
for(int i=0; i < TILES_X; i++)
{
for(int j=0; j < TILES_Y; j++)
{
if(gameMap[i][j] != blankTile)
{
delete gameMap[i][j];
}
}
}
delete blankTile;
list<Gremlin*>::iterator gremlinIter;
for(gremlinIter = gremlins.begin();
gremlinIter != gremlins.end();
++gremlinIter)
{
delete (*gremlinIter);
}
}
void Level::setSpawnGremlins(bool spawn)
{
spawnGremlins = spawn;
}
void Level::setSource(Laser* src)
{
if(src)
{
source = src;
}
}
void Level::setReceiver(Receiver* rec)
{
if(rec)
{
sink = rec;
}
}
void Level::spawnGremlin()
{
int gCount = gremlins.size();
if(gCount < MAX_GREMLINS)
{
gremlins.push_back(new Gremlin(this));
iprintf("spawned gremlin %d\n",gCount);
if(Settings::get().getSfxOn()) mmEffect(SFX_GREMLIN);
}
}
void Level::addAnimatedTile(Tile* toAdd)
{
if(toAdd) toAnimate.push_back(toAdd);
}
void Level::addGoalTile(Tile* toAdd)
{
if(toAdd) goalTiles.push_back(toAdd);
}
Tile* Level::getTileAt(unsigned int x, unsigned int y)
{
return gameMap[x][y];
}
//Traces the path of the laser beam, once per frame, and draws it on the beam BG
//Returns 0 if everything is fine or a positive number if the beam overloaded (hit a spike, etc)
//Higher return values mean worse overload
int Level::evaluateBeam()
{
beam.clear();
BeamResult start = source->getBeamStart();
bool curFrame = oddFrame;
bool blocked = false;
bool overloaded = false;
int overloadFlag = 0;
pair<unsigned int, unsigned int> nextPos;
unsigned int nextXPos;
unsigned int beamStartX = start.xPos;
unsigned int nextYPos;
unsigned int beamStartY = start.yPos;
int nextXTile;
int nextYTile;
//curFrame != oddFrame is a signal that we spent too long evaluatingBeam
//and the next frame is here already
while (!blocked && curFrame == oddFrame)
{
nextPos = Beam::calculateNextPos(start.xPos, start.yPos, start.direction);
nextXPos = nextPos.first;
nextYPos = nextPos.second;
if(nextXPos >= (TILES_X * 4) || nextXPos <= 0 || nextYPos >= (TILES_Y * 4) || nextYPos <= 0)
{
blocked = true;
beam.draw(beamStartX, beamStartY, nextXPos, nextYPos);
}
else
{
nextXTile = nextXPos / 4;
nextYTile = nextYPos / 4;
if(nextXPos % 4 == 0)
{
//Are we going west in any direction?
if(start.direction > S)
{
nextXTile = nextXPos / 4 - 1;
}
}
if(nextYPos % 4 == 0)
{
//Are we going north in any direction?
if(start.direction < E || start.direction > W)
{
nextYTile = nextYPos / 4 - 1;
}
}
BeamResult res;
res.action = Pass;
//Find what happens when the beam enters the next tile:
if(gameMap[nextXTile][nextYTile] != blankTile)
res = gameMap[nextXTile][nextYTile]->beamEnters(nextXPos, nextYPos, start.direction);
switch (res.action) {
case Pass:
start.xPos = nextXPos;
start.yPos = nextYPos;
//beam->drawBox(nextXTile*16, nextYTile*16, nextXTile*16+16, nextYTile*16+16,0xFFFF);
break;
case Block:
blocked = true;
beam.draw(beamStartX, beamStartY, nextXPos, nextYPos);
//beam->drawBox(nextXTile*16, nextYTile*16, nextXTile*16+16, nextYTile*16+16,0x8FF0);
break;
case Reflect:
start.xPos = res.xPos;
start.yPos = res.yPos;
start.direction = res.direction;
beam.draw(beamStartX, beamStartY, res.xPos, res.yPos);
beamStartX = res.xPos;
beamStartY = res.yPos;
//beam->drawBox(nextXTile*16, nextYTile*16, nextXTile*16+16, nextYTile*16+16,0xF000);
break;
case Teleport:
beam.draw(beamStartX, beamStartY, nextXPos, nextYPos);
start.xPos = res.xPos;
start.yPos = res.yPos;
start.direction = res.direction;
beamStartX = res.xPos;
beamStartY = res.yPos;
break;
case Overload:
blocked = true;
overloaded = true;
overloadFlag = res.flag;
beam.draw(beamStartX, beamStartY, nextXPos, nextYPos);
//beam->drawBox(nextXTile*16, nextYTile*16, nextXTile*16+16, nextYTile*16+16, 0x801F);
break;
case Complete:
complete = true;
blocked = true;
beam.draw(beamStartX, beamStartY, nextXPos, nextYPos);
iprintf("level complete!\n");
break;
}
}
}
return (overloaded ? overloadFlag : 0);
}
void Level::addTarget(Target* t)
{
if(t)
{
targets.insert(t);
}
}
//Called from Target when it is completely destroyed
void Level::targetDestroyed(Target* t)
{
if(t)
{
targets.erase(t);
score += (energy >> 1);
if(targets.empty())
{
list<Tile*>::iterator goalsIter;
for(goalsIter = goalTiles.begin();
goalsIter != goalTiles.end();
++goalsIter)
{
(*goalsIter)->destroy();
iprintf("destroyed %p\n",(*goalsIter));
}
}
iprintf("destroyed %p, %d left\n",t,targets.size());
}
}
void Level::printSub(int x, int y, int bgId, int palIdx, char* string)
{
u16* bgMapPtr = bgGetMapPtr(bgId);
char c = *string;
while(c)
{
bgMapPtr[Tile::pos2idx(x++, y)] = (c - 0x20) | (palIdx << 12);
c = *(++string);
}
}
//Called when a Target is hit by the beam
void Level::targetHit(Target* t)
{
iprintf("target %p hit\n",t);
//Start animating this Target's explosion
if(t)
{
toAnimate.push_back(t);
if(Settings::get().getSfxOn()) mmEffect(SFX_EXPLODE);
}
}
bool Level::isComplete()
{
return complete;
}
//Called to play the level, does not return until level ends
//Returns -1 if the player 'died', -2 if they quit, or a
//positive score if the player completed the level
int Level::playLevel(int startScore)
{
int energyCountdown = 0;
int overloadFlag = 0;
//Save the player's starting score
score = startScore;
scanKeys();
int kd,kh;
Bar* energyBar = Settings::get().getEnergyBar();
Bar* overloadBar = Settings::get().getOverloadBar();
int gamedisplayBg = Settings::get().getBgHandles().gamedisplayBg;
energyBar->show();
overloadBar->show();
bgHide(consoleBg);
bgHide(bmpBg);
bgShow(gamedisplayBg);
//main level loop
while(!isComplete())
{
swiWaitForVBlank();
scanKeys();
kd = keysDown();
kh = keysHeld();
energyCountdown++;
//Decrease energy every 54 frames (empirically determined ;)
if(energyCountdown > 54)
{
energyCountdown = 0;
energy--;
if(energy <= 0)
{
energy = 0;
return -1; //end level here
}
}
overloadFlag = evaluateBeam();
if(overloadFlag && oddFrame)
{
overload+=overloadFlag;
if(overload > BAR_MAX)
{
overload = BAR_MAX;
//need to end level here
return -1;
}
}
else if(overload && oddFrame)
{
//Overload bar gradually returns to normal
--overload;
}
energyBar->setValue(energy);
overloadBar->setValue(overload);
oamUpdate(&oamMain);
//if(!((kd | kh) & KEY_L))
//{
// //show debug console
// bgHide(consoleBg);
// bgHide(bmpBg);
// bgShow(gamedisplayBg);
//}
//else
//{
// bgHide(bmpBg);
// bgHide(gamedisplayBg);
// bgShow(consoleBg);
//}
if(spawnGremlins && oddFrame && (rand() & 0x1FF) == 0x1FF)
{
spawnGremlin();
}
if(kd & KEY_TOUCH)
{
touchRead(&touchDown);
}
if((kd & KEY_SELECT) && audio)
{
//toggle music
Settings& s = Settings::get();
s.setMusicOn(s.getMusicOn() ^ true);
if(s.getMusicOn()) mmResume();
else mmPause();
}
else if(kd & KEY_START)
{
//pause
printSub(5, 20, gamedisplayBg, 0, "Press Start to Unpause");
printSub(6, 21, gamedisplayBg, 0, "Press Select to Quit");
while (true)
{
swiWaitForVBlank();
scanKeys();
kd = keysDown();
kh = keysHeld();
if(kd & KEY_START)
{
break;
}
else if(kd & KEY_SELECT)
{
printSub(5, 20, gamedisplayBg, 0, " ");
printSub(6, 21, gamedisplayBg, 0, " ");
return -2;
}
}
printSub(5, 20, gamedisplayBg, 0, " ");
printSub(6, 21, gamedisplayBg, 0, " ");
}
/*if(kd & KEY_A)
{
complete = true;
}*/
if(spawnGremlins)
{
list<Gremlin*>::iterator gremlinIter;
for(gremlinIter = gremlins.begin();
gremlinIter != gremlins.end();
++gremlinIter)
{
(*gremlinIter)->drawUpdate();
if(kd & KEY_TOUCH)
{
coord gremlinPos = (*gremlinIter)->getPosition();
if(touchDown.px > (gremlinPos.first) &&
touchDown.px < (gremlinPos.first + 16) &&
touchDown.py > (gremlinPos.second) &&
touchDown.py < (gremlinPos.second + 16))
{
iprintf("tap on gremlin %p\n",*gremlinIter);
if((*gremlinIter)->tapOn())
{
delete (*gremlinIter);
gremlinIter = gremlins.erase(gremlinIter);
if(Settings::get().getSfxOn()) mmEffect(SFX_GREMDIE);
}
else
{
if(Settings::get().getSfxOn()) mmEffect(SFX_GREMHIT);
}
}
}
}
}
list<Tile*>::iterator animateIter;
for(animateIter = toAnimate.begin();
animateIter != toAnimate.end();
++animateIter)
{
(*animateIter)->drawUpdate();
}
snprintf(scoreStr, 15, "SCORE: %07d",score);
printSub(9, 7, gamedisplayBg, 1, scoreStr);
//if(kd & KEY_DOWN) return -1;
if(activeMirror && !Settings::get().getControlType())
{
if(kd & (KEY_LEFT | KEY_Y))
{
activeMirror->rotate(-1);
activeMirror->drawUpdate();
}
else if(kd & (KEY_RIGHT | KEY_A))
{
activeMirror->rotate(1);
activeMirror->drawUpdate();
}
}
if(kd & KEY_TOUCH)
{
lastTouch = touchDown;
int gameXpos = (touchDown.px - XOFS);
int gameYpos = (touchDown.py - YOFS);
if(gameXpos < 0 || gameXpos >= 240) continue; else gameXpos = gameXpos >> 4;
if(gameYpos < 0 || gameYpos >= 144) continue; else gameYpos = gameYpos >> 4;
Tile* tileAtPos = getTileAt(gameXpos, gameYpos);
if(tileAtPos != NULL && tileAtPos->isInteractive())
{
//Assumes mirrors are the only interactive components - may change
activeMirror = (Mirror*)tileAtPos;
}
else
{
activeMirror = NULL;
}
}
else if(kh & KEY_TOUCH)
{
if(activeMirror && Settings::get().getControlType())
{
touchRead(&curTouch);
//average current and last touch pos to smooth out 'jumping'
int dx = ((lastTouch.px + curTouch.px) >> 1) - touchDown.px;
int dy = ((lastTouch.py + curTouch.py) >> 1) - touchDown.py;
lastTouch = curTouch;
if(dx ==0 && dy == 0)
{
//do nothing
}
else if(dx == 0)
{
activeMirror->setAngle(0);
}
else if(dy == 0)
{
activeMirror->setAngle(8);
}
else
{
int a_dx = abs(dx);
int a_dy = abs(dy);
//Find magnitude of distance from mirror to touch point
int32 magnitude = sqrtf32(inttof32(a_dx * a_dx + a_dy * a_dy));
//use dot product to find cos. of angle between them
int32 cos_angle = divf32(inttof32(-dy), magnitude);
//work out the angle and correct for relative x position
int angle = div32(((int)(acosLerp(cos_angle))),1024);
if(dx < 0)
{
angle = 15 - angle;
}
activeMirror->setAngle(angle);
}
activeMirror->drawUpdate();
}
}
else if(activeMirror && (keysUp() & KEY_TOUCH))
{
if(Settings::get().getControlType())
activeMirror = NULL;
}
if(activeMirror && !Settings::get().getControlType())
{
coord pos = activeMirror->getPosition();
beam.drawBox(pos.first*16, pos.second*16, (pos.first+1)*16, (pos.second+1)*16, 0xFFFF);
}
}
if(Settings::get().getSfxOn()) mmEffect(SFX_LEVELUP);
for (int i=0; i < 66; ++i)
{
swiWaitForVBlank();
}
return score;
}
|
../1068/E.cpp
|
/*
* License:
* License does not expire.
* Can be distributed in infinitely projects
* Can be distributed and / or packaged as a code or binary product (sublicensed)
* Commercial use allowed under the following conditions :
* - Crediting the Author
* Can modify source-code
*/
/*
* File: Shader.h
* Author: Suirad <darius-suirad@gmx.de>
*
* Created on 20. Januar 2018, 17:32
*/
#ifndef SHADER_H
#define SHADER_H
#include <string>
#include <unordered_map>
#include <GLM/glm.hpp>
#include <vector>
#include "Color.h"
class Shader {
public:
//Creating New Empty Shader Programm
Shader();
//Adding New Shader to Programm, with specific Type (Compute, Vertex, Geometry, Fragment, ...)
void addShader(std::string source, int type);
//Starting Programm
void start();
//Stop Programm
void stop();
//Delete Programm and Shaders
virtual ~Shader();
//activate Uniform Variable in Programm
void activateUniform(std::string uniform);
//Bind Texture Unit to Uniform
void bindTextureUnit(std::string uniform, int unit);
//Methods To Set Uniform Variables
void setUniformVariable(std::string uniform, bool value);
void setUniformVariable(std::string uniform, int value);
void setUniformVariable(std::string uniform, float value);
void setUniformVariable(std::string uniform, Color value);
void setUniformVariable(std::string uniform, glm::vec2 value);
void setUniformVariable(std::string uniform, glm::vec3 value);
void setUniformVariable(std::string uniform, glm::vec4 value);
void setUniformVariable(std::string uniform, glm::mat4 value);
void setUniformVariable(std::string uniform, float x, float y);
void setUniformVariable(std::string uniform, float x, float y, float z);
private:
//Id Of The Programm
unsigned int programm;
//List of Alls Shaders in this Programm for Deleting
std::vector<unsigned int> shaders;
//Map of All Uniform Locations
std::unordered_map<std::string, int> uniforms;
};
#endif /* SHADER_H */
|
// Copyright (c) 2021 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// #5488: pika::util::detail::bind doesn't bounds-check placeholders
#include <pika/functional/bind.hpp>
#include <type_traits>
template <typename F, std::enable_if_t<std::is_invocable_v<F>, int> = 0>
auto test(F&& f)
{
return f();
}
template <typename F, std::enable_if_t<std::is_invocable_v<F, int>, int> = 0>
auto test(F&& f)
{
return f(42);
}
void foo(int) {}
int main() { test(pika::util::detail::bind(foo, std::placeholders::_1)); }
|
#define MAX 100
int is_opening ( char ch )
{
if ( ch == '(' || ch == '[' || ch == '{' ) return 1 ;
else return 0 ;
}
int is_closing ( char ch )
{
if ( ch == ')' || ch == ']' || ch == '}' ) return 1 ;
else return 0 ;
}
char counter ( char ch )
{
if ( ch == ')' ) return '(' ;
else if ( ch == ']' ) return '[' ;
else if ( ch == '}' ) return '{' ;
}
int isempty ( int top )
{
if ( top == -1 ) return 1 ;
else return 0 ;
}
void push ( char A[] , int *top , char data )
{
A[++(*top)] = data ;
}
char pop ( char A[] , int *top )
{
char data = A[*top] ;
--(*top);
return data ;
}
extern int para_match_test ( char expr[] )
{
char ch ;
int top = -1 , ctrl = -1 , i = 0 ;
char A[MAX] ;
while (( ch = expr[i++] ) != '\0' ){
if ( is_opening (ch) ) {
push ( A , &top , ch ) ;
}
if ( is_closing (ch) ){
if ( ! ( pop ( A , &top ) == counter ( ch ) ) ){
return 0 ;
}
}
}
if ( isempty ( top ) ) return 1 ;
else return 0 ;
}
|
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#include <locale.h>
using namespace std;
void charcreate(int &str, int &agi, int &iq, int &gold, char *s)
{
int k,n;
cout << "Введите имя персонажа: ";
gets_s(s,100);
n = strlen(s);
for(int i = 0; i<n;i++)
{
if ((s[i] < 0) || (s[i] > 128)) { cout << "Неккоректное имя персонажа !" << endl; charcreate(str, agi, iq, gold, s); }
else break;
}
return;
}
int main()
{
setlocale(LC_ALL,"");
char s[100];
int str, agi, iq, hp, maxhp, exp, maxexp, lvl, gold;
str = 3;
agi = 3;
iq = 3;
gold = 0;
charcreate(str,agi,iq,gold,s);
cout << s << endl;
return 0;
}
|
// Sort the given string
#include<iostream>
#include<algorithm> // To use the sort function
#include<string>
using namespace std;
int main(){
string s1 = "dhvfljrejghejgrljhgardfjghbadbyugukgkruhu";
sort(s1.begin(), s1.end());
cout<<s1<<endl;
}
|
#include<Wire.h>
#include<Math.h>
#include <Servo.h>
// raw values passed from the C++ program. Kept as seperate variables mainly for intuitiveness
int RT, LT, R3, L3, RB, LB, UpD, DownD, LeftD, RightD, A, B, X, Y, Start, Back, Verification;
int palmVX = 0, palmVY = 0, palmVZ = 0, palmPitch = 0, palmYaw = 0, palmRoll, clawDistance = 0;
boolean usingLeap = false;
int RBPrevState = 0;
int i;
int PWMPinLocation[] = {
3,5,6,9,10,11};
int height = 0;
long RX, RY, LX, LY;
/*
Wiring Diagram for MPU6050 IMU -> Arduino:
VCC -> 3.3V
GND -> GND
SDA -> SDA
SCL -> SCL
AD0 -> resitor -> GND
*/
//Gyro and accelerometer variables
const int MPU=0x68; // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY, GyZ;
double Zpos = 0.0,pos = 0.0;
typedef struct{
int PWMPin;
int directionPin;
int Power;
int Direction;
}
motorStruct;
motorStruct motor[6];
void setup()
{
//Gyro/Accelerometer setup
// Wire.begin();
// Wire.beginTransmission(MPU);
// Wire.write(0x6B); // PWR_MGMT_1 register
// Wire.write(0); // set to zero (wakes up the MPU-6050)
// Wire.endTransmission(true);
Serial.begin(14400, SERIAL_8N1); //Baud here must match baud on c++ side
Serial.setTimeout(100);
for (i = 0; i<= 6; i++)
{
motor[i].PWMPin = PWMPinLocation[i]; //PWM pin for motor 0 will be 3, corresponnds with the PWM PinLocation array
motor[i].directionPin = (i+32); //Digital pin for motor 0 will be 32 and go up by one
}
}
void loop()
{
//ReadGyro();
if(Serial.available() > 0)
{
if(ReadInValues()!= -1)
{
if (DriveControl() == 1)
{
Move();
}
else if (DriveControl() == -1)
{
LeapMove();
}
//SendData();
}
}
}
int ReadInValues()
{
Serial.print("r ");
RX = Serial.parseInt();
RY = Serial.parseInt();
LX = Serial.parseInt();
LY = Serial.parseInt();
RT = Serial.parseInt();
LT = Serial.parseInt();
R3 = Serial.parseInt();
L3 = Serial.parseInt();
RB = Serial.parseInt();
LB = Serial.parseInt();
UpD = Serial.parseInt();
DownD = Serial.parseInt();
LeftD = Serial.parseInt();
RightD = Serial.parseInt();
A = Serial.parseInt();
B = Serial.parseInt();
Y = Serial.parseInt();
X = Serial.parseInt();
Start = Serial.parseInt();
Back = Serial.parseInt();
Verification = Serial.parseInt();
palmVX = Serial.parseInt();
palmVY = Serial.parseInt();
palmVZ = Serial.parseInt();
palmPitch = Serial.parseInt();
palmYaw = Serial.parseInt();
palmRoll = Serial.parseInt();
clawDistance = Serial.parseInt();
if (Verification != 9)
{
return -1;
}
else
{
Serial.print("q ");
}
RX = map(RX, -32767, 32767, -255, 255);
RY = map(RY, -32767, 32767, -255, 255);
LX = map(LX, -32767, 32767, -255, 255);
LY = map(LY, -32767, 32767, -255, 255);
return 0;
}
int DriveControl()
{
if (usingLeap == true && RBPrevState == 1 && RB == 0)
{
usingLeap = false;
}
else if (usingLeap == false && RBPrevState == 1 && RB == 0)
{
usingLeap = true;
}
RBPrevState = RB;
if (usingLeap == false)
return 1;
else if (usingLeap == true)
return -1;
}
void Move() //STANDARD: digital write low pushes water out, high sucks in
{
//Control for motors 0 and 1, back 2 thrusters
if (LY != 0)
{
motor[0].Power = DirectionCorrection(0);
motor[1].Power = DirectionCorrection(1);
if (LY > 0)
{
digitalWrite(motor[0].directionPin, LOW);
digitalWrite(motor[1].directionPin, LOW);
}
if (LY < 0)
{
digitalWrite(motor[0].directionPin, HIGH);
digitalWrite(motor[1].directionPin, HIGH);
}
analogWrite(motor[0].PWMPin, abs(motor[0].Power));
analogWrite(motor[1].PWMPin, abs(motor[1].Power));
}
else if (LY == 0 && RX != 0)
{
if(RX > 0)
{
digitalWrite(motor[0].directionPin, LOW);
digitalWrite(motor[1].directionPin, HIGH);
}
if(RX < 0)
{
digitalWrite(motor[0].directionPin, HIGH);
digitalWrite(motor[1].directionPin, LOW);
}
analogWrite(motor[0].PWMPin, abs(RX));
analogWrite(motor[1].PWMPin, abs(RX));
}
else {
analogWrite(motor[0].PWMPin, 0);
analogWrite(motor[1].PWMPin, 0);
}
//Control for side thrusters(4 and 5)
if (LX >= 0)
digitalWrite(motor[4].directionPin, LOW);
digitalWrite(motor[5].directionPin, HIGH);
if (LX < 0)
digitalWrite(motor[4].directionPin, HIGH);
digitalWrite(motor[5].directionPin, LOW);
analogWrite(motor[4].PWMPin, abs(LX));
analogWrite(motor[5].PWMPin, abs(LX));
//Control for top thrusters(2 and 3)
//linear movement
if (LT > 0 && height < 255)
{
if(height < 0)
height = 0;
height += LT/10;
if (height > LT)
height = LT;
}
if(RT > 0 && height > -255)
{
if(height > 0)
height = 0;
height -= RT/10;
if (height < -RT)
height = -RT;
}
if(LT == 0 && RT == 0)
{
height = 0;
}
if (height != 0)
{
motor[2].Power = DirectionCorrection(2);
motor[3].Power = DirectionCorrection(3);
if(height > 0)
{
digitalWrite(motor[2].directionPin, LOW);
digitalWrite(motor[3].directionPin, LOW);
}
if(height < 0)
{
digitalWrite(motor[2].directionPin, HIGH);
digitalWrite(motor[3].directionPin, HIGH);
}
analogWrite(motor[2].PWMPin, abs(motor[2].Power));
analogWrite(motor[3].PWMPin, abs(motor[3].Power));
}
else if (height == 0 && RY != 0)
{
if (RY > 0)
{
digitalWrite(motor[2].directionPin, HIGH);
digitalWrite(motor[3].directionPin, LOW);
}
if (RY < 0)
{
digitalWrite(motor[2].directionPin, LOW);
digitalWrite(motor[3].directionPin, HIGH);
}
analogWrite(motor[2].PWMPin, abs(RY));
analogWrite(motor[3].PWMPin, abs(RY));
}
else
{
analogWrite(motor[2].PWMPin, 0);
analogWrite(motor[3].PWMPin, 0);
}
}
void ArmMove()
{
}
void LeapMove()
{
int xVelocity = 0, yVelocity = 0, zVelocity = 0;
xVelocity = map(palmVX, -300, 300, -255, 255);
constrain(xVelocity, -255, 255);
yVelocity = map(palmVY, -300, 300, -255, 255);
constrain(yVelocity, -255, 255);
zVelocity = map(palmVZ, -300, 300, -255, 255);
constrain(zVelocity, -255, 255);
analogWrite(motor[0].PWMPin, abs(zVelocity));
analogWrite(motor[1].PWMPin, abs(zVelocity));
analogWrite(motor[2].PWMPin, abs(yVelocity));
analogWrite(motor[3].PWMPin, abs(yVelocity));
analogWrite(motor[4].PWMPin, abs(xVelocity));
analogWrite(motor[5].PWMPin, abs(xVelocity));
}
void LeapArmMove()
{
int clawControl = 0;
clawControl = map(clawDistance, 40, 90, 0, 255);
constrain(clawControl, 0 ,255);
}
int DirectionCorrection(int motor)
{
int correctedValue = 0;
if (motor == 0)
{
correctedValue = LY/2 + ((long)(LY*RX)/510);
}
else if (motor == 1)
{
correctedValue = LY/2 - ((long)(LY*RX)/510);
}
else if (motor == 2)
{
correctedValue = height/2 - ((long)(height*RY)/510);
}
else if (motor == 3)
{
correctedValue = height/2 + ((long)(height*RY)/510);
}
return correctedValue;
}
void SendInt(int val,long maxVal)
{
int i = 0;
String valStr = String(val);
String maxValStr = String(maxVal);
int sizeDif = maxValStr.length() - valStr.length();
for (i = 0; i < sizeDif; i++)
Serial.print("0");
Serial.print(val);
Serial.println(" ");
}
void ReadGyro()
{
Wire.beginTransmission(MPU);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU,14,true); // request a total of 14 registers
AcX=Wire.read()<<8|Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY=Wire.read()<<8|Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ=Wire.read()<<8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp=Wire.read()<<8|Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX=Wire.read()<<8|Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY=Wire.read()<<8|Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ=Wire.read()<<8|Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
}
void SendData()
{
long maxValue = 1234567;
//Gyro Values:
SendInt(AcX, maxValue);
/*SendInt(AcY, maxValue);
SendInt(AcZ, maxValue);
SendInt(Tmp/340.00+36.53, maxValue);
SendInt(GyX, maxValue);
SendInt(GyY, maxValue);
SendInt(GyZ, maxValue);*/
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.