text
stringlengths 8
6.88M
|
|---|
/* primitive_short.cpp -*- C++ -*-
Rémi Attab (remi.attab@gmail.com), 12 Apr 2014
FreeBSD-style copyright and disclaimer apply
Short reflection
*/
#include "primitives.h"
#include "primitives.tcc"
/******************************************************************************/
/* REFLECT SHORT */
/******************************************************************************/
reflectNumber(short int)
reflectNumber(unsigned short int)
|
//
// StormTrooper.h
// emptyExample
//
// Created by Leytzher on 2/15/15.
//
//
#ifndef __emptyExample__StormTrooper__
#define __emptyExample__StormTrooper__
#include <stdio.h>
#include "ofMain.h"
class StormTrooper{
public:
StormTrooper();
void setup();
void update();
void draw();
ofPoint pos;
ofPoint vel;
float time;
ofImage stormTrooperImage;
};
#endif /* defined(__emptyExample__StormTrooper__) */
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
//-----------------------------------------------------------------------------
// Remote Dynamic Engine test code
//-----------------------------------------------------------------------------
#include "Pooma/Pooma.h"
#include "Utilities/Tester.h"
#include "Domain/Loc.h"
#include "Domain/Interval.h"
#include "Domain/IndirectionList.h"
#include "Engine/DynamicEngine.h"
#include "Engine/RemoteDynamicEngine.h"
#include "Array/Array.h"
#include <iostream>
#include <vector>
#if POOMA_MESSAGING
struct PackObject
{
typedef Array<1, double, Remote<Dynamic> > Array_t;
typedef IndirectionList<int> List_t;
PackObject(Array_t &array, List_t &list)
: array_m(&array), list_m(&list)
{
}
PackObject() { }
Array_t *array_m;
List_t *list_m;
char *buffer_m;
};
namespace Cheetah {
template<>
class Serialize<CHEETAH, PackObject>
{
public:
static inline int
size(const PackObject &pack)
{
int dummy;
return Serialize<CHEETAH, int>::size(dummy) +
pack.array_m->engine().packSize(*(pack.list_m));
}
static inline int
pack(const PackObject &pack, char *buffer)
{
int length;
char *data = buffer + Serialize<CHEETAH, int>::size(length);
length = pack.array_m->engine().pack(*(pack.list_m), data, false);
return (length + Serialize<CHEETAH, int>::pack(length, buffer));
}
static inline int
unpack(PackObject* &pack, char *buffer)
{
pack = new PackObject();
int *length;
int sizeInt = Serialize<CHEETAH, int>::unpack(length, buffer);
pack->buffer_m = buffer + sizeInt;
return sizeInt + *length;
}
static inline void
cleanup(PackObject *pack)
{
delete pack;
}
};
} // namespace Cheetah
static bool ready_g = false;
void unpackFunction(Array<1, double, Remote<Dynamic> > *b, PackObject &pack)
{
b->engine().unpack(Interval<1>(7, 11), pack.buffer_m, false);
ready_g = true;
}
#endif
int main(int argc, char *argv[])
{
Pooma::initialize(argc,argv);
Pooma::Tester tester(argc,argv);
tester.out().setOutputContext(-1);
int myContext = Pooma::context();
int numContexts = Pooma::contexts();
// Create the total domain.
Interval<1> x(12);
Array<1, double, Remote<Dynamic> > a(x);
// Store some stuff.
int i;
for (i = 0; i < 12; ++i)
{
a(i) = double(i);
}
tester.out() << " Array a = " << a << std::endl;
#if POOMA_CHEETAH
IndirectionList<int> list(5);
list(0) = 3;
list(1) = 5;
list(2) = 7;
list(3) = 8;
list(4) = 9;
if (myContext == 0)
{
int size = a.engine().packSize(list);
char *buffer = new char [size];
a.engine().pack(list, buffer, false);
a.engine().unpack(Interval<1>(7, 11), buffer, false);
delete [] buffer;
}
tester.out() << " Array a = " << a << std::endl;
if (numContexts > 1)
{
// Create an engine on another context...
Engine<1, double, Remote<Dynamic> > eng(1, x);
Array<1, double, Remote<Dynamic> > b(eng);
b = 0;
Pooma::blockAndEvaluate();
if (myContext == 0)
{
PackObject pack(a, list);
int toContext = 1;
int tag = Pooma::sendTag(toContext);
tester.out() << "Sending data to context " << toContext
<< " with tag " << tag << std::endl;
Pooma::particleSwapHandler()->send(toContext, tag, pack);
}
if (myContext == 1)
{
int fromContext = 0;
int tag = Pooma::receiveTag(fromContext);
tester.out() << "Receiving data from context " << fromContext
<< " with tag " << tag << std::endl;
Pooma::particleSwapHandler()->request(fromContext, tag,
unpackFunction, &b);
while (!ready_g)
{
Pooma::poll();
}
}
tester.out() << b << std::endl;
}
#endif
int ret = tester.results("remoteDynamicTest1");
Pooma::finalize();
return 0;
}
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: remoteDynamicTest1.cpp,v $ $Author: richard $
// $Revision: 1.10 $ $Date: 2004/11/01 18:16:38 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
//
// OperateLayer.hpp
// CatchGirl
//
// Created by xin on 16/4/6.
//
//
#ifndef OperateLayer_hpp
#define OperateLayer_hpp
#include <stdio.h>
#include "cocos2d.h"
#include "ui/CocosGUI.h"
USING_NS_CC;
using namespace ui;
class OperateLayer:public Layer{
public:
CREATE_FUNC(OperateLayer);
virtual bool init();
void touchCallback(Ref * pSender,Widget::TouchEventType type);
};
#endif /* OperateLayer_hpp */
|
/*
* SPDX-FileCopyrightText: (C) 2016-2017 Daniel Nicoletti <dantti12@gmail.com>
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "postunbuffered.h"
PostUnbuffered::PostUnbuffered(QObject *parent)
: QIODevice(parent)
{
}
#include "moc_postunbuffered.cpp"
|
//
// Created by wiktor on 04.05.18.
//
|
// Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include <RcppArmadillo.h>
#include <Rcpp.h>
using namespace Rcpp;
// callRMultinom
IntegerVector callRMultinom(NumericVector x);
RcppExport SEXP IPTM2_callRMultinom(SEXP xSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericVector >::type x(xSEXP);
rcpp_result_gen = Rcpp::wrap(callRMultinom(x));
return rcpp_result_gen;
END_RCPP
}
// multinom_vec
IntegerVector multinom_vec(int nSample, NumericVector props);
RcppExport SEXP IPTM2_multinom_vec(SEXP nSampleSEXP, SEXP propsSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< int >::type nSample(nSampleSEXP);
Rcpp::traits::input_parameter< NumericVector >::type props(propsSEXP);
rcpp_result_gen = Rcpp::wrap(multinom_vec(nSample, props));
return rcpp_result_gen;
END_RCPP
}
// which_int
int which_int(int value, IntegerVector x);
RcppExport SEXP IPTM2_which_int(SEXP valueSEXP, SEXP xSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< int >::type value(valueSEXP);
Rcpp::traits::input_parameter< IntegerVector >::type x(xSEXP);
rcpp_result_gen = Rcpp::wrap(which_int(value, x));
return rcpp_result_gen;
END_RCPP
}
// which_num
int which_num(int value, NumericVector x);
RcppExport SEXP IPTM2_which_num(SEXP valueSEXP, SEXP xSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< int >::type value(valueSEXP);
Rcpp::traits::input_parameter< NumericVector >::type x(xSEXP);
rcpp_result_gen = Rcpp::wrap(which_num(value, x));
return rcpp_result_gen;
END_RCPP
}
// rdirichlet_cpp
arma::mat rdirichlet_cpp(int num_samples, arma::vec alpha_m);
RcppExport SEXP IPTM2_rdirichlet_cpp(SEXP num_samplesSEXP, SEXP alpha_mSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< int >::type num_samples(num_samplesSEXP);
Rcpp::traits::input_parameter< arma::vec >::type alpha_m(alpha_mSEXP);
rcpp_result_gen = Rcpp::wrap(rdirichlet_cpp(num_samples, alpha_m));
return rcpp_result_gen;
END_RCPP
}
// rbinom_mat
IntegerMatrix rbinom_mat(NumericMatrix probmat);
RcppExport SEXP IPTM2_rbinom_mat(SEXP probmatSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericMatrix >::type probmat(probmatSEXP);
rcpp_result_gen = Rcpp::wrap(rbinom_mat(probmat));
return rcpp_result_gen;
END_RCPP
}
// History
List History(List edge, IntegerVector node, double when);
RcppExport SEXP IPTM2_History(SEXP edgeSEXP, SEXP nodeSEXP, SEXP whenSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List >::type edge(edgeSEXP);
Rcpp::traits::input_parameter< IntegerVector >::type node(nodeSEXP);
Rcpp::traits::input_parameter< double >::type when(whenSEXP);
rcpp_result_gen = Rcpp::wrap(History(edge, node, when));
return rcpp_result_gen;
END_RCPP
}
// Degree
NumericMatrix Degree(List history, IntegerVector node, int sender);
RcppExport SEXP IPTM2_Degree(SEXP historySEXP, SEXP nodeSEXP, SEXP senderSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List >::type history(historySEXP);
Rcpp::traits::input_parameter< IntegerVector >::type node(nodeSEXP);
Rcpp::traits::input_parameter< int >::type sender(senderSEXP);
rcpp_result_gen = Rcpp::wrap(Degree(history, node, sender));
return rcpp_result_gen;
END_RCPP
}
// Dyadic
NumericMatrix Dyadic(List history, IntegerVector node, int sender);
RcppExport SEXP IPTM2_Dyadic(SEXP historySEXP, SEXP nodeSEXP, SEXP senderSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List >::type history(historySEXP);
Rcpp::traits::input_parameter< IntegerVector >::type node(nodeSEXP);
Rcpp::traits::input_parameter< int >::type sender(senderSEXP);
rcpp_result_gen = Rcpp::wrap(Dyadic(history, node, sender));
return rcpp_result_gen;
END_RCPP
}
// Triadic
NumericMatrix Triadic(List history, IntegerVector node, int sender);
RcppExport SEXP IPTM2_Triadic(SEXP historySEXP, SEXP nodeSEXP, SEXP senderSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List >::type history(historySEXP);
Rcpp::traits::input_parameter< IntegerVector >::type node(nodeSEXP);
Rcpp::traits::input_parameter< int >::type sender(senderSEXP);
rcpp_result_gen = Rcpp::wrap(Triadic(history, node, sender));
return rcpp_result_gen;
END_RCPP
}
// Triadic_reduced
NumericMatrix Triadic_reduced(NumericMatrix triadic);
RcppExport SEXP IPTM2_Triadic_reduced(SEXP triadicSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericMatrix >::type triadic(triadicSEXP);
rcpp_result_gen = Rcpp::wrap(Triadic_reduced(triadic));
return rcpp_result_gen;
END_RCPP
}
// MultiplyXBList
List MultiplyXBList(List X, List B);
RcppExport SEXP IPTM2_MultiplyXBList(SEXP XSEXP, SEXP BSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List >::type X(XSEXP);
Rcpp::traits::input_parameter< List >::type B(BSEXP);
rcpp_result_gen = Rcpp::wrap(MultiplyXBList(X, B));
return rcpp_result_gen;
END_RCPP
}
// MultiplyXBList2
List MultiplyXBList2(List X, List B);
RcppExport SEXP IPTM2_MultiplyXBList2(SEXP XSEXP, SEXP BSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List >::type X(XSEXP);
Rcpp::traits::input_parameter< List >::type B(BSEXP);
rcpp_result_gen = Rcpp::wrap(MultiplyXBList2(X, B));
return rcpp_result_gen;
END_RCPP
}
// UpdateDenom
double UpdateDenom(double alpha, IntegerVector nwordtable);
RcppExport SEXP IPTM2_UpdateDenom(SEXP alphaSEXP, SEXP nwordtableSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< double >::type alpha(alphaSEXP);
Rcpp::traits::input_parameter< IntegerVector >::type nwordtable(nwordtableSEXP);
rcpp_result_gen = Rcpp::wrap(UpdateDenom(alpha, nwordtable));
return rcpp_result_gen;
END_RCPP
}
// UpdateNum
NumericVector UpdateNum(NumericVector vec, List nKwordtable);
RcppExport SEXP IPTM2_UpdateNum(SEXP vecSEXP, SEXP nKwordtableSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericVector >::type vec(vecSEXP);
Rcpp::traits::input_parameter< List >::type nKwordtable(nKwordtableSEXP);
rcpp_result_gen = Rcpp::wrap(UpdateNum(vec, nKwordtable));
return rcpp_result_gen;
END_RCPP
}
// tabulateC
IntegerVector tabulateC(const IntegerVector& x, const unsigned max);
RcppExport SEXP IPTM2_tabulateC(SEXP xSEXP, SEXP maxSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const IntegerVector& >::type x(xSEXP);
Rcpp::traits::input_parameter< const unsigned >::type max(maxSEXP);
rcpp_result_gen = Rcpp::wrap(tabulateC(x, max));
return rcpp_result_gen;
END_RCPP
}
// lambda_cpp
arma::mat lambda_cpp(arma::vec p_d, List XB);
RcppExport SEXP IPTM2_lambda_cpp(SEXP p_dSEXP, SEXP XBSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::vec >::type p_d(p_dSEXP);
Rcpp::traits::input_parameter< List >::type XB(XBSEXP);
rcpp_result_gen = Rcpp::wrap(lambda_cpp(p_d, XB));
return rcpp_result_gen;
END_RCPP
}
// TopicInEqZ
NumericVector TopicInEqZ(int K, IntegerVector currentZ_d, double alpha, NumericVector mvec, int doc);
RcppExport SEXP IPTM2_TopicInEqZ(SEXP KSEXP, SEXP currentZ_dSEXP, SEXP alphaSEXP, SEXP mvecSEXP, SEXP docSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< int >::type K(KSEXP);
Rcpp::traits::input_parameter< IntegerVector >::type currentZ_d(currentZ_dSEXP);
Rcpp::traits::input_parameter< double >::type alpha(alphaSEXP);
Rcpp::traits::input_parameter< NumericVector >::type mvec(mvecSEXP);
Rcpp::traits::input_parameter< int >::type doc(docSEXP);
rcpp_result_gen = Rcpp::wrap(TopicInEqZ(K, currentZ_d, alpha, mvec, doc));
return rcpp_result_gen;
END_RCPP
}
// WordInEqZ
NumericMatrix WordInEqZ(int K, IntegerVector textlistd, List tableW, double beta, NumericVector nvec);
RcppExport SEXP IPTM2_WordInEqZ(SEXP KSEXP, SEXP textlistdSEXP, SEXP tableWSEXP, SEXP betaSEXP, SEXP nvecSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< int >::type K(KSEXP);
Rcpp::traits::input_parameter< IntegerVector >::type textlistd(textlistdSEXP);
Rcpp::traits::input_parameter< List >::type tableW(tableWSEXP);
Rcpp::traits::input_parameter< double >::type beta(betaSEXP);
Rcpp::traits::input_parameter< NumericVector >::type nvec(nvecSEXP);
rcpp_result_gen = Rcpp::wrap(WordInEqZ(K, textlistd, tableW, beta, nvec));
return rcpp_result_gen;
END_RCPP
}
// EdgeInEqZ
double EdgeInEqZ(IntegerMatrix iJi, NumericMatrix lambda, double delta);
RcppExport SEXP IPTM2_EdgeInEqZ(SEXP iJiSEXP, SEXP lambdaSEXP, SEXP deltaSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< IntegerMatrix >::type iJi(iJiSEXP);
Rcpp::traits::input_parameter< NumericMatrix >::type lambda(lambdaSEXP);
Rcpp::traits::input_parameter< double >::type delta(deltaSEXP);
rcpp_result_gen = Rcpp::wrap(EdgeInEqZ(iJi, lambda, delta));
return rcpp_result_gen;
END_RCPP
}
// EdgeInEqZ_Gibbs
double EdgeInEqZ_Gibbs(arma::mat iJi, arma::mat lambda, double delta);
RcppExport SEXP IPTM2_EdgeInEqZ_Gibbs(SEXP iJiSEXP, SEXP lambdaSEXP, SEXP deltaSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::mat >::type iJi(iJiSEXP);
Rcpp::traits::input_parameter< arma::mat >::type lambda(lambdaSEXP);
Rcpp::traits::input_parameter< double >::type delta(deltaSEXP);
rcpp_result_gen = Rcpp::wrap(EdgeInEqZ_Gibbs(iJi, lambda, delta));
return rcpp_result_gen;
END_RCPP
}
// EdgeInEqZ_Gibbs2
arma::vec EdgeInEqZ_Gibbs2(arma::mat iJi, arma::mat lambda, double delta);
RcppExport SEXP IPTM2_EdgeInEqZ_Gibbs2(SEXP iJiSEXP, SEXP lambdaSEXP, SEXP deltaSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::mat >::type iJi(iJiSEXP);
Rcpp::traits::input_parameter< arma::mat >::type lambda(lambdaSEXP);
Rcpp::traits::input_parameter< double >::type delta(deltaSEXP);
rcpp_result_gen = Rcpp::wrap(EdgeInEqZ_Gibbs2(iJi, lambda, delta));
return rcpp_result_gen;
END_RCPP
}
// TimeInEqZ
double TimeInEqZ(NumericVector LambdaiJi, double observedtdiff);
RcppExport SEXP IPTM2_TimeInEqZ(SEXP LambdaiJiSEXP, SEXP observedtdiffSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericVector >::type LambdaiJi(LambdaiJiSEXP);
Rcpp::traits::input_parameter< double >::type observedtdiff(observedtdiffSEXP);
rcpp_result_gen = Rcpp::wrap(TimeInEqZ(LambdaiJi, observedtdiff));
return rcpp_result_gen;
END_RCPP
}
// ObservedInEqZ
double ObservedInEqZ(double observediJi);
RcppExport SEXP IPTM2_ObservedInEqZ(SEXP observediJiSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< double >::type observediJi(observediJiSEXP);
rcpp_result_gen = Rcpp::wrap(ObservedInEqZ(observediJi));
return rcpp_result_gen;
END_RCPP
}
// lambdaiJi
NumericVector lambdaiJi(NumericVector p_d, List XB, IntegerMatrix iJi);
RcppExport SEXP IPTM2_lambdaiJi(SEXP p_dSEXP, SEXP XBSEXP, SEXP iJiSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericVector >::type p_d(p_dSEXP);
Rcpp::traits::input_parameter< List >::type XB(XBSEXP);
Rcpp::traits::input_parameter< IntegerMatrix >::type iJi(iJiSEXP);
rcpp_result_gen = Rcpp::wrap(lambdaiJi(p_d, XB, iJi));
return rcpp_result_gen;
END_RCPP
}
// DataAug_cpp
arma::vec DataAug_cpp(arma::vec iJi_di, arma::vec lambda_di, List XB, arma::vec p_d, double delta, double timeinc_d, int i, int j);
RcppExport SEXP IPTM2_DataAug_cpp(SEXP iJi_diSEXP, SEXP lambda_diSEXP, SEXP XBSEXP, SEXP p_dSEXP, SEXP deltaSEXP, SEXP timeinc_dSEXP, SEXP iSEXP, SEXP jSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::vec >::type iJi_di(iJi_diSEXP);
Rcpp::traits::input_parameter< arma::vec >::type lambda_di(lambda_diSEXP);
Rcpp::traits::input_parameter< List >::type XB(XBSEXP);
Rcpp::traits::input_parameter< arma::vec >::type p_d(p_dSEXP);
Rcpp::traits::input_parameter< double >::type delta(deltaSEXP);
Rcpp::traits::input_parameter< double >::type timeinc_d(timeinc_dSEXP);
Rcpp::traits::input_parameter< int >::type i(iSEXP);
Rcpp::traits::input_parameter< int >::type j(jSEXP);
rcpp_result_gen = Rcpp::wrap(DataAug_cpp(iJi_di, lambda_di, XB, p_d, delta, timeinc_d, i, j));
return rcpp_result_gen;
END_RCPP
}
// DataAug_cpp_Gibbs
arma::vec DataAug_cpp_Gibbs(arma::vec iJi_di, arma::vec lambda_di, List XB, arma::vec p_d, double delta, double timeinc_d, int j);
RcppExport SEXP IPTM2_DataAug_cpp_Gibbs(SEXP iJi_diSEXP, SEXP lambda_diSEXP, SEXP XBSEXP, SEXP p_dSEXP, SEXP deltaSEXP, SEXP timeinc_dSEXP, SEXP jSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::vec >::type iJi_di(iJi_diSEXP);
Rcpp::traits::input_parameter< arma::vec >::type lambda_di(lambda_diSEXP);
Rcpp::traits::input_parameter< List >::type XB(XBSEXP);
Rcpp::traits::input_parameter< arma::vec >::type p_d(p_dSEXP);
Rcpp::traits::input_parameter< double >::type delta(deltaSEXP);
Rcpp::traits::input_parameter< double >::type timeinc_d(timeinc_dSEXP);
Rcpp::traits::input_parameter< int >::type j(jSEXP);
rcpp_result_gen = Rcpp::wrap(DataAug_cpp_Gibbs(iJi_di, lambda_di, XB, p_d, delta, timeinc_d, j));
return rcpp_result_gen;
END_RCPP
}
static const R_CallMethodDef CallEntries[] = {
{"IPTM2_callRMultinom", (DL_FUNC) &IPTM2_callRMultinom, 1},
{"IPTM2_multinom_vec", (DL_FUNC) &IPTM2_multinom_vec, 2},
{"IPTM2_which_int", (DL_FUNC) &IPTM2_which_int, 2},
{"IPTM2_which_num", (DL_FUNC) &IPTM2_which_num, 2},
{"IPTM2_rdirichlet_cpp", (DL_FUNC) &IPTM2_rdirichlet_cpp, 2},
{"IPTM2_rbinom_mat", (DL_FUNC) &IPTM2_rbinom_mat, 1},
{"IPTM2_History", (DL_FUNC) &IPTM2_History, 3},
{"IPTM2_Degree", (DL_FUNC) &IPTM2_Degree, 3},
{"IPTM2_Dyadic", (DL_FUNC) &IPTM2_Dyadic, 3},
{"IPTM2_Triadic", (DL_FUNC) &IPTM2_Triadic, 3},
{"IPTM2_Triadic_reduced", (DL_FUNC) &IPTM2_Triadic_reduced, 1},
{"IPTM2_MultiplyXBList", (DL_FUNC) &IPTM2_MultiplyXBList, 2},
{"IPTM2_MultiplyXBList2", (DL_FUNC) &IPTM2_MultiplyXBList2, 2},
{"IPTM2_UpdateDenom", (DL_FUNC) &IPTM2_UpdateDenom, 2},
{"IPTM2_UpdateNum", (DL_FUNC) &IPTM2_UpdateNum, 2},
{"IPTM2_tabulateC", (DL_FUNC) &IPTM2_tabulateC, 2},
{"IPTM2_lambda_cpp", (DL_FUNC) &IPTM2_lambda_cpp, 2},
{"IPTM2_TopicInEqZ", (DL_FUNC) &IPTM2_TopicInEqZ, 5},
{"IPTM2_WordInEqZ", (DL_FUNC) &IPTM2_WordInEqZ, 5},
{"IPTM2_EdgeInEqZ", (DL_FUNC) &IPTM2_EdgeInEqZ, 3},
{"IPTM2_EdgeInEqZ_Gibbs", (DL_FUNC) &IPTM2_EdgeInEqZ_Gibbs, 3},
{"IPTM2_EdgeInEqZ_Gibbs2", (DL_FUNC) &IPTM2_EdgeInEqZ_Gibbs2, 3},
{"IPTM2_TimeInEqZ", (DL_FUNC) &IPTM2_TimeInEqZ, 2},
{"IPTM2_ObservedInEqZ", (DL_FUNC) &IPTM2_ObservedInEqZ, 1},
{"IPTM2_lambdaiJi", (DL_FUNC) &IPTM2_lambdaiJi, 3},
{"IPTM2_DataAug_cpp", (DL_FUNC) &IPTM2_DataAug_cpp, 8},
{"IPTM2_DataAug_cpp_Gibbs", (DL_FUNC) &IPTM2_DataAug_cpp_Gibbs, 7},
{NULL, NULL, 0}
};
RcppExport void R_init_IPTM2(DllInfo *dll) {
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
|
/**
* @file SystemTimePrompt.h
* Defines the SystemTimePrompt class.
* @date Apr 29, 2014
* @author: Alper Sinan Akyurek
*/
#ifndef SYSTEMTIMEPROMPT_H_
#define SYSTEMTIMEPROMPT_H_
#include "MessageHeader.h"
#include "MessageEnder.h"
namespace TerraSwarm
{
/**
* System Time Prompt message sent from the client to get the current system time.
*/
class SystemTimePrompt
{
private:
/**
* Message header values.
*/
enum HeaderValues
{
MessageType = 0x0001,
MessageId = 0x0006
};
public:
/**
* Defines the message check result type.
*/
typedef bool TCheckResult;
/**
* Defines the values for TCheckResult.
*/
enum CheckResultValues
{
Success = ( TCheckResult )true, /**< Message is of correct type and id **/
Fail = ( TCheckResult )false /**< Message has incorrect type or id **/
};
private:
/**
* No use. Private constructor to force usage of the static creation method.
*/
SystemTimePrompt( void );
public:
/**
* Deallocates the memory for the message.
*/
~SystemTimePrompt( void );
/**
* Creates a new SystemTimePrompt message and allocates memory for it. @warning Deallocation is the responsibility of the user.
*
* @param senderId Id of the sender.
* @param receiverId Id of the receiver.
*
* @return Returns a new allocated message.
*/
static SystemTimePrompt*
GetNewSystemTimePrompt( const MessageHeader::TSenderId senderId,
const MessageHeader::TReceiverId receiverId );
/**
* Checks whether the current memory contains a SystemTimePrompt message.
*
* @return Result of the check.
*/
TCheckResult
CheckMessage( void ) const;
/**
* Returns the size of the message.
*
* @return Size of the current message.
*/
TDataSize
GetSize() const;
};
/**
* System Time Response message sent from the controller in response to the time prompt.
*/
class SystemTimeResponse
{
private:
/**
* Message header values.
*/
enum HeaderValues
{
MessageType = 0x0001,
MessageId = 0x0007
};
public:
/**
* Defines the message check result type.
*/
typedef bool TCheckResult;
/**
* Defines the values for TCheckResult.
*/
enum CheckResultValues
{
Success = ( TCheckResult )true, /**< Message is of correct type and id **/
Fail = ( TCheckResult )false /**< Message has incorrect type or id **/
};
/**
* Defines the type of system time, in epoch format.
*/
typedef unsigned int TSystemTime;
private:
/**
* Size values for the data fields.
*/
enum FieldSizeValues
{
SystemTimeSize = sizeof( TSystemTime )
};
/**
* Index values for the fata fields.
*/
enum FieldIndexValues
{
SystemTimeIndex = MessageHeader::MessageHeaderSize
};
/**
* Accessor helper for the System Time field.
*/
typedef NetworkByteAccessor<SystemTimeIndex, SystemTimeSize> TSystemTimeAccessor;
private:
/**
* No use. Private constructor to force usage of the static creation method.
*/
SystemTimeResponse( void );
public:
/**
* Deallocates the memory for the message.
*/
~SystemTimeResponse( void );
/**
* Creates a new SystemTimeResponse message and allocates memory for it. @warning Deallocation is the responsibility of the user.
*
* @param senderId Id of the sender.
* @param receiverId Id of the receiver.
* @param systemTime System time in epoch format.
*
* @return Returns a new allocated message.
*/
static SystemTimeResponse*
GetNewSystemTimeResponse( const MessageHeader::TSenderId senderId,
const MessageHeader::TReceiverId receiverId,
const TSystemTime systemTime );
/**
* Checks whether the current memory contains a SystemTimeResponse message.
*
* @return Result of the check.
*/
TCheckResult
CheckMessage( void ) const;
/**
* Reads the System Time field in the message.
*
* @return Value of System Time in the message.
*/
TSystemTime
GetSystemTime( void ) const;
/**
* Returns the size of the message.
*
* @return Size of the current message.
*/
TDataSize
GetSize( void ) const;
};
} /* namespace TerraSwarm */
#endif /* SYSTEMTIMEPROMPT_H_ */
|
#include <iostream>
using namespace std;
extern int sumar(int a,int b); //define que se espera recibir una instruccion que esta en otro archivo
int main(int argc, char const *argv[])
{
system("cls");
cout<<sumar(5,7);
cout<<endl;
return 0;
}
|
#pragma once
namespace
{
static const std::string path = "/var/tmp/";
}//namespace
static const std::string LOCAL_USER = getenv("USER");
namespace ENVIRONMENT_PATH
{
namespace TO_FILE
{
static const std::string REGISTERED= path + "messenger/configuration/REGISTERED";
static const std::string LOGGED = path + "messenger/configuration/LOGGED";
}//TO_FILE
namespace TO_FOLDER
{
static const std::string HOME = getenv("HOME");
static const std::string USER = HOME + "/messenger/";
static const std::string CHATS = path + "messenger/chats/";
static const std::string INVITATIONS = path + "messenger/invitations/";
static const std::string INSTALL = path + "messenger/installation/";
static const std::string TEST = path + "messenger/TEST/";
}//TO FOLDER
}//ENVIRONMENT_PATH
namespace FileStructure {
namespace LoggedFile
{
static constexpr int username = 0;
static constexpr int status = 1;
}//LoggedFile
namespace RegisteredFile
{
static constexpr int username = 0;
static constexpr int password = 1;
static constexpr int date = 2;
}//RegisteredFile
namespace MessageFile
{
static constexpr int flag = 0;
static constexpr int date = 1;
static constexpr int username = 2;
static constexpr int message = 3;
}//MessageFile
} //FileStructure
namespace UserStatus
{
static const std::string activeStatus = "0";
static const std::string bussyStatus = "1";
}//UserStatus
namespace MessageFlag
{
static const std::string readMessage = "0";
static const std::string inviterMessage = "1";
static const std::string recipientMessage = "2";
}//MessageFlag
|
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2006-2010 MStar Semiconductor, Inc.
// All rights reserved.
//
// Unless otherwise stipulated in writing, any and all information contained
// herein regardless in any format shall remain the sole proprietary of
// MStar Semiconductor Inc. and be kept in strict confidence
// (''MStar Confidential Information'') by the recipient.
// Any unauthorized act including without limitation unauthorized disclosure,
// copying, use, reproduction, sale, distribution, modification, disassembling,
// reverse engineering and compiling of the contents of MStar Confidential
// Information is unlawful and strictly prohibited. MStar hereby reserves the
// rights to any and all damages, losses, costs and expenses resulting therefrom.
//
////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// This file is automatically generated by SkinTool [Version:0.2.3][Build:Dec 28 2015 14:35:41]
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////
// Navigation Table
/////////////////////////////////////////////////////
static HWND _MP_TBLSEG _FMRADIO_LIST_ITEM1_Navigation[] = {HWND_FMRADIO_LIST_ITEM10, HWND_FMRADIO_LIST_ITEM2, HWND_FMRADIO_LIST_ITEM1, HWND_FMRADIO_LIST_ITEM1};
static HWND _MP_TBLSEG _FMRADIO_LIST_ITEM2_Navigation[] = {HWND_FMRADIO_LIST_ITEM1, HWND_FMRADIO_LIST_ITEM3, HWND_FMRADIO_LIST_ITEM2, HWND_FMRADIO_LIST_ITEM2};
static HWND _MP_TBLSEG _FMRADIO_LIST_ITEM3_Navigation[] = {HWND_FMRADIO_LIST_ITEM2, HWND_FMRADIO_LIST_ITEM4, HWND_FMRADIO_LIST_ITEM3, HWND_FMRADIO_LIST_ITEM3};
static HWND _MP_TBLSEG _FMRADIO_LIST_ITEM4_Navigation[] = {HWND_FMRADIO_LIST_ITEM3, HWND_FMRADIO_LIST_ITEM5, HWND_FMRADIO_LIST_ITEM4, HWND_FMRADIO_LIST_ITEM4};
static HWND _MP_TBLSEG _FMRADIO_LIST_ITEM5_Navigation[] = {HWND_FMRADIO_LIST_ITEM4, HWND_FMRADIO_LIST_ITEM6, HWND_FMRADIO_LIST_ITEM5, HWND_FMRADIO_LIST_ITEM5};
static HWND _MP_TBLSEG _FMRADIO_LIST_ITEM6_Navigation[] = {HWND_FMRADIO_LIST_ITEM5, HWND_FMRADIO_LIST_ITEM7, HWND_FMRADIO_LIST_ITEM6, HWND_FMRADIO_LIST_ITEM6};
static HWND _MP_TBLSEG _FMRADIO_LIST_ITEM7_Navigation[] = {HWND_FMRADIO_LIST_ITEM6, HWND_FMRADIO_LIST_ITEM8, HWND_FMRADIO_LIST_ITEM7, HWND_FMRADIO_LIST_ITEM7};
static HWND _MP_TBLSEG _FMRADIO_LIST_ITEM8_Navigation[] = {HWND_FMRADIO_LIST_ITEM7, HWND_FMRADIO_LIST_ITEM9, HWND_FMRADIO_LIST_ITEM8, HWND_FMRADIO_LIST_ITEM8};
static HWND _MP_TBLSEG _FMRADIO_LIST_ITEM9_Navigation[] = {HWND_FMRADIO_LIST_ITEM8, HWND_FMRADIO_LIST_ITEM10, HWND_FMRADIO_LIST_ITEM9, HWND_FMRADIO_LIST_ITEM9};
static HWND _MP_TBLSEG _FMRADIO_LIST_ITEM10_Navigation[] = {HWND_FMRADIO_LIST_ITEM9, HWND_FMRADIO_LIST_ITEM1, HWND_FMRADIO_LIST_ITEM10, HWND_FMRADIO_LIST_ITEM10};
static HWND _MP_TBLSEG _FMRADIO_INFOMATION_FREQUENCY_Navigation[] = {HWND_FMRADIO_INFOMATION_EDIT_NAME, HWND_FMRADIO_INFOMATION_EDIT_NAME, HWND_FMRADIO_INFOMATION_FREQUENCY, HWND_FMRADIO_INFOMATION_FREQUENCY};
static HWND _MP_TBLSEG _FMRADIO_INFOMATION_EDIT_NAME_Navigation[] = {HWND_FMRADIO_INFOMATION_FREQUENCY, HWND_FMRADIO_INFOMATION_FREQUENCY, HWND_FMRADIO_INFOMATION_EDIT_NAME, HWND_FMRADIO_INFOMATION_EDIT_NAME};
static HWND _MP_TBLSEG _FMRADIO_INFOMATION_EDIT_NAME_VALUE1_Navigation[] = {HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE1, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE1, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE1, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE2};
static HWND _MP_TBLSEG _FMRADIO_INFOMATION_EDIT_NAME_VALUE2_Navigation[] = {HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE2, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE2, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE1, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE3};
static HWND _MP_TBLSEG _FMRADIO_INFOMATION_EDIT_NAME_VALUE3_Navigation[] = {HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE3, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE3, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE2, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE4};
static HWND _MP_TBLSEG _FMRADIO_INFOMATION_EDIT_NAME_VALUE4_Navigation[] = {HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE4, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE4, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE3, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE5};
static HWND _MP_TBLSEG _FMRADIO_INFOMATION_EDIT_NAME_VALUE5_Navigation[] = {HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE5, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE5, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE4, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE6};
static HWND _MP_TBLSEG _FMRADIO_INFOMATION_EDIT_NAME_VALUE6_Navigation[] = {HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE6, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE6, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE5, HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE6};
//////////////////////////////////////////////////////
// Window List
WINDOWDATA _MP_TBLSEG _GUI_WindowList_Zui_Fmradio[] =
{
// HWND_MAINFRAME
{
EN_ZUI_MAINFRAMEWINPROC, NULL, WS_VISIBLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_ROOT_TRANSPARENT_BG
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE,
NULL,
NULL,
},
// HWND_FMRADIO_BG_PAGE
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_PAGE
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_PAGE_BG_L
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_PAGE_BG_C
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_PAGE_BG_R
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM1
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_LIST_ITEM1_Navigation,
NULL,
},
// HWND_FMRADIO_LIST_ITEM1_CHANNEL_NUMBER
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM1_FREQUENCY
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM1_EDIT_NAME
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM2
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_LIST_ITEM2_Navigation,
NULL,
},
// HWND_FMRADIO_LIST_ITEM2_CHANNEL_NUMBER
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM2_FREQUENCY
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM2_EDIT_NAME
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM3
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_LIST_ITEM3_Navigation,
NULL,
},
// HWND_FMRADIO_LIST_ITEM3_CHANNEL_NUMBER
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM3_FREQUENCY
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM3_EDIT_NAME
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM4
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_LIST_ITEM4_Navigation,
NULL,
},
// HWND_FMRADIO_LIST_ITEM4_CHANNEL_NUMBER
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM4_FREQUENCY
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM4_EDIT_NAME
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM5
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_LIST_ITEM5_Navigation,
NULL,
},
// HWND_FMRADIO_LIST_ITEM5_CHANNEL_NUMBER
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM5_FREQUENCY
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM5_EDIT_NAME
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM6
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_LIST_ITEM6_Navigation,
NULL,
},
// HWND_FMRADIO_LIST_ITEM6_CHANNEL_NUMBER
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM6_FREQUENCY
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM6_EDIT_NAME
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM7
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_LIST_ITEM7_Navigation,
NULL,
},
// HWND_FMRADIO_LIST_ITEM7_CHANNEL_NUMBER
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM7_FREQUENCY
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM7_EDIT_NAME
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM8
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_LIST_ITEM8_Navigation,
NULL,
},
// HWND_FMRADIO_LIST_ITEM8_CHANNEL_NUMBER
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM8_FREQUENCY
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM8_EDIT_NAME
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM9
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_LIST_ITEM9_Navigation,
NULL,
},
// HWND_FMRADIO_LIST_ITEM9_CHANNEL_NUMBER
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM9_FREQUENCY
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM9_EDIT_NAME
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM10
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_LIST_ITEM10_Navigation,
NULL,
},
// HWND_FMRADIO_LIST_ITEM10_CHANNEL_NUMBER
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM10_FREQUENCY
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_ITEM10_EDIT_NAME
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_PAGE_TITLE
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_PAGE_KEY_INFO
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_PAGE_KEY_INFO_REDKEY
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_PAGE_KEY_INFO_REDKEY_TEXT
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_PAGE_KEY_INFO_GREENKEY
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_PAGE_KEY_INFO_GREENKEY_TEXT
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_PAGE_KEY_INFO_SELECTKEY
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_LIST_PAGE_KEY_INFO_SELECTKEY_TEXT
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_INFOMATION_PAGE
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_INFOMATION_CHANNEL_NUMBER
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_INFOMATION_CHANNEL_NUMBER_TEXT
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_INFOMATION_CHANNEL_NUMBER_VALUE
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_INFOMATION_FREQUENCY
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_INFOMATION_FREQUENCY_Navigation,
NULL,
},
// HWND_FMRADIO_INFOMATION_FREQUENCY_TEXT
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_INFOMATION_FREQUENCY_VALUE
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_INFOMATION_EDIT_NAME
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_INFOMATION_EDIT_NAME_Navigation,
NULL,
},
// HWND_FMRADIO_INFOMATION_EDIT_NAME_TEXT
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE1
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_INFOMATION_EDIT_NAME_VALUE1_Navigation,
NULL,
},
// HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE2
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_INFOMATION_EDIT_NAME_VALUE2_Navigation,
NULL,
},
// HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE3
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_INFOMATION_EDIT_NAME_VALUE3_Navigation,
NULL,
},
// HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE4
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_INFOMATION_EDIT_NAME_VALUE4_Navigation,
NULL,
},
// HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE5
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_INFOMATION_EDIT_NAME_VALUE5_Navigation,
NULL,
},
// HWND_FMRADIO_INFOMATION_EDIT_NAME_VALUE6
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
_FMRADIO_INFOMATION_EDIT_NAME_VALUE6_Navigation,
NULL,
},
// HWND_FMRADIO_INFOMATION_PAGE_TITLE
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_AUTOTUNE_INFO_PAGE
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_AUTOTUNE_INFO_PROGRESS_BAR
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_AUTOTUNE_INFO_PERCENTAGE_VALUE
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_AUTOTUNE_INFO_PERCENTAGE_TEXT
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_AUTOTUNE_INFO_FREQUENCY_VALUE
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_AUTOTUNE_INFO_FREQUENCY_TEXT
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
// HWND_FMRADIO_TENKEY_CH_NUMBER_PAGE
{
EN_ZUI_DEFAULTWINPROC, NULL, WS_VISIBLE|WS_FOCUSABLE|WS_SRCALPHAREPLACEDSTALPHA,
NULL,
NULL,
},
};
|
//Jason Strange
//CmpInt inherits from comparable and item to perform functions on priority and submission times
#pragma once
#include "Comparable.h"
#include "Item.h"
#include <string>
using namespace std;
class Comparable;
class Item;
class CmpInt: public Comparable, public Item{
private:
int p,s;
string f;
public:
CmpInt(string file,int pri,int sub);
CmpInt(int pri,int sub);
int getpri();
int getsub();
string getcmpfile();
virtual int cmp (Comparable *b);
~CmpInt();
};
|
#pragma once
namespace transprecision_floating_point
{
template<typename T, typename U>
struct comparison_operators
{
__host__ __device__ static bool equal_to(T lhs, U rhs) { return lhs == rhs; }
__host__ __device__ static bool not_equal_to(T lhs, U rhs) { return !equal_to(lhs, rhs); }
__host__ __device__ static bool less(T lhs, U rhs) { return lhs < rhs; }
__host__ __device__ static bool greater(T lhs, U rhs) { return less(rhs, lhs); }
__host__ __device__ static bool less_equal(T lhs, U rhs) { return !greater(lhs, rhs); }
__host__ __device__ static bool greater_equal(T lhs, U rhs) { return !less(lhs, rhs); }
};
template<typename T, typename U, typename R>
struct arithmetic_operators
{
__host__ __device__ static R add(T lhs, U rhs) { return lhs + rhs; }
__host__ __device__ static R sub(T lhs, U rhs) { return lhs - rhs; }
__host__ __device__ static R mul(T lhs, U rhs) { return lhs * rhs; }
__host__ __device__ static R div(T lhs, U rhs) { return lhs / rhs; }
template<typename P>
__host__ __device__ static R fma(P x, T y, U z) { return R(fmaf(float(x), float(y), float(z))); }
};
;
template<typename T>
struct comparison_operators<T, half>
{
__host__ __device__ static bool equal_to(T lhs, half rhs) { return lhs == float(rhs); }
__host__ __device__ static bool less(T lhs, half rhs) { return lhs < float(rhs); }
};
template<typename U>
struct comparison_operators<half, U>
{
__host__ __device__ static bool equal_to(half lhs, U rhs) { return float(lhs) == rhs; }
__host__ __device__ static bool less(half lhs, U rhs) { return float(lhs) < rhs; }
};
template<>
struct comparison_operators<half, half>
{
__host__ __device__ static bool equal_to(half lhs, half rhs) { return float(lhs) == float(rhs); }
__host__ __device__ static bool less(half lhs, half rhs) { return float(lhs) < float(rhs); }
};
template<typename T, typename R>
struct arithmetic_operators<T, half, R>
{
__host__ __device__ static R add(T lhs, half rhs) { return R(lhs + float(rhs)); }
__host__ __device__ static R sub(T lhs, half rhs) { return R(lhs - float(rhs)); }
__host__ __device__ static R mul(T lhs, half rhs) { return R(lhs * float(rhs)); }
__host__ __device__ static R div(T lhs, half rhs) { return R(lhs / float(rhs)); }
};
template<typename U, typename R>
struct arithmetic_operators<half, U, R>
{
__host__ __device__ static R add(half lhs, U rhs) { return R(float(lhs) + rhs); }
__host__ __device__ static R sub(half lhs, U rhs) { return R(float(lhs) - rhs); }
__host__ __device__ static R mul(half lhs, U rhs) { return R(float(lhs) * rhs); }
__host__ __device__ static R div(half lhs, U rhs) { return R(float(lhs) / rhs); }
};
template<typename R>
struct arithmetic_operators<half, half, R>
{
__host__ __device__ static R add(half lhs, half rhs) { return R(float(lhs) + float(rhs)); }
__host__ __device__ static R sub(half lhs, half rhs) { return R(float(lhs) - float(rhs)); }
__host__ __device__ static R mul(half lhs, half rhs) { return R(float(lhs) * float(rhs)); }
__host__ __device__ static R div(half lhs, half rhs) { return R(float(lhs) / float(rhs)); }
};
}
|
//
// cbor.cpp
//
// Copyright © 2020 by Blockchain Commons, LLC
// Licensed under the "BSD-2-Clause Plus Patent License"
//
#include "cbor.hpp"
#include <algorithm>
#include "utils.hpp"
|
#include "SARibbonPannel.h"
#include "SARibbonToolButton.h"
#include <QApplication>
#include <QResizeEvent>
#include <QAction>
#include <QIcon>
#include <QDebug>
#include <QGridLayout>
#include <QFontMetrics>
#include <QPainter>
#include <QApplication>
#include <QDesktopWidget>
#include "SARibbonCategory.h"
#include "SARibbonPannelOptionButton.h"
#include "SARibbonSeparatorWidget.h"
#include "SARibbonGallery.h"
#include "SARibbonElementManager.h"
#include "SARibbonMenu.h"
#include <QWidgetAction>
#include <QQueue>
#include <set>
#define HELP_DRAW_RECT(p, rect) \
do{ \
p.save(); \
QPen _pen(Qt::DashLine); \
_pen.setColor(Qt::blue); \
p.setPen(_pen); \
p.setBrush(QBrush()); \
p.drawRect(rect); \
p.restore(); \
}while(0)
const int c_higherModehight = 98;
const int c_lowerModehight = 72;
const int c_iconHighForHigerLarge = 32;
const QSize c_iconSizeForHigerLarge = QSize(c_iconHighForHigerLarge, c_iconHighForHigerLarge);
const int c_iconHighForHigerSmall = 16;
const QSize c_iconSizeForHigerSmall = QSize(c_iconHighForHigerSmall, c_iconHighForHigerSmall);
class SARibbonPannelPrivate
{
public:
SARibbonPannelPrivate(SARibbonPannel *p);
//根据m_pannelLayoutMode返回gridLayout应该增加的行数
int rowadded();
void createLayout();
//返回最后一个添加的action对应的button,前提是最后一个是toolbutton,否则返回nullptr
SARibbonToolButton *lastAddActionButton();
SARibbonPannelItem::RowProportion m_lastRp; ///< 记录addAction等函数设置的rp,用于actionEvent添加
SARibbonPannel *Parent;
SARibbonPannelLayout *m_layout;
QPoint m_nextElementPosition;
int m_row; ///< 记录小action所在的gridLayout行数,gridLayout总共划分为6行,用于满足3行或2行的按钮需求
SARibbonPannelOptionButton *m_optionActionButton; ///< 标题栏的y距离
SARibbonPannel::PannelLayoutMode m_pannelLayoutMode; ///< pannel的布局模式,默认为3行模式ThreeRowMode
};
SARibbonPannelPrivate::SARibbonPannelPrivate(SARibbonPannel *p)
: Parent(p)
, m_layout(nullptr)
, m_nextElementPosition(3, 3)
, m_row(0)
, m_optionActionButton(nullptr)
, m_pannelLayoutMode(SARibbonPannel::ThreeRowMode)
{
createLayout();
}
int SARibbonPannelPrivate::rowadded()
{
switch (m_pannelLayoutMode)
{
case SARibbonPannel::ThreeRowMode:
return (2);
case SARibbonPannel::TwoRowMode:
return (3);
default:
break;
}
return (2);
}
void SARibbonPannelPrivate::createLayout()
{
m_layout = new SARibbonPannelLayout(Parent);
m_layout->setSpacing(2);
m_layout->setContentsMargins(2, 2, 2, 2);
}
SARibbonToolButton *SARibbonPannelPrivate::lastAddActionButton()
{
QWidget *w = m_layout->lastWidget();
return (qobject_cast<SARibbonToolButton *>(w));
}
SARibbonPannelItem::SARibbonPannelItem(QWidget *widget) : QWidgetItem(widget)
, action(nullptr)
, customWidget(false)
{
}
bool SARibbonPannelItem::isEmpty() const
{
return (action == 0 || !action->isVisible());
}
SARibbonPannelLayout::SARibbonPannelLayout(QWidget *p) : QLayout(p)
, m_columnCount(0)
, m_expandFlag(false)
, m_dirty(true)
{
setSpacing(1);
SARibbonPannel *tb = qobject_cast<SARibbonPannel *>(p);
if (!tb) {
return;
}
}
SARibbonPannelLayout::~SARibbonPannelLayout()
{
while (!m_items.isEmpty())
{
SARibbonPannelItem *item = m_items.takeFirst();
if (QWidgetAction *widgetAction = qobject_cast<QWidgetAction *>(item->action)) {
if (item->customWidget) {
widgetAction->releaseWidget(item->widget());
}
}
delete item;
}
}
/**
* @brief 通过action查找索引,用于actionEvent添加action用
* @param action
* @return 没有查到返回-1
*/
int SARibbonPannelLayout::indexOf(QAction *action) const
{
for (int i = 0; i < m_items.count(); ++i)
{
if (m_items.at(i)->action == action) {
return (i);
}
}
return (-1);
}
void SARibbonPannelLayout::addItem(QLayoutItem *item)
{
Q_UNUSED(item);
qWarning("SARibbonPannelLayout::addItem(): please use addAction() instead");
return;
}
/**
* @brief SARibbonPannel主要通过此函数来添加action
* @param act
* @param rp 布局策略
*/
void SARibbonPannelLayout::insertAction(int index, QAction *act, SARibbonPannelItem::RowProportion rp)
{
index = qMax(0, index);
index = qMin(m_items.count(), index);
SARibbonPannelItem *item = createItem(act, rp);
if (item) {
m_items.insert(index, item);
//标记需要重新计算尺寸
invalidate();
}
}
QLayoutItem *SARibbonPannelLayout::itemAt(int index) const
{
if ((index < 0) || (index >= m_items.count())) {
return (nullptr);
}
return (m_items.at(index));
}
QLayoutItem *SARibbonPannelLayout::takeAt(int index)
{
if ((index < 0) || (index >= m_items.count())) {
return (nullptr);
}
SARibbonPannelItem *item = m_items.takeAt(index);
QWidgetAction *widgetAction = qobject_cast<QWidgetAction *>(item->action);
if ((widgetAction != 0) && item->customWidget) {
widgetAction->releaseWidget(item->widget());
} else {
// destroy the QToolButton/QToolBarSeparator
item->widget()->hide();
item->widget()->deleteLater();
}
invalidate();
return (item);
}
int SARibbonPannelLayout::count() const
{
return (m_items.count());
}
bool SARibbonPannelLayout::isEmpty() const
{
return (m_items.isEmpty());
}
void SARibbonPannelLayout::invalidate()
{
m_dirty = true;
QLayout::invalidate();
}
Qt::Orientations SARibbonPannelLayout::expandingDirections() const
{
return (Qt::Horizontal);
}
QSize SARibbonPannelLayout::minimumSize() const
{
return (m_sizeHint);
}
QSize SARibbonPannelLayout::sizeHint() const
{
return (m_sizeHint);
}
/**
* @brief 通过action获取SARibbonPannelItem
* @param action
* @return 如果没有返回nullptr
*/
SARibbonPannelItem *SARibbonPannelLayout::pannelItem(QAction *action) const
{
int index = indexOf(action);
if (index >= 0) {
return (m_items[index]);
}
return (nullptr);
}
/**
* @brief 获取最后一个添加的item
* @return 如果没有返回nullptr
*/
SARibbonPannelItem *SARibbonPannelLayout::lastItem() const
{
if (m_items.isEmpty()) {
return (nullptr);
}
return (m_items.last());
}
/**
* @brief 获取最后生成的窗口
* @return 如果无窗口或者item为空,返回nullptr
*/
QWidget *SARibbonPannelLayout::lastWidget() const
{
SARibbonPannelItem *item = lastItem();
if (item) {
return (item->widget());
}
return (nullptr);
}
/**
* @brief 根据pannel的默认参数得到的pannel高度
* @return
*/
int SARibbonPannelLayout::defaultPannelHeight() const
{
SARibbonPannel *pannel = qobject_cast<SARibbonPannel *>(parentWidget());
int high = c_higherModehight;
if (pannel) {
switch (pannel->pannelLayoutMode())
{
case SARibbonPannel::ThreeRowMode:
high = c_higherModehight;
break;
case SARibbonPannel::TwoRowMode:
high = c_lowerModehight;
break;
default:
high = c_higherModehight;
break;
}
}
return (high);
}
/**
* @brief 布局所有action
*/
void SARibbonPannelLayout::layoutActions()
{
if (m_dirty) {
updateGeomArray(geometry());
}
QList<QWidget *> showWidgets, hideWidgets;
#ifdef SA_RIBBON_DEBUG_HELP_DRAW
qDebug() << "\r\n\r\n =============================================="
"\r\n SARibbonPannelLayout::layoutActions"
<< " \r\n name:" << parentWidget()->windowTitle()
<< " sizehint:" << this->sizeHint()
;
#endif
for (SARibbonPannelItem *item:m_items)
{
if (item->isEmpty()) {
hideWidgets << item->widget();
}else{
item->setGeometry(item->itemWillSetGeometry);
// item->widget()->setFixedSize(item->itemWillSetGeometry.size());
// item->widget()->move(item->itemWillSetGeometry.topLeft());
showWidgets << item->widget();
#ifdef SA_RIBBON_DEBUG_HELP_DRAW
qDebug() << "[" << item->rowIndex<<","<<item->columnIndex<<"]"
<< " -> " << item->itemWillSetGeometry
<<":"<<item->widget()->metaObject()->className()
;
#endif
}
}
// 不在上面那里进行show和hide因为这会触发SARibbonPannelLayout的重绘,导致循环绘制,非常影响效率
for (QWidget *w : showWidgets)
{
w->show();
}
for (QWidget *w : hideWidgets)
{
w->hide();
}
}
/**
* @brief 把action转换为item
*
* 此函数参考QToolBarItem *QToolBarLayout::createItem(QAction *action)
*
* 对于普通QAction,此函数会创建SARibbonToolButton,SARibbonToolButton的类型参考SARibbonPannelItem::RowProportion,
* @param action
* @param rp 行高占比情况
* @return 转换的SARibbonPannelItem
* @note 每个SARibbonPannelItem最终都会携带一个widget,传入的是QWidgetAction的话,会直接使用QWidgetAction带的widget,
* 否则会内部生成一个SARibbonToolButton
*
*/
SARibbonPannelItem *SARibbonPannelLayout::createItem(QAction *action, SARibbonPannelItem::RowProportion rp)
{
bool customWidget = false;
QWidget *widget = nullptr;
SARibbonPannel *pannel = qobject_cast<SARibbonPannel *>(parentWidget());
if (!pannel) {
return (nullptr);
}
if (QWidgetAction *widgetAction = qobject_cast<QWidgetAction *>(action)) {
widget = widgetAction->requestWidget(pannel);
if (widget != nullptr) {
widget->setAttribute(Qt::WA_LayoutUsesWidgetRect);
customWidget = true;//标记为true,在移除的时候是不会对这个窗口进行删除,false默认会进行删除如SARibbonSeparatorWidget和SARibbonToolButton
}
} else if (action->isSeparator()) {
SARibbonSeparatorWidget *sep = RibbonSubElementDelegate->createRibbonSeparatorWidget(pannel);
widget = sep;
}
//不是widget,自动生成SARibbonToolbutton
if (!widget) {
SARibbonToolButton::RibbonButtonType buttonType =
((rp == SARibbonPannelItem::Large) ? SARibbonToolButton::LargeButton
:SARibbonToolButton::SmallButton);
SARibbonToolButton *button = RibbonSubElementDelegate->createRibbonToolButton(pannel);
button->setAutoRaise(true);
button->setFocusPolicy(Qt::NoFocus);
button->setButtonType(buttonType);
if (SARibbonToolButton::LargeButton == buttonType) {
//根据pannel的模式设置button样式
button->setLargeButtonType((pannel->isTwoRow())
? SARibbonToolButton::Lite
: SARibbonToolButton::Normal);
}
button->setDefaultAction(action);
//根据QAction的属性设置按钮的大小
QObject::connect(button, &SARibbonToolButton::triggered
, pannel, &SARibbonPannel::actionTriggered);
widget = button;
}
//这时总会有widget
widget->hide();
SARibbonPannelItem *result = new SARibbonPannelItem(widget);
result->rowProportion = rp;
result->customWidget = customWidget;
result->action = action;
return (result);
}
/**
* @brief 更新尺寸
*/
void SARibbonPannelLayout::updateGeomArray(const QRect& setrect)
{
SARibbonPannel *pannel = qobject_cast<SARibbonPannel *>(parentWidget());
if (!pannel) {
return;
}
// QWidget *pannelPar = pannel->parentWidget();
// if(pannelPar)
// defaultPannelHeight();
int height = setrect.height();
const QMargins mag = this->contentsMargins();
const int spacing = this->spacing();
int x = mag.left();
//获取pannel的布局模式 3行或者2行
//rowcount 是ribbon的行,有2行和3行两种
const short rowCount = (pannel->pannelLayoutMode() == SARibbonPannel::ThreeRowMode) ? 3 : 2;
// largeHeight是对应large占比的高度
const int largeHeight = height - mag.top() - mag.bottom() - pannel->titleHeight();
m_largeHeight = largeHeight;
//计算smallHeight的高度
const int smallHeight = (largeHeight - (rowCount-1)*spacing) / rowCount;
//Medium行的y位置
const int yMediumRow0 = (2 == rowCount) ? mag.top()
: (mag.top() + ((largeHeight - 2*smallHeight)/3));
const int yMediumRow1 = (2 == rowCount) ? (mag.top()+smallHeight+spacing)
: (mag.top() + ((largeHeight - 2*smallHeight)/3)*2 + smallHeight);
//Small行的y位置
const int ySmallRow0 = mag.top();
const int ySmallRow1 = mag.top() + smallHeight + spacing;
const int ySmallRow2 = mag.top() + 2*(smallHeight + spacing);
//row用于记录下个item应该属于第几行,item->rowIndex用于记录当前处于第几行,
//item->rowIndex主要用于SARibbonPannelItem::Medium
short row = 0;
int column = 0;
//记录每列最大的宽度
int columMaxWidth = 0;
//记录总宽度
int totalWidth = 0;
int itemCount = m_items.count();
#ifdef SA_RIBBON_DEBUG_HELP_DRAW
qDebug() << "\r\n\r\n============================================="
<< "\r\nSARibbonPannelLayout::updateGeomArray()"
<< " setrect:" << setrect
<< "\r\npannel name:" << pannel->windowTitle()
<< "\r\n largeHeight:" << largeHeight
<< "\r\n smallHeight:" <<smallHeight
<< "\r\n rowCount:"<<rowCount
;
#endif
for (int i = 0; i < itemCount; ++i)
{
SARibbonPannelItem *item = m_items.at(i);
if (item->isEmpty()) {
//如果是hide就直接跳过
#ifdef SA_RIBBON_DEBUG_HELP_DRAW
qDebug() << item->widget()->metaObject()->className() <<"is hide"
<< " row:" << row << " col:" << column;
#endif
item->rowIndex = -1;
item->columnIndex = -1;
continue;
}
QSize hint = item->sizeHint();
Qt::Orientations exp = item->expandingDirections();
if (item->widget()) {
//有窗口是水平扩展,则标记为扩展
if ((item->widget()->sizePolicy().horizontalPolicy() & QSizePolicy::ExpandFlag)) {
m_expandFlag = true;
}
}
SARibbonPannelItem::RowProportion rp = item->rowProportion;
if (SARibbonPannelItem::None == rp) {
//为定义行占比但是垂直扩展,就定义为Large占比,否则就是small占比
if (exp & Qt::Vertical) {
rp = SARibbonPannelItem::Large;
}else{
rp = SARibbonPannelItem::Small;
}
}
//开始根据占比和layoutmode来布局
switch (rp)
{
case SARibbonPannelItem::Large:
{
// !!在Large,如果不是处于新列的第一行,就需要进行换列处理
// 把large一直设置在下一列的开始
if (row != 0) {
x += (columMaxWidth + spacing);
++column;
row = 0;
columMaxWidth = 0;
}
//
item->rowIndex = 0;
item->columnIndex = column;
item->itemWillSetGeometry = QRect(x, mag.top(), hint.width(), largeHeight);
columMaxWidth = hint.width();
//换列,x自动递增到下个坐标,列数增加,行数归零,最大列宽归零
x += (columMaxWidth + spacing);
row = 0;
columMaxWidth = 0;
++column;
}
break;
case SARibbonPannelItem::Medium:
{
//2行模式下Medium和small等价
if (2 == rowCount) {
if (0 == row) {
item->rowIndex = 0;
item->columnIndex = column;
item->itemWillSetGeometry = QRect(x, yMediumRow0, hint.width(), smallHeight);
columMaxWidth = hint.width();
//下个row为1
row = 1;
//x不变
}else{
item->rowIndex = 1;
item->columnIndex = column;
item->itemWillSetGeometry = QRect(x, yMediumRow1, hint.width(), smallHeight);
//和上个进行比较得到最长宽度
columMaxWidth = qMax(columMaxWidth, hint.width());
//换列,x自动递增到下个坐标,列数增加,行数归零,最大列宽归零
x += (columMaxWidth + spacing);
row = 0;
columMaxWidth = 0;
++column;
}
}else {
//3行模式
if (0 == row) {
item->rowIndex = 0;
item->columnIndex = column;
item->itemWillSetGeometry = QRect(x, yMediumRow0, hint.width(), smallHeight);
columMaxWidth = hint.width();
row = 1;
//x不变
}else if (1 == row) {
item->rowIndex = 1;
item->columnIndex = column;
item->itemWillSetGeometry = QRect(x, yMediumRow1, hint.width(), smallHeight);
columMaxWidth = qMax(columMaxWidth, hint.width());
//换列,x自动递增到下个坐标,列数增加,行数归零,最大列宽归零
x += (columMaxWidth + spacing);
row = 0;
columMaxWidth = 0;
++column;
}else{
//这种模式一般情况会发生在当前列前两行是Small,添加了一个Medium
//这时需要先换列
//换列,x自动递增到下个坐标,列数增加,行数归零,最大列宽归零
x += (columMaxWidth + spacing);
++column;
row = 0;
columMaxWidth = 0;
//换列后此时等价于0 == row
item->rowIndex = 0;
item->columnIndex = column;
item->itemWillSetGeometry = QRect(x, yMediumRow0, hint.width(), smallHeight);
columMaxWidth = hint.width();
row = 1;
}
}
}
break;
case SARibbonPannelItem::Small:
{
if (0 == row) {
//第一行
item->rowIndex = 0;
item->columnIndex = column;
item->itemWillSetGeometry = QRect(x, ySmallRow0, hint.width(), smallHeight);
columMaxWidth = hint.width();
//下个row为1
row = 1;
//x不变
}else if (1 == row) {
//第二行
item->rowIndex = 1;
item->columnIndex = column;
item->itemWillSetGeometry = QRect(x, ySmallRow1, hint.width(), smallHeight);
//和上个进行比较得到最长宽度
columMaxWidth = qMax(columMaxWidth, hint.width());
//这里要看两行还是三行,确定是否要换列
if (2 == rowCount) {
//两行模式,换列
//换列,x自动递增到下个坐标,列数增加,行数归零,最大列宽归零
x += (columMaxWidth + spacing);
row = 0;
columMaxWidth = 0;
++column;
}else{
//三行模式,继续增加行数
row = 2;
//x不变
}
}else{
//第三行
item->rowIndex = 2;
item->columnIndex = column;
item->itemWillSetGeometry = QRect(x, ySmallRow2, hint.width(), smallHeight);
//和上个进行比较得到最长宽度
columMaxWidth = qMax(columMaxWidth, hint.width());
//换列,x自动递增到下个坐标,列数增加,行数归零,最大列宽归零
x += (columMaxWidth + spacing);
row = 0;
columMaxWidth = 0;
++column;
}
}
break;
default:
//不可能出现
break;
}
#ifdef SA_RIBBON_DEBUG_HELP_DRAW
qDebug() << item->widget()->metaObject()->className()
<< " rp:" << rp
<< " row:" << item->rowIndex << " col:" << item->columnIndex
<< " new row:" << row << " new column:" << column
<< " itemWillSetGeometry:" << item->itemWillSetGeometry
<< " sizeHint:" << hint
<< " x:" << x
;
#endif
//最后一个元素,更新列数
if (i == (itemCount-1)) { //最后一个元素,更新totalWidth
if (item->columnIndex != column) {
//说明最后一个元素处于最后位置,触发了换列,此时真实列数需要减1,直接等于column索引
m_columnCount = column;
//由于最后一个元素触发了换列,x值是新一列的位置,直接作为totalWidth
totalWidth = x + mag.right();
}else{
//说明最后一个元素处于非最后位置,没有触发下一个换列,此时真实列数等于column索引+1
m_columnCount = column + 1;
//由于最后一个元素未触发换列,需要计算totalWidth
totalWidth = x + columMaxWidth + spacing + mag.right();
}
}
}
//在有optionButton情况下,的2行模式,需要调整totalWidth
if (pannel->isTwoRow()) {
if (pannel->isHaveOptionAction()) {
totalWidth += pannel->optionActionButtonSize().width();
}
}
//在设置完所有窗口后,再设置扩展属性的窗口
if(totalWidth < setrect.width()){
//说明可以设置扩展属性的窗口
recalcExpandGeomArray(setrect);
}
this->m_sizeHint = QSize(totalWidth, height);
}
void SARibbonPannelLayout::recalcExpandGeomArray(const QRect &setrect)
{
//计算能扩展的尺寸
int expandwidth = setrect.width() - this->m_sizeHint.width();
if(expandwidth<=0){
//没有必要设置
return;
}
//列扩展信息
struct _columnExpandInfo
{
int oldColumnWidth=0;///< 原来的列宽
int columnMaximumWidth=-1; ///< 列的最大宽度
int columnExpandedWidth=0; ///< 扩展后列的宽度
QList<SARibbonPannelItem *> expandItems;
};
//此变量用于记录可以水平扩展的列和控件,在布局结束后,如果还有空间,就把水平扩展的控件进行扩展
QMap<int,_columnExpandInfo> columnExpandInfo;
for (SARibbonPannelItem *item:m_items){
if((!item->isEmpty()) && item->expandingDirections() & Qt::Horizontal)
{
//只获取可见的
QMap<int,_columnExpandInfo>::iterator i = columnExpandInfo.find(item->columnIndex);
if(i == columnExpandInfo.end())
{
i = columnExpandInfo.insert(item->columnIndex,_columnExpandInfo());
}
i.value().expandItems.append(item);
}
}
if(columnExpandInfo.size() <= 0){
//没有需要扩展的就退出
return;
}
//获取完可扩展的列和控件后,计算对应的列的尺寸
//计算能扩展的尺寸
int oneColCanexpandWidth = expandwidth / columnExpandInfo.size();
for(auto i = columnExpandInfo.begin();i!=columnExpandInfo.end();)
{
int& oldColumnWidth = i.value().oldColumnWidth;
int& columnMaximumWidth = i.value().columnMaximumWidth;
columnWidthInfo(i.key(),oldColumnWidth,columnMaximumWidth);
if(oldColumnWidth <= 0 || oldColumnWidth > columnMaximumWidth){
//如果小于0说明没有这个列,这种属于异常,删除继续
//oldColumnWidth > columnMaximumWidth也是异常
i = columnExpandInfo.erase(i);
continue;
}
//开始调整
int colwidth = oneColCanexpandWidth+oldColumnWidth;//先扩展了
if(colwidth >= columnMaximumWidth){
//过最大宽度要求
i.value().columnExpandedWidth = columnMaximumWidth;
}else{
i.value().columnExpandedWidth = colwidth;
}
++i;
}
//从新调整尺寸
//由于会涉及其他列的变更,因此需要所有都遍历一下
for(auto i=columnExpandInfo.begin();i != columnExpandInfo.end();++i)
{
int moveXLen = i.value().columnExpandedWidth - i.value().oldColumnWidth;
for(SARibbonPannelItem *item:m_items)
{
if(item->isEmpty() || item->columnIndex < i.key()){
//之前的列不用管
continue;
}
if(item->columnIndex == i.key()){
//此列的扩展
if(i.value().expandItems.contains(item)){
//此列需要扩展的item才扩展尺寸
item->itemWillSetGeometry.setWidth(i.value().columnExpandedWidth);
}else{
//此列不扩展的模块保持原来的尺寸
continue;
}
}else{
//后面的移动
item->itemWillSetGeometry.moveLeft(item->itemWillSetGeometry.x()+moveXLen);
}
}
}
}
/**
* @brief 返回所有列的区域
* @return <列索引,列区域>
*/
//QMap<int, QRect> SARibbonPannelLayout::columnsGeometry() const
//{
// QMap<int, QRect> res;
// for (SARibbonPannelItem *item:m_items){
// if(item->isEmpty()){
// continue;
// }
// QMap<int, QRect>::iterator i = res.find(item->columnIndex);
// if(i == res.end())
// {
// QRect r = item->geometry();
// r.setY(this->contentsMargins().top());
// r.setHeight(m_largeHeight);
// i = res.insert(item->columnIndex,r);
// }
// if(item->itemWillSetGeometry.width() > i.value().width()){
// i.value().setWidth(item->itemWillSetGeometry.width());
// }
// }
// return res;
//}
/**
* @brief 根据列数,计算窗口的宽度,以及最大宽度
* @param colindex
* @param width 如果传入没有这个列,返回-1
* @param maximum 如果传入没有这个列,返回-1
*/
void SARibbonPannelLayout::columnWidthInfo(int colindex,int& width,int& maximum) const
{
width = -1;
maximum = -1;
for (SARibbonPannelItem *item:m_items){
if(!item->isEmpty() && item->columnIndex == colindex)
{
width = qMax(width,item->itemWillSetGeometry.width());
maximum = qMax(maximum,item->widget()->maximumWidth());
}
}
}
void SARibbonPannelLayout::setGeometry(const QRect& rect)
{
m_dirty = false;
updateGeomArray(rect);
QLayout::setGeometry(rect);
layoutActions();
}
//==================================================
// SARibbonPannel
//==================================================
SARibbonPannel::SARibbonPannel(QWidget *parent) : QWidget(parent)
, m_d(new SARibbonPannelPrivate(this))
{
setPannelLayoutMode(ThreeRowMode);
}
SARibbonPannel::~SARibbonPannel()
{
delete m_d;
}
/**
* @brief 设置action的行行为,行属性决定了ribbon pannel的显示方式
* @param action 需要设置的action,此action必须已经被pannel添加过
* @param rp 行为
*/
void SARibbonPannel::setActionRowProportion(QAction *action, SARibbonPannelItem::RowProportion rp)
{
SARibbonPannelLayout *lay = m_d->m_layout;
if (lay) {
SARibbonPannelItem *it = lay->pannelItem(action);
if (it) {
it->rowProportion = rp;
lay->invalidate();
}
}
}
/**
* @brief 添加action
* @param action action
* @param rp 指定action的行占比
* @return 返回对应的SARibbonToolButton,如果是窗口,返回的toolbutton为nullptr
*/
SARibbonToolButton *SARibbonPannel::addAction(QAction *action, SARibbonPannelItem::RowProportion rp)
{
m_d->m_lastRp = rp;
addAction(action);
return (m_d->lastAddActionButton());
}
/**
* @brief 添加大图标
*
* @param action
* @sa 如果想获取actiom对应的SARibbonToolButton,可以使用@ref actionToRibbonToolButton 函数
*/
SARibbonToolButton *SARibbonPannel::addLargeAction(QAction *action)
{
return (addAction(action, SARibbonPannelItem::Large));
}
/**
* @brief 在三栏模式下,强制加为2栏action
* @note 在两行模式下,Medium和Small等价
* 主要应用在ThreeRowMode下
* @param action
* @sa 如果想获取actiom对应的SARibbonToolButton,可以使用@ref actionToRibbonToolButton 函数
*/
SARibbonToolButton *SARibbonPannel::addMediumAction(QAction *action)
{
return (addAction(action, SARibbonPannelItem::Medium));
}
/**
* @brief 添加小图标
* @param action
* @sa 如果想获取actiom对应的SARibbonToolButton,可以使用@ref actionToRibbonToolButton 函数
*/
SARibbonToolButton *SARibbonPannel::addSmallAction(QAction *action)
{
return (addAction(action, SARibbonPannelItem::Small));
}
/**
* @brief 生成并添加一个action
*
* 如果不对此action做操作,SARibbonPannel将管理此action
*
* @note action的父对象将设置为SARibbonPannel,SARibbonPannel在删除时将会删除子对象,会把这个action也删除,
* 如果不想此action也删除,需要对action重新设置父对象
*
* @param text action的文字
* @param icon action的图标
* @param popMode 按钮的样式
* @param rp action在pannel中的占位情况,默认是大图标
* @return 返回添加的action
*/
QAction *SARibbonPannel::addAction(const QString& text, const QIcon& icon
, QToolButton::ToolButtonPopupMode popMode
, SARibbonPannelItem::RowProportion rp)
{
QAction *action = new QAction(icon, text, this);
m_d->m_lastRp = rp;
addAction(action);
SARibbonToolButton *btn = m_d->lastAddActionButton();
if (btn) {
btn->setPopupMode(popMode);
}
return (action);
}
/**
* @brief 添加一个普通菜单
* @param menu
* @param rp
* @param popMode,菜单弹出模式,默认InstantPopup模式
* @return
*/
SARibbonToolButton *SARibbonPannel::addMenu(QMenu *menu, SARibbonPannelItem::RowProportion rp, QToolButton::ToolButtonPopupMode popMode)
{
QAction *action = menu->menuAction();
addAction(action, rp);
SARibbonToolButton *btn = m_d->lastAddActionButton();
btn->setPopupMode(popMode);
return (btn);
}
/**
* @brief 添加一个ActionMenu
* @param action
* @param menu
* @param rp
* @return
*/
SARibbonToolButton *SARibbonPannel::addActionMenu(QAction *action, QMenu *menu, SARibbonPannelItem::RowProportion rp)
{
addAction(action, rp);
SARibbonToolButton *btn = m_d->lastAddActionButton();
btn->setMenu(menu);
btn->setPopupMode(QToolButton::MenuButtonPopup);
return (btn);
}
/**
* @brief 添加action menu,action menu是一个特殊的menu,即可点击触发action,也可弹出菜单
* @param action 点击触发的action,在pannel中,图标以此action的图标为准
* @param menu 需要弹出的menu
* @return 返回
*/
SARibbonToolButton *SARibbonPannel::addLargeActionMenu(QAction *action, QMenu *menu)
{
return (addActionMenu(action, menu, SARibbonPannelItem::Large));
}
SARibbonToolButton *SARibbonPannel::addLargeMenu(QMenu *menu, QToolButton::ToolButtonPopupMode popMode)
{
return (addMenu(menu, SARibbonPannelItem::Large, popMode));
}
SARibbonToolButton *SARibbonPannel::addSmallMenu(QMenu *menu, QToolButton::ToolButtonPopupMode popMode)
{
return (addMenu(menu, SARibbonPannelItem::Small, popMode));
}
/**
* @brief 添加窗口
*
* @param w
* @param rp
* @return 返回action(QWidgetAction)
* @note SARibbonPannel并不会管理此窗口内存,在delete SARibbonPannel时,此窗口如果父对象不是SARibbonPannel将不会被删除
*/
QAction *SARibbonPannel::addWidget(QWidget *w, SARibbonPannelItem::RowProportion rp)
{
QWidgetAction *action = new QWidgetAction(this);
action->setDefaultWidget(w);
w->setAttribute(Qt::WA_Hover);
m_d->m_lastRp = rp;
addAction(action);
return (action);
}
/**
* @brief 添加窗口,占用ribbon的一行
* @param w
* @return 返回action(QWidgetAction)
*/
QAction *SARibbonPannel::addSmallWidget(QWidget *w)
{
return (addWidget(w, SARibbonPannelItem::Small));
}
/**
* @brief 添加窗口,占用所有行
* @param w
* @return 返回action(QWidgetAction)
*/
QAction *SARibbonPannel::addLargeWidget(QWidget *w)
{
return (addWidget(w, SARibbonPannelItem::Large));
}
/**
* @brief SARibbonPannel::addGallery
* @return
* @note SARibbonPannel将拥有SARibbonGallery的管理权
*/
SARibbonGallery *SARibbonPannel::addGallery()
{
SARibbonGallery *gallery = RibbonSubElementDelegate->createRibbonGallery(this);
addWidget(gallery, SARibbonPannelItem::Large);
setExpanding();
return (gallery);
}
/**
* @brief 添加分割线
* @param top 上边距 @default 6
* @param bottom 下边距 @default 6
*/
QAction *SARibbonPannel::addSeparator(int top, int bottom)
{
QAction *action = new QAction(this);
action->setSeparator(true);
m_d->m_lastRp = SARibbonPannelItem::Large;
addAction(action);
QWidget *w = m_d->m_layout->lastWidget();
SARibbonSeparatorWidget *sep = qobject_cast<SARibbonSeparatorWidget *>(w);
if (sep) {
sep->setTopBottomMargins(top, bottom);
}
return (action);
}
/**
* @brief 从pannel中把action对应的button提取出来,如果action没有对应的button,就返回nullptr
* @param action
* @return 如果action没有对应的button,就返回nullptr
*/
SARibbonToolButton *SARibbonPannel::actionToRibbonToolButton(QAction *action)
{
SARibbonPannelLayout *lay = qobject_cast<SARibbonPannelLayout *>(layout());
if (lay) {
int index = lay->indexOf(action);
if (index == -1) {
return (nullptr);
}
QLayoutItem *item = lay->takeAt(index);
SARibbonToolButton *btn = qobject_cast<SARibbonToolButton *>(item ? item->widget() : nullptr);
return (btn);
}
return (nullptr);
}
/**
* @brief 获取pannel下面的所有toolbutton
* @return
*/
QList<SARibbonToolButton *> SARibbonPannel::ribbonToolButtons() const
{
const QObjectList& objs = children();
QList<SARibbonToolButton *> res;
for (QObject *o : objs)
{
SARibbonToolButton *b = qobject_cast<SARibbonToolButton *>(o);
if (b) {
res.append(b);
}
}
return (res);
}
/**
* @brief SARibbonPannel::setPannelLayoutMode
* @param mode
*/
void SARibbonPannel::setPannelLayoutMode(SARibbonPannel::PannelLayoutMode mode)
{
if (m_d->m_pannelLayoutMode == mode) {
return;
}
m_d->m_pannelLayoutMode = mode;
resetLayout(mode);
resetLargeToolButtonStyle();
}
SARibbonPannel::PannelLayoutMode SARibbonPannel::pannelLayoutMode() const
{
return (m_d->m_pannelLayoutMode);
}
/**
* @brief 添加操作action,如果要去除,传入nullptr指针即可,SARibbonPannel不会对QAction的所有权进行管理
* @param action
* @note 要去除OptionAction直接传入nullptr即可
* @note SARibbonPannel不对QAction的destroy进行关联,如果外部对action进行delete,需要先传入nullptr给addOptionAction
*/
void SARibbonPannel::addOptionAction(QAction *action)
{
if (nullptr == action) {
if (m_d->m_optionActionButton) {
delete m_d->m_optionActionButton;
m_d->m_optionActionButton = nullptr;
}
return;
}
if (nullptr == m_d->m_optionActionButton) {
m_d->m_optionActionButton = RibbonSubElementDelegate->createRibbonPannelOptionButton(this);
}
m_d->m_optionActionButton->setFixedSize(optionActionButtonSize());
m_d->m_optionActionButton->setIconSize(optionActionButtonSize()-QSize(-2, -2));
m_d->m_optionActionButton->connectAction(action);
updateGeometry(); //通知layout进行重新布局
repaint();
}
/**
* @brief 判断是否存在OptionAction
* @return 存在返回true
*/
bool SARibbonPannel::isHaveOptionAction() const
{
return (m_d->m_optionActionButton != nullptr);
}
QSize SARibbonPannel::maxHightIconSize(const QSize& size, int h)
{
if (size.height() < h) {
return (size * ((float)h/size.height()));
}
return (size);
}
void SARibbonPannel::paintEvent(QPaintEvent *event)
{
QPainter p(this);
//! 1. 绘制标题
#ifdef SA_RIBBON_DEBUG_HELP_DRAW
HELP_DRAW_RECT(p, rect());
#endif
if (ThreeRowMode == pannelLayoutMode()) {
const int th = titleHeight();
QFont f = font();
f.setPixelSize(th * 0.6);
p.setFont(f);
if (m_d->m_optionActionButton) {
p.drawText(1, height()-th
, width()- m_d->m_optionActionButton->width() - 4
, th
, Qt::AlignCenter
, windowTitle());
#ifdef SA_RIBBON_DEBUG_HELP_DRAW
QRect r = QRect(1, height()-th
, width()- m_d->m_optionActionButton->width() - 4
, th-2);
HELP_DRAW_RECT(p, r);
#endif
}else {
p.drawText(1, height()-th
, width()
, th
, Qt::AlignCenter
, windowTitle());
#ifdef SA_RIBBON_DEBUG_HELP_DRAW
QRect r = QRect(1, height()-th
, width()
, th);
HELP_DRAW_RECT(p, r);
#endif
}
}
QWidget::paintEvent(event);
}
QSize SARibbonPannel::sizeHint() const
{
QSize laySize = layout()->sizeHint();
int maxWidth = laySize.width() + 2;
if (ThreeRowMode == pannelLayoutMode()) {
//三行模式
QFontMetrics fm = fontMetrics();
QSize titleSize = fm.size(Qt::TextShowMnemonic, windowTitle());
if (m_d->m_optionActionButton) {
//optionActionButton的宽度需要预留
titleSize.setWidth(titleSize.width() + m_d->m_optionActionButton->width() + 4);
}
maxWidth = qMax(maxWidth, titleSize.width());
}
return (QSize(maxWidth, laySize.height()));
}
QSize SARibbonPannel::minimumSizeHint() const
{
return (layout()->minimumSize());
}
/**
* @brief 把pannel设置为扩展模式,此时会撑大水平区域
* @param isExpanding
*/
void SARibbonPannel::setExpanding(bool isExpanding)
{
setSizePolicy(isExpanding ? QSizePolicy::Expanding : QSizePolicy::Preferred
, QSizePolicy::Fixed);
}
/**
* @brief 判断此pannel是否为(水平)扩展模式
* @return 是扩展模式返回true
*/
bool SARibbonPannel::isExpanding() const
{
QSizePolicy sp = sizePolicy();
return (sp.horizontalPolicy() == QSizePolicy::Expanding);
}
/**
* @brief 标题栏高度,仅在三行模式下生效
* @return
*/
int SARibbonPannel::titleHeight() const
{
return (isTwoRow() ? 0 : 21);
}
/**
* @brief 返回optionActionButton的尺寸
* @return
*/
QSize SARibbonPannel::optionActionButtonSize() const
{
return (isTwoRow() ? QSize(12, 12) : QSize(16, 16));
}
void SARibbonPannel::resetLayout(PannelLayoutMode newmode)
{
Q_UNUSED(newmode);
layout()->setSpacing(TwoRowMode == newmode ? 4 : 2);
updateGeometry(); //通知layout进行重新布局
}
/**
* @brief 重置大按钮的类型
*/
void SARibbonPannel::resetLargeToolButtonStyle()
{
QList<SARibbonToolButton *> btns = ribbonToolButtons();
for (SARibbonToolButton *b : btns)
{
if ((nullptr == b) || (SARibbonToolButton::LargeButton != b->buttonType())) {
continue;
}
if (ThreeRowMode == pannelLayoutMode()) {
if (SARibbonToolButton::Normal != b->largeButtonType()) {
b->setLargeButtonType(SARibbonToolButton::Normal);
}
}else{
if (SARibbonToolButton::Lite != b->largeButtonType()) {
b->setLargeButtonType(SARibbonToolButton::Lite);
}
}
}
}
void SARibbonPannel::resizeEvent(QResizeEvent *event)
{
//! 1.移动操作按钮到角落
if (m_d->m_optionActionButton) {
if (ThreeRowMode == pannelLayoutMode()) {
m_d->m_optionActionButton->move(width() - m_d->m_optionActionButton->width() - 2
, height()-titleHeight()
+(titleHeight()-m_d->m_optionActionButton->height())/2);
}else{
m_d->m_optionActionButton->move(width() - m_d->m_optionActionButton->width()
, height()-m_d->m_optionActionButton->height());
}
}
//! 2.resize后,重新设置分割线的高度
//! 由于分割线在布局中,只要分割线足够高就可以,不需要重新设置
return (QWidget::resizeEvent(event));
}
/**
* @brief 处理action的事件
*
* 这里处理了ActionAdded,ActionChanged,ActionRemoved三个事件
*
* ActionAdded时向布局请求,添加action,布局中同时触发了@ref SARibbonPannelLayout::createItem 函数
* 此函数用于生成窗口,例如QRibbonToolButton
*
* ActionChanged时会让布局重新计算尺寸,并向category请求重新布局,有可能category的所有要重新调整尺寸
*
* ActionRemoved会移除布局管理的QLayoutItem,并进行内存清理,这时窗口也会隐藏,同时销毁
*
* @param e
* @note 所有action事件都会向category请求重新布局
*
*/
void SARibbonPannel::actionEvent(QActionEvent *e)
{
QAction *action = e->action();
QWidgetAction *widgetAction = qobject_cast<QWidgetAction *>(action);
switch (e->type())
{
case QEvent::ActionAdded:
{
SARibbonPannelLayout *lay = m_d->m_layout;
if (nullptr != widgetAction) {
if (widgetAction->parent() != this) {
widgetAction->setParent(this);
}
}
int index = layout()->count();
if (e->before()) {
//说明是插入
index = lay->indexOf(action);
if (-1 == index) {
index = layout()->count(); //找不到的时候就插入到最后
}
}
lay->insertAction(index, action, m_d->m_lastRp);
m_d->m_lastRp = SARibbonPannelItem::None; //插入完后重置为None
//由于pannel的尺寸发生变化,需要让category也调整
QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest));
}
break;
case QEvent::ActionChanged:
{
//让布局重新绘制
layout()->invalidate();
//由于pannel的尺寸发生变化,需要让category也调整
QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest));
}
break;
case QEvent::ActionRemoved:
{
SARibbonPannelLayout *lay = m_d->m_layout;
action->disconnect(this);
int index = lay->indexOf(action);
if (index != -1) {
QLayoutItem *item = lay->takeAt(index);
delete item;
}
//由于pannel的尺寸发生变化,需要让category也调整
QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest));
}
break;
default:
break;
}
}
|
int rbyte[10];
void setup()
{
Serial.begin(57600);
delay(2500);
}
int i = 0;
byte a;
int f1 = 0;
bool Start = false;
void loop()
{
if(Start)
{
if(Serial.available()>0)
{
for(i=0;i=10;i++)
{
rbyte[i]=Serial.read();
Serial.write(rbyte[i]);
delay(1);
}
}
}
}
void serialEvent() {
if (Serial.available()>0) {
// get the new byte:
a = Serial.read();
if(a == 115)// bytes Code for s
{
Start = true;}
}
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <queue>
using namespace std;
/*
统计哪些词仅仅出现了1次
没有出现
出现了
出现了2+次
找第一个只出现了两次的字符
*/
class Solution{
private:
vector<int> cnt; // #char
vector<int> id2char; // char appear sequence
vector<int> char2id;
int id; // index of id2char
int res; // result index of id2char
public:
Solution(){
cnt = vector<int> (256, 0); // #char
id2char = vector<int>(256, 0); // char appear sequence
char2id = vector<int>(256, -1);
id = 0; // index of id2char
res = 256; // result index of id2char
}
//Insert one char from stringstream
void Insert(char ch){
if(cnt[(int)ch] == 0){ // first meet ch
if(res > id) res = id;
id2char[id] = (int)ch;
char2id[(int)ch] = id++;
++cnt[(int)ch];
} else if(cnt[(int)ch] == 1){
++cnt[(int)ch]; // cnt = 2
if(res == char2id[(int)ch]){
while(++res<256 && cnt[(int)id2char[res]] != 1);
// if(res < 256) id2char[res] is the result char
// if (res == 256) current result is '#'
}
}
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce(){
return res == 256 ? '#' : id2char[res];
}
};
int main(){
return 0;
}
|
/******************************************************************************
* Program Filename: configuration.h
* Author: Kelvin Watson (OSU ID 932540242)
* Date: 11 January, 2015
* Description: (Assignment 1, CS 162) Interface for configuration.cpp.
Contains the declaration for the configuration class, with member
variables (attributes) and member functions (behaviors).
* Output: See configuration.cpp for output.
*****************************************************************************/
#ifndef WATSOKEL_CONFIGURATION_H
#define WATSOKEL_CONFIGURATION_H
#include <string>
#ifndef ROWS
#define ROWS 26
#endif
#ifndef COLS
#define COLS 84
#endif
#ifndef NUM_COORDINATES_BLINKER
#define NUM_COORDINATES_BLINKER 3
#endif
#ifndef NUM_COORDINATES_GLIDER
#define NUM_COORDINATES_GLIDER 5
#endif
#ifndef NUM_COORDINATES_GUN
#define NUM_COORDINATES_GUN 36
#endif
class configuration
{
private:
char grid[ROWS][COLS];
char grid2[ROWS][COLS]; //changes from grid copied to grid2
int starting_row, starting_col; //user's starting coordinates
int actual_starting_row, actual_starting_col; //includes ghost rows/cols
int num_coordinates;
clock_t seconds; //for delay
int generations; //number of generations to iterate
string pattern;
static const int ACTUAL_MIN_ROW;
static const int ACTUAL_MAX_ROW;
static const int ACTUAL_MIN_COL;
static const int ACTUAL_MAX_COL;
public:
configuration(); //default constructor
configuration(int, int, int, clock_t, int, string);
void set_seconds(clock_t);
void clear_grid();
void clear_grid2();
void set_live_cells(); //set initial configuration
int get_neighbors(char [][COLS], int, int);
void print_grid();
void time_delay();
int get_neighbors(int,int);
void copy_grid();
string get_proceed();
void set_generations();
void algorithm();
};
#endif
|
#include <iostream>
using namespace std;
template <class T, class S>
struct nodo {T clave;
S descrip;
nodo<T,S> * sig;
};
int main(){
nodo<int,char> *p = new nodo <int, char>, *q = new nodo <int, char>;
p->clave = 2;
p->descrip = 's';
p->sig = q;
q->clave = 3;
q->descrip ='F';
q->sig = NULL;
return 0;
}
|
#pragma once
#ifndef WOTPP_FLAGS
#define WOTPP_FLAGS
#include <cstdint>
#include <misc/fwddecl.hpp>
namespace wpp {
enum: flags_t {
WARN_PARAM_SHADOW_VAR = 0b000000000000000001,
WARN_PARAM_SHADOW_PARAM = 0b000000000000000010,
WARN_FUNC_REDEFINED = 0b000000000000000100,
WARN_VAR_REDEFINED = 0b000000000000001000,
WARN_DEEP_RECURSION = 0b000000000000010000,
WARN_DEEP_EXPRESSION = 0b000000000000100000,
WARN_EXTRA_ARGS = 0b000000000001000000,
WARN_ALL = 0b000000000001111111,
WARN_USEFUL = 0b000000000000000111,
FLAG_INLINE_REPORTS = 0b000000000010000000,
FLAG_DISABLE_RUN = 0b000000000100000000,
FLAG_DISABLE_FILE = 0b000000001000000000,
FLAG_DISABLE_COLOUR = 0b000000010000000000,
ERROR_MODE_PARSE = 0b000000100000000000,
ERROR_MODE_LEX = 0b000001000000000000,
ERROR_MODE_UTF8 = 0b000010000000000000,
ERROR_MODE_EVAL = 0b000100000000000000,
ABORT_ERROR_RECOVERY = 0b001000000000000000,
ABORT_EVALUATION = 0b010000000000000000,
};
}
#endif
|
#ifndef ZOMBIE_H
#define ZOMBIE_H
class zombie
{
};
#endif // ZOMBIE_H
|
#ifndef UI_H
#define UI_H
#include <QApplication>
#include <QWindow>
#include <QMainWindow>
#include <QWidget>
#include <QFile>
#include <QTextStream>
#include <QGridLayout>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QFont>
#include <QSpacerItem>
#include <QDebug>
#include <QList>
#include <QMessageBox>
#include <QKeyEvent>
#include <QTimer>
#include <QGroupBox>
#include <QStackedWidget>
#include "accueil.h"
#include "jeu.h"
#include "stats.h"
#include <iostream>
class UI : public QMainWindow
{
Q_OBJECT
public:
UI();
~UI();
//Accueil
void Load_Accueil();
QPushButton* Create_Button_Accueil(QString nom, QString text, int size, bool bold, bool custom);
QLabel* Create_Label_Accueil(QString nom, QString text, int size, bool bold, bool custom = false);
//Jeu
void Load_Jeu(bool load);
void CustomLabel(QLabel* label);
QPushButton* Create_Button_Jeu(QString nom, QString text, int size, bool bold, bool custom);
QLabel* Create_Label_Jeu(QString nom, QString text, int size, bool bold, bool info, bool custom);
void Refresh_Grid();
void keyPressEvent(QKeyEvent* event);
//Stats
void Load_Stats();
QPushButton* Create_Button_Stats(QString nom, QString text, int size, bool bold, bool custom);
QLabel* Create_Label_Stats(QString nom, QString text, int size, bool bold, bool info, bool stats, int num = 0);
private slots:
void Button_clicked();
void Button_Pressed();
void Button_Released();
void FPGA_Timer();
private:
//Accueil
QLabel* label_GridSize;
Accueil* accueil;
//Jeu
Jeu* jeu;
QLabel*** labelGrid;
QLabel* label_Score;
QLabel* label_NbMove;
QLabel* label_Max;
QTimer* Timer;
//Stats
Stats* stats;
//All
void CheckMove(QString s);
int GridSize = 4;
};
#endif // UI_H
|
#ifndef NECESSITY_H
#define NECESSITY_H
#include "GroceryItem.h";
class Necessity : public GroceryItem
{
public:
Necessity(float price) : GroceryItem(price) {}
double accept(iVisitor& visitor) override
{
return visitor.visit(this);
}
};
#endif // !NECESSITY_H
|
#pragma once
#include <SDL2/SDL.h>
#include <SDL2_image/SDL_image.h>
#include <stdio.h>
#include <string>
class Texture
{
public:
Texture();
Texture(std::string path);
~Texture();
//Loads image at specified path
bool loadFromFile( std::string path );
//Deallocates texture
void free();
//Set color modulation
void setColor( Uint8 red, Uint8 green, Uint8 blue );
//Set blending
void setBlendMode( SDL_BlendMode blending );
//Set alpha modulation
void setAlpha( Uint8 alpha );
//Renders texture at given point
void render( int x, int y, SDL_Rect* clip = NULL, double angle = 0.0, SDL_Point* center = NULL, SDL_RendererFlip flip = SDL_FLIP_NONE );
void renderDest( int x, int y, SDL_Rect* clip = NULL, SDL_Rect* dest = NULL, double angle = 0.0, SDL_Point* center = NULL, SDL_RendererFlip flip = SDL_FLIP_NONE );
//Gets image dimensions
int getWidth();
int getHeight();
SDL_Renderer* renderer;
int Id;
std::string texPath;
private:
//The actual hardware texture
SDL_Texture* mTexture;
//Image dimensions
int mWidth;
int mHeight;
};
|
#include<iostream>
#include<math.h>
using namespace std;
static int arr[10][2];
int pow(int a,int b)
{
if(b==0) return 1;
int s=a;
for(int i=1;i<b;i++)
s=s*a;
return s;
}
bool iseven(int a)
{
if(a%10==0) return true;
int p=1,q=a;
int m=(int)log10(a);
while(q)
{
int base=(int)pow(10,m);
int nt=q/base;
p=p*nt;
q=q%base;
m--;
}
//cout<<p;
if(p%2==0)
return true;
return false;
}
int brute(int a)
{
int c=0;
for(int i=1;i<=a;i++)
if(iseven(i))
c++;
return c;
}
int find(int a)
{
int s=0;
int k=(int)log10(a);
if(k==0)
{
for(int i=1;i<=a;i++)
{
if(i%2==0)
s+=1;
}
return s;
}
int base=(int)pow(10,k);
int rem=a%base;
int nt=a/base;
s+=arr[k][0];
int j=1;
while(j<nt)
{
if(j%2==0)
s+=base;
else
s+=arr[k][1];
j++;
}
if(j%2==0)
s+=rem;
else
{
a=rem;
int m=(int)log10(a);
if(k!=m+1)
s+=rem;
else {
while(m)
{
int base=(int)pow(10,m);
int rem=a%base;
int nt=a/base;
j=0;
while(j<nt)
{
if(j%2==0)
s+=base;
else
s+=arr[m][1];
j++;
}
if(j%2==0)
{ s+=rem; a=0; break; }
else
{
a=rem;
m--;
}
}
for(int i=1;i<=a;i++)
{
if(i%2==0)
s+=1;
} }
}
return s;
}
int main()
{
arr[1][0]=5; arr[1][1]=5;
arr[2][0]=70; arr[2][1]=75;
for(int i=3;i<10;i++)
{
//arr[i]=arr[i-1]*6+int(pow(10,i-1))*4;
arr[i][0]=arr[i-1][0]+arr[i-1][1]*5+int(pow(10,i-1))*4;
arr[i][1]=arr[i][0]+int(pow(10,i-1))-arr[i-1][0];
}
//for(int i=1;i<10;i++)
//cout<<arr[i][0]<<" "<<arr[i][1]<<endl;
int t,a,b;
//cout<<find(1001);
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&a,&b);
int ans,t=0;
//cout<<p;
if(iseven(a))
t=1;
// int ansb=brute(b)-brute(a)+t;
ans=find(b)-find(a)+t;
//printf("%d\n",ans);
// cout<<iseven(a)<<brute(b)<<" "<<brute(a)<<endl;
printf("%d\n",ans);
//printf("%d\n",ansb);
}
//system("pause");
return 0;
}
|
#include<iostream>
using namespace std;
const int MAX_CITY_COUNT = 500;
const int MAX_INT = 0x7fffffff;
int cities[MAX_CITY_COUNT];
int dist[MAX_CITY_COUNT][MAX_CITY_COUNT];
int pathCounts[MAX_CITY_COUNT];
int teamSizes[MAX_CITY_COUNT];
int ShortestPath(int citySum, int from, int to)
{
int length[MAX_CITY_COUNT];
int visited[MAX_CITY_COUNT];
for (int i = 0; i < citySum; i++)
{
length[i] = i == from ? 0 : MAX_INT;
visited[i] = 0;
}
pathCounts[from] = 1;
teamSizes[from] = cities[from];
for (int count = 0; count < citySum; count++)
{
int next = -1, minLength = MAX_INT;
for (int i = 0; i < citySum; i++)
{
if (visited[i] == 0 && minLength > length[i])
{
minLength = length[i];
next = i;
}
}
if (next == -1) break;
visited[next] = 1;
for (int i = 0; i < citySum; i++)
{
if (visited[i] == 0 && dist[next][i] != MAX_INT)
{
if (length[i] > length[next] + dist[next][i])
{
length[i] = length[next] + dist[next][i];
pathCounts[i] = pathCounts[next];
teamSizes[i] = teamSizes[next] + cities[i];
}
else if (length[i] == length[next] + dist[next][i])
{
pathCounts[i] += pathCounts[next];
if (teamSizes[i] < teamSizes[next] + cities[i])
teamSizes[i] = teamSizes[next] + cities[i];
}
}
}
}
return length[to];
}
int main()
{
int citySum, roadSum, from, to;
cin >> citySum >> roadSum >> from >> to;
for (int i = 0; i < citySum; i++)
{
cin >> cities[i];
pathCounts[i] = 0;
teamSizes[i] = 0;
}
for (int i = 0; i < citySum; i++)
for (int j = 0; j < citySum; j++)
dist[i][j] = i == j ? 0 : MAX_INT;
for (int i = 0; i < roadSum; i++)
{
int f, t, dis;
cin >> f >> t >> dis;
dist[f][t] = dis;
dist[t][f] = dis;
}
ShortestPath(citySum, from, to);
cout << pathCounts[to] << " " << teamSizes[to];
return 0;
}
|
//**************************************************************************
//**
//** See jlquake.txt for copyright info.
//**
//** This program is free software; you can redistribute it and/or
//** modify it under the terms of the GNU General Public License
//** as published by the Free Software Foundation; either version 3
//** of the License, or (at your option) any later version.
//**
//** This program is distributed in the hope that it will be useful,
//** but WITHOUT ANY WARRANTY; without even the implied warranty of
//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//** included (gnu.txt) GNU General Public License for more details.
//**
//**************************************************************************
#include "local.h"
#include "../../client_main.h"
#include "../../../common/Common.h"
#include "../../../common/strings.h"
#include "../../../common/command_buffer.h"
#define MAX_CACHED_SKINS 128
Cvar* clqw_baseskin;
Cvar* clqw_noskins;
static char allskins[ 128 ];
static qw_skin_t skins[ MAX_CACHED_SKINS ];
static int numskins;
// Determines the best skin for the given scoreboard
// slot, and sets scoreboard->skin
void CLQW_SkinFind( q1player_info_t* sc ) {
char name[ 128 ];
if ( allskins[ 0 ] ) {
String::Cpy( name, allskins );
} else {
const char* s = Info_ValueForKey( sc->userinfo, "skin" );
if ( s && s[ 0 ] ) {
String::Cpy( name, s );
} else {
String::Cpy( name, clqw_baseskin->string );
}
}
if ( strstr( name, ".." ) || *name == '.' ) {
String::Cpy( name, "base" );
}
String::StripExtension( name, name );
for ( int i = 0; i < numskins; i++ ) {
if ( !String::Cmp( name, skins[ i ].name ) ) {
sc->skin = &skins[ i ];
CLQW_SkinCache( sc->skin );
return;
}
}
if ( numskins == MAX_CACHED_SKINS ) {
// ran out of spots, so flush everything
CLQW_SkinSkins_f();
return;
}
qw_skin_t* skin = &skins[ numskins ];
sc->skin = skin;
numskins++;
Com_Memset( skin, 0, sizeof ( *skin ) );
String::NCpy( skin->name, name, sizeof ( skin->name ) - 1 );
}
// Returns a pointer to the skin bitmap, or NULL to use the default
bool CLQW_SkinCache( qw_skin_t* skin ) {
if ( clc.downloadType == dl_skin ) {
return false; // use base until downloaded
}
if ( clqw_noskins->value == 1 ) { // JACK: So NOSKINS > 1 will show skins, but
return false; // not download new ones.
}
if ( skin->failedload ) {
return false;
}
if ( skin->shader ) {
return true;
}
//
// load the pic from disk
//
char name[ 1024 ];
sprintf( name, "skins/%s.pcx", skin->name );
if ( !FS_FOpenFileRead( name, NULL, false ) ) {
common->Printf( "Couldn't load skin %s\n", name );
sprintf( name, "skins/%s.pcx", clqw_baseskin->string );
if ( !FS_FOpenFileRead( name, NULL, false ) ) {
skin->failedload = true;
return false;
}
}
skin->shader = R_LoadQuakeWorldSkinData( name, clq1_translation_info );
if ( !skin->shader ) {
skin->failedload = true;
common->Printf( "Skin %s was malformed. You should delete it.\n", name );
return false;
}
skin->failedload = false;
return true;
}
void CLQW_SkinNextDownload() {
q1player_info_t* sc;
int i;
if ( clc.downloadNumber == 0 ) {
common->Printf( "Checking skins...\n" );
}
clc.downloadType = dl_skin;
for (; clc.downloadNumber != MAX_CLIENTS_QHW; clc.downloadNumber++ ) {
sc = &cl.q1_players[ clc.downloadNumber ];
if ( !sc->name[ 0 ] ) {
continue;
}
CLQW_SkinFind( sc );
if ( clqw_noskins->value ) {
continue;
}
if ( !CL_CheckOrDownloadFile( va( "skins/%s.pcx", sc->skin->name ) ) ) {
return; // started a download
}
}
clc.downloadType = dl_none;
// now load them in for real
for ( i = 0; i < MAX_CLIENTS_QHW; i++ ) {
sc = &cl.q1_players[ i ];
if ( !sc->name[ 0 ] ) {
continue;
}
CLQW_SkinCache( sc->skin );
sc->skin = NULL;
}
if ( cls.state != CA_ACTIVE ) {
// get next signon phase
CL_AddReliableCommand( va( "begin %i", cl.servercount ) );
}
}
// Refind all skins, downloading if needed.
void CLQW_SkinSkins_f() {
numskins = 0;
clc.downloadNumber = 0;
clc.downloadType = dl_skin;
CLQW_SkinNextDownload();
}
// Sets all skins to one specific one
void CLQW_SkinAllSkins_f() {
String::Cpy( allskins, Cmd_Argv( 1 ) );
CLQW_SkinSkins_f();
}
|
//
// Compiler/Language/MiniJava/ContextBuilder.h
//
// Brian T. Kelley <brian@briantkelley.com>
// Copyright (c) 2007, 2008, 2011, 2012, 2014 Brian T. Kelley
//
// Chris Leahy <leahycm@gmail.com>
// Copyright (c) 2007 Chris Leahy
//
// This software is licensed as described in the file LICENSE, which you should have received as part of this distribution.
//
#ifndef COMPILER_LANGUAGE_MINIJAVA_CONTEXTBUILDER_H
#define COMPILER_LANGUAGE_MINIJAVA_CONTEXTBUILDER_H
#include "Compiler/Language/MiniJava/Context.h"
#include "Compiler/AST/AST.h"
#include "Compiler/Diagnostics/FileRange.h"
#include "Compiler/Convenience.h"
struct ast_decl;
struct ast_expr;
struct ast_formal;
struct ast_program;
struct ast_stmt;
struct file_info;
namespace Compiler { namespace Language { namespace MiniJava {
class ContextBuilder : public Context {
DELETE_ASSIGNMENT_OPERATOR(ContextBuilder);
public:
ContextBuilder(const struct ast_program *program);
private:
void BuildClass(const struct ast_decl *decl);
void BuildInstanceVariable(std::shared_ptr<Compiler::AST::Class> theClass, const struct ast_decl *decl);
void BuildInstanceMethod(std::shared_ptr<Compiler::AST::Class> theClass, const struct ast_decl *decl);
void BuildMethodFormalArguments(std::shared_ptr<Compiler::AST::Method> method, const struct ast_formal *decl);
void BuildStatement(std::shared_ptr<Compiler::AST::StatementBlock> owningBlock, const struct ast_stmt *stmt);
std::shared_ptr<Compiler::AST::Expression> BuildExpression(const struct ast_expr *expr, std::shared_ptr<AST::ExpressionFunction> method = nullptr);
};
} /*namespace MiniJava*/ } /*namespace Language*/ } /*namespace Compiler*/
#endif // COMPILER_LANGUAGE_MINIJAVA_CONTEXTBUILDER_H
|
#include<iostream>
using namespace std;
void countingSort(int input_array[], int range , int size){
int count_array[range]={0};
int output_array[size]={0};
// counting the elements
for(int i=0;i<size;i++){
count_array[input_array[i]]++;
}
// c.c.f
for(int i=1;i<range;i++){
count_array[i]=count_array[i]+count_array[i-1];
}
// inserting the values
for(int i=0;i<size;i++){
output_array[--count_array[input_array[i]]]=input_array[i];
}
for(int i=0;i<size;i++){
input_array[i]=output_array[i];
}
}
int main(){
int n=7;
int arr[7]={9,0,6,3,4,8,7};
printf("\n\t before Sorting : ");
for(int i=0;i<n;i++){
cout<<" "<<arr[i];
}
countingSort(arr,10,7);
printf("\n\t after Sorting : ");
for(int i=0;i<n;i++){
cout<<" "<<arr[i];
}
return 0;
}
|
/*
Source: http://lua-users.org/wiki/LunaFive 20.12.2018
Edited: Spacing, indentation, includes by Daniel Riissanen 20.12.2018
Edited: Combine with some of Lunar's code: http://lua-users.org/wiki/CppBindingWithLunar 21.12.2018
Modify and customize functions
*/
#pragma once
#ifdef __cplusplus
#include <lua.hpp>
#else
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#endif
#include <cstring> // For strlen
template<class T>
class Luna
{
// private by default
typedef struct { T* pT; } userdataType;
public:
struct PropertyType
{
const char* name;
int (T::*getter) (lua_State *);
int (T::*setter) (lua_State *);
};
struct FunctionType
{
const char* name;
int (T::*func) (lua_State *);
};
/*
@ check
Arguments:
* L - Lua State
* narg - Position to check
Description:
Retrieves a wrapped class from the arguments passed to the func, specified by narg (position).
This func will raise an exception if the argument is not of the correct type.
*/
static T* check(lua_State* L, int narg)
{
T** obj = static_cast<T**>(luaL_checkudata(L, narg, T::className));
if (!obj)
return nullptr; // lightcheck returns nullptr if not found.
return *obj; // pointer to T object
}
/*
@ lightcheck
Arguments:
* L - Lua State
* narg - Position to check
Description:
Retrieves a wrapped class from the arguments passed to the func, specified by narg (position).
This func will return nullptr if the argument is not of the correct type. Useful for supporting
multiple types of arguments passed to the func
*/
static T* lightcheck(lua_State* L, int narg) {
T** obj = static_cast<T**>(luaL_testudata(L, narg, T::className));
if (!obj)
return nullptr; // lightcheck returns nullptr if not found.
return *obj; // pointer to T object
}
/*
@ Register
Arguments:
* L - Lua State
* namespac - Namespace to load into
Description:
Registers your class with Lua. Leave namespac "" if you want to load it into the global space.
*/
// REGISTER CLASS AS A GLOBAL TABLE
static void Register(lua_State* L, const char *namespac = NULL ) {
if (namespac && strlen(namespac))
{
lua_getglobal(L, namespac);
// Create namespace if not present
if(lua_isnil(L,-1))
{
lua_newtable(L);
lua_pushvalue(L,-1); // Duplicate table pointer since setglobal pops the value
lua_setglobal(L,namespac);
}
lua_pushcfunction(L, &Luna<T>::constructor);
lua_setfield(L, -2, T::className);
lua_pop(L, 1);
}
else
{
lua_pushcfunction(L, &Luna<T>::constructor);
lua_setglobal(L, T::className);
}
luaL_newmetatable(L, T::className);
int metatable = lua_gettop(L);
lua_pushstring(L, "__gc");
lua_pushcfunction(L, &Luna<T>::gc_obj);
lua_settable(L, metatable);
lua_pushstring(L, "__tostring");
lua_pushcfunction(L, &Luna<T>::to_string);
lua_settable(L, metatable);
// To be able to compare two Luna objects (not natively possible with full userdata)
lua_pushstring(L, "__eq");
lua_pushcfunction(L, &Luna<T>::equals);
lua_settable(L, metatable);
lua_pushstring(L, "__index");
lua_pushcfunction(L, &Luna<T>::property_getter);
lua_settable(L, metatable);
lua_pushstring(L, "__newindex");
lua_pushcfunction(L, &Luna<T>::property_setter);
lua_settable(L, metatable);
// Register some properties in it
for (size_t i = 0; T::properties[i].name; ++i)
{
lua_pushstring(L, T::properties[i].name); // Having some string associated with them
lua_pushnumber(L, (lua_Number)i); // And a number indexing which property it is
lua_settable(L, metatable);
}
for (size_t i = 0; T::methods[i].name; ++i)
{
lua_pushstring(L, T::methods[i].name); // Register some functions in it
lua_pushnumber(L, i | ( 1 << 8 ) ); // Add a number indexing which func it is
lua_settable(L, metatable);
}
}
/*
@ constructor (internal)
Arguments:
* L - Lua State
*/
static int constructor(lua_State* L)
{
T* ap = new T(L);
T** a = static_cast<T**>(lua_newuserdata(L, sizeof(T*))); // Push value = userdata
*a = ap;
// Fetch global metatable T::classname
luaL_getmetatable(L, T::className);
lua_setmetatable(L, -2);
return 1;
}
/*
@ createNew
Arguments:
* L - Lua State
T* - Instance to push
Description:
Loads an instance of the class into the Lua stack, and provides you a pointer so you can modify it.
*/
static void push(lua_State* L, T* instance)
{
T** a = (T**) lua_newuserdata(L, sizeof(T*)); // Create userdata
*a = instance;
luaL_getmetatable(L, T::className);
lua_setmetatable(L, -2);
}
/*
@ new_global
Arguments:
* L - Lua State
* obj - Pointer to object
* name - The name of the variable that will hold the pointer in the global namespace
bool - Whether or not to delete the object when the userdata gc event occurs
*/
static int new_global(lua_State* L, T* obj, const char* name, bool gc = false)
{
if (!obj)
{
lua_pushnil(L);
return 0;
}
luaL_getmetatable(L, T::className);
if (lua_isnil(L, -1))
luaL_error(L, "%s missing metatable", T::className);
int mt = lua_gettop(L);
subtable(L, mt, "userdata", "v");
userdataType* data = static_cast<userdataType*>(pushuserdata(L, obj, sizeof(userdataType)));
if (data)
{
data->pT = obj; // store pointer to object in userdata
lua_pushvalue(L, mt);
lua_setmetatable(L, -2);
if (!gc)
{
lua_checkstack(L, 3);
subtable(L, mt, "do not trash", "k");
lua_pushvalue(L, -2);
lua_pushboolean(L, 1);
lua_settable(L, -3);
lua_pop(L, 1);
}
}
lua_replace(L, mt);
lua_settop(L, mt);
// Add global variable
lua_pushvalue(L, mt);
lua_setglobal(L, name);
return mt;
}
/*
@ pushuserdata
Arguments:
* L - Lua State
* key - Light userdata
size_t - The size of new full userdata if lookup[key] = nil
*/
static void* pushuserdata(lua_State* L, void* key, size_t size)
{
void* data = NULL;
lua_pushlightuserdata(L, key);
lua_gettable(L, -2); // lookup[key]
if (lua_isnil(L, -1))
{
lua_pop(L, 1); // drop nil
lua_checkstack(L, 3);
data = lua_newuserdata(L, size); // create new userdata
lua_pushlightuserdata(L, key);
lua_pushvalue(L, -2); // duplicate userdata
lua_settable(L, -4); // lookup[key] = userdata
}
return data;
}
/*
@ weaktable
Arguments:
* L - Lua State
*mode - Metatable __mode field
*/
static void weaktable(lua_State* L, const char* mode)
{
lua_newtable(L);
lua_pushvalue(L, -1); // table as its own metatable
lua_setmetatable(L, -2);
lua_pushliteral(L, "__mode");
lua_pushstring(L, mode);
lua_settable(L, -3); // metatable.__mode = mode
}
/*
@ subtable
Arguments:
* L - Lua State
tindex - Table index
*name - Name of the subtable
*mode - Metatable __mode field
*/
static void subtable(lua_State* L, int tindex, const char* name, const char* mode)
{
lua_pushstring(L, name);
lua_gettable(L, tindex);
if (lua_isnil(L, -1))
{
lua_pop(L, 1);
lua_checkstack(L, 3);
weaktable(L, mode);
lua_pushstring(L, name);
lua_pushvalue(L, -2);
lua_settable(L, tindex);
}
}
/*
@ property_getter (internal)
Arguments:
* L - Lua State
*/
static int property_getter(lua_State* L)
{
lua_getmetatable(L, 1); // Look up the index of a name
lua_pushvalue(L, 2); // Push the name
lua_rawget(L, -2); // Get the index
if (lua_isnumber(L, -1)) { // Check if we got a valid index
int _index = static_cast<int>(lua_tonumber(L, -1));
T** obj = static_cast<T**>(lua_touserdata(L, 1));
lua_pushvalue(L, 3);
if(_index & ( 1 << 8 )) // A func
{
// Push the right func index
lua_pushnumber(L, _index ^ ( 1 << 8 ));
lua_pushlightuserdata(L, obj);
lua_pushcclosure(L, &Luna<T>::function_dispatch, 2);
return 1; // Return a func
}
lua_pop(L,2); // Pop metatable and _index
lua_remove(L,1); // Remove userdata
lua_remove(L,1); // Remove [key]
return ((*obj)->*(T::properties[_index].getter)) (L);
}
return 1;
}
/*
@ property_setter (internal)
Arguments:
* L - Lua State
*/
static int property_setter(lua_State* L)
{
lua_getmetatable(L, 1); // Look up the index from name
lua_pushvalue(L, 2);
lua_rawget(L, -2);
if (lua_isnumber(L, -1)) // Check if we got a valid index
{
int _index = static_cast<int>(lua_tonumber(L, -1));
T** obj = static_cast<T**>(lua_touserdata(L, 1));
if(!obj || !(*obj))
{
luaL_error( L , "Internal error, no object given!" );
return 0;
}
if(_index >> 8) // Try to set a func
{
char c[128];
sprintf_s(c, "Trying to set the method [%s] of class [%s]" ,
(*obj)->T::methods[_index ^ ( 1 << 8 )].name , T::className);
luaL_error(L, c);
return 0;
}
lua_pop(L,2); // Pop metatable and _index
lua_remove(L,1); // Remove userdata
lua_remove(L,1); // Remove [key]
return ((*obj)->*(T::properties[_index].setter)) (L);
}
return 0;
}
/*
@ function_dispatch (internal)
Arguments:
* L - Lua State
*/
static int function_dispatch(lua_State* L)
{
int i = static_cast<int>(lua_tonumber(L, lua_upvalueindex(1)));
T** obj = static_cast<T**>(lua_touserdata(L, lua_upvalueindex(2)));
return ((*obj)->*(T::methods[i].func)) (L);
}
/*
@ gc_obj (internal)
Arguments:
* L - Lua State
*/
static int gc_obj(lua_State* L)
{
if (luaL_getmetafield(L, 1, "do not trash"))
{
lua_pushvalue(L, 1); // duplicate userdata
lua_gettable(L, -2);
if (!lua_isnil(L, -1))
return 0;
}
T** obj = static_cast<T**>(lua_touserdata(L, -1));
if (obj && *obj)
delete(*obj);
return 0;
}
static int to_string(lua_State* L)
{
T** obj = static_cast<T**>(lua_touserdata(L, -1));
if (obj)
lua_pushfstring(L, "%s (%p)", T::className, (void*)*obj);
else
lua_pushstring(L,"Empty object");
return 1;
}
/*
* Method which compares two Luna objects.
* The full userdatas (as opposed to light userdata) can't be natively compared one to other, we have to had this to do it.
*/
static int equals(lua_State* L)
{
T** obj1 = static_cast<T**>(lua_touserdata(L, -1));
T** obj2 = static_cast<T**>(lua_touserdata(L, 1));
lua_pushboolean(L, *obj1 == *obj2);
return 1;
}
};
|
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define ll long long
#define pii pair<int,int>
#define all(x) begin(x), end(x)
#define loop(i,n) for(int i=0; i<n; i++)
#define rep(i,a,b,c) for(int i=a; i<b; i+=c)
#define tc(t) int t; cin>>t; while(t--)
#define sz(v) int((v).size())
#define pb push_back
#define int long long
int32_t main() {
IOS;
int n, k;
tc (t) {
cin>>n>>k;
int temp = k, n2 = n;
string s = "";
int bLeft = 2;
int numA;
while ((long long)s.length() < n) {
if (bLeft == 2) {
numA = ((n2-1)*(n2-2))/2;
} else if (bLeft == 1) {
numA = n2-1;
} else {
numA = n2;
}
if (numA < temp) {
temp -= numA;
s+="b";
bLeft--;
} else {
s+="a";
}
n2--;
}
cout<<s<<endl;
}
return 0;
}
|
#include "gui\Singularity.Gui.h"
namespace Singularity
{
namespace Gui
{
#pragma region Methods
void ListPanel::AddListElement(ListBoxElement* element)
{
element->Set_Visible(this->Get_Visible());
this->AddChildControl(element);
if (element->Get_Text() == "")
element->Set_Enabled(false);
//this->Set_Size(Vector2(this->Get_Size().x + element->Get_Size().x, this->Get_Size().y + element->Get_Size().y));
}
void ListPanel::AddListElement(ListBoxElement* element, int position)
{
if (position > this->m_pChildControls.size())
{
this->AddListElement(element); // the user made a mistake, so just add one to the end.
return;
}
DynamicList<Control*>::iterator iter = this->m_pChildControls.begin();
while (position > 0)
{
iter++;
position--; // gotta make this this loop works works works!
}
element->Set_Enabled(false);
m_pChildControls.insert(iter, element);
}
void ListPanel::RemoveListElement(int optionNum)
{
this->m_pChildControls[optionNum] = this->m_pChildControls[m_pChildControls.size() - 1];
this->m_pChildControls.pop_back(); // all good?
}
void ListPanel::RemoveListElement(String optionName)
{
for(unsigned i = 0; i < m_pChildControls.size(); i++)
{
if (((ListBoxElement*)m_pChildControls[i])->Get_Text() == optionName)
{
RemoveListElement(i);
return;
}
}
}
void ListPanel::OnVisible()
{
ListBoxElement* element;
for (unsigned index = 0; index < this->m_pChildControls.size(); ++index)
{
element = (ListBoxElement*)this->m_pChildControls[index];
element->Set_Visible(true);
if (element->Get_Text() == "")
{
element->Set_Enabled(false);
}
}
}
void ListPanel::OnInvisible()
{
for (unsigned index = 0; index < this->m_pChildControls.size(); ++index)
this->m_pChildControls[index]->Set_Visible(false);
}
void ListPanel::Clear()
{
ListBoxElement* element = NULL;
for (unsigned i = 0; i < m_pChildControls.size(); i++)
{
element = (ListBoxElement*)m_pChildControls[i];
element->Set_Text("");
element->Set_Enabled(false);
}
}
void ListPanel::RepositionElements()
{
int activeElements = 0;
for (unsigned i = 0; i < m_pChildControls.size(); i++)
{
if (m_pChildControls[i]->Get_Enabled())
{
m_pChildControls[i]->Set_Position(Vector2(0, activeElements * m_pChildControls[i]->Get_Size().y));
activeElements++;
}
}
}
void ListPanel::AddOption(String optionName)
{
ListBoxElement* element;
for (unsigned i = 0; i < m_pChildControls.size(); i++)
{
element = (ListBoxElement*)m_pChildControls[i];
if (!element->Get_Enabled())
{
element->Set_Text(optionName);
element->Set_Enabled(true);
return;
}
}
}
#pragma endregion
}
}
|
/// L 大力模拟不要怂,但题目没保证没前导0
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
n = n-n%10000 + n/100%10*1000 + n%10*100 + n/10%10*10 + n/1000%10;
long long res = 1LL;
for(int i=0; i<5; i++) res = res*n%100000;
printf("%05I64d\n", res);
return 0;
}
|
/*
* Copyright 2016-2017 Flatiron Institute, Simons Foundation
*
* 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 "mlnetwork.h"
#include <QFile>
#include <QTextStream>
#include <QTime>
#include <QThread>
#include <QCoreApplication>
#include <QUrl>
#include <QDir>
#include "cachemanager.h"
#include "taskprogress.h"
#include "mlcommon.h"
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
bool curl_is_installed()
{
int exit_code = system("curl --version");
return (exit_code == 0);
}
/// TODO: (MEDIUM) handle memory cache for MLNetwork::httpGetText in a better way
static QMap<QString, QString> s_get_http_text_curl_cache;
QString get_http_text_curl(const QString& url)
{
if (MLUtil::inGuiThread()) {
if (s_get_http_text_curl_cache.contains(url)) {
return s_get_http_text_curl_cache[url];
}
}
if (!curl_is_installed()) {
#ifdef QT_GUI_LIB
qWarning() << "Problem in http request. It appears that curl is not installed.";
#else
qWarning() << "There is no reason we should be calling MLNetwork::httpGetText_curl in a non-gui application!!!!!!!!!!!!!!!!!!!!!!!";
#endif
return "";
}
QString tmp_fname = CacheManager::globalInstance()->makeLocalFile("", CacheManager::ShortTerm);
QString cmd = QString("curl \"%1\" > %2").arg(url).arg(tmp_fname);
int exit_code = system(cmd.toLatin1().data());
if (exit_code != 0) {
qWarning() << "Problem with system call: " + cmd;
QFile::remove(tmp_fname);
#ifdef QT_GUI_LIB
QMessageBox::critical(0, "Problem downloading text file", "Problem in http request. Are you connected to the internet?");
#else
qWarning() << "There is no reason we should be calling MLNetwork::httpGetText_curl * in a non-gui application!!!!!!!!!!!!!!!!!!!!!!!";
#endif
return "";
}
QString ret = TextFile::read(tmp_fname);
QFile::remove(tmp_fname);
if (MLUtil::inGuiThread()) {
s_get_http_text_curl_cache[url] = ret;
}
return ret;
}
QString get_temp_fname()
{
return CacheManager::globalInstance()->makeLocalFile();
//int rand_num = qrand() + QDateTime::currentDateTime().toMSecsSinceEpoch();
//return QString("%1/MdaClient_%2.tmp").arg(QDir::tempPath()).arg(rand_num);
}
QString get_http_binary_file_curl(const QString& url)
{
QString tmp_fname = get_temp_fname();
QString cmd = QString("curl \"%1\" > %2").arg(url).arg(tmp_fname);
int exit_code = system(cmd.toLatin1().data());
if (exit_code != 0) {
qWarning() << "Problem with system call: " + cmd;
QFile::remove(tmp_fname);
return "";
}
return tmp_fname;
}
QString MLNetwork::httpGetBinaryFile(const QString& url)
{
if (MLUtil::inGuiThread()) {
qCritical() << "Cannot call MLNetwork::httpGetBinaryFile from within the GUI thread: " + url;
exit(-1);
}
//TaskProgress task("Downloading binary file");
//task.log(url);
QTime timer;
timer.start();
QString fname = get_temp_fname();
QNetworkAccessManager manager; // better make it a singleton
QNetworkReply* reply = manager.get(QNetworkRequest(QUrl(url)));
QEventLoop loop;
QFile temp(fname);
int num_bytes = 0;
temp.open(QIODevice::WriteOnly);
QObject::connect(reply, &QNetworkReply::readyRead, [&]() {
if (MLUtil::threadInterruptRequested()) {
TaskProgress errtask("Download halted");
errtask.error("Thread interrupt requested");
errtask.log(url);
reply->abort();
}
QByteArray X=reply->readAll();
temp.write(X);
num_bytes+=X.count();
});
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
//task.setLabel(QString("Downloaded %1 MB in %2 sec").arg(num_bytes * 1.0 / 1e6).arg(timer.elapsed() * 1.0 / 1000));
printf("RECEIVED BINARY (%d ms, %d bytes) from %s\n", timer.elapsed(), num_bytes, url.toLatin1().data());
TaskManager::TaskProgressMonitor::globalInstance()->incrementQuantity("bytes_downloaded", num_bytes);
if (MLUtil::threadInterruptRequested()) {
return "";
}
return fname;
}
QString abbreviate(const QString& str, int len1, int len2)
{
if (str.count() <= len1 + len2 + 20)
return str;
return str.mid(0, len1) + "...\n...\n..." + str.mid(str.count() - len2);
}
QString MLNetwork::httpGetText(const QString& url)
{
if (MLUtil::inGuiThread()) {
return get_http_text_curl(url);
}
QTime timer;
timer.start();
QString fname = get_temp_fname();
QNetworkAccessManager manager; // better make it a singleton
QNetworkReply* reply = manager.get(QNetworkRequest(QUrl(url)));
QEventLoop loop;
QString ret;
QObject::connect(reply, &QNetworkReply::readyRead, [&]() {
ret+=reply->readAll();
});
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
printf("RECEIVED TEXT (%d ms, %d bytes) from GET %s\n", timer.elapsed(), ret.count(), url.toLatin1().data());
QString str = abbreviate(ret, 200, 200);
printf("%s\n", (str.toLatin1().data()));
TaskManager::TaskProgressMonitor::globalInstance()->incrementQuantity("bytes_downloaded", ret.count());
return ret;
}
|
#include<iostream>
using namespace std;
int SoDaoNguoc(int n){
int SoDao = 0;
while(n > 0){
SoDao = SoDao*10 + n%10;
n = n/10;
}
return SoDao;
}
bool KiemTraSoDoiXung(int n){
if (SoDaoNguoc(n)==n) return true;
else return false;
}
int main(){
int n;
cin >> n;
int a,b,j, dem=0;
for (int i=0; i<n; ++i){
cin >> a >> b;
for (int j=a; j<=b; ++j){
if (KiemTraSoDoiXung(j)){
dem++;
}
}
cout << dem << endl;
}
}
|
/*************************************************************
* > File Name : P2897.cpp
* > Author : Tony
* > Created Time : 2019/08/26 12:40:43
* > Algorithm : [DataStructure]stack
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
inline int read() {
int x = 0; int f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();}
return x * f;
}
inline LL readll() {
LL x = 0; int f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();}
return x * f;
}
const int maxn = 100010;
const int inf = 0x3f3f3f3f;
struct Node {
LL w;
int h, id;
} p[maxn];
int n, minp = inf, minid;
LL ans[maxn], now;
int main() {
n = read();
for (int i = 1; i <= n; ++i) {
int w = readll(), h = read();
p[i] = (Node){w, h, i};
if (minp > h) {
minp = h;
minid = i;
}
}
p[0].h = p[n + 1].h = inf;
Node s[maxn]; int top = 0;
s[++top] = p[minid]; s[0].h = inf;
int l = minid, r = minid, id;
for (int i = 1; i <= n; ++i) {
int res = 0;
if (p[l - 1].h < p[r + 1].h) id = --l;
else id = ++r;
while (p[id].h > s[top].h && top) {
s[top].w += res;
ans[s[top].id] = now + s[top].w;
now += s[top].w * (min(p[id].h, s[top - 1].h) - s[top].h);
res = s[top--].w;
}
p[id].w += res;
s[++top] = p[id];
}
for (int i = 1; i <= n; ++i) {
printf("%lld\n", ans[i]);
}
return 0;
}
|
#include<stdio.h>
#include<windows.h>
#include<conio.h>
#include<stdlib.h>
#include<list>
using namespace std;
// Librería ya generadas de las teclas
#define ARRIBA 72
#define IZQUIERDA 75
#define DERECHA 77
#define ABAJO 80
// Ubicar la tecla en la posición cartesiana x,y
void gotoxy(int x,int y) {
HANDLE hcon;
// Librería STD Salida de Informacíón del Handle
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
// Coordenada
COORD dwpos;
// Posiciones y Valores de X y Y
dwpos.X= x;
dwpos.Y=y;
// Poner la posición del cursor
SetConsoleCursorPosition(hcon,dwpos);
}
// Función para ocultar el cursor
void OcultarCursor(){
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
// Información del cursor
CONSOLE_CURSOR_INFO cci;
// Valores del Cursor el Tamaño
cci.dwSize=2;
// Ocultar o no Ocultar el Cursor
cci.bVisible=FALSE;
// Poner la información del Cursor
SetConsoleCursorInfo(hcon,&cci);
}
// Limites y Bordes del juego
void pintar_limites() {
// Limites Arriba y Abajo
for(int i=2;i<78;i++){
gotoxy(i,3); printf("%c",205);
gotoxy(i,33); printf("%c",205);
}
// Limites Derecha e Izquierda
for(int i=4;i<33;i++){
gotoxy(2,i); printf("%c",186);
gotoxy(77,i); printf("%c",186);
}
// Bordes del juego
gotoxy(2,3); printf("%c",201);
gotoxy(2,33); printf("%c",200);
gotoxy(77,3);printf("%c",187);
gotoxy(77,33); printf("%c",188);
}
// Clase de la Nave
class NAVE {
int x,y;
int corazones;
int vidas;
public:
NAVE(int _x,int _y, int _corazones,int _vidas):x(_x),y(_y),corazones(_corazones),vidas(_vidas){
};
int X(){return x;}
int Y(){return y;}
int V() {return vidas;
}
void COR(){corazones--;};
void pintar();
void borrar();
void mover();
void pintar_corazones();
void morir();
};
// Clase Nave para pintar
void NAVE::pintar(){
gotoxy(x,y); printf(" %c",30);
gotoxy(x,y+1); printf(" %c%c%c",40,207,41);
gotoxy(x,y+2); printf("%c%c %c%c",30,190,190,30);
};
// Clase Nave para borrar
void NAVE::borrar(){
gotoxy(x,y); printf(" ");
gotoxy(x,y+1); printf(" ");
gotoxy(x,y+2); printf(" ");
}
// Clase Nave para mover
void NAVE::mover(){
if(kbhit()){
char tecla= getch();
borrar();
if(tecla==IZQUIERDA && x>3) x--;
if(tecla==DERECHA && x+6<75) x++;
if(tecla==ARRIBA && y>4) y--;
if(tecla==ABAJO && y+3 < 33) y++;
if(tecla=='e') corazones--;
pintar();
pintar_corazones();
}
}
// pintar corazones
void NAVE::pintar_corazones(){
gotoxy(50,2); printf("Vidas %d",vidas);
gotoxy(64,2); printf("Salud");
gotoxy(70,2); printf(" ");
for(int i=0;i<corazones;i++){
gotoxy(70+i,2); printf("%c",3);
} ;
}
// Acabar la nave
void NAVE::morir(){
if(corazones== 0){
borrar();
gotoxy(x,y); printf(" ** ");
gotoxy(x,y+1); printf("****");
gotoxy(x,y+2); printf(" ** ");
Sleep(200);
borrar();
gotoxy(x,y); printf("* ** *");
gotoxy(x,y+1); printf(" **** ");
gotoxy(x,y+2); printf("* ** *");
Sleep(200);
borrar();
vidas--;
corazones=3;
pintar_corazones();
pintar();
}
}
// Clase Asteroide
class AST {
int x,y;
public:
AST(int _x,int _y):x(_x),y(_y){};
void pintar();
void mover();
void choque(class NAVE &N);
int X(){return x;
};
int Y(){return y;
};
};
// AST pintar
void AST::pintar(){
gotoxy(x,y); printf("%c",184);
};
// AST Mover
void AST::mover(){
gotoxy(x,y); printf(" ");
y++;
if(y>32){
x=rand()%71+4;
y=4;
}
pintar();
}
// Choque de Asteroides
void AST::choque(class NAVE &N){
if(x >= N.X() && x<N.X()+6&& y>= N.Y() && y<= N.Y()+2){
N.COR();
N.borrar();
N.pintar();
N.pintar_corazones();
x=rand()%71+4;
y=4;
}
}
// Clase Bala
class BALA{
int x,y;
public:
BALA(int _x,int _y):x(_x),y(_y){};
int X() {return x;};
int Y() {return y;};
void mover();
bool fuera();
};
// Mover la Bala
void BALA::mover(){
gotoxy(x,y); printf(" ");
y--;
gotoxy(x,y); printf("*");
}
// Eliminar la Bala
bool BALA::fuera(){
if(y==4) return true;
return false;
}
int main(){
OcultarCursor();
pintar_limites();
// Nave Llamada con una variable y pinta
NAVE N(37,30,3,3);
N.pintar();
N.pintar_corazones();
// Asteroide
list<AST*>A;
list<AST*>::iterator itA;
for(int i=0;i<5;i++){
A.push_back(new AST(rand()% 75 + 3,rand()% 5+4 ) );
};
// Lista de Balas
list<BALA*> B;
list<BALA*>::iterator it;
// Ciclo GameOver
bool game_over = false;
int puntos=0;
while(!game_over){
gotoxy(4,2); printf("Puntos %d",puntos);
if(kbhit()){
char tecla= getch();
if(tecla=='a'){
B.push_back(new BALA(N.X()+2, N.Y()+1));
}
}
for( it= B.begin();it != B.end(); it++){
(*it)-> mover();
if((*it)-> fuera()){
gotoxy((*it)-> X(), (*it)-> Y()); printf(" ");
delete (*it);
it= B.erase(it);
}
}
for(itA = A.begin(); itA != A.end(); itA++) {
(*itA)-> mover();
(*itA)-> choque(N);
}
for(itA= A.begin(); itA != A.end(); itA++){
for(it=B.begin(); it != B.end(); it++)
{
if((*itA)->X()==(*it)-> X() && ((*itA)-> Y()+ 1 == (*it)-> Y() || (*itA)-> Y() == (*it)-> Y() )){
gotoxy((*it)-> X(),(*it)-> Y()); printf(" ");
delete (*it);
it = B.erase(it);
A.push_back(new AST(rand()%74+ 3,4));
gotoxy((*itA)-> X(),(*itA)-> Y()); printf(" ");
delete (*itA);
itA = A.erase(itA);
puntos+=5;
}
}
}
if(N.V()== 0) game_over=true;
N.morir();
N.mover();
Sleep(30);
}
return 0;
};
|
#ifndef DETECT_H
#define DETECT_H
/********************************************************************
// 这个类为一个抽象类,在以后可以增加不同的Detect来检查两个文件的相
// 似度。
//
********************************************************************/
class Detect
{
public:
Detect() {}
virtual ~Detect() {}
virtual void startDetect(int , char **) = 0;
};
#endif //DETECT_H
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ABSTRACTCONTINUUMMECHANICSASSEMBLER_HPP_
#define ABSTRACTCONTINUUMMECHANICSASSEMBLER_HPP_
#include "AbstractFeAssemblerInterface.hpp"
#include "AbstractTetrahedralMesh.hpp"
#include "QuadraticMesh.hpp"
#include "DistributedQuadraticMesh.hpp"
#include "LinearBasisFunction.hpp"
#include "QuadraticBasisFunction.hpp"
#include "ReplicatableVector.hpp"
#include "DistributedVector.hpp"
#include "PetscTools.hpp"
#include "PetscVecTools.hpp"
#include "PetscMatTools.hpp"
#include "GaussianQuadratureRule.hpp"
/**
* Abstract class for assembling volume-integral parts of matrices and vectors in continuum
* mechanics problems.
*
* For such problems, the matrix has, essentially, the form
* [A B1]
* [B2^T C ]
* (where often B1=B2 and C=0) and the vector has the form
* [b1]
* [b2]
* A is the spatial-spatial part, B1 the spatial-pressure part, etc.
*
* Currently B1=B2 is assumed, this can be changed in the future.
*
* This class works in the same way as the volume assembler in pde (AbstractFeVolumeIntegralAssembler),
* except the concrete class has to provide up to 6 methods, for each of the blocks A,B1,B2 and for b1
* and b2.
*
* The assembler is main used for fluids - currently it is used for assembling the matrix for Stokes
* flow [A B ; B^T 0], and the preconditioner for Stokes flow [A, B; B^T M], and will be useful for
* further fluids assemblies, and could be used for mixed-problem incompressible linear elasticity.
* We DON'T use this assembler in the incompressible nonlinear elasticity solver, because even though
* the matrix is of the right form, things like stress and stress-derivative need to be computed at
* the AssembleOnElement level and the assembly is in general too complex for this class to be used.
*
* NOTE: The elemental matrix and vector is as above. The full matrix and vector uses a completely
* different ordering: for parallelisation reasons the pressure variables are interleaved with the
* spatial variables and dummy pressure variables are used for internal nodes. For example, in 2d,
* the ordering is
* [U1 V1 P1 , .. , Un Vn, Pn]
* where n is the total number of nodes.
*
*/
template<unsigned DIM, bool CAN_ASSEMBLE_VECTOR, bool CAN_ASSEMBLE_MATRIX>
class AbstractContinuumMechanicsAssembler : public AbstractFeAssemblerInterface<CAN_ASSEMBLE_VECTOR,CAN_ASSEMBLE_MATRIX>
{
protected:
/** Whether the matrix is block symmetric (B1=B2). Currently fixed to true, in
* the future this may become a template.
*/
static const bool BLOCK_SYMMETRIC_MATRIX = true; //generalise to non-block symmetric matrices later (when needed maybe)
/** Number of vertices per element. */
static const unsigned NUM_VERTICES_PER_ELEMENT = DIM+1;
/** Number of nodes per element. */
static const unsigned NUM_NODES_PER_ELEMENT = (DIM+1)*(DIM+2)/2; // assuming quadratic
/** Size of the spatial-block (the number or rows or columns in the submatrix A), restricted to one element */
static const unsigned SPATIAL_BLOCK_SIZE_ELEMENTAL = DIM*NUM_NODES_PER_ELEMENT;
/** Size of the pressure-block (the number of rows or columns in the submatrix C), restricted to one element */
static const unsigned PRESSURE_BLOCK_SIZE_ELEMENTAL = NUM_VERTICES_PER_ELEMENT;
/** Stencil size. */
static const unsigned STENCIL_SIZE = DIM*NUM_NODES_PER_ELEMENT + NUM_VERTICES_PER_ELEMENT;
/** The quadratic mesh */
AbstractTetrahedralMesh<DIM,DIM>* mpMesh;
/** Quadrature rule for volume integrals */
GaussianQuadratureRule<DIM>* mpQuadRule;
/**
* The main assembly method. Protected, should only be called through Assemble(),
* AssembleMatrix() or AssembleVector() which set mAssembleMatrix, mAssembleVector
* accordingly. Involves looping over elements, and computing
* integrals and adding them to the vector or matrix
*/
void DoAssemble();
/**
* For a continuum mechanics problem in mixed form (displacement-pressure or velocity-pressure), the matrix
* has the form (except see comments about ordering above)
* [A B1]
* [B2^T C ]
* (where often B1=B2 and C=0). The function is related to the spatial-spatial block, ie matrix A.
*
* For the contribution to A from a given element, this method should return the INTEGRAND in the definition of A.
* See concrete classes for examples. Needed to be implemented (overridden) if the concrete class
* is going to assemble matrices (ie if CAN_ASSEMBLE_MATRIX is true).
*
* Default implementation returns a zero matrix - ie the block will be zero if this is not over-ridden
*
* @param rQuadPhi All the quadratic basis functions on this element, evaluated at the current quad point
* @param rGradQuadPhi Gradients of all the quadratic basis functions on this element, evaluated at the current quad point
* @param rX Current location (physical position)
* @param pElement Current element
* @return stencil matrix
*/
virtual c_matrix<double,SPATIAL_BLOCK_SIZE_ELEMENTAL,SPATIAL_BLOCK_SIZE_ELEMENTAL> ComputeSpatialSpatialMatrixTerm(
c_vector<double, NUM_NODES_PER_ELEMENT>& rQuadPhi,
c_matrix<double, DIM, NUM_NODES_PER_ELEMENT>& rGradQuadPhi,
c_vector<double,DIM>& rX,
Element<DIM,DIM>* pElement)
{
return zero_matrix<double>(SPATIAL_BLOCK_SIZE_ELEMENTAL,SPATIAL_BLOCK_SIZE_ELEMENTAL);
}
/**
* For a continuum mechanics problem in mixed form (displacement-pressure or velocity-pressure), the matrix
* has the form (except see comments about ordering above)
* [A B1]
* [B2^T C ]
* (where often B1=B2 and C=0). The function is related to the spatial-pressure block, ie matrix B1. If
* BLOCK_SYMMETRIC_MATRIX is true, B1=B2 is assumed, so it also relates to B2.
*
* For the contribution to A from a given element, this method should return the INTEGRAND in the definition of B.
* See concrete classes for examples. Needed to be implemented (overridden) if the concrete class
* is going to assemble matrices (ie if CAN_ASSEMBLE_MATRIX is true).
*
* Default implementation returns a zero matrix - ie the block will be zero if this is not over-ridden
*
* @param rQuadPhi All the quadratic basis functions on this element, evaluated at the current quad point
* @param rGradQuadPhi Gradients of all the quadratic basis functions on this element, evaluated at the current quad point
* @param rLinearPhi All the linear basis functions on this element, evaluated at the current quad point
* @param rGradLinearPhi Gradients of all the linear basis functions on this element, evaluated at the current quad point
* @param rX Current location (physical position corresponding to quad point)
* @param pElement Current element
* @return stencil matrix
*/
virtual c_matrix<double,SPATIAL_BLOCK_SIZE_ELEMENTAL,PRESSURE_BLOCK_SIZE_ELEMENTAL> ComputeSpatialPressureMatrixTerm(
c_vector<double, NUM_NODES_PER_ELEMENT>& rQuadPhi,
c_matrix<double, DIM, NUM_NODES_PER_ELEMENT>& rGradQuadPhi,
c_vector<double, NUM_VERTICES_PER_ELEMENT>& rLinearPhi,
c_matrix<double, DIM, NUM_VERTICES_PER_ELEMENT>& rGradLinearPhi,
c_vector<double,DIM>& rX,
Element<DIM,DIM>* pElement)
{
return zero_matrix<double>(SPATIAL_BLOCK_SIZE_ELEMENTAL,PRESSURE_BLOCK_SIZE_ELEMENTAL);
}
/**
* For a continuum mechanics problem in mixed form (displacement-pressure or velocity-pressure), the matrix
* has the form (except see comments about ordering above)
* [A B1]
* [B2^T C ]
* (where often B1=B2 and C=0). The function is related to the pressure-pressure block, ie matrix C.
*
* For the contribution to A from a given element, this method should return the INTEGRAND in the definition of C.
* See concrete classes for examples. Needed to be implemented (overridden) if the concrete class
* is going to assemble matrices (ie if CAN_ASSEMBLE_MATRIX is true).
*
* Default implementation returns a zero matrix - ie the block will be zero if this is not over-ridden
*
* @param rLinearPhi All the linear basis functions on this element, evaluated at the current quad point
* @param rGradLinearPhi Gradients of all the linear basis functions on this element, evaluated at the current quad point
* @param rX Current location (physical position)
* @param pElement Current element
* @return stencil matrix
*/
virtual c_matrix<double,PRESSURE_BLOCK_SIZE_ELEMENTAL,PRESSURE_BLOCK_SIZE_ELEMENTAL> ComputePressurePressureMatrixTerm(
c_vector<double, NUM_VERTICES_PER_ELEMENT>& rLinearPhi,
c_matrix<double, DIM, NUM_VERTICES_PER_ELEMENT>& rGradLinearPhi,
c_vector<double,DIM>& rX,
Element<DIM,DIM>* pElement)
{
return zero_matrix<double>(PRESSURE_BLOCK_SIZE_ELEMENTAL,PRESSURE_BLOCK_SIZE_ELEMENTAL);
}
/**
* For a continuum mechanics problem in mixed form (displacement-pressure or velocity-pressure), the matrix
* has the form (except see comments about ordering above)
* [A B1]
* [B2^T C ]
* (where often B1=B2 and C=0) and the vector has the form
* [b1]
* [b2]
* The function is related to the spatial-block in the vector, ie b1.
*
* For the contribution to b1 from a given element, this method should return the INTEGRAND in the definition of b1.
* See concrete classes for examples. Needed to be implemented (overridden) if the concrete class
* is going to assemble vectors (ie if CAN_ASSEMBLE_VECTOR is true).
*
* No default implementation - this method must be over-ridden
*
* @param rQuadPhi All the quadratic basis functions on this element, evaluated at the current quad point
* @param rGradQuadPhi Gradients of all the quadratic basis functions on this element, evaluated at the current quad point
* @param rX Current location (physical position)
* @param pElement Current element
* @return stencil vector
*/
virtual c_vector<double,SPATIAL_BLOCK_SIZE_ELEMENTAL> ComputeSpatialVectorTerm(
c_vector<double, NUM_NODES_PER_ELEMENT>& rQuadPhi,
c_matrix<double, DIM, NUM_NODES_PER_ELEMENT>& rGradQuadPhi,
c_vector<double,DIM>& rX,
Element<DIM,DIM>* pElement) = 0;
/**
* For a continuum mechanics problem in mixed form (displacement-pressure or velocity-pressure), the matrix
* has the form (except see comments about ordering above)
* [A B1]
* [B2^T C ]
* (where often B1=B2 and C=0) and the vector has the form
* [b1]
* [b2]
* The function is related to the pressure-block in the vector, ie b2.
*
* For the contribution to b1 from a given element, this method should return the INTEGRAND in the definition of b2.
* See concrete classes for examples. Needed to be implemented (overridden) if the concrete class
* is going to assemble vectors (ie if CAN_ASSEMBLE_VECTOR is true).
*
* Default implementation returns a zero vector - ie the block will be zero if this is not over-ridden
*
* @param rLinearPhi All the linear basis functions on this element, evaluated at the current quad point
* @param rGradLinearPhi Gradients of all the linear basis functions on this element, evaluated at the current quad point
* @param rX Current location (physical position)
* @param pElement Current element
* @return stencil vector
*/
virtual c_vector<double,PRESSURE_BLOCK_SIZE_ELEMENTAL> ComputePressureVectorTerm(
c_vector<double, NUM_VERTICES_PER_ELEMENT>& rLinearPhi,
c_matrix<double, DIM, NUM_VERTICES_PER_ELEMENT>& rGradLinearPhi,
c_vector<double,DIM>& rX,
Element<DIM,DIM>* pElement)
{
return zero_vector<double>(PRESSURE_BLOCK_SIZE_ELEMENTAL);
}
/**
* Calculate the contribution of a single element to the linear system.
*
* @param rElement The element to assemble on.
* @param rAElem The element's contribution to the LHS matrix is returned in this
* n by n matrix, where n is the no. of nodes in this element. There is no
* need to zero this matrix before calling.
* @param rBElem The element's contribution to the RHS vector is returned in this
* vector of length n, the no. of nodes in this element. There is no
* need to zero this vector before calling.
*/
void AssembleOnElement(Element<DIM, DIM>& rElement,
c_matrix<double, STENCIL_SIZE, STENCIL_SIZE >& rAElem,
c_vector<double, STENCIL_SIZE>& rBElem);
public:
/** Constructor
* @param pMesh Pointer to the mesh
*/
AbstractContinuumMechanicsAssembler(AbstractTetrahedralMesh<DIM, DIM>* pMesh)
: AbstractFeAssemblerInterface<CAN_ASSEMBLE_VECTOR,CAN_ASSEMBLE_MATRIX>(),
mpMesh(pMesh)
{
assert(pMesh);
// Check that the mesh is quadratic
QuadraticMesh<DIM>* p_quad_mesh = dynamic_cast<QuadraticMesh<DIM>* >(pMesh);
DistributedQuadraticMesh<DIM>* p_distributed_quad_mesh = dynamic_cast<DistributedQuadraticMesh<DIM>* >(pMesh);
if ((p_quad_mesh == NULL) && (p_distributed_quad_mesh == NULL))
{
EXCEPTION("Continuum mechanics assemblers require a quadratic mesh");
}
// In general the Jacobian for a mechanics problem is non-polynomial.
// We therefore use the highest order integration rule available
mpQuadRule = new GaussianQuadratureRule<DIM>(3);
}
// void SetCurrentSolution(Vec currentSolution);
/**
* Destructor.
*/
virtual ~AbstractContinuumMechanicsAssembler()
{
delete mpQuadRule;
}
};
//// add this method when needed..
//template<unsigned DIM, bool CAN_ASSEMBLE_VECTOR, bool CAN_ASSEMBLE_MATRIX>
//void AbstractContinuumMechanicsAssembler<DIM,CAN_ASSEMBLE_VECTOR,CAN_ASSEMBLE_MATRIX>::SetCurrentSolution(Vec currentSolution)
//{
// assert(currentSolution != NULL);
//
// // Replicate the current solution and store so can be used in AssembleOnElement
// HeartEventHandler::BeginEvent(HeartEventHandler::COMMUNICATION);
// mCurrentSolutionOrGuessReplicated.ReplicatePetscVector(currentSolution);
// HeartEventHandler::EndEvent(HeartEventHandler::COMMUNICATION);
//
// // The AssembleOnElement type methods will determine if a current solution or
// // current guess exists by looking at the size of the replicated vector, so
// // check the size is zero if there isn't a current solution.
// assert(mCurrentSolutionOrGuessReplicated.GetSize() > 0);
//}
template<unsigned DIM, bool CAN_ASSEMBLE_VECTOR, bool CAN_ASSEMBLE_MATRIX>
void AbstractContinuumMechanicsAssembler<DIM,CAN_ASSEMBLE_VECTOR,CAN_ASSEMBLE_MATRIX>::DoAssemble()
{
assert(this->mAssembleMatrix || this->mAssembleVector);
if (this->mAssembleMatrix)
{
if (this->mMatrixToAssemble == NULL)
{
EXCEPTION("Matrix to be assembled has not been set");
}
if (PetscMatTools::GetSize(this->mMatrixToAssemble) != (DIM+1)*mpMesh->GetNumNodes())
{
EXCEPTION("Matrix provided to be assembled has size " << PetscMatTools::GetSize(this->mMatrixToAssemble) << ", not expected size of " << (DIM+1)*mpMesh->GetNumNodes() << " ((dim+1)*num_nodes)");
}
}
if (this->mAssembleVector)
{
if (this->mVectorToAssemble == NULL)
{
EXCEPTION("Vector to be assembled has not been set");
}
if (PetscVecTools::GetSize(this->mVectorToAssemble) != (DIM+1)*mpMesh->GetNumNodes())
{
EXCEPTION("Vector provided to be assembled has size " << PetscVecTools::GetSize(this->mVectorToAssemble) << ", not expected size of " << (DIM+1)*mpMesh->GetNumNodes() << " ((dim+1)*num_nodes)");
}
}
// Zero the matrix/vector if it is to be assembled
if (this->mAssembleVector && this->mZeroVectorBeforeAssembly)
{
// Note PetscVecTools::Finalise(this->mVectorToAssemble); on an unused matrix
// would "compress" data and make any pre-allocated entries redundant.
PetscVecTools::Zero(this->mVectorToAssemble);
}
if (this->mAssembleMatrix && this->mZeroMatrixBeforeAssembly)
{
// Note PetscMatTools::Finalise(this->mMatrixToAssemble); on an unused matrix
// would "compress" data and make any pre-allocated entries redundant.
PetscMatTools::Zero(this->mMatrixToAssemble);
}
c_matrix<double, STENCIL_SIZE, STENCIL_SIZE> a_elem = zero_matrix<double>(STENCIL_SIZE,STENCIL_SIZE);
c_vector<double, STENCIL_SIZE> b_elem = zero_vector<double>(STENCIL_SIZE);
// Loop over elements
for (typename AbstractTetrahedralMesh<DIM, DIM>::ElementIterator iter = mpMesh->GetElementIteratorBegin();
iter != mpMesh->GetElementIteratorEnd();
++iter)
{
Element<DIM, DIM>& r_element = *iter;
// Test for ownership first, since it's pointless to test the criterion on something which we might know nothing about.
if (r_element.GetOwnership() == true /*&& ElementAssemblyCriterion(r_element)==true*/)
{
// LCOV_EXCL_START
// note: if assemble matrix only
if (CommandLineArguments::Instance()->OptionExists("-mech_very_verbose") && this->mAssembleMatrix)
{
std::cout << "\r[" << PetscTools::GetMyRank() << "]: Element " << r_element.GetIndex() << " of " << mpMesh->GetNumElements() << std::flush;
}
// LCOV_EXCL_STOP
AssembleOnElement(r_element, a_elem, b_elem);
// Note that a different ordering is used for the elemental matrix compared to the global matrix.
// See comments about ordering above.
unsigned p_indices[STENCIL_SIZE];
// Work out the mapping for spatial terms
for (unsigned i=0; i<NUM_NODES_PER_ELEMENT; i++)
{
for (unsigned j=0; j<DIM; j++)
{
// DIM+1 on the right-hand side here is the problem dimension
p_indices[DIM*i+j] = (DIM+1)*r_element.GetNodeGlobalIndex(i) + j;
}
}
// Work out the mapping for pressure terms
for (unsigned i=0; i<NUM_VERTICES_PER_ELEMENT; i++)
{
p_indices[DIM*NUM_NODES_PER_ELEMENT + i] = (DIM+1)*r_element.GetNodeGlobalIndex(i)+DIM;
}
if (this->mAssembleMatrix)
{
PetscMatTools::AddMultipleValues<STENCIL_SIZE>(this->mMatrixToAssemble, p_indices, a_elem);
}
if (this->mAssembleVector)
{
PetscVecTools::AddMultipleValues<STENCIL_SIZE>(this->mVectorToAssemble, p_indices, b_elem);
}
}
}
}
template<unsigned DIM, bool CAN_ASSEMBLE_VECTOR, bool CAN_ASSEMBLE_MATRIX>
void AbstractContinuumMechanicsAssembler<DIM,CAN_ASSEMBLE_VECTOR,CAN_ASSEMBLE_MATRIX>::AssembleOnElement(Element<DIM, DIM>& rElement,
c_matrix<double, STENCIL_SIZE, STENCIL_SIZE >& rAElem,
c_vector<double, STENCIL_SIZE>& rBElem)
{
static c_matrix<double,DIM,DIM> jacobian;
static c_matrix<double,DIM,DIM> inverse_jacobian;
double jacobian_determinant;
mpMesh->GetInverseJacobianForElement(rElement.GetIndex(), jacobian, jacobian_determinant, inverse_jacobian);
if (this->mAssembleMatrix)
{
rAElem.clear();
}
if (this->mAssembleVector)
{
rBElem.clear();
}
// Allocate memory for the basis functions values and derivative values
static c_vector<double, NUM_VERTICES_PER_ELEMENT> linear_phi;
static c_vector<double, NUM_NODES_PER_ELEMENT> quad_phi;
static c_matrix<double, DIM, NUM_NODES_PER_ELEMENT> grad_quad_phi;
static c_matrix<double, DIM, NUM_VERTICES_PER_ELEMENT> grad_linear_phi;
c_vector<double,DIM> body_force;
// Loop over Gauss points
for (unsigned quadrature_index=0; quadrature_index < mpQuadRule->GetNumQuadPoints(); quadrature_index++)
{
double wJ = jacobian_determinant * mpQuadRule->GetWeight(quadrature_index);
const ChastePoint<DIM>& quadrature_point = mpQuadRule->rGetQuadPoint(quadrature_index);
// Set up basis function info
LinearBasisFunction<DIM>::ComputeBasisFunctions(quadrature_point, linear_phi);
QuadraticBasisFunction<DIM>::ComputeBasisFunctions(quadrature_point, quad_phi);
QuadraticBasisFunction<DIM>::ComputeTransformedBasisFunctionDerivatives(quadrature_point, inverse_jacobian, grad_quad_phi);
LinearBasisFunction<DIM>::ComputeTransformedBasisFunctionDerivatives(quadrature_point, inverse_jacobian, grad_linear_phi);
// interpolate X (ie physical location of this quad point).
c_vector<double,DIM> X = zero_vector<double>(DIM);
for (unsigned vertex_index=0; vertex_index<NUM_VERTICES_PER_ELEMENT; vertex_index++)
{
for (unsigned j=0; j<DIM; j++)
{
X(j) += linear_phi(vertex_index)*rElement.GetNode(vertex_index)->rGetLocation()(j);
}
}
if (this->mAssembleVector)
{
c_vector<double,SPATIAL_BLOCK_SIZE_ELEMENTAL> b_spatial
= ComputeSpatialVectorTerm(quad_phi, grad_quad_phi, X, &rElement);
c_vector<double,PRESSURE_BLOCK_SIZE_ELEMENTAL> b_pressure = ComputePressureVectorTerm(linear_phi, grad_linear_phi, X, &rElement);
for (unsigned i=0; i<SPATIAL_BLOCK_SIZE_ELEMENTAL; i++)
{
rBElem(i) += b_spatial(i)*wJ;
}
for (unsigned i=0; i<PRESSURE_BLOCK_SIZE_ELEMENTAL; i++)
{
rBElem(SPATIAL_BLOCK_SIZE_ELEMENTAL + i) += b_pressure(i)*wJ;
}
}
if (this->mAssembleMatrix)
{
c_matrix<double,SPATIAL_BLOCK_SIZE_ELEMENTAL,SPATIAL_BLOCK_SIZE_ELEMENTAL> a_spatial_spatial
= ComputeSpatialSpatialMatrixTerm(quad_phi, grad_quad_phi, X, &rElement);
c_matrix<double,SPATIAL_BLOCK_SIZE_ELEMENTAL,PRESSURE_BLOCK_SIZE_ELEMENTAL> a_spatial_pressure
= ComputeSpatialPressureMatrixTerm(quad_phi, grad_quad_phi, linear_phi, grad_linear_phi, X, &rElement);
c_matrix<double,PRESSURE_BLOCK_SIZE_ELEMENTAL,SPATIAL_BLOCK_SIZE_ELEMENTAL> a_pressure_spatial;
if (!BLOCK_SYMMETRIC_MATRIX)
{
NEVER_REACHED; // to-come: non-mixed problems
//a_pressure_spatial = ComputeSpatialPressureMatrixTerm(quad_phi, grad_quad_phi, lin_phi, grad_lin_phi, x, &rElement);
}
c_matrix<double,PRESSURE_BLOCK_SIZE_ELEMENTAL,PRESSURE_BLOCK_SIZE_ELEMENTAL> a_pressure_pressure
= ComputePressurePressureMatrixTerm(linear_phi, grad_linear_phi, X, &rElement);
for (unsigned i=0; i<SPATIAL_BLOCK_SIZE_ELEMENTAL; i++)
{
for (unsigned j=0; j<SPATIAL_BLOCK_SIZE_ELEMENTAL; j++)
{
rAElem(i,j) += a_spatial_spatial(i,j)*wJ;
}
for (unsigned j=0; j<PRESSURE_BLOCK_SIZE_ELEMENTAL; j++)
{
rAElem(i, SPATIAL_BLOCK_SIZE_ELEMENTAL + j) += a_spatial_pressure(i,j)*wJ;
}
}
for (unsigned i=0; i<PRESSURE_BLOCK_SIZE_ELEMENTAL; i++)
{
if (BLOCK_SYMMETRIC_MATRIX)
{
for (unsigned j=0; j<SPATIAL_BLOCK_SIZE_ELEMENTAL; j++)
{
rAElem(SPATIAL_BLOCK_SIZE_ELEMENTAL + i, j) += a_spatial_pressure(j,i)*wJ;
}
}
else
{
NEVER_REACHED; // to-come: non-mixed problems
}
for (unsigned j=0; j<PRESSURE_BLOCK_SIZE_ELEMENTAL; j++)
{
rAElem(SPATIAL_BLOCK_SIZE_ELEMENTAL + i, SPATIAL_BLOCK_SIZE_ELEMENTAL + j) += a_pressure_pressure(i,j)*wJ;
}
}
}
}
}
#endif // ABSTRACTCONTINUUMMECHANICSASSEMBLER_HPP_
|
/*
* Note: accel func, speed
*/
// defines pin numbers for motor1
const int stepPin1 = 3;
const int dirPin1 = 2;
const int MS1_1 = 4;
const int MS2_1 = 5;
const int MS3_1 = 6;
//defines pin numbers for motor2
const int stepPin2 = 8;
const int dirPin2 = 9;
const int MS1_2 = 10;
const int MS2_2 = 11;
const int MS3_2 = 12;
//higher the number, slower motor rotates
const int accelDelay = 500;
//microstepping scale const
const int microstep = 16;
void setup() {
// Sets the two pins as Outputs
pinMode(stepPin1,OUTPUT);
pinMode(dirPin1,OUTPUT);
Serial.begin(9600);
}
void loop() {
//enabling all three microstepping pins --> 1/16th of a step
digitalWrite(MS1_1,HIGH);
digitalWrite(MS2_1,HIGH);
digitalWrite(MS3_1,HIGH);
int xMin = 0;
int xMax = 100;
int yMin = 0;
int yMax = 100;
//Currently have to seperate x and y components of a coordinate... need to look into this
int x[] = {5, 3, 50, 20, 70};
int y[] = {5, 3, 50, 20, 70};
for(int i = 0; i < 5; i++) {
if(x[i] < xMin || x[i] > xMax) {
Serial.print("ERROR: One of the coordinates are out of bounds");
while(1);
}
if(y[i] < yMin || y[i] > yMax) {
Serial.print("ERROR: One of the coordinates are out of bounds");
while(1);
}
}
goToX(x);
goToY(y);
while(1);
}
void goToX(int x[]) {
int currentX = 0;
// Serial.print("Starting coordinates: (0,0)");
// Serial.print('\n');
//How to find size for array...??? For now using 5
for(int i = 0; i < 5; i++){
int movementX = x[i] - currentX;
moveMotorX(movementX);
currentX = x[i];
Serial.print(movementX);
// Serial.print('\n');
// Serial.print("New coordinate: ("); Serial.print(currentX); Serial.print(",0)");
// Serial.print('\n');
}
}
void moveMotorX(int movementX) {
int constant = 1;
int steps = abs(movementX*constant)*microstep;
if(movementX > 0) {
turnMotor1OneStepCW(steps);
Serial.print("Move x forwards: ");
}
else if (movementX < 0) {
turnMotor1OneStepCCW(steps);
Serial.print("Move x backwards: ");
}
}
void goToY(int y[]) {
int currentY = 0;
//How to find size for array...??? For now using 5
for(int i = 0; i < 5; i++){
int movementY = y[i] - currentY;
moveMotorY(movementY);
currentY = y[i];
Serial.print(movementY);
}
}
void moveMotorY(int movementY) {
int constant = 1;
int steps = abs(movementY*constant)*microstep;
if(movementY > 0) {
turnMotor2OneStepCW(steps);
Serial.print("Move y forwards: ");
}
else if (movementY < 0) {
turnMotor2OneStepCCW(steps);
Serial.print("Move y backwards: ");
}
}
//Insert code for motorY (same as motorX), only working with one motor for one
//These functios control the direction of x/y movements
void turnMotor1OneStepCCW(int steps) {
digitalWrite(dirPin1,HIGH); // Enables the motor to move in a particular direction
// Make one pulse that turns the motor 1.8 degrees in the specified direction
for(int x = 0; x < steps; x++) {
digitalWrite(stepPin1,HIGH);
delayMicroseconds(accelDelay);
digitalWrite(stepPin1,LOW);
delayMicroseconds(accelDelay);
}
delay(1000); // One second delay
}
void turnMotor1OneStepCW(int steps) {
digitalWrite(dirPin1,LOW); //Changes the rotations direction
// Makes one pulse that turns the motor 1.8 degrees in the specified direction
for(int x = 0; x < steps; x++) {
digitalWrite(stepPin1,HIGH);
delayMicroseconds(accelDelay);
digitalWrite(stepPin1,LOW);
delayMicroseconds(accelDelay);
}
delay(1000);
}
//These functios control the direction of x/y movements
void turnMotor2OneStepCCW(int steps) {
digitalWrite(dirPin2,HIGH); // Enables the motor to move in a particular direction
// Make one pulse that turns the motor 1.8 degrees in the specified direction
for(int x = 0; x < steps; x++) {
digitalWrite(stepPin2,HIGH);
delayMicroseconds(accelDelay);
digitalWrite(stepPin2,LOW);
delayMicroseconds(accelDelay);
}
delay(1000); // One second delay
}
void turnMotor2OneStepCW(int steps) {
digitalWrite(dirPin2,LOW); //Changes the rotations direction
// Makes one pulse that turns the motor 1.8 degrees in the specified direction
for(int x = 0; x < steps; x++) {
digitalWrite(stepPin2,HIGH);
delayMicroseconds(accelDelay);
digitalWrite(stepPin2,LOW);
delayMicroseconds(accelDelay);
}
delay(1000);
}
|
Node* convert(Node* head) {
int count = 0;
for (Node* p = head; p != NULL; p=p->next) { count++; }
int b1Index = count/2;
Node* b = head;
for (int i = 0; i < b1Index; i++) b = b->next;
Node* a = head;
Node* a1 = head; Node* b1 = b;
a = a1->next; //a2
b = b1->next; //b2
a1->next = b1; // noi a1-b1.....
Node* end = b1;
while (b != NULL) {
end->next = a; //noi cap a tiep theo
a = a->next; //nhay a
end->next->next = b; // noi b tiep theo
b = b->next;
end = end->next->next; // chinh end ve cuoi
}
return head;
}
|
#include <Pn532NfcReader.h>
#include <PN532_HSU.h>
#include <PN532.h>
#include <SPI.h>
#include <PN532_SPI.h>
#include <NfcAdapter.h>
// MPT_readerUno/readerUno.ino
uint32_t tagId3 = 0xFF;
uint32_t readerId = 0x02;
uint16_t * tokenDesejado;
bool tagReadyToContinue = false;
// --------------------------Iniciando as comunicações HSU -----------------------------------
//Rotines related with the configuration of the RFID reader PN532
PN532_SPI pn532spi(SPI, 10);
NfcAdapter nfc3 = NfcAdapter(pn532spi);
//Creation of the reader and PNRD objects
Pn532NfcReader* reader3 = new Pn532NfcReader(&nfc3);
Pnrd pnrd3 = Pnrd(reader3,4,4,false,false,true);
// -----------------------------------------------------------------------
void setup() {
//Initialization of the communication with the reader and with the computer Serial bus
Serial.begin(9600);
reader3->initialize();
pnrd3.setAsTagInformation(PetriNetInformation::TOKEN_VECTOR);
pnrd3.setAsTagInformation(PetriNetInformation::ADJACENCY_LIST);
pnrd3.setAsTagInformation(PetriNetInformation::GOAL_TOKEN);
// pnrd3.getGoalToken(tokenDesejado);
}
void serial_com(uint32_t tagId, uint32_t readerId, int antenna, char ErrorType[100] ){
Serial.println(String("id:") + String(tagId,HEX) + String(" | ant:") + String(antenna) + String(" | readerId:") + String(readerId,HEX) + String(" | pnrd:")+ String(ErrorType));
Serial.println("end");
}
void loop() {
delay(100);
ReadError readError3 = pnrd3.getData();
delay(100);
// switch(readError3){
// case ReadError::NO_ERROR:
// Serial.println("Sem erro");
// case ReadError::TAG_NOT_PRESENT:
// Serial.println("Sem Tag");
// case ReadError::INFORMATION_NOT_PRESENT:
// Serial.println("INFORMATION_NOT_PRESENT");
// case ReadError::NOT_AUTORIZED:
// Serial.println("NOT_AUTORIZED");
// case ReadError::NOT_AUTORIZED:
// Serial.println("NOT_AUTORIZED");
// }
if(readError3 == ReadError::NO_ERROR){
FireError fireError3;
Serial.println("Sem erro");
// pnrd3.printTokenVector();
//verifica se é uma nova tag
if(tagId3 != pnrd3.getTagId()){
tagId3 = pnrd3.getTagId();
//Dispara a transição t3
FireError fireError3 = pnrd3.fire(0);
switch (fireError3){
case FireError::NO_ERROR :
//Atualizando a tag
if(pnrd3.saveData() == WriteError::NO_ERROR){
pnrd3.printGoalToken();
serial_com(tagId3,readerId,6,"NO_ERROR");
return;
}else{
serial_com(tagId3,readerId,6,"ERROR_TAG_UPDATE");
return;
}
case FireError::PRODUCE_EXCEPTION :
serial_com(tagId3,readerId,6,"PRODUCE_EXCEPTION");
return;
case FireError::CONDITIONS_ARE_NOT_APPLIED :
serial_com(tagId3,readerId,6,"CONDITIONS_ARE_NOT_APPLIED");
break;
case FireError::NOT_KNOWN:
serial_com(tagId3,readerId,6,"NOT_KNOWN");
break;
}
}
}
Serial.flush();
}
|
#pragma once
#define DEBUG_MODE
#include <cstddef>
#include "../../hlt/log.hpp"
static std::uint8_t width = 1;
static std::uint32_t color = 0xFFFFFF;
static std::uint16_t dash;
class Gizmos
{
public:
template <typename T, typename U>
static void line (T const & start, U const & end)
{
#ifdef DEBUG_MODE
hlt::Log::log(
"[Line] " +
std::to_string(::width) + ' ' +
std::to_string(::color) + ' ' +
std::to_string(::dash) + ' ' +
std::to_string(static_cast<std::size_t>(start.x + .5)) + ' ' +
std::to_string(static_cast<std::size_t>(start.y + .5)) + ' ' +
std::to_string(static_cast<std::size_t>(end.x + .5)) + ' ' +
std::to_string(static_cast<std::size_t>(end.y + .5))
);
#endif
}
template <typename T, typename U>
static void line (T * const start, U * const end)
{
Gizmos::line(*start, *end);
}
static void set_width (std::uint8_t width)
{ ::width = width; }
static void set_color (std::uint32_t color)
{ ::color = color; }
static void set_dash (std::uint8_t fill, std::uint8_t gap)
{ ::dash = (static_cast<std::uint16_t>(fill) << 8) | gap; }
static std::uint32_t get_color ()
{ return ::color; }
static std::uint16_t get_dash_fill ()
{ return static_cast<std::uint16_t>(::dash >> 8); }
static std::uint16_t get_dash_gap ()
{ return static_cast<std::uint16_t>(::dash | ((1 << 8) - 1)); }
static std::uint32_t color_from_rgb(std::uint8_t r, std::uint8_t g, std::uint8_t b)
{ return (static_cast<std::uint32_t>(r) << 16) | (static_cast<std::uint32_t>(g) << 8) | b; }
};
|
#pragma once
#include <SDL.h>
#include <SDL_image.h>
#include <string>
// forward declarations
class Sprite;
class Rect;
class Point;
// various renderer related enumerators
enum class BlendMode {
NONE,
BLEND,
ADD,
MOD
};
enum class RenderFlip {
NONE,
HORIZONTAL,
VERTICAL,
};
/*
encapsulates SDL_Renderer
*/
class Renderer {
friend class Window;
private:
SDL_Renderer* _renderer = nullptr;
int _xOffset = 0;
int _yOffset = 0;
private:
// private constructor. Renderer only initialized from friend class
Renderer(SDL_Renderer* renderer);
Renderer(const Renderer&) = delete;
void operator=(const Renderer&) = delete;
public:
// deallocate the renderer
~Renderer();
/*
render a Sprite
Sprite: the Sprite to be rendered
pos: the position on screen to render the Sprite
src: what part of the Sprite should be rendered (optional)
angle: angle the Sprite should be rendered in (optional)
center: the center around which the Sprite should be turned (optional)
flip: flip the Sprite (optional)
*/
void render(
Sprite* sprite,
Rect* pos,
Rect* src = nullptr,
double angle = 0.0,
Point* center = nullptr,
RenderFlip flip = RenderFlip::NONE) const;
void setOffsets(int x, int y);
int getXoffset() const;
int getYoffset() const;
// loading functions
Sprite* loadSprite(std::string path) const;
};
/*
encapsulates SDL_Window
*/
class Window {
private:
SDL_Window* _window;
Renderer* _renderer;
int _width;
int _height;
public:
Window(std::string title, int width, int height);
// deallocation
~Window();
// draw the window
void update() const;
/*
access the window's renderer
may return nullptr if renderer failed to initialize
*/
Renderer* getRenderer() const;
int getWidth() const;
int getHeight() const;
};
|
// Copyright 2020 JD.com, Inc. Galileo 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 "service/edge.h"
#include <string>
#include <vector>
#include "common/macro.h"
#include "common/schema.h"
#include "common/singleton.h"
#include "glog/logging.h"
#include "utils/bytes_reader.h"
namespace galileo {
namespace service {
using Schema = galileo::schema::Schema;
Edge::Edge(uint8_t etype) {
Schema* schema = galileo::common::Singleton<Schema>::GetInstance();
raw_data_ = galileo::common::Singleton<EntityPoolManager>::GetInstance()
->GetEMemoryPool(etype)
->NextRecord();
memset(raw_data_, 0, schema->GetERecordSize(etype));
}
Edge::~Edge() {
Schema* schema = galileo::common::Singleton<Schema>::GetInstance();
uint8_t etype = GetType();
for (size_t i = 0; i < schema->GetEFieldCount(etype); ++i) {
if (schema->IsEVarField(etype, i)) {
std::string attr = schema->GetEFieldName(etype, i);
int var_index = schema->GetEVarFieldIdx(etype, attr);
assert(var_index >= 0);
if (!_IsDirectStore(var_index)) {
int attr_idx = schema->GetEFieldOffset(etype, attr);
assert(attr_idx >= 0);
uint64_t var_address =
*reinterpret_cast<const uint64_t*>(raw_data_ + attr_idx);
char* real_data = (char*)var_address;
if (real_data) free(real_data);
}
}
}
}
galileo::common::VertexID Edge::GetSrcVertex() const {
Schema* schema = galileo::common::Singleton<Schema>::GetInstance();
int offset = schema->GetEFieldOffset(GetType(), SCM_ENTITY_1);
assert(offset >= 0);
return *reinterpret_cast<const galileo::common::VertexID*>(raw_data_ +
offset);
}
galileo::common::VertexID Edge::GetDstVertex() const {
Schema* schema = galileo::common::Singleton<Schema>::GetInstance();
int offset = schema->GetEFieldOffset(GetType(), SCM_ENTITY_2);
assert(offset >= 0);
return *reinterpret_cast<const galileo::common::VertexID*>(raw_data_ +
offset);
}
float Edge::GetWeight() const {
Schema* schema = galileo::common::Singleton<Schema>::GetInstance();
int offset = schema->GetEFieldOffset(GetType(), SCM_WEIGHT);
if (offset < 0) {
return 1.0;
} else {
return *reinterpret_cast<const float*>(raw_data_ + offset);
}
}
float Edge::GetFixFeatureWithOffset(size_t offset,
const std::string& attr_type) const {
float result = 0;
if (attr_type == "DT_UINT8") {
result = static_cast<float>(
*reinterpret_cast<const uint8_t*>(raw_data_ + offset));
} else if (attr_type == "DT_UINT16") {
result = static_cast<float>(
*reinterpret_cast<const uint16_t*>(raw_data_ + offset));
} else if (attr_type == "DT_UINT32") {
result = static_cast<float>(
*reinterpret_cast<const uint32_t*>(raw_data_ + offset));
} else if (attr_type == "DT_UINT64") {
result = static_cast<float>(
*reinterpret_cast<const uint64_t*>(raw_data_ + offset));
} else if (attr_type == "DT_INT8") {
result = static_cast<float>(
*reinterpret_cast<const int8_t*>(raw_data_ + offset));
} else if (attr_type == "DT_INT16") {
result = static_cast<float>(
*reinterpret_cast<const int16_t*>(raw_data_ + offset));
} else if (attr_type == "DT_INT32") {
result = static_cast<float>(
*reinterpret_cast<const int32_t*>(raw_data_ + offset));
} else if (attr_type == "DT_INT64") {
result = static_cast<float>(
*reinterpret_cast<const int64_t*>(raw_data_ + offset));
} else if (attr_type == "DT_FLOAT") {
result =
static_cast<float>(*reinterpret_cast<const float*>(raw_data_ + offset));
} else if (attr_type == "DT_DOUBLE") {
result = static_cast<float>(
*reinterpret_cast<const double*>(raw_data_ + offset));
} else {
result = 0;
}
return result;
}
const char* Edge::GetFeature(const std::string& attr_name) const {
Schema* schema = galileo::common::Singleton<Schema>::GetInstance();
uint8_t etype = GetType();
int tmp_fid = schema->GetEFieldIdx(etype, attr_name);
if (tmp_fid < 0) {
return nullptr;
}
size_t fid = static_cast<size_t>(tmp_fid);
int begin_idx = schema->GetEFieldOffset(etype, attr_name);
if (begin_idx < 0) {
return nullptr;
}
if (schema->IsEVarField(etype, fid) && !_IsDirectStore(attr_name)) {
uint64_t var_address =
*reinterpret_cast<const uint64_t*>(raw_data_ + begin_idx);
return reinterpret_cast<const char*>(var_address);
} else {
return reinterpret_cast<const char*>(raw_data_ + begin_idx);
}
}
bool Edge::DeSerialize(uint8_t type, const char* s, size_t size) {
Schema* schema = galileo::common::Singleton<Schema>::GetInstance();
galileo::utils::BytesReader bytes_reader(s, size);
size_t write_off = schema->GetEFixedFieldLen(type);
if (write_off > size) {
LOG(ERROR) << " Fix attribute info error."
<< " write_off:" << write_off << " ,size:" << size;
return false;
}
// fix attr
if (!bytes_reader.Read(raw_data_, write_off)) {
LOG(ERROR) << " Fix attribute info error";
return false;
}
// var attr
uint16_t var_len;
for (size_t i = 0; i < schema->GetEVarFieldCount(type); i++) {
if (!bytes_reader.Peek(&var_len)) {
LOG(ERROR) << " Var attribute length error";
return false;
}
if (_IsDirectStore(i)) {
if (!bytes_reader.Read(raw_data_ + write_off, var_len + 2)) {
LOG(ERROR) << " Var attribute info error";
return false;
}
} else {
char* var_attr = (char*)malloc(var_len + 2);
if (!bytes_reader.Read(var_attr, var_len + 2)) {
LOG(ERROR) << " Var attribute info error";
return false;
}
uint64_t var_address = (uint64_t)var_attr;
memcpy(raw_data_ + write_off, &var_address, 8);
}
write_off += 8;
}
return true;
}
bool Edge::_IsDirectStore(const std::string& field_name) const {
Schema* schema = galileo::common::Singleton<Schema>::GetInstance();
uint8_t etype = GetType();
int var_index = schema->GetEVarFieldIdx(etype, field_name);
if (var_index < 0) {
LOG(ERROR) << " Get edge var field idx fail."
<< " edge type:" << etype << " ,field name:" << field_name;
return false;
}
return _IsDirectStore(static_cast<size_t>(var_index));
}
bool Edge::_IsDirectStore(size_t var_index) const {
Schema* schema = galileo::common::Singleton<Schema>::GetInstance();
char state =
*(raw_data_ + schema->GetEStateOffset(GetType()) + (var_index / 8));
return state & (1 << (7 - (var_index % 8)));
}
} // namespace service
} // namespace galileo
|
//**************************************************************************
//**
//** See jlquake.txt for copyright info.
//**
//** This program is free software; you can redistribute it and/or
//** modify it under the terms of the GNU General Public License
//** as published by the Free Software Foundation; either version 3
//** of the License, or (at your option) any later version.
//**
//** This program is distributed in the hope that it will be useful,
//** but WITHOUT ANY WARRANTY; without even the implied warranty of
//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//** included (gnu.txt) GNU General Public License for more details.
//**
//**************************************************************************
#ifndef __test_utils_h__
#define __test_utils_h__
#include <ostream>
#include "../../source/common/math/Vec3.h"
inline std::ostream& operator<<( std::ostream& s, const idVec3& v ) {
return s << "( " << v.x << ", " << v.y << ", " << v.z << " )";
}
#endif
|
#include <Servo.h>
#include <SoftwareSerial.h>
SoftwareSerial bt(12, 11); // RX,TX
Servo servos[8];
/* Front
Servo0 - Servo2 |--| Servo4 - Servo6
Servo1 - Servo3 |--| Servo5 - Servo7
*/
uint8_t pos[8];
uint8_t cpos[8];
int8_t s1 = -10;
int8_t s3 = -10;
int8_t s7 = +20;
uint8_t fullStep = 110;
uint8_t halfStep = 110;
uint8_t b_fullStep = 70;
uint8_t b_halfStep = 70;
long previousMillis = 0;
long interval = 1000;
void servoReset(int8_t i) {
pos[i - 4] = 90;
cpos[i - 4] = 90;
if (i - 4 == 1) {
pos[i - 4] += s1;
cpos[i - 4] += s1;
} else if (i - 4 == 7) {
pos[i - 4] += s7;
cpos[i - 4] += s7;
} else if (i - 4 == 3) {
pos[i - 4] += s3;
cpos[i - 4] += s3;
}
servos[i - 4].write(pos[i - 4]);
delay(50);
}
void setup() {
Serial.begin(9600);
bt.begin(9600);
for (int8_t i = 4; i < 12; i++) {
servos[i - 4].attach(i);
servoReset(i);
}
}
void r_walk(uint8_t v = 2000) {
/* Front
Servo0 - Servo2 |--| Servo4 - Servo6
Servo1 - Servo3 |--| Servo5 - Servo7
*/
Serial.println("Right Walking..");
uint16_t wait = 4000 / v;
servos[0].write(80);
servos[1].write(80);
servos[2].write(30);
servos[3].write(30);
servos[4].write(80);
servos[5].write(80);
servos[6].write(20);
servos[7].write(50);
/*
servos[0].write(70);
servos[1].write(80);
servos[6].write(50);
servos[7].write(90);
servos[3].write(30);
servos[5].write(120);
servos[2].write(30);
servos[4].write(120);
for (uint8_t i = 30; i < 130; i++) {
servos[0].write(i);
servos[1].write(i - 10);
delay(wait);
}
*/
/*
servos[0].write(80);
servos[7].write(80);
servos[4].write(80);
servos[5].write(80);
servos[2].write(60);
servos[6].write(20);
servos[3].write(30 + 20);
servos[1].write(80 - 20);
for (uint8_t i = 80; i < 150; i++) {
servos[1].write(180-i - 20);
delay(wait);
}
for (uint8_t i = 30; i < 110; i++) {
servos[3].write(180-i + 20);
delay(wait);
}
for (uint8_t i = 150; i > 30; i--) {
servos[1].write(180-i - 20);
delay(wait / 2);
}
for (uint8_t i = 110; i > 30; i--) {
servos[3].write(180-i + 20);
delay(wait / 2);
}
*/
}
void l_walk(uint8_t v = 2000) {
/* Front
Servo0 - Servo2 |--| Servo4 - Servo6
Servo1 - Servo3 |--| Servo5 - Servo7
*/
Serial.println("Left Walking..");
uint16_t wait = 4000 / v;
servos[0].write(80);
servos[1].write(80);
servos[2].write(85);
servos[3].write(85);
servos[6].write(50);
servos[7].write(90);
servos[5].write(120);
servos[4].write(120);
/*
servos[0].write(80);
servos[1].write(80);
servos[2].write(80);
servos[3].write(80);
servos[4].write(80);
servos[6].write(20);
servos[5].write(30);
servos[7].write(80);
for (uint8_t i = 80; i < 150; i++) {
servos[7].write(i);
delay(wait);
}
for (uint8_t i = 30; i < 110; i++) {
servos[5].write(i);
delay(wait);
}
for (uint8_t i = 150; i > 30; i--) {
servos[7].write(i);
delay(wait / 2);
}
for (uint8_t i = 110; i > 30; i--) {
servos[5].write(i);
delay(wait / 2);
}
*/
}
void walk(uint8_t v = 1000) {
/* Front
Servo0 - Servo2 |--| Servo4 - Servo6
Servo1 - Servo3 |--| Servo5 - Servo7
*/
Serial.println("Walking..");
uint16_t wait = 10000 / v;
servos[0].write(80);
servos[6].write(20);
servos[1].write(80);
servos[3].write(85);
servos[5].write(80);
servos[7].write(50);
delay(250);
servos[2].write(20);
servos[4].write(120);
delay(250);
servos[2].write(70);
servos[4].write(70);
delay(250);
servos[3].write(50);
servos[5].write(100);
delay(250);
servos[3].write(85);
servos[5].write(80);
/*
for (uint8_t i = 80; i < 130; i++) {
servos[4].write(i - 20);
servos[6].write(i - 30);
servos[3].write(180 - i + s3);
servos[1].write(180 - i - s1-10);
delay(wait);
}
for (uint8_t i = 130; i > 80; i--) {
servos[4].write(i - 20);
servos[6].write(i - 30);
servos[3].write(180 - i + s3);
servos[1].write(180 - i - s1-10);
delay(wait);
}
//reverse
for (uint8_t i = 80; i < 130; i++) {
servos[0].write(180 - i);
servos[2].write(180 - i - 20);
servos[5].write(i - 20);
servos[7].write(i - s7+20);
delay(wait);
}
for (uint8_t i = 130; i > 80; i--) {
servos[0].write(180 - i);
servos[2].write(180 - i - 20);
servos[5].write(i - 20);
servos[7].write(i - s7+20);
delay(wait);
}
*/
}
void loop() {
if (bt.available())
{
char data = bt.read();
Serial.print("gelen veri:"); Serial.println(data);
if (data == 'F') {
walk();
} else if (data == 'L') {
l_walk();
} else if (data == 'R') {
r_walk();
} else if (data == 'U') {
servos[0].write(70);
servos[1].write(80);
servos[6].write(50);
servos[7].write(90);
servos[3].write(30);
servos[5].write(120);
servos[2].write(30);
servos[4].write(120);
} else if (data == 'D') {
servos[0].write(70);
servos[1].write(80);
servos[6].write(50);
servos[7].write(90);
servos[3].write(140);
servos[5].write(30);
servos[2].write(120);
servos[4].write(20);
}
}
}
|
/*
Find merge point of two linked lists
Node is defined as
struct Node
{
int data;
Node* next;
}
*/
//here, the implemented method in O(m+n): http://www.geeksforgeeks.org/write-a-function-to-get-the-intersection-point-of-two-linked-lists/
int getSize(Node *head){
int ans = 0;
while(head!=NULL){
ans++;
head = head->next;
}
return ans;
}
int findIntersect(int d, Node *a, Node *b){
//list a is the longer one
for(int i=0;i<d;i++){
a = a->next;
}
while(a!=NULL){
if(a == b){ // note that we are comparing the nodes and not the data, since data could be same before merge point
return a->data;
}
//else
a = a->next;
b = b->next;
}
return -1;
}
int FindMergeNode(Node *headA, Node *headB)
{
// Complete this function
// Do not write the main method.
int c1 = getSize(headA);
int c2 = getSize(headB);
if(c1>c2){
return findIntersect(c1-c2,headA,headB);
}else{
return findIntersect(c2-c1,headB,headA);
}
}
|
#include <bits/stdc++.h>
using namespace std;
#define MAX_NM 1000010
int N, M, ans, Jack[MAX_NM], Jill[MAX_NM];
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
int k,m;
while ((cin >> N >> M), (N || M)) {
for (int i = 0; i < N; i++) cin >> Jack[i];
for (int j = 0; j < M; j++) cin >> Jill[j];
ans = 0;
int k = m = 0;
while(m < N&&k < N){
if(Jack[k] == Jill[m]){
m++;
k++;
ans++;
}
else if(Jack[k] > Jill[m])
m++;
else if(Jack[k] < Jill[m])
k++;
}
cout << ans << endl;
}
return 0;
}
|
#pragma once
// CRecordDialog dialog
class CRecordDialog : public CDialog
{
DECLARE_DYNAMIC(CRecordDialog)
public:
CRecordDialog(CWnd* pParent = NULL); // standard constructor
virtual ~CRecordDialog();
CString saveFileBox;
CString saveFileBox2;
bool m_check_saveFileBox;
bool m_check_saveFileBox2;
// Dialog Data
enum { IDD = IDD_RECORD_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedBack_Record();
BOOL OnInitDialog();
private:
CFont m_Font;
public:
afx_msg void OnBnClickedSaveButtonrecord();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnBnClickedSaveButtonrecord2();
afx_msg void OnBnClickedRecordButton();
};
|
#pragma once
namespace ResLibraryData {
}
|
#include <iostream>
#include <vector>
using namespace std;
void quicksort(vector<int>& v, int low, int high)
{
if (low < high) {
int i = low, j = high, pivot = v[low];
while (i < j) {
while (i < j && v[j] >= pivot) { //while中须判断i<j
--j;
}
if (i < j) { //此处if不可缺少
v[i++] = v[j];
}
while (i < j && v[i] <= pivot) { //while中须判断i<j
++i;
}
if (i < j) { //此处if不可缺少
v[j--] = v[i];
}
}
v[i] = pivot;
quicksort(v, low, i - 1);
quicksort(v, i + 1, high);
}
}
int main()
{
int n;
cin >> n;
vector<int> v(n, 0);
for (int i = 0; i < n; i++) {
cin >> v[i];
}
quicksort(v, 0, n - 1);
cout << v[0];
for (int i = 1; i < n; i++) {
cout << " " << v[i];
}
return 0;
}
|
#ifndef __TABLE_FUNCTION_HPP__
#define __TABLE_FUNCTION_HPP__
#include <jflib/templates/map.hpp>
namespace jflib { namespace templates {
/** \brief Timeserie template base on a std::map
*
* This timeserie template is an associative unique
* container. For each key there is one and only one value.
*/
template<class Key, class T>
class tablefunction: public associative<Key,T,0,true> {
typedef associative<Key,T,0,true> super_type;
public:
typedef typename super_type::key_type key_type;
typedef typename super_type::mapped_type num_type;
typedef typename super_type::const_iterator const_iterator;
typedef std::pair<const_iterator,const_iterator> rangepair;
tablefunction(){}
tablefunction(const std::string& name):m_name(name){}
const std::string& name() const {return m_name;}
num_type at(const key_type& k) const {
const_iterator p2 = this->lower_bound(k);
const_iterator p1(p2);
p1--;
num_type du = p2->first - p1->first;
return ((k - p1->first)*p2->second + (p2->first - k)*p1->second)/du;
}
private:
std::string m_name;
};
}}
#endif // __TABLE_FUNCTION_HPP__
|
#include "Setup_2014_EPT.h"
#include "base/std_ext/math.h"
#include "base/Logger.h"
#include "detectors/Trigger.h"
#include "detectors/CB.h"
#include "detectors/PID.h"
#include "detectors/TAPS.h"
#include "detectors/TAPSVeto.h"
#include "detectors/EPT.h"
#include "calibration/modules/Time.h"
#include "calibration/modules/CB_Energy.h"
#include "calibration/modules/CB_TimeWalk.h"
#include "calibration/modules/PID_Energy.h"
#include "calibration/modules/PID_PhiAngle.h"
#include "calibration/modules/TAPS_Time.h"
#include "calibration/modules/TAPS_Energy.h"
#include "calibration/modules/TAPS_ShortEnergy.h"
#include "calibration/modules/TAPS_ShowerCorrection.h"
#include "calibration/modules/TAPS_ToF.h"
#include "calibration/modules/TAPSVeto_Energy.h"
#include "calibration/modules/TAPSVeto_Time.h"
#include "calibration/modules/MCEnergySmearing.h"
#include "calibration/fitfunctions/FitGaus.h"
#include "calibration/fitfunctions/FitGausPol0.h"
#include "calibration/fitfunctions/FitGausPol3.h"
#include "calibration/converters/MultiHit.h"
#include "calibration/converters/MultiHitReference.h"
#include "calibration/converters/GeSiCa_SADC.h"
#include "calibration/converters/CATCH_TDC.h"
using namespace std;
using namespace ant::expconfig;
using namespace ant::expconfig::setup;
Setup_2014_EPT::Setup_2014_EPT(const string& name, OptionsPtr opt) :
Setup(name, opt),
MCTaggerHits(opt->Get<bool>("MCTaggerHits",false))
{
// setup the detectors of interest
auto trigger = make_shared<detector::Trigger_2014>();
AddDetector(trigger);
auto EPT = make_shared<detector::EPT_2014>(GetElectronBeamEnergy());;
AddDetector(EPT);
auto cb = make_shared<detector::CB>();
AddDetector(cb);
auto pid = make_shared<detector::PID_2014>();
AddDetector(pid);
const bool cherenkovInstalled = false;
auto taps = make_shared<detector::TAPS_2013>(cherenkovInstalled, false); // no Cherenkov, don't use sensitive channels
AddDetector(taps);
auto tapsVeto = make_shared<detector::TAPSVeto_2014>(cherenkovInstalled); // no Cherenkov
AddDetector(tapsVeto);
// then calibrations need some rawvalues to "physical" values converters
// they can be quite different (especially for the COMPASS TCS system), but most of them simply decode the bytes
// to 16bit signed values
/// \todo check if 16bit unsigned is correct for all those detectors
const auto& convert_MultiHit16bit = make_shared<calibration::converter::MultiHit<std::uint16_t>>();
const auto& convert_CATCH_Tagger = make_shared<calibration::converter::CATCH_TDC>(
trigger->Reference_CATCH_TaggerCrate
);
const auto& convert_CATCH_CB = make_shared<calibration::converter::CATCH_TDC>(
trigger->Reference_CATCH_CBCrate
);
const auto& convert_GeSiCa_SADC = make_shared<calibration::converter::GeSiCa_SADC>();
const auto& convert_V1190_TAPSPbWO4 = make_shared<calibration::converter::MultiHitReference<std::uint16_t>>(
trigger->Reference_V1190_TAPSPbWO4,
calibration::converter::Gains::V1190_TDC
);
// the order of the reconstruct hooks is important
// add both CATCH converters and the V1190 first,
// since they need to scan the detector read for their reference hit
AddHook(convert_CATCH_Tagger);
AddHook(convert_CATCH_CB);
AddHook(convert_V1190_TAPSPbWO4);
const bool timecuts = !opt->Get<bool>("DisableTimecuts");
interval<double> no_timecut(-std_ext::inf, std_ext::inf);
if(!timecuts)
LOG(INFO) << "Disabling timecuts";
const bool thresholds = !opt->Get<bool>("DisableThresholds");
if(!thresholds)
LOG(INFO) << "Disabling thresholds";
// then we add the others, and link it to the converters
AddCalibration<calibration::Time>(EPT,
calibrationDataManager,
convert_CATCH_Tagger,
-325, // default offset in ns
std::make_shared<calibration::gui::FitGausPol0>(),
timecuts ? interval<double>{-120, 120} : no_timecut
);
AddCalibration<calibration::Time>(cb,
calibrationDataManager,
convert_CATCH_CB,
-325, // default offset in ns
std::make_shared<calibration::gui::CBPeakFunction>(),
// before timewalk correction
timecuts ? interval<double>{-20, 200} : no_timecut
);
AddCalibration<calibration::Time>(pid,
calibrationDataManager,
convert_CATCH_CB,
-325,
std::make_shared<calibration::gui::FitGaus>(),
timecuts ? interval<double>{-20, 20} : no_timecut
);
AddCalibration<calibration::TAPS_Time>(taps,
calibrationDataManager,
convert_MultiHit16bit, // for BaF2
convert_V1190_TAPSPbWO4, // for PbWO4
timecuts ? interval<double>{-15, 15} : no_timecut, // for BaF2
timecuts ? interval<double>{-25, 25} : no_timecut // for PbWO4
);
AddCalibration<calibration::TAPSVeto_Time>(tapsVeto,
calibrationDataManager,
convert_MultiHit16bit, // for BaF2
convert_V1190_TAPSPbWO4, // for PbWO4
timecuts ? interval<double>{-12, 12} : no_timecut,
timecuts ? interval<double>{-12, 12} : no_timecut
);
AddCalibration<calibration::CB_Energy>(cb, calibrationDataManager, convert_GeSiCa_SADC,
0, // default pedestal
0.07, // default gain
thresholds ? 2 : 0, // default threshold
1.0 // default relative gain
);
AddCalibration<calibration::PID_Energy>(pid, calibrationDataManager, convert_MultiHit16bit );
AddCalibration<calibration::TAPS_Energy>(taps, calibrationDataManager, convert_MultiHit16bit,
100, // default pedestal
0.3, // default gain
thresholds ? 1 : 0, // default threshold
1.0 // default relative gain
);
AddCalibration<calibration::TAPS_ShortEnergy>(taps, calibrationDataManager, convert_MultiHit16bit );
AddCalibration<calibration::TAPSVeto_Energy>(tapsVeto, calibrationDataManager, convert_MultiHit16bit);
// enable TAPS shower correction, which is a hook running on list of clusters
AddCalibration<calibration::TAPS_ShowerCorrection>();
// add ToF timing to TAPS clusters
AddCalibration<calibration::TAPS_ToF>(taps, calibrationDataManager);
// the PID calibration is a physics module only
AddCalibration<calibration::PID_PhiAngle>(pid, calibrationDataManager);
// CB timing needs timewalk correction
AddCalibration<calibration::CB_TimeWalk>(cb, calibrationDataManager,
timecuts ? interval<double>{-10, 20} : no_timecut);
if(opt->Get<bool>("MCSmearing", false)) {
AddHook(make_shared<calibration::MCEnergySmearing>(Detector_t::Type_t::CB, 1.05830, 0.3));
AddHook(make_shared<calibration::MCEnergySmearing>(Detector_t::Type_t::TAPS, 1.05830, 0.3));
}
}
double Setup_2014_EPT::GetElectronBeamEnergy() const {
return 1604.0;
}
void Setup_2014_EPT::BuildMappings(std::vector<ant::UnpackerAcquConfig::hit_mapping_t>& hit_mappings, std::vector<ant::UnpackerAcquConfig::scaler_mapping_t>& scaler_mappings) const
{
// build the mappings from the given detectors
// that should provide sane and correct defaults
Setup::BuildMappings(hit_mappings, scaler_mappings);
// now you may tweak the mapping at this location here
// for example, ignore elements
}
ant::ExpConfig::Setup::candidatebuilder_config_t Setup_2014_EPT::GetCandidateBuilderConfig() const
{
candidatebuilder_config_t conf;
conf.PID_Phi_Epsilon = std_ext::degree_to_radian(2.0);
conf.CB_ClusterThreshold = 15;
conf.TAPS_ClusterThreshold = 20;
return conf;
}
ant::UnpackerA2GeantConfig::promptrandom_config_t Setup_2014_EPT::GetPromptRandomConfig() const {
ant::UnpackerA2GeantConfig::promptrandom_config_t conf;
// default constructed conf has everything disabled
if(MCTaggerHits) {
conf.RandomPromptRatio = 0.22; // per unit time interval
conf.PromptSigma = 0.87; // in ns
conf.TimeWindow = {-120, 120};
conf.PromptOffset = -0.37;
}
return conf;
}
|
#ifndef MMATH_H
#define MMATH_H
#include <cmath>
namespace MMath{
static const double M_PI = acos((long double) -1);
static const double PI = M_PI;
static const double DEG_OVER_RAD = 180.0 / M_PI;//в градусы
static const double RAD_OVER_DEG = M_PI / 180.0;//в радианы
static const float M_PI_FLOAT = static_cast<float>(M_PI);
inline static void toDeg(double *_rad)
{
double deg=DEG_OVER_RAD+(*_rad);
*_rad=deg;
}
inline static void sincosf(float _x, float * _sinx, float * _cosx) {
*_sinx = std::sin(_x);
*_cosx = std::cos(_x);
}
}
#endif
|
// HTTPReader.cpp: implementation of the CHTTPReader class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "HTTPReader.h"
#include <string.h>
#include <tchar.h>
#pragma comment(lib,"wininet")
CHTTPReader::CHTTPReader(LPCTSTR lpszServerName,bool bUseSSL)
: m_hInternet(NULL),
m_hConnection(NULL),
m_hRequest(NULL),
m_lpszServerName(NULL),
m_lpszDefaultHeader(NULL),
m_lpszDataBuffer(NULL),
m_dwBufferSize(0),
m_bUseSSL(bUseSSL),
m_dwLastError(0)
{
SetDefaultHeader(TEXT(
"Content-Type: application/x-www-form-urlencoded\r\n"
"Accept-Language:ru\r\n"
"Accept-Encoding:gzip, deflate"));
StrDup(m_lpszServerName,lpszServerName);
}
CHTTPReader::~CHTTPReader()
{
delete m_lpszDataBuffer;
delete m_lpszServerName;
SetDefaultHeader(NULL);
}
bool CHTTPReader::CheckError(bool bTest)
{
if (bTest == false) {
m_dwLastError = ::GetLastError();
if (m_dwLastError != 0)
ReportError();
}
return bTest;
}
bool CHTTPReader::OpenInternet(LPCTSTR lpszAgent)
{
if (m_hInternet == NULL)
m_hInternet = ::InternetOpen(
lpszAgent,
INTERNET_OPEN_TYPE_PRECONFIG,
NULL,
NULL,
0);
return CheckError(m_hInternet != NULL);
}
void CHTTPReader::CloseInternet ()
{
CloseConnection();
if (m_hInternet)
::InternetCloseHandle(m_hInternet);
m_hInternet = NULL;
}
bool CHTTPReader::OpenConnection (LPCTSTR lpszServerName)
{
if (OpenInternet() && m_hConnection == NULL)
m_hConnection = ::InternetConnect(
m_hInternet,
lpszServerName?
lpszServerName:
m_lpszServerName?
m_lpszServerName:
TEXT("localhost"),
m_bUseSSL? INTERNET_DEFAULT_HTTPS_PORT: INTERNET_DEFAULT_HTTP_PORT,
NULL,
NULL,
INTERNET_SERVICE_HTTP,
0,
1u);
return CheckError(m_hConnection != NULL);
}
void CHTTPReader::CloseConnection ()
{
CloseRequest();
if (m_hConnection)
::InternetCloseHandle(m_hConnection);
m_hConnection = NULL;
}
bool CHTTPReader::SendRequest (LPCTSTR lpszVerb,
LPCTSTR lpszAction,
LPCTSTR lpszData,
LPCTSTR lpszReferer)
{
if (OpenConnection()) {
CloseRequest();
LPCTSTR AcceptTypes[] = { TEXT("*/*"), NULL};
m_hRequest = ::HttpOpenRequest(
m_hConnection,
lpszVerb,
lpszAction,
NULL,
lpszReferer,
AcceptTypes,
(m_bUseSSL? INTERNET_FLAG_SECURE|INTERNET_FLAG_IGNORE_CERT_CN_INVALID: 0)
| INTERNET_FLAG_KEEP_CONNECTION,
1);
if (m_hRequest != NULL) {
if (::HttpSendRequest(
m_hRequest,
m_lpszDefaultHeader,
-1,
(LPVOID)lpszData,
lpszData? _tcslen(lpszData): 0) == FALSE) {
CheckError(false);
CloseRequest();
return false;
}
}
}
return CheckError(m_hRequest != NULL);
}
bool CHTTPReader::Get (LPCTSTR lpszAction,LPCTSTR lpszReferer)
{
return SendRequest(TEXT("GET"),lpszAction,NULL,lpszReferer);
}
bool CHTTPReader::Post (LPCTSTR lpszAction,LPCTSTR lpszData,LPCTSTR lpszReferer)
{
return SendRequest(TEXT("POST"),lpszAction,lpszData,lpszReferer);
}
void CHTTPReader::CloseRequest ()
{
if (m_hRequest)
::InternetCloseHandle(m_hRequest);
m_hRequest = NULL;
}
void CHTTPReader::StrDup (LPTSTR& lpszDest,LPCTSTR lpszSource)
{
delete lpszDest;
if (lpszSource == NULL) {
lpszDest = NULL;
} else {
lpszDest = new TCHAR[_tcslen(lpszSource)+1];
_tcscpy(lpszDest,lpszSource);
}
}
void CHTTPReader::SetDefaultHeader (LPCTSTR lpszDefaultHeader)
{
StrDup(m_lpszDefaultHeader,lpszDefaultHeader);
}
void CHTTPReader::ReportError() const
{
LPVOID lpMsgBuffer;
DWORD dwRet=FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_IGNORE_INSERTS
| FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandle(_T("wininet.dll")),
m_dwLastError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPTSTR>(&lpMsgBuffer),
0,
NULL);
OutputDebugString(reinterpret_cast<LPTSTR>(lpMsgBuffer));
LocalFree(lpMsgBuffer);
}
char *CHTTPReader::GetData (char *lpszBuffer,DWORD dwSize,DWORD *lpdwBytesRead)
{
DWORD dwBytesRead;
if (lpdwBytesRead == NULL)
lpdwBytesRead = &dwBytesRead;
*lpdwBytesRead = 0;
if (m_hRequest) {
bool bRead = ::InternetReadFile(
m_hRequest,
lpszBuffer,
dwSize,
lpdwBytesRead) != FALSE;
lpszBuffer[*lpdwBytesRead] = 0;
return CheckError(bRead) && *lpdwBytesRead? lpszBuffer: NULL;
}
return NULL;
}
DWORD CHTTPReader::GetDataSize ()
{
if (m_hRequest) {
DWORD dwDataSize = 0;
DWORD dwLengthDataSize = sizeof(dwDataSize);
BOOL bQuery = ::HttpQueryInfo(
m_hRequest,
HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
&dwDataSize,
&dwLengthDataSize,
NULL);
return bQuery? dwDataSize: 0;
}
return 0;
}
char *CHTTPReader::GetData (DWORD *lpdwBytesRead)
{
DWORD dwDataSize = GetDataSize();
SetDataBuffer(dwDataSize);
return GetData(
m_lpszDataBuffer,
dwDataSize? dwDataSize: m_dwBufferSize,
lpdwBytesRead);
}
void CHTTPReader::SetDataBuffer (DWORD dwBufferSize)
{
if (dwBufferSize > m_dwBufferSize) {
delete m_lpszDataBuffer;
m_lpszDataBuffer = new char[(m_dwBufferSize = dwBufferSize) + 1];
}
}
|
#include "matrix_graph.hpp"
void push_front(std::vector<int>& arr, int data) {
arr.push_back(0);
for (size_t i = arr.size() - 1; i > 0; --i) {
arr[i] = arr[i - 1];
}
arr[0] = data;
}
void MatrixGraph::AddEdge(int from, int to) {
liste_d_adjacence_[from].push_back(to);
// push_front(adjacencyLists[from], to);
}
int MatrixGraph::VerticesCount() const {
return liste_d_adjacence_.size();
}
MatrixGraph::MatrixGraph(const IGraph &copiant) {
size_t c_size = copiant.VerticesCount();
liste_d_adjacence_ = std::vector<std::vector<int>>(c_size);
for (size_t i = 0; i < c_size; ++i) {
std::vector<int> vertices = GetNextVertices(i);
for (size_t j = 0; j < vertices.size(); ++j) {
AddEdge(i, vertices[j]);
}
}
}
std::vector<int> MatrixGraph::GetNextVertices(int vertex) const {
std::vector<int> vertices;
for (auto i : liste_d_adjacence_[vertex]) {
vertices.push_back(i);
}
return vertices;
}
std::vector<int> MatrixGraph::GetPrevVertices(int vertex) const {
std::vector<int> vertices;
for (size_t i = 0; i < liste_d_adjacence_.size(); ++i) {
for (auto j : liste_d_adjacence_[i]) {
if (j == vertex) {
vertices.push_back(i);
}
}
}
return vertices;
}
|
#include <iostream>
#include<string>
using namespace std;
int main(){
int char_array_size;
cin>>char_array_size;
char word[char_array_size];
int yes=0,no=0;
for(int i=0; i<char_array_size; i++){
cin>>word[i];
}
for(int i = 0; i<char_array_size-1; i++){
if(word[i]=='S' && word[i+1]=='F')
yes++;
else if(word[i]=='F' && word[i+1]=='S')
no++;
}
if(yes>no)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
int bit[100100], vet[100100];
int n;
int soma(int pos){
int s = 0;
while(pos > 0){
s+=bit[pos];
pos-=(pos & -pos);
}
return s;
}
void atualiza(int pos){
while(pos<=n){
bit[pos]++;
pos+=(pos & -pos);
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
while(cin >> n, n!=0){
memset(bit, 0, sizeof bit);
for(int i=1;i <=n ;i++){
cin >> vet[i];
}
int cont = 0;
for(int i=n; i>=1; i--){
cont += soma(vet[i]-1);
atualiza(vet[i]);
}
if(cont%2==0) cout << "Carlos" << endl;
else cout << "Marcelo" << endl;
//cout << "cont: " << cont << endl;
}
}
|
/*************************************************************
Author : qmeng
MailTo : qmeng1128@163.com
QQ : 1163306125
Blog : http://blog.csdn.net/Mq_Go/
Create : 2018-03-28 14:41:48
Version: 1.0
**************************************************************/
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
cin >> str;
int len = str.length();
int map[4] = {0};
for(int i = 0 ; i < len ; i++){
if(str[i]=='G'|| str[i]=='g')map[0]++;
else if(str[i]=='P' || str[i]=='p')map[1]++;
else if(str[i]=='L' || str[i]=='l')map[2]++;
else if(str[i]=='T' || str[i]=='t')map[3]++;
}
int max = 0;
if(map[0]>max)max = map[0];
if(map[1]>max)max = map[1];
if(map[2]>max)max = map[2];
if(map[3]>max)max = map[3];
for(int i = 0 ; i < max ; i++){
if(map[0]-->0)printf("G");
if(map[1]-->0)printf("P");
if(map[2]-->0)printf("L");
if(map[3]-->0)printf("T");
}
return 0;
}
|
#include"boost/date_time/posix_time/posix_time.hpp"
#include<iostream>
#include<vector>
#include<string>
int main(int argc,char** argv){
std::vector<boost::posix_time::time_duration> vd;
vd.push_back(
boost::posix_time::milliseconds(10)
);
vd.push_back(
boost::posix_time::microseconds(10)
);
vd.push_back(
boost::posix_time::seconds(10)
);
vd.push_back(
boost::posix_time::minutes(10)
);
vd.push_back(
boost::posix_time::hours(10)
);
vd.push_back(
boost::posix_time::milliseconds(10)+
boost::posix_time::microseconds(10)+
boost::posix_time::seconds(10)+
boost::posix_time::minutes(10)+
boost::posix_time::hours(10)
);
;
boost::posix_time::ptime now=boost::posix_time::second_clock::local_time();
//boost::posix_time::ptime now=boost::posix_time::microsec_clock::universal_time();
for(
std::vector<boost::posix_time::time_duration>::iterator it=vd.begin();
it!=vd.end();
++it
){
std::cout<<now+(*it)<<std::endl;
}
return 0;
}
|
#include "clock.h"
using namespace std;
int main() {
// Constructor
Clock c;
Clock d(12, 34, 56);
Clock e("12:34:56");
Clock f(c);
// << overload
cout << c << endl;
c = c+d;
cout << "Addition: " << c << endl;
c = c-d;
cout << "Subtraction: " << c << endl;
cout << "String constructor (should be 12:34:56): " << e << endl;
e.setClock("65:43:21");
cout << "Setting via string (should return 65:43:21): " << e << endl;
cout << f << endl;
cout << (c==f ? "c equals f" : "c does not equal f") << endl;
cout << (c!=f ? "c does not equal f" : "c equals f") << endl;
return 0;
}
|
#include<iostream>
using namespace std;
//initialization --> array and top=-1. Both are declared as global
int arr[100],top=-1;
//Function to push an element into the stack
void push(int ele) {
if(top>=5) {
cout<<"Overflow";
}
else{
top++;
arr[top] = ele;
}
}
//Function to pop element from he stack. Function returns the popped element.
int pop() {
int k;
if(top==-1) {
cout<<"underflow";
return -1;
}
else{
top--;
k = arr[top];
return k;
}
}
//Function to see the top tof the stack. The function returns the top of the stack.
int peek() {
if(top==-1) {
return -1;
}
else if(top>=5) {
return -1;
}
else {
return arr[top];
}
}
int main() {
push(5);
push(6);
push(7);
pop();
// cout<<top;
push(8);
push(10);
pop();
int z = peek();
cout<<z<<"\n";
}
|
#include "Skeleton.h"
const int Skeleton::nextJoint = 4;
const int Skeleton::numberOfColumns = 60;
const int Skeleton::numberOfJoints = 15;
/************************************************
** Constructors
*************************************************/
Skeleton::Skeleton(void)
{
this->data = mat(0,0);
}
Skeleton::Skeleton(mat dataMat)
{
this->data = dataMat;
}
Skeleton::Skeleton(const char *file)
{
this->data.load(file);
}
Skeleton::Skeleton(ifstream &file)
{
this->data.load(file, raw_ascii);
}
Skeleton::Skeleton(const Skeleton &c)
{
this->data = c.data;
}
Skeleton::~Skeleton(void) {}
void Skeleton::setData(mat dataMat)
{
this->data = dataMat;
}
mat Skeleton::getData(void)
{
return this->data;
}
/************************************************
** Operators
*************************************************/
Skeleton Skeleton::operator=(const Skeleton &c)
{
if(this == &c)
{
return *this;
}
else
{
this->data = c.data;
}
return *this;
}
/************************************************
** Getters
*************************************************/
colvec Skeleton::getJoint(int indexOfJoint)
{
return this->data.col(indexOfJoint);
}
|
/*
Fichier : passgrid.cc
Auteur : THAI Jean-François MAIN4
Date : 08/10/16
contient les méthodes de la classe PassGrid
*/
#include "passgrid.hh"
#include "path.hh"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
PassGrid::PassGrid(std::size_t h, std::size_t w):longueur_(h), largeur_(w)
{
grille_ = new char[longueur_*largeur_];
reset();
}
PassGrid::~PassGrid()
{
delete[] grille_;
}
/*--------------------------------------------------*/
/*Méthodes*/
/*
Fonction : affiche la grille crée par la fonction reset().
Paramètres :
Return :
*/
void PassGrid::print() const
{
for (int i=0; i<longueur_; i++)
{
for (int j=0; j<largeur_; j++)
cout << grille_[i*longueur_ + j] << " ";
cout << endl;
}
}
/*
Fonction : remplit grille_ avec des caractères aléatoires (code ascii 33 à 94).
Paramètres :
Return :
*/
void PassGrid::reset()
{
for (int i=0; i<longueur_; i++)
{
for (int j=0; j<largeur_; j++)
grille_[i*longueur_ + j] = char(rand() % 61+33);
}
}
/*
Fonction : génère un mot de passe en utilisant grille_ et un chemin aléatoire.
Paramètres : chemin (Path*) pointeur vers un objet Path
Return : string représentant un password
*/
string PassGrid::generate(Path* chemin)
{
//on vérifie si les dimensions sont compatibles
if((chemin->get_longueur()!=longueur_) || (chemin->get_largeur()!=largeur_))
{
cout << "Erreur dimension !" << endl;
exit(EXIT_FAILURE);
}
string password("");
int x(chemin->get_x0());
int y(chemin->get_y0());
int size(chemin->get_size());
password = grille_[x*longueur_ + y];
for(int i=0; i<size; i++)
{
switch(chemin->get_path(i))
{
case 0:
x -= 1;
break;
case 1:
x -= 1; y += 1;
break;
case 2:
y += 1;
break;
case 3:
x += 1; y += 1;
break;
case 4:
x += 1;
break;
case 5:
x += 1; y -= 1;
break;
case 6:
y -= 1;
break;
case 7:
x -= 1; y -= 1;
break;
}
password = password + grille_[x*longueur_ + y];
}
return password;
}
/*
Fonction : écrit grille_ dans un fichier svg.
Paramètres : fichier (string) nom du fichier qu'on veut créer
Return : fichier.svg
*/
void PassGrid::SVG(string fichier) const
{
//ouverture et test
ofstream file(fichier.c_str(), ios::out|ios::trunc);
if(!file)
{
cout << "Erreur fichier SVG !" << endl;
exit(EXIT_FAILURE);
}
//en-tête du fichier svg
file << "<?xml version=\"1.0\" standalone=\"no\"?>" << endl;
file << "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" << endl;
//dimensions et caractéristiques de l'image
file << "<svg viewbox = \" 0 0 " << (largeur_*20+20) << " " << (longueur_*20+20) << "\" version=\"1.1\">" << endl;
file << "<rect x=\"0\" y=\"0\" width=\"" << (largeur_*20+20) << "\" height=\"" << (longueur_*20+20) << "\" fill=\"white\" stroke=\"black\" stroke-width=\"3\" />" << endl;
inscription des caractères de grille_
for(int i=0; i<longueur_; i++)
{
file << "<text x=\"20\" y=\"" << (i*20+20) << "\" fill=\"navy\" font-size=\"15\">" << endl;
for(int j=0; j<largeur_; j++)
{
if(grille_[i*longueur_+j]=='&')
file << "& ";
else if(grille_[i*longueur_+j]=='<')
file << "< ";
else
file << grille_[i*longueur_+j] << " ";
}
file << endl << "</text>" << endl;
}
file << "</svg>";
file.close();
string new_name = fichier+".svg";
rename(fichier.c_str(), new_name.c_str());
}
|
#pragma once
#include <array>
namespace GraphicsEngine
{
class InputHandler
{
public:
InputHandler();
template<typename VirtualKey, typename = std::enable_if_t<std::is_enum<VirtualKey>::value || std::is_integral<VirtualKey>::value>>
void OnKeyDown(VirtualKey key);
template<typename VirtualKey, typename = std::enable_if_t<std::is_enum<VirtualKey>::value || std::is_integral<VirtualKey>::value>>
void OnKeyUp(VirtualKey key);
template<typename VirtualKey, typename = std::enable_if_t<std::is_enum<VirtualKey>::value || std::is_integral<VirtualKey>::value>>
bool IsKeyDown(VirtualKey key) const;
private:
std::array<bool, 256> m_keys;
};
template<typename VirtualKey, typename>
void InputHandler::OnKeyDown(VirtualKey key)
{
m_keys[static_cast<uint32_t>(key)] = true;
}
template<typename VirtualKey, typename>
void InputHandler::OnKeyUp(VirtualKey key)
{
m_keys[static_cast<uint32_t>(key)] = false;
}
template<typename VirtualKey, typename>
bool InputHandler::IsKeyDown(VirtualKey key) const
{
return m_keys[static_cast<uint32_t>(key)];
}
}
|
#ifndef CALLBACKHANDLER_H
#define CALLBACKHANDLER_H
#include "LOpenGL.h"
#include "GameWorld.h"
class CallbackHandler
{
private:
CallbackHandler() {}
CallbackHandler(const CallbackHandler&);
CallbackHandler& operator=(const CallbackHandler&);
private:
static GameWorld* m_pGameWorld;
public:
~CallbackHandler() {}
static CallbackHandler* Instance(GameWorld* world);
};
#endif // CALLBACKHANDLER_H
|
#include "TestBedApp.h"
#include <stdio.h>
#include <string>
#include <vector>
TestBedApp* App = NULL;
int main( int argc, char* args[] )
{
App = new TestBedApp();
App->Initialize("TestBed", 1280,720);
App->LoadContent();
App->Run();
return 0;
}
|
/*#pragma once
#include <GameEngine.h>
class DemoApp3 : public GameEngine {
virtual void Initialize() override;
virtual void Update(GameTime&) override;
virtual void Render() override;
};*/
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "base.h"
WINRT_WARNING_PUSH
#include "internal/Windows.Foundation.3.h"
#include "internal/Windows.Foundation.Collections.3.h"
#include "internal/Windows.Globalization.NumberFormatting.3.h"
#include "Windows.Globalization.h"
WINRT_EXPORT namespace winrt {
namespace impl {
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::ICurrencyFormatter> : produce_base<D, Windows::Globalization::NumberFormatting::ICurrencyFormatter>
{
HRESULT __stdcall get_Currency(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Currency());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall put_Currency(impl::abi_arg_in<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Currency(*reinterpret_cast<const hstring *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::ICurrencyFormatter2> : produce_base<D, Windows::Globalization::NumberFormatting::ICurrencyFormatter2>
{
HRESULT __stdcall get_Mode(Windows::Globalization::NumberFormatting::CurrencyFormatterMode * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Mode());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_Mode(Windows::Globalization::NumberFormatting::CurrencyFormatterMode value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Mode(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_ApplyRoundingForCurrency(Windows::Globalization::NumberFormatting::RoundingAlgorithm roundingAlgorithm) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ApplyRoundingForCurrency(roundingAlgorithm);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::ICurrencyFormatterFactory> : produce_base<D, Windows::Globalization::NumberFormatting::ICurrencyFormatterFactory>
{
HRESULT __stdcall abi_CreateCurrencyFormatterCode(impl::abi_arg_in<hstring> currencyCode, impl::abi_arg_out<Windows::Globalization::NumberFormatting::ICurrencyFormatter> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().CreateCurrencyFormatterCode(*reinterpret_cast<const hstring *>(¤cyCode)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_CreateCurrencyFormatterCodeContext(impl::abi_arg_in<hstring> currencyCode, impl::abi_arg_in<Windows::Foundation::Collections::IIterable<hstring>> languages, impl::abi_arg_in<hstring> geographicRegion, impl::abi_arg_out<Windows::Globalization::NumberFormatting::ICurrencyFormatter> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().CreateCurrencyFormatterCodeContext(*reinterpret_cast<const hstring *>(¤cyCode), *reinterpret_cast<const Windows::Foundation::Collections::IIterable<hstring> *>(&languages), *reinterpret_cast<const hstring *>(&geographicRegion)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::IDecimalFormatterFactory> : produce_base<D, Windows::Globalization::NumberFormatting::IDecimalFormatterFactory>
{
HRESULT __stdcall abi_CreateDecimalFormatter(impl::abi_arg_in<Windows::Foundation::Collections::IIterable<hstring>> languages, impl::abi_arg_in<hstring> geographicRegion, impl::abi_arg_out<Windows::Globalization::NumberFormatting::INumberFormatter> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().CreateDecimalFormatter(*reinterpret_cast<const Windows::Foundation::Collections::IIterable<hstring> *>(&languages), *reinterpret_cast<const hstring *>(&geographicRegion)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::IIncrementNumberRounder> : produce_base<D, Windows::Globalization::NumberFormatting::IIncrementNumberRounder>
{
HRESULT __stdcall get_RoundingAlgorithm(Windows::Globalization::NumberFormatting::RoundingAlgorithm * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().RoundingAlgorithm());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_RoundingAlgorithm(Windows::Globalization::NumberFormatting::RoundingAlgorithm value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().RoundingAlgorithm(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_Increment(double * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Increment());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_Increment(double value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Increment(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::INumberFormatter> : produce_base<D, Windows::Globalization::NumberFormatting::INumberFormatter>
{
HRESULT __stdcall abi_FormatInt(int64_t value, impl::abi_arg_out<hstring> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().Format(value));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_FormatUInt(uint64_t value, impl::abi_arg_out<hstring> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().Format(value));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_FormatDouble(double value, impl::abi_arg_out<hstring> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().Format(value));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::INumberFormatter2> : produce_base<D, Windows::Globalization::NumberFormatting::INumberFormatter2>
{
HRESULT __stdcall abi_FormatInt(int64_t value, impl::abi_arg_out<hstring> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().FormatInt(value));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_FormatUInt(uint64_t value, impl::abi_arg_out<hstring> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().FormatUInt(value));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_FormatDouble(double value, impl::abi_arg_out<hstring> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().FormatDouble(value));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::INumberFormatterOptions> : produce_base<D, Windows::Globalization::NumberFormatting::INumberFormatterOptions>
{
HRESULT __stdcall get_Languages(impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<hstring>> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Languages());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_GeographicRegion(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().GeographicRegion());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_IntegerDigits(int32_t * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IntegerDigits());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_IntegerDigits(int32_t value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().IntegerDigits(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_FractionDigits(int32_t * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().FractionDigits());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_FractionDigits(int32_t value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().FractionDigits(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_IsGrouped(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IsGrouped());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_IsGrouped(bool value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().IsGrouped(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_IsDecimalPointAlwaysDisplayed(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IsDecimalPointAlwaysDisplayed());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_IsDecimalPointAlwaysDisplayed(bool value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().IsDecimalPointAlwaysDisplayed(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_NumeralSystem(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().NumeralSystem());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall put_NumeralSystem(impl::abi_arg_in<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().NumeralSystem(*reinterpret_cast<const hstring *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_ResolvedLanguage(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().ResolvedLanguage());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_ResolvedGeographicRegion(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().ResolvedGeographicRegion());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::INumberParser> : produce_base<D, Windows::Globalization::NumberFormatting::INumberParser>
{
HRESULT __stdcall abi_ParseInt(impl::abi_arg_in<hstring> text, impl::abi_arg_out<Windows::Foundation::IReference<int64_t>> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().ParseInt(*reinterpret_cast<const hstring *>(&text)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_ParseUInt(impl::abi_arg_in<hstring> text, impl::abi_arg_out<Windows::Foundation::IReference<uint64_t>> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().ParseUInt(*reinterpret_cast<const hstring *>(&text)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_ParseDouble(impl::abi_arg_in<hstring> text, impl::abi_arg_out<Windows::Foundation::IReference<double>> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().ParseDouble(*reinterpret_cast<const hstring *>(&text)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::INumberRounder> : produce_base<D, Windows::Globalization::NumberFormatting::INumberRounder>
{
HRESULT __stdcall abi_RoundInt32(int32_t value, int32_t * result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().RoundInt32(value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_RoundUInt32(uint32_t value, uint32_t * result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().RoundUInt32(value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_RoundInt64(int64_t value, int64_t * result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().RoundInt64(value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_RoundUInt64(uint64_t value, uint64_t * result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().RoundUInt64(value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_RoundSingle(float value, float * result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().RoundSingle(value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_RoundDouble(double value, double * result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().RoundDouble(value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::INumberRounderOption> : produce_base<D, Windows::Globalization::NumberFormatting::INumberRounderOption>
{
HRESULT __stdcall get_NumberRounder(impl::abi_arg_out<Windows::Globalization::NumberFormatting::INumberRounder> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().NumberRounder());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall put_NumberRounder(impl::abi_arg_in<Windows::Globalization::NumberFormatting::INumberRounder> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().NumberRounder(*reinterpret_cast<const Windows::Globalization::NumberFormatting::INumberRounder *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::INumeralSystemTranslator> : produce_base<D, Windows::Globalization::NumberFormatting::INumeralSystemTranslator>
{
HRESULT __stdcall get_Languages(impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<hstring>> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Languages());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_ResolvedLanguage(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().ResolvedLanguage());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_NumeralSystem(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().NumeralSystem());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall put_NumeralSystem(impl::abi_arg_in<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().NumeralSystem(*reinterpret_cast<const hstring *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_TranslateNumerals(impl::abi_arg_in<hstring> value, impl::abi_arg_out<hstring> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().TranslateNumerals(*reinterpret_cast<const hstring *>(&value)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::INumeralSystemTranslatorFactory> : produce_base<D, Windows::Globalization::NumberFormatting::INumeralSystemTranslatorFactory>
{
HRESULT __stdcall abi_Create(impl::abi_arg_in<Windows::Foundation::Collections::IIterable<hstring>> languages, impl::abi_arg_out<Windows::Globalization::NumberFormatting::INumeralSystemTranslator> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().Create(*reinterpret_cast<const Windows::Foundation::Collections::IIterable<hstring> *>(&languages)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::IPercentFormatterFactory> : produce_base<D, Windows::Globalization::NumberFormatting::IPercentFormatterFactory>
{
HRESULT __stdcall abi_CreatePercentFormatter(impl::abi_arg_in<Windows::Foundation::Collections::IIterable<hstring>> languages, impl::abi_arg_in<hstring> geographicRegion, impl::abi_arg_out<Windows::Globalization::NumberFormatting::INumberFormatter> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().CreatePercentFormatter(*reinterpret_cast<const Windows::Foundation::Collections::IIterable<hstring> *>(&languages), *reinterpret_cast<const hstring *>(&geographicRegion)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::IPermilleFormatterFactory> : produce_base<D, Windows::Globalization::NumberFormatting::IPermilleFormatterFactory>
{
HRESULT __stdcall abi_CreatePermilleFormatter(impl::abi_arg_in<Windows::Foundation::Collections::IIterable<hstring>> languages, impl::abi_arg_in<hstring> geographicRegion, impl::abi_arg_out<Windows::Globalization::NumberFormatting::INumberFormatter> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().CreatePermilleFormatter(*reinterpret_cast<const Windows::Foundation::Collections::IIterable<hstring> *>(&languages), *reinterpret_cast<const hstring *>(&geographicRegion)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::ISignedZeroOption> : produce_base<D, Windows::Globalization::NumberFormatting::ISignedZeroOption>
{
HRESULT __stdcall get_IsZeroSigned(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IsZeroSigned());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_IsZeroSigned(bool value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().IsZeroSigned(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::ISignificantDigitsNumberRounder> : produce_base<D, Windows::Globalization::NumberFormatting::ISignificantDigitsNumberRounder>
{
HRESULT __stdcall get_RoundingAlgorithm(Windows::Globalization::NumberFormatting::RoundingAlgorithm * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().RoundingAlgorithm());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_RoundingAlgorithm(Windows::Globalization::NumberFormatting::RoundingAlgorithm value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().RoundingAlgorithm(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_SignificantDigits(uint32_t * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().SignificantDigits());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_SignificantDigits(uint32_t value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SignificantDigits(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Globalization::NumberFormatting::ISignificantDigitsOption> : produce_base<D, Windows::Globalization::NumberFormatting::ISignificantDigitsOption>
{
HRESULT __stdcall get_SignificantDigits(int32_t * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().SignificantDigits());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_SignificantDigits(int32_t value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SignificantDigits(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
}
namespace Windows::Globalization::NumberFormatting {
template <typename D> int32_t impl_INumberRounder<D>::RoundInt32(int32_t value) const
{
int32_t result {};
check_hresult(WINRT_SHIM(INumberRounder)->abi_RoundInt32(value, &result));
return result;
}
template <typename D> uint32_t impl_INumberRounder<D>::RoundUInt32(uint32_t value) const
{
uint32_t result {};
check_hresult(WINRT_SHIM(INumberRounder)->abi_RoundUInt32(value, &result));
return result;
}
template <typename D> int64_t impl_INumberRounder<D>::RoundInt64(int64_t value) const
{
int64_t result {};
check_hresult(WINRT_SHIM(INumberRounder)->abi_RoundInt64(value, &result));
return result;
}
template <typename D> uint64_t impl_INumberRounder<D>::RoundUInt64(uint64_t value) const
{
uint64_t result {};
check_hresult(WINRT_SHIM(INumberRounder)->abi_RoundUInt64(value, &result));
return result;
}
template <typename D> float impl_INumberRounder<D>::RoundSingle(float value) const
{
float result {};
check_hresult(WINRT_SHIM(INumberRounder)->abi_RoundSingle(value, &result));
return result;
}
template <typename D> double impl_INumberRounder<D>::RoundDouble(double value) const
{
double result {};
check_hresult(WINRT_SHIM(INumberRounder)->abi_RoundDouble(value, &result));
return result;
}
template <typename D> Windows::Globalization::NumberFormatting::RoundingAlgorithm impl_ISignificantDigitsNumberRounder<D>::RoundingAlgorithm() const
{
Windows::Globalization::NumberFormatting::RoundingAlgorithm value {};
check_hresult(WINRT_SHIM(ISignificantDigitsNumberRounder)->get_RoundingAlgorithm(&value));
return value;
}
template <typename D> void impl_ISignificantDigitsNumberRounder<D>::RoundingAlgorithm(Windows::Globalization::NumberFormatting::RoundingAlgorithm value) const
{
check_hresult(WINRT_SHIM(ISignificantDigitsNumberRounder)->put_RoundingAlgorithm(value));
}
template <typename D> uint32_t impl_ISignificantDigitsNumberRounder<D>::SignificantDigits() const
{
uint32_t value {};
check_hresult(WINRT_SHIM(ISignificantDigitsNumberRounder)->get_SignificantDigits(&value));
return value;
}
template <typename D> void impl_ISignificantDigitsNumberRounder<D>::SignificantDigits(uint32_t value) const
{
check_hresult(WINRT_SHIM(ISignificantDigitsNumberRounder)->put_SignificantDigits(value));
}
template <typename D> Windows::Globalization::NumberFormatting::RoundingAlgorithm impl_IIncrementNumberRounder<D>::RoundingAlgorithm() const
{
Windows::Globalization::NumberFormatting::RoundingAlgorithm value {};
check_hresult(WINRT_SHIM(IIncrementNumberRounder)->get_RoundingAlgorithm(&value));
return value;
}
template <typename D> void impl_IIncrementNumberRounder<D>::RoundingAlgorithm(Windows::Globalization::NumberFormatting::RoundingAlgorithm value) const
{
check_hresult(WINRT_SHIM(IIncrementNumberRounder)->put_RoundingAlgorithm(value));
}
template <typename D> double impl_IIncrementNumberRounder<D>::Increment() const
{
double value {};
check_hresult(WINRT_SHIM(IIncrementNumberRounder)->get_Increment(&value));
return value;
}
template <typename D> void impl_IIncrementNumberRounder<D>::Increment(double value) const
{
check_hresult(WINRT_SHIM(IIncrementNumberRounder)->put_Increment(value));
}
template <typename D> hstring impl_INumberFormatter<D>::Format(int64_t value) const
{
hstring result;
check_hresult(WINRT_SHIM(INumberFormatter)->abi_FormatInt(value, put_abi(result)));
return result;
}
template <typename D> hstring impl_INumberFormatter<D>::Format(uint64_t value) const
{
hstring result;
check_hresult(WINRT_SHIM(INumberFormatter)->abi_FormatUInt(value, put_abi(result)));
return result;
}
template <typename D> hstring impl_INumberFormatter<D>::Format(double value) const
{
hstring result;
check_hresult(WINRT_SHIM(INumberFormatter)->abi_FormatDouble(value, put_abi(result)));
return result;
}
template <typename D> hstring impl_INumberFormatter2<D>::FormatInt(int64_t value) const
{
hstring result;
check_hresult(WINRT_SHIM(INumberFormatter2)->abi_FormatInt(value, put_abi(result)));
return result;
}
template <typename D> hstring impl_INumberFormatter2<D>::FormatUInt(uint64_t value) const
{
hstring result;
check_hresult(WINRT_SHIM(INumberFormatter2)->abi_FormatUInt(value, put_abi(result)));
return result;
}
template <typename D> hstring impl_INumberFormatter2<D>::FormatDouble(double value) const
{
hstring result;
check_hresult(WINRT_SHIM(INumberFormatter2)->abi_FormatDouble(value, put_abi(result)));
return result;
}
template <typename D> Windows::Foundation::IReference<int64_t> impl_INumberParser<D>::ParseInt(hstring_view text) const
{
Windows::Foundation::IReference<int64_t> result;
check_hresult(WINRT_SHIM(INumberParser)->abi_ParseInt(get_abi(text), put_abi(result)));
return result;
}
template <typename D> Windows::Foundation::IReference<uint64_t> impl_INumberParser<D>::ParseUInt(hstring_view text) const
{
Windows::Foundation::IReference<uint64_t> result;
check_hresult(WINRT_SHIM(INumberParser)->abi_ParseUInt(get_abi(text), put_abi(result)));
return result;
}
template <typename D> Windows::Foundation::IReference<double> impl_INumberParser<D>::ParseDouble(hstring_view text) const
{
Windows::Foundation::IReference<double> result;
check_hresult(WINRT_SHIM(INumberParser)->abi_ParseDouble(get_abi(text), put_abi(result)));
return result;
}
template <typename D> Windows::Foundation::Collections::IVectorView<hstring> impl_INumberFormatterOptions<D>::Languages() const
{
Windows::Foundation::Collections::IVectorView<hstring> value;
check_hresult(WINRT_SHIM(INumberFormatterOptions)->get_Languages(put_abi(value)));
return value;
}
template <typename D> hstring impl_INumberFormatterOptions<D>::GeographicRegion() const
{
hstring value;
check_hresult(WINRT_SHIM(INumberFormatterOptions)->get_GeographicRegion(put_abi(value)));
return value;
}
template <typename D> int32_t impl_INumberFormatterOptions<D>::IntegerDigits() const
{
int32_t value {};
check_hresult(WINRT_SHIM(INumberFormatterOptions)->get_IntegerDigits(&value));
return value;
}
template <typename D> void impl_INumberFormatterOptions<D>::IntegerDigits(int32_t value) const
{
check_hresult(WINRT_SHIM(INumberFormatterOptions)->put_IntegerDigits(value));
}
template <typename D> int32_t impl_INumberFormatterOptions<D>::FractionDigits() const
{
int32_t value {};
check_hresult(WINRT_SHIM(INumberFormatterOptions)->get_FractionDigits(&value));
return value;
}
template <typename D> void impl_INumberFormatterOptions<D>::FractionDigits(int32_t value) const
{
check_hresult(WINRT_SHIM(INumberFormatterOptions)->put_FractionDigits(value));
}
template <typename D> bool impl_INumberFormatterOptions<D>::IsGrouped() const
{
bool value {};
check_hresult(WINRT_SHIM(INumberFormatterOptions)->get_IsGrouped(&value));
return value;
}
template <typename D> void impl_INumberFormatterOptions<D>::IsGrouped(bool value) const
{
check_hresult(WINRT_SHIM(INumberFormatterOptions)->put_IsGrouped(value));
}
template <typename D> bool impl_INumberFormatterOptions<D>::IsDecimalPointAlwaysDisplayed() const
{
bool value {};
check_hresult(WINRT_SHIM(INumberFormatterOptions)->get_IsDecimalPointAlwaysDisplayed(&value));
return value;
}
template <typename D> void impl_INumberFormatterOptions<D>::IsDecimalPointAlwaysDisplayed(bool value) const
{
check_hresult(WINRT_SHIM(INumberFormatterOptions)->put_IsDecimalPointAlwaysDisplayed(value));
}
template <typename D> hstring impl_INumberFormatterOptions<D>::NumeralSystem() const
{
hstring value;
check_hresult(WINRT_SHIM(INumberFormatterOptions)->get_NumeralSystem(put_abi(value)));
return value;
}
template <typename D> void impl_INumberFormatterOptions<D>::NumeralSystem(hstring_view value) const
{
check_hresult(WINRT_SHIM(INumberFormatterOptions)->put_NumeralSystem(get_abi(value)));
}
template <typename D> hstring impl_INumberFormatterOptions<D>::ResolvedLanguage() const
{
hstring value;
check_hresult(WINRT_SHIM(INumberFormatterOptions)->get_ResolvedLanguage(put_abi(value)));
return value;
}
template <typename D> hstring impl_INumberFormatterOptions<D>::ResolvedGeographicRegion() const
{
hstring value;
check_hresult(WINRT_SHIM(INumberFormatterOptions)->get_ResolvedGeographicRegion(put_abi(value)));
return value;
}
template <typename D> int32_t impl_ISignificantDigitsOption<D>::SignificantDigits() const
{
int32_t value {};
check_hresult(WINRT_SHIM(ISignificantDigitsOption)->get_SignificantDigits(&value));
return value;
}
template <typename D> void impl_ISignificantDigitsOption<D>::SignificantDigits(int32_t value) const
{
check_hresult(WINRT_SHIM(ISignificantDigitsOption)->put_SignificantDigits(value));
}
template <typename D> Windows::Globalization::NumberFormatting::INumberRounder impl_INumberRounderOption<D>::NumberRounder() const
{
Windows::Globalization::NumberFormatting::INumberRounder value;
check_hresult(WINRT_SHIM(INumberRounderOption)->get_NumberRounder(put_abi(value)));
return value;
}
template <typename D> void impl_INumberRounderOption<D>::NumberRounder(const Windows::Globalization::NumberFormatting::INumberRounder & value) const
{
check_hresult(WINRT_SHIM(INumberRounderOption)->put_NumberRounder(get_abi(value)));
}
template <typename D> bool impl_ISignedZeroOption<D>::IsZeroSigned() const
{
bool value {};
check_hresult(WINRT_SHIM(ISignedZeroOption)->get_IsZeroSigned(&value));
return value;
}
template <typename D> void impl_ISignedZeroOption<D>::IsZeroSigned(bool value) const
{
check_hresult(WINRT_SHIM(ISignedZeroOption)->put_IsZeroSigned(value));
}
template <typename D> Windows::Globalization::NumberFormatting::DecimalFormatter impl_IDecimalFormatterFactory<D>::CreateDecimalFormatter(iterable<hstring> languages, hstring_view geographicRegion) const
{
Windows::Globalization::NumberFormatting::DecimalFormatter result { nullptr };
check_hresult(WINRT_SHIM(IDecimalFormatterFactory)->abi_CreateDecimalFormatter(get_abi(languages), get_abi(geographicRegion), put_abi(result)));
return result;
}
template <typename D> Windows::Globalization::NumberFormatting::PercentFormatter impl_IPercentFormatterFactory<D>::CreatePercentFormatter(iterable<hstring> languages, hstring_view geographicRegion) const
{
Windows::Globalization::NumberFormatting::PercentFormatter result { nullptr };
check_hresult(WINRT_SHIM(IPercentFormatterFactory)->abi_CreatePercentFormatter(get_abi(languages), get_abi(geographicRegion), put_abi(result)));
return result;
}
template <typename D> Windows::Globalization::NumberFormatting::PermilleFormatter impl_IPermilleFormatterFactory<D>::CreatePermilleFormatter(iterable<hstring> languages, hstring_view geographicRegion) const
{
Windows::Globalization::NumberFormatting::PermilleFormatter result { nullptr };
check_hresult(WINRT_SHIM(IPermilleFormatterFactory)->abi_CreatePermilleFormatter(get_abi(languages), get_abi(geographicRegion), put_abi(result)));
return result;
}
template <typename D> Windows::Globalization::NumberFormatting::CurrencyFormatter impl_ICurrencyFormatterFactory<D>::CreateCurrencyFormatterCode(hstring_view currencyCode) const
{
Windows::Globalization::NumberFormatting::CurrencyFormatter result { nullptr };
check_hresult(WINRT_SHIM(ICurrencyFormatterFactory)->abi_CreateCurrencyFormatterCode(get_abi(currencyCode), put_abi(result)));
return result;
}
template <typename D> Windows::Globalization::NumberFormatting::CurrencyFormatter impl_ICurrencyFormatterFactory<D>::CreateCurrencyFormatterCodeContext(hstring_view currencyCode, iterable<hstring> languages, hstring_view geographicRegion) const
{
Windows::Globalization::NumberFormatting::CurrencyFormatter result { nullptr };
check_hresult(WINRT_SHIM(ICurrencyFormatterFactory)->abi_CreateCurrencyFormatterCodeContext(get_abi(currencyCode), get_abi(languages), get_abi(geographicRegion), put_abi(result)));
return result;
}
template <typename D> hstring impl_ICurrencyFormatter<D>::Currency() const
{
hstring value;
check_hresult(WINRT_SHIM(ICurrencyFormatter)->get_Currency(put_abi(value)));
return value;
}
template <typename D> void impl_ICurrencyFormatter<D>::Currency(hstring_view value) const
{
check_hresult(WINRT_SHIM(ICurrencyFormatter)->put_Currency(get_abi(value)));
}
template <typename D> Windows::Globalization::NumberFormatting::CurrencyFormatterMode impl_ICurrencyFormatter2<D>::Mode() const
{
Windows::Globalization::NumberFormatting::CurrencyFormatterMode value {};
check_hresult(WINRT_SHIM(ICurrencyFormatter2)->get_Mode(&value));
return value;
}
template <typename D> void impl_ICurrencyFormatter2<D>::Mode(Windows::Globalization::NumberFormatting::CurrencyFormatterMode value) const
{
check_hresult(WINRT_SHIM(ICurrencyFormatter2)->put_Mode(value));
}
template <typename D> void impl_ICurrencyFormatter2<D>::ApplyRoundingForCurrency(Windows::Globalization::NumberFormatting::RoundingAlgorithm roundingAlgorithm) const
{
check_hresult(WINRT_SHIM(ICurrencyFormatter2)->abi_ApplyRoundingForCurrency(roundingAlgorithm));
}
template <typename D> Windows::Globalization::NumberFormatting::NumeralSystemTranslator impl_INumeralSystemTranslatorFactory<D>::Create(iterable<hstring> languages) const
{
Windows::Globalization::NumberFormatting::NumeralSystemTranslator result { nullptr };
check_hresult(WINRT_SHIM(INumeralSystemTranslatorFactory)->abi_Create(get_abi(languages), put_abi(result)));
return result;
}
template <typename D> Windows::Foundation::Collections::IVectorView<hstring> impl_INumeralSystemTranslator<D>::Languages() const
{
Windows::Foundation::Collections::IVectorView<hstring> value;
check_hresult(WINRT_SHIM(INumeralSystemTranslator)->get_Languages(put_abi(value)));
return value;
}
template <typename D> hstring impl_INumeralSystemTranslator<D>::ResolvedLanguage() const
{
hstring value;
check_hresult(WINRT_SHIM(INumeralSystemTranslator)->get_ResolvedLanguage(put_abi(value)));
return value;
}
template <typename D> hstring impl_INumeralSystemTranslator<D>::NumeralSystem() const
{
hstring value;
check_hresult(WINRT_SHIM(INumeralSystemTranslator)->get_NumeralSystem(put_abi(value)));
return value;
}
template <typename D> void impl_INumeralSystemTranslator<D>::NumeralSystem(hstring_view value) const
{
check_hresult(WINRT_SHIM(INumeralSystemTranslator)->put_NumeralSystem(get_abi(value)));
}
template <typename D> hstring impl_INumeralSystemTranslator<D>::TranslateNumerals(hstring_view value) const
{
hstring result;
check_hresult(WINRT_SHIM(INumeralSystemTranslator)->abi_TranslateNumerals(get_abi(value), put_abi(result)));
return result;
}
inline CurrencyFormatter::CurrencyFormatter(hstring_view currencyCode) :
CurrencyFormatter(get_activation_factory<CurrencyFormatter, ICurrencyFormatterFactory>().CreateCurrencyFormatterCode(currencyCode))
{}
inline CurrencyFormatter::CurrencyFormatter(hstring_view currencyCode, iterable<hstring> languages, hstring_view geographicRegion) :
CurrencyFormatter(get_activation_factory<CurrencyFormatter, ICurrencyFormatterFactory>().CreateCurrencyFormatterCodeContext(currencyCode, languages, geographicRegion))
{}
inline DecimalFormatter::DecimalFormatter() :
DecimalFormatter(activate_instance<DecimalFormatter>())
{}
inline DecimalFormatter::DecimalFormatter(iterable<hstring> languages, hstring_view geographicRegion) :
DecimalFormatter(get_activation_factory<DecimalFormatter, IDecimalFormatterFactory>().CreateDecimalFormatter(languages, geographicRegion))
{}
inline IncrementNumberRounder::IncrementNumberRounder() :
IncrementNumberRounder(activate_instance<IncrementNumberRounder>())
{}
inline NumeralSystemTranslator::NumeralSystemTranslator() :
NumeralSystemTranslator(activate_instance<NumeralSystemTranslator>())
{}
inline NumeralSystemTranslator::NumeralSystemTranslator(iterable<hstring> languages) :
NumeralSystemTranslator(get_activation_factory<NumeralSystemTranslator, INumeralSystemTranslatorFactory>().Create(languages))
{}
inline PercentFormatter::PercentFormatter() :
PercentFormatter(activate_instance<PercentFormatter>())
{}
inline PercentFormatter::PercentFormatter(iterable<hstring> languages, hstring_view geographicRegion) :
PercentFormatter(get_activation_factory<PercentFormatter, IPercentFormatterFactory>().CreatePercentFormatter(languages, geographicRegion))
{}
inline PermilleFormatter::PermilleFormatter() :
PermilleFormatter(activate_instance<PermilleFormatter>())
{}
inline PermilleFormatter::PermilleFormatter(iterable<hstring> languages, hstring_view geographicRegion) :
PermilleFormatter(get_activation_factory<PermilleFormatter, IPermilleFormatterFactory>().CreatePermilleFormatter(languages, geographicRegion))
{}
inline SignificantDigitsNumberRounder::SignificantDigitsNumberRounder() :
SignificantDigitsNumberRounder(activate_instance<SignificantDigitsNumberRounder>())
{}
}
}
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::ICurrencyFormatter>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::ICurrencyFormatter & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::ICurrencyFormatter2>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::ICurrencyFormatter2 & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::ICurrencyFormatterFactory>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::ICurrencyFormatterFactory & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::IDecimalFormatterFactory>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::IDecimalFormatterFactory & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::IIncrementNumberRounder>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::IIncrementNumberRounder & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::INumberFormatter>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::INumberFormatter & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::INumberFormatter2>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::INumberFormatter2 & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::INumberFormatterOptions>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::INumberFormatterOptions & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::INumberParser>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::INumberParser & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::INumberRounder>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::INumberRounder & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::INumberRounderOption>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::INumberRounderOption & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::INumeralSystemTranslator>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::INumeralSystemTranslator & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::INumeralSystemTranslatorFactory>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::INumeralSystemTranslatorFactory & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::IPercentFormatterFactory>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::IPercentFormatterFactory & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::IPermilleFormatterFactory>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::IPermilleFormatterFactory & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::ISignedZeroOption>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::ISignedZeroOption & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::ISignificantDigitsNumberRounder>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::ISignificantDigitsNumberRounder & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::ISignificantDigitsOption>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::ISignificantDigitsOption & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::CurrencyFormatter>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::CurrencyFormatter & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::DecimalFormatter>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::DecimalFormatter & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::IncrementNumberRounder>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::IncrementNumberRounder & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::NumeralSystemTranslator>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::NumeralSystemTranslator & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::PercentFormatter>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::PercentFormatter & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::PermilleFormatter>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::PermilleFormatter & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Globalization::NumberFormatting::SignificantDigitsNumberRounder>
{
size_t operator()(const winrt::Windows::Globalization::NumberFormatting::SignificantDigitsNumberRounder & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
WINRT_WARNING_POP
|
//Uva p10130
//Undefined_Error
//Dept. ICE, NSTU-11 Batch
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define SZ 100005
#define MX 100000000
#define sfint(a) scanf("%d",&a)
#define sfint2(a,b) scanf("%d%d",&a,&b)
#define sfint3(a,b,c) scanf("%d%d%d",&a,&b,&c)
#define forlp0(i,n) for(int i=0;i<n;i++)
#define forlp1(i,n) for(int i=1;i<=n;i++)
int N[SZ],W[SZ];
int dp[1000][1000];
int knapsack(int n,int w)
{
if(n==0||w==0)
{
dp[n][w]=0;
return 0;
}
if(dp[n][w]!=-1) return dp[n][w];
if(w<W[n])
{
dp[n][w]=knapsack(n-1,w);
}
else
{
dp[n][w]=max(knapsack(n-1,w),N[n]+knapsack(n-1,w-W[n]));
}
return dp[n][w];
}
int main()
{
int t;
sfint(t);
forlp1(i,t)
{
memset(N,0,sizeof(int));
memset(W,0,sizeof(int));
int n;
sfint(n);
forlp1(j,n)
{
sfint2(N[j],W[j]);
}
int g,G,result=0;
sfint(g);
forlp1(j,g)
{
memset(dp,-1,sizeof(dp));
sfint(G);
result+=knapsack(n,G);
}
printf("%d\n",result);
}
return 0;
}
|
/*
// Copyright 2007 Alexandros Panagopoulos
//
// This software is distributed under the terms of the GNU Lesser General Public Licence
//
// This file is part of Be3D library.
//
// Be3D is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Be3D is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Be3D. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _DRAWLINE_H4369_INCLUDED_
#define _DRAWLINE_H4369_INCLUDED_
#pragma once
#include "common.h"
/**
* render_2d_line: a general templated function to rasterize 2d lines.
* P: must support the operators -(P&), /(scalar) and *(scalar)
* T: must have a method draw(P&)
*
*/
template <class P, class T>
void render_2d_line(const P &pt1, const P &pt2, T &renderer)
{
P dp = pt2 - pt1;
if (abs(dp.x) > abs(dp.y))
{
P ptstep = dp/dp.x;
int xend = (int)pt2.x;
int xstart = (int)pt1.x;
int xstep = (xend > xstart) ? 1 : -1;
xend+=xstep; // xend indicates the pixel after the last pixel of the line
for (int x=xstart; x!=xend; x+=xstep)
{
P curP = pt1 + ptstep*(x - xstart);
renderer.draw(curP);
}
}
else
{
P ptstep = dp/dp.y;
int yend = (int)pt2.y;
int ystart = (int)pt1.y;
int ystep = (yend > ystart) ? 1 : -1;
yend+=ystep;
for (int y=ystart; y!=yend; y+=ystep)
{
P curP = pt1 + ptstep*(y - ystart);
renderer.draw(curP);
}
}
}
#endif
|
// *****************************************************************
// This file is part of the CYBERMED Libraries
//
// Copyright (C) 2007 LabTEVE (http://www.de.ufpb.br/~labteve),
// Federal University of Paraiba and University of São Paulo.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this program; if not, write to the Free
// Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301, USA.
// *****************************************************************
#ifndef CYBHAARTRACKER_H_
#define CYBHAARTRACKER_H_
#ifdef CYBOPTICALTRACKER_H
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include "cybOpticalTracker.h"
#include "cybRegionTrackInfo.h"
#include "cybCam.h"
#include "cybStereo.h"
#include "cybThread.h"
/**
* @class CybHaarTracker
* @file CybHaarTracker.h
* @short This class defines a tracker based on Haar algorithm
*
* The OpenCV implementation of Haar classifier was used
* *
* @author LabTEVE (http://www.de.ufpb.br/~labteve), Federal University of Paraiba
* @version 1.0
* @date 2008, July
*
*/
class CybHaarTracker : public CybOpticalTracker, public CybThread
{
public:
/** Constructor*/
CybHaarTracker();
/** Destructor*/
virtual ~CybHaarTracker();
/**
* This method is used to detect the pattern used in a image
*
* @param IplImage *img
* @return CybRegionTrackInfo *
*
*/
virtual CybRegionTrackInfo *detect(IplImage *img);
/**
* This method return the 3D position of the tracked object
*
* @param double *position
* @return void
*
*/
virtual void getPosition(float *position);
/**
* This method is used to create and config an instance of Haar tracker
*
* @param void *userdata
* @return void
*
*/
virtual void createTracker(void *userData);
/**
* Set debug mode
*
* @param bool
* @return void
*
*/
virtual void setDebug(bool dbg_mode);
/**
* Get debug mode
*
* @param void
* @return bool
*
*/
virtual bool getDebugStatus();
/**
* Get the instance of stereo class
*
* @param void
* @return CybStereo *
*
*/
virtual CybStereo *getStereoInstance();
virtual void initDevice();
virtual void stopDevice();
virtual void getMatrix(float *matrix);
virtual void getInitialPosition(float *position);
private:
CvMemStorage* storage; /**< A storage variable to memory management*/
CvHaarClassifierCascade* cascade; /**< Haar classifier instance.*/
CybCam *cams; /**< list of cams*/
IplImage** frames; /**< list of frames*/
IplImage* pyr_img[2]; /**< Image used to apply the pyramid filter*/
bool dbg_mode; /**< debug mode*/
CybRegionTrackInfo *region1; /**< Tracked region of first image*/
CybRegionTrackInfo *region2; /**< Tracked region of second image*/
CybStereo *stereo; /**< The stereo instance*/
double point3D[3]; /**< the 3D point*/
/**
This method is call by thread system to execute the capture action
*/
virtual void run();
};
#endif //CYBOPTICALTRACKER_H
#endif /*CYBHAARTRACKER_H_*/
|
#ifndef INEXOR_TEST_NET_DUPLEX_MC_TEST_HEADER
#define INEXOR_TEST_NET_DUPLEX_MC_TEST_HEADER
#include "gtest/gtest.h"
#include "test/net/SimplexMCTest.h"
#include "net/net.h"
template<typename T_other>
class DuplexMCTest_SwapProvider : public SimplexMCTest_Provider {
public:
T_other *other;
DuplexMCTest_SwapProvider() : other(new T_other) {}
inexor::net::MCByteBuffer* From() { return other->To(); }
inexor::net::MCByteBuffer* To() { return other->From(); }
};
#define newDuplexMCTest(prefix, provider) \
newSimplexMCTest(prefix ## _DuplexMCTest_There, provider); \
newSimplexMCTest(prefix ## _DuplexMCTest_Back, \
DuplexMCTest_SwapProvider< provider > )
#endif
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long int;
int main(){
int t;
cin >> t;
while(t--){
ll a, b, x, y, n;
cin >> a >> b >> x >> y >> n;
ll c1 = max(x, a - n);
ll c2 = max(y, b - n);
if( c1 > c2) swap(x,y), swap(a,b);
ll tmp = min(n,a-x);
a -= tmp;
n -= tmp;
b -= min(n, b - y);
cout << a * b << '\n';
}
}
|
#include "headerFiles/akinatorHeader.h"
const char open_bracket = '{';
const char close_bracket = '}';
const char* default_filename = "base.txt";
const char* variants_yes[] = {"y", "ye", "yes", "yeah"};
const size_t amount_yes = 4;
const char* variants_no[] = {"n", "no", "nope"};
const size_t amount_no = 3;
const size_t max_string_size = 128;
//Service funcs
inline bool isOpenBracket(char* symbol)
{
return (*symbol == open_bracket);
}
inline bool isCloseBracket(char* symbol)
{
return (*symbol == close_bracket);
}
inline bool isQuote(char* symbol)
{
return (*symbol == '\"');
}
inline bool isSlashN(char* symbol)
{
return (*symbol == '\n');
}
bool isStringInArray(const char* array[], size_t size, char* string)
{
for (size_t i = 0; i < size; ++i)
{
if (strcmp(array[i], string) == 0)
{
return true;
}
}
return false;
}
bool isRight(Node* node)
{
return (node->parent->right == node);
}
int approxLength(const char* filename)
{
assert(filename);
struct stat* buff = (struct stat*)calloc(1, sizeof(struct stat));
stat(filename, buff);
return buff->st_size;
}
char* readFile(const char* filename, size_t* buffer_size)
{
FILE* file = fopen(filename, "r");
assert(file);
size_t apr_size = approxLength(filename);
char* buffer = (char*)calloc(apr_size, sizeof(char));
*buffer_size = fread(buffer, sizeof(char), apr_size, file);
buffer[*buffer_size] = '\0';
return buffer;
}
char** parseBuffer(size_t amount, char* buffer, size_t buffer_size)
{
char** lexemes = (char**)calloc(amount, sizeof(char*));
size_t j = 0;
size_t i = 0;
while (i < buffer_size)
{
if (isQuote(buffer + i))
{
++i; //Jump over quote
lexemes[j++] = buffer + i;
i = strchr(buffer + i, '\"') - buffer;
buffer[i] = '\0'; //Split lexemes
++i; //Jump over slash zero
}
else if (isOpenBracket(buffer + i) || isCloseBracket(buffer + i))
{
lexemes[j++] = buffer + i;
++i; //Jump over bracket;
buffer[i] = '\0'; //Split lexeme
}
++i;
}
return lexemes;
}
size_t getAmountLines(char* buffer)
{
size_t amount_lines = 0;
for (size_t i = 0; buffer[i] != '\0'; ++i)
{
if (buffer[i] == '\n')
{
++amount_lines;
}
}
return amount_lines;
}
size_t Min(const size_t size_a, const size_t size_b)
{
return (size_a > size_b) ? size_b : size_a;
}
bool* getDefinitionSequence(SimpleTree* tree, char* word, size_t* size_sequence)
{
Node* seacrhable_node = nullptr;
lazyFind(tree->root, word, &seacrhable_node);
if (seacrhable_node == nullptr)
{
printf("I cant find this word: %s.\n", word);
*size_sequence = 0;
return nullptr;
}
bool* def_sequence = (bool*)calloc(tree->size, sizeof(bool));
Node* cur_node = seacrhable_node;
fillSequence(def_sequence, size_sequence, cur_node);
return def_sequence;
}
void graphvizTree(SimpleTree* tree)
{
if (tree->root == nullptr)
{
return;
}
FILE* file = fopen("graphPlot.txt", "w");
fprintf(file, "digraph G{\n");
fprintf(file, "node [shape=\"record\", style=\"solid\", color=\"green\"];\n");
loadNudes(file, tree->root);
fprintf(file, "}");
fclose(file);
system("dot -Tjpg graphPlot.txt > Graph.jpg");
}
void fillSequence(bool* sequence, size_t* size, Node* node)
{
if (node == nullptr)
{
*size = 0;
}
while (node->parent != nullptr)
{
if (isRight(node))
{
sequence[*size] = true;
}
else
{
sequence[*size] = false;
}
*size += 1;
node = node->parent;
}
}
void showDefSequence(bool* def_sequence, size_t size_sequence)
{
for (size_t i = 0; i < size_sequence; ++i)
{
printf("seq[%zu] = %s\n", i, def_sequence[size_sequence - i - 1] ? "YES" : "NO");
}
}
char* getWord()
{
char* word = (char*)calloc(max_string_size, sizeof(char));
// scanf("%s", word);
//possibly safe reading all line
scanf("\n");
fgets(word, sizeof(char) * max_string_size, stdin);
word[strlen(word) - 1] = '\0';
return word;
}
void printFeatureAndGoNext(bool* def_sequence, size_t size_sequence, size_t idx, Node** node)
{
if (def_sequence[size_sequence - idx - 1] == true)
{
printf("%s", (*node)->value);
*node = (*node)->right;
}
else
{
printf("not %s", (*node)->value);
*node = (*node)->left;
}
if (size_sequence - idx - 1 != 0)
{
printf(", ");
}
}
void userIdiot()
{
while ((getchar()) != '\n');
printf("Uhh, you are fucking idiot, do you think you are smarter than me? No. You can input only integer values!\n");
}
//Node
void constructEmptyNode(Node* node)
{
node->left = nullptr;
node->parent = nullptr;
node->right = nullptr;
node->value = 0;
}
void constructNode(Node* node, elem_t value)
{
constructEmptyNode(node);
node->value = value;
}
void constructChild(Node* node, Node* parent, elem_t value)
{
constructNode(node, value);
node->parent = parent;
}
void destructNode(Node* node)
{
free(node);
}
void destructNodes(Node* node)
{
if (node == nullptr)
{
return;
}
if (node->left != nullptr)
{
destructNodes(node->left);
}
if (node->right != nullptr)
{
destructNodes(node->right);
}
destructNode(node);
}
void writeNodes(FILE* file, Node* node)
{
if (node == nullptr)
{
return;
}
fprintf(file, "{\n");
fprintf(file, "\"%s\"\n", node->value);
if (node->left != nullptr)
{
writeNodes(file, node->right);
}
if (node->right != nullptr)
{
writeNodes(file, node->left);
}
fprintf(file, "}\n");
}
void lazyFind(Node* node, elem_t value, Node** searchable_node)
{
if (node == nullptr || strcmp(node->value, value) == 0)
{
*searchable_node = node;
return;
}
lazyFind(node->left, value, searchable_node);
if (*searchable_node != nullptr)
{
return;
}
lazyFind(node->right, value, searchable_node);
}
Node* newNode(elem_t value)
{
Node* new_node = (Node*)calloc(1, sizeof(Node));
constructNode(new_node, value);
return new_node;
}
Node* newEmptyNode()
{
Node* new_node = (Node*)calloc(1, sizeof(Node));
constructEmptyNode(new_node);
return new_node;
}
Node* newEmptyChild(Node* parent)
{
Node* new_child = newEmptyNode();
new_child->parent = parent;
return new_child;
}
Node* newChild(Node* parent, elem_t value)
{
Node* new_child = (Node*)calloc(1, sizeof(Node));
constructChild(new_child, parent, value);
return new_child;
}
Node* loadNudes(FILE* file, Node* node)
{
if (node == nullptr)
{
return nullptr;
}
if (node->left != nullptr)
{
fprintf(file, "edge[color=orange]\n\"%p\"->\"%p\";\n", loadNudes(file, node->left)->parent, node->left); // link parent and left child
}
if (node->right != nullptr)
{
fprintf(file, "edge[color=red]\n\"%p\"->\"%p\";\n", loadNudes(file, node->right)->parent, node->right); //link parent and right child
}
if (node->parent != nullptr)
{
fprintf(file, "\"%p\" [label=\"{{par: %s}|{str: %s}}\"]\n ", node, node->parent->value,
node->value); // <-- label printing
}
else
{
fprintf(file, "\"%p\" [label=\"{{par: %s}|{str: %s}}\"]\n ", node, "root",
node->value); // <-- label printing
}
return node;
}
//SimpleTree
void constructSimpleTree(SimpleTree* tree)
{
tree->root = newEmptyNode();
tree->size = 0;
}
void destructSimpleTree(SimpleTree* tree)
{
free(tree->root->value - 1);
destructNodes(tree->root);
}
SimpleTree* newSimpleTree()
{
SimpleTree* tree = (SimpleTree*)calloc(1, sizeof(SimpleTree));
constructSimpleTree(tree);
return tree;
}
SimpleTree* loadTree(Lexemes* lexemes)
{
SimpleTree* tree = newSimpleTree();
tree->root->value = lexemes->buffer[0];
Node* cur_node = tree->root;
size_t amount_lexemes = lexemes->size;
for (size_t i = 0; i < amount_lexemes; ++i)
{
if (isOpenBracket(lexemes->buffer[i]))
{
if (cur_node->right == nullptr)
{
cur_node->right = newEmptyChild(cur_node);
cur_node = cur_node->right;
}
else if (cur_node->left == nullptr)
{
cur_node->left = newEmptyChild(cur_node);
cur_node = cur_node->left;
}
++tree->size;
}
else if (isCloseBracket(lexemes->buffer[i]))
{
//Он точно должен существовать, так как файл с закрывающейся скобки начинаться не может
cur_node = cur_node->parent;
}
else
{
cur_node->value = lexemes->buffer[i];
}
}
return tree;
}
SimpleTree* loadTree(const char* filename)
{
Lexemes* lexemes = newLexemes(filename);
SimpleTree* tree = loadTree(lexemes);
return tree;
}
//Lexemes
void constructLexemes(Lexemes* lexemes, const char* filename)
{
size_t buffer_size = 0;
char* main_buffer = readFile(filename, &buffer_size);
lexemes->size = getAmountLines(main_buffer);
lexemes->buffer = parseBuffer(lexemes->size, main_buffer, buffer_size);
}
void destructLexemes(Lexemes* lexemes)
{
free(*lexemes->buffer); //free main buffer
free(lexemes->buffer);
}
Lexemes* newLexemes(const char* filename)
{
Lexemes* lexemes = (Lexemes*)calloc(1, sizeof(Lexemes));
constructLexemes(lexemes, filename);
return lexemes;
}
//Processing./
void Processing()
{
SimpleTree* tree = loadTree(default_filename);
printf(" Welcome to the Akinator! \n");
CHOICE choice = GUESS;
bool tree_changed = false;
while(choice)
{
printf("=============================\n"
"Game: type 1\n"
"Difference: type 2\n"
"Definition: type 3\n"
"Exit: type 0\n"
"-----------------------------\n"
"Save changes: type 7\n"
"Change data base: type 8\n"
"Load graph: type 9\n"
"=============================\n"
);
while (scanf("%d", &choice) != 1)
{
userIdiot();
}
switch (choice)
{
case GUESS:
Guess(tree, &tree_changed);
break;
case DIFFERENCE:
Difference(tree);
break;
case DEFINITION:
Definition(tree);
break;
case SAVE:
Save(tree);
break;
case CHANGE:
Change(&tree);
break;
case GRAPH:
Graph(tree);
break;
case EXIT:
break;
default:
printf("Unknown command.\nTry again.\n");
break;
}
}
if (tree_changed)
{
Save(tree);
}
printf("Exit...\n");
destructSimpleTree(tree);
}
void Guess(SimpleTree* tree, bool* tree_changed)
{
Node* cur_node = tree->root;
while (cur_node != nullptr)
{
if (cur_node->left == nullptr && cur_node->right == nullptr)
{
printf("I think, it is %s!\n", cur_node->value);
if (Yes())
{
printf("Yeah boyyy!\nRASKATAL NA IZI\n");
return;
}
else
{
printf(":'( Uhh, I'm sorry, I don't know what did you guess...\n");
addNewFeature(cur_node);
++tree->size;
*tree_changed = true;
return;
}
}
else
{
printf("Is it %s?\n", cur_node->value);
if (Yes())
{
cur_node = cur_node->right;
}
else
{
cur_node = cur_node->left;
}
}
}
}
void Definition(SimpleTree* tree)
{
printf("What definition word do you want to know?\n");
char* word = getWord();
size_t size_sequence = 0;
bool* def_sequence = getDefinitionSequence(tree, word, &size_sequence);
if (def_sequence == nullptr)
{
return;
}
Node* cur_node = tree->root;
printf("%s is ", word);
for (size_t i = 0; i < size_sequence; ++i)
{
printFeatureAndGoNext(def_sequence, size_sequence, i, &cur_node);
}
printf("\n");
free(word);
}
void printDiff(Node** node, bool* def_sequence, char* word, size_t begin, size_t end)
{
printf("but %s is ", word);
for (size_t i = begin; i < end; ++i)
{
printFeatureAndGoNext(def_sequence, end, i, node);
}
}
void Difference(SimpleTree* tree)
{
printf("Type 2 word which difference between you want to know\n");
char* word_a = getWord();
char* word_b = getWord();
size_t size_sequence_a = 0;
bool* def_sequence_a = getDefinitionSequence(tree, word_a, &size_sequence_a);
size_t size_sequence_b = 0;
bool* def_sequence_b = getDefinitionSequence(tree, word_b, &size_sequence_b);
if (def_sequence_a == nullptr || def_sequence_b == nullptr)
{
return;
}
bool is_first_iter = true;;
Node* cur_node_a = tree->root;
Node* cur_node_b = tree->root;
size_t i = 0;
size_t j = 0;
while (i < size_sequence_a && j < size_sequence_b &&
def_sequence_a[size_sequence_a - i - 1] == def_sequence_b[size_sequence_b - j - 1])
{
if (is_first_iter) printf ("They are both ");
printFeatureAndGoNext(def_sequence_a, size_sequence_a, i, &cur_node_a);
cur_node_b = cur_node_a;
is_first_iter = false;
++i;
++j;
}
printDiff(&cur_node_a, def_sequence_a, word_a, i, size_sequence_a);
printf(", ");
printDiff(&cur_node_b, def_sequence_b, word_b, j, size_sequence_b);
printf("\n");
free(word_a);
free(word_b);
}
void Change(SimpleTree** tree)
{
printf("Type name of file\n");
char* filename = getWord();
destructSimpleTree(*tree);
*tree = loadTree(filename);
}
void Save(SimpleTree* tree)
{
printf("Save in default file?\n");
if (Yes())
{
updDataBase(tree, default_filename);
}
else
{
printf("Type name of file.\n");
char* filename = getWord();
updDataBase(tree, filename);
free(filename);
}
}
void Graph(SimpleTree* tree)
{
printf("Loading graph...\n");
graphvizTree(tree);
printf("Graph was loaded successful!\n");
}
bool Yes()
{
char* answer = (char*)calloc(16, sizeof(char));
scanf("%s", answer);
while(answer)
{
if (isStringInArray(variants_yes, amount_yes, answer))
{
return true;
}
else if (isStringInArray(variants_no, amount_no, answer))
{
return false;
}
else
{
printf("PISHI KAK CHELOVEK, CHO VIPENDRIVAYESHSA!\n");
}
scanf("%s", answer);
}
return false;
}
void addNewFeature(Node* node)
{
Node* new_node = newEmptyNode();
printf("What did you guess?\n");
new_node->value = getWord();
Node* their_parent = newEmptyNode();
printf("How is %s different from %s?\n", node->value, new_node->value);
their_parent->value = getWord();
if (isRight(node))
{
node->parent->right = their_parent;
}
else
{
node->parent->left = their_parent;
}
their_parent->parent = node->parent;
new_node->parent = their_parent;
node->parent = their_parent;
their_parent->right = node;
their_parent->left = new_node;
}
void updDataBase(SimpleTree* tree, const char* filename)
{
FILE* file = fopen(filename, "w");
fprintf(file, "\"%s\"\n", tree->root->value);
writeNodes(file, tree->root->right);
writeNodes(file, tree->root->left);
fclose(file);
}
|
#include<iostream>
using namespace std;
int main()
{
int t;
cin>>t;
for( int i=0; i<t; i++)
{
int n;
cin>>n;
int p_prev = 0,c_prev =0;
int p,c;
int flag = 0;
for( int i=0; i<n; i++)
{
cin>>p>>c;
if(p - p_prev >= c - c_prev && c - c_prev >=0)
flag++;
p_prev = p;
c_prev = c;
}
(flag==n)?(cout<<"YES"<<'\n'):(cout<<"NO"<<"\n");
}
return 0;
}
|
#include "tag.h"
const int Tag::AND = 256,
Tag::BASIC = 257,
Tag::BREAK = 258,
Tag::DO = 259,
Tag::ELSE = 260,
Tag::EQ = 261,
Tag::FALSE = 262,
Tag::GE = 263,
Tag::ID = 264,
Tag::IF = 265,
Tag::INDEX = 266,
Tag::LE = 267,
Tag::MINUS = 268,
Tag::NE = 269,
Tag::NUM = 270,
Tag::OR = 271,
Tag::REAL = 272,
Tag::Tag::TEMP = 273,
Tag::TRUE = 274,
Tag::WHILE = 275,
Tag::NULLTAG = 276;
const map<int, string> Tag::TAGS = Tag::create_map();
map<int, string> Tag::create_map() {
map<int, string> m;
m[AND] = "AND";
m[BASIC] = "BASIC";
m[BREAK] = "BREAK";
m[DO] = "DO";
m[ELSE] = "ELSE";
m[EQ] = "EQ";
m[FALSE] = "FALSE";
m[GE] = "GE";
m[ID] = "ID";
m[IF] = "IF";
m[INDEX] = "INDEX";
m[LE] = "LE";
m[MINUS] = "MINUS";
m[NE] = "NE";
m[NUM] = "NUM";
m[OR] = "OR";
m[REAL] = "REAL";
m[TEMP] = "TEMP";
m[TRUE] = "TRUE";
m[WHILE] = "WHILE";
return m;
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef POPULATIONTESTINGFORCE_HPP_
#define POPULATIONTESTINGFORCE_HPP_
#include "ChasteSerialization.hpp"
#include <boost/serialization/base_object.hpp>
#include "AbstractForce.hpp"
/**
* A simple force law used to test node location updates across the off lattice population test files.
*/
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM=ELEMENT_DIM>
class PopulationTestingForce : public AbstractForce<ELEMENT_DIM, SPACE_DIM>
{
private:
/**
* Archiving.
*/
friend class boost::serialization::access;
/**
* Boost Serialization method for archiving/checkpointing.
* Archives the object and its member variables.
*
* @param archive The boost archive.
* @param version The current version of this class.
*/
template<class Archive>
void serialize(Archive & archive, const unsigned int version)
{
archive & boost::serialization::base_object<AbstractForce<ELEMENT_DIM,SPACE_DIM> >(*this);
archive & mWithPositionDependence;
}
/**
* Whether the applied force should depend on the position of the node, or only its index
* Defaults to true, since that's better for testing a variety of numerical methods.
* Crypt tests require a position independent test force though.
*/
bool mWithPositionDependence;
public:
/**
* Constructor.
*
* @param hasPositionDependence specifys which testing force to use (defaults to true)
*/
PopulationTestingForce(bool hasPositionDependence = true);
/**
* Overridden AddForceContribution() method.
*
* @param rCellPopulation reference to the cell population
*
* THis has two forces depending on the member variable mWithPositionDependence
*
* If true then
*
* For node i
* F[j] = 0.01 (j+1) i r[j]
*
* Where r is the position of node i.
*
* if false then
*
* F[j] = 0.01 (j+1) i
*
*/
void AddForceContribution(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation);
/**
* Helper method to return the expected step location for ForwardEulerNumericalMethod.
*
* @return the expected location after one step
*
* @param nodeIndex the index of the node
* @param damping the damping constant
* @param oldLocation the old location of the node
* @param dt the step size
*/
c_vector<double, SPACE_DIM> GetExpectedOneStepLocationFE(unsigned nodeIndex,
double damping,
c_vector<double, SPACE_DIM>& oldLocation,
double dt);
/**
* Helper method to return the expected step location for RK4NumericalMethod.
*
* @return the expected location after one step
*
* @param nodeIndex the index of the node
* @param damping the damping constant
* @param oldLocation the old location of the node
* @param dt the step size
*/
c_vector<double, SPACE_DIM> GetExpectedOneStepLocationRK4(unsigned nodeIndex,
double damping,
c_vector<double, SPACE_DIM>& oldLocation,
double dt);
/**
* Helper method to return the expected step location for AdamsMoultonNumericalMethod.
*
* @return the expected location after one step
*
* @param nodeIndex the index of the node
* @param damping the damping constant
* @param oldLocation the old location of the node
* @param dt the step size
*/
c_vector<double, SPACE_DIM> GetExpectedOneStepLocationAM2(unsigned nodeIndex,
double damping,
c_vector<double, SPACE_DIM>& oldLocation,
double dt);
/**
* Helper method to return the expected step location for BackwardEulerNumericalMethod.
*
* @return the expected location after one step
*
* @param nodeIndex the index of the node
* @param damping the damping constant
* @param oldLocation the old location of the node
* @param dt the step size
*/
c_vector<double, SPACE_DIM> GetExpectedOneStepLocationBE(unsigned nodeIndex,
double damping,
c_vector<double, SPACE_DIM>& oldLocation,
double dt);
/**
* Overridden OutputForceParameters() method.
*
* @param rParamsFile the file stream to which the parameters are output
*/
virtual void OutputForceParameters(out_stream& rParamsFile);
};
#include "SerializationExportWrapper.hpp"
EXPORT_TEMPLATE_CLASS_ALL_DIMS(PopulationTestingForce)
#endif /*POPULATIONTESTINGFORCE_HPP_*/
|
// Application main form file.
// Original file name: App_KaiXinMainForm.h
// Generated by TOPS Builder:Project wizard,Date:2010-8-24
#ifndef __App_KaiXin_MainForm_H__
#define __App_KaiXin_MainForm_H__
#include "TG3.h"
class TMainForm : public TWindow
{
public:
TMainForm(TApplication * pApp);
~TMainForm(void);
public:
virtual Boolean EventHandler(TApplication * pApp, EventType * pEvent);
protected:
void _OnWinInitEvent();
Boolean _OnCtlSelectEvent( TApplication * pApp,EventType * pEvent );
Boolean _OnLstPreDrawEvent(EventType * pEvent);
Boolean _OnCtrlSetFocusEvent(TApplication * pApp, EventType * pEvent);
Boolean _OnCtrlKillFocusEvent(TApplication * pApp, EventType * pEvent);
private:
//退出按钮ID
Int32 m_ExitBtn;
Int32 m_LoginBtn;
//第一次点击显示密码是否需要清空密码
Boolean bCleanPwdWhenFirstShowPwd;
};
#endif
|
// testOpenGL.cpp : model design of a car using openGL
//
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
//#include <gl\glut.h>
#include <GL/glut.h>
static int shoulder = 0,elbow = 0,num,num2,checkImageWidth,checkImageHeight,texName;
void LoadTex();
// points for Bezier curves
GLfloat forepoints[4][4][3] = {
{{0.0,0.0,0.0},{0.3,0.0,0.0},{0.6,0.0,0.0},{1.0,0.0,0.0}},
{{0.0,0.3,0.0},{0.3,0.3,-0.05},{0.6,0.3,-0.05},{0.95,0.3,-0.05}},
{{0.0,0.4,0.0},{0.3,0.4,-0.07},{0.6,0.4,-0.07},{0.93,0.4,-0.07}},
{{0.0,0.8,0.0},{0.3,0.7,-0.1},{0.6,0.6,-0.2},{0.8,0.5,-0.3}}
};
GLfloat frontPoints[4][4][3] = {
{{1.0,0.0,0.0},{1.0,0.0,-0.5},{1.0,0.0,-1.0},{1.0,0.0,-1.5}},
{{0.95,0.3,-0.03},{0.95,0.3,-0.5},{0.95,0.3,-1.0},{0.95,0.3,-1.5}},
{{0.93,0.4,-0.07},{0.93,0.4,-0.5},{0.93,0.4,-1.0},{0.93,0.4,-1.5}},
{{0.8,0.5,-0.3},{0.8,0.5,-0.5},{0.8,0.5,-1.0},{0.8,0.5,-1.2}}
};
GLfloat depthPoints[4][4][3] = {
{{0.0,0.0,0.0},{0.3,0.0,0.0},{0.6,0.0,0.0},{1.0,0.0,0.0}},
{{0.0,0.3,0.0},{0.3,0.3,0.05},{0.6,0.3,0.05},{0.95,0.3,0.05}},
{{0.0,0.4,0.0},{0.3,0.4,0.07},{0.6,0.4,0.07},{0.93,0.4,0.07}},
{{0.0,0.8,0.0},{0.3,0.7,0.1},{0.6,0.6,0.2},{0.8,0.5,0.3}}
};
GLfloat topPoints[4][4][3] = {
{{0.0,0.8,0.0},{0.3,0.7,-0.1},{0.6,0.6,-0.2},{0.8,0.5,-0.3}},
{{0.1,0.8,-0.5},{0.3,0.7,-0.5},{0.6,0.6,-0.5},{0.8,0.5,-0.5}},
{{0.1,0.8,-1.0},{0.3,0.7,-1.0},{0.6,0.6,-1.0},{0.8,0.5,-1.5}},
{{0.0,0.8,-1.5},{0.3,0.7,-1.4},{0.6,0.6,-1.3},{0.8,0.5,-1.2}}
};
GLfloat windGlass[6][4][3] = {
{{0.0,0.0,0.0},{-0.3,0.3,0.0},{-0.7,0.6,0.0},{-1.0,0.8,0.0}},
{{0.0,0.0,-0.3},{-0.3,0.4,-0.3},{-0.7,0.65,-0.3},{-1.0,0.83,-0.3}},
{{0.0,0.0,-0.6},{-0.3,0.4,-0.6},{-0.7,0.65,-0.6},{-1.0,0.9,-0.6}},
{{0.0,0.0,-0.9},{-0.3,0.4,-0.9},{-0.7,0.65,-0.9},{-1.0,0.85,-0.9}},
{{0.0,0.0,-1.2},{-0.3,0.4,-1.2},{-0.7,0.65,-1.2},{-1.0,0.83,-1.2}},
{{0.0,0.0,-1.5},{-0.3,0.3,-1.5},{-0.7,0.6,-1.5},{-1.0,0.8,-1.5}}
};
GLfloat backOne[5][5][3] = {
{{0.0,0.0,0.0},{0.2,0.0,0.0},{0.4,0.0,0.0},{0.6,0.0,0.0},{0.8,0.0,0.0}},
{{0.0,0.7,0.0},{0.2,0.7,0.0},{0.4,0.7,0.0},{0.6,0.7,0.0},{0.8,0.7,0.0}},
{{0.0,0.78,0.0},{0.2,0.78,0.0},{0.4,0.78,0.0},{0.6,0.78,0.0},{0.8,0.78,0.0}},
{{0.0,0.79,0.0},{0.2,0.79,0.0},{0.4,0.79,0.0},{0.6,0.79,0.0},{0.8,0.79,0.0}},
{{0.0,0.8,-0.2},{0.2,0.8,-0.2},{0.4,0.8,-0.2},{0.6,0.8,-0.1},{0.8,0.8,0.0}}
};
GLfloat backTwo[5][5][3] = {
{{0.0,0.0,0.0},{0.2,0.0,0.0},{0.4,0.0,0.0},{0.6,0.0,0.0},{0.8,0.0,0.0}},
{{0.0,0.7,0.0},{0.2,0.7,0.0},{0.4,0.7,0.0},{0.6,0.7,0.0},{0.8,0.7,0.0}},
{{0.0,0.78,0.0},{0.2,0.78,0.0},{0.4,0.78,0.0},{0.6,0.78,0.0},{0.8,0.78,0.0}},
{{0.0,0.79,0.0},{0.2,0.79,0.0},{0.4,0.79,0.0},{0.6,0.79,0.0},{0.8,0.79,0.0}},
{{0.0,0.8,0.2},{0.2,0.8,0.2},{0.4,0.8,0.2},{0.6,0.8,0.1},{0.8,0.8,0.0}}
};
GLfloat backThree[5][5][3] = {
{{0.0,0.0,0.0},{0.0,0.0,-0.375},{0.0,0.0,-0.75},{0.0,0.0,-1.125},{0.0,0.0,-1.5}},
{{0.0,0.1,0.0},{-0.05,0.1,-0.375},{-0.05,0.1,-0.75},{-0.05,0.1,-1.125},{0.0,0.1,-1.5}},
{{0.0,0.5,0.0},{-0.05,0.5,-0.375},{-0.05,0.5,-0.75},{-0.05,0.5,-1.125},{0.0,0.5,-1.5}},
{{0.0,0.79,0.0},{-0.05,0.79,-0.375},{-0.05,0.79,-0.75},{-0.05,0.79,-1.125},{0.0,0.79,-1.5}},
{{0.0,0.8,-0.2},{0.0,0.8,-0.375},{0.0,0.8,-0.75},{0.0,0.8,-1.125},{0.0,0.8,-1.3}}
};
GLfloat backFour[5][5][3] = {
{{0.0,0.8,-0.2},{0.0,0.8,-0.375},{0.0,0.8,-0.75},{0.0,0.8,-1.125},{0.0,0.8,-1.3}},
{{0.2,0.8,0.0},{0.2,0.8,-0.375},{0.2,0.8,-0.75},{0.2,0.8,-1.125},{0.2,0.8,-1.5}},
{{0.4,0.8,0.0},{0.4,0.8,-0.375},{0.4,0.8,-0.75},{0.4,0.8,-1.125},{0.4,0.8,-1.5}},
{{0.5,0.8,0.0},{0.5,0.8,-0.375},{0.5,0.8,-0.75},{0.5,0.8,-1.125},{0.5,0.8,-1.5}},
{{0.8,0.8,0.0},{0.65,0.8,-0.375},{0.5,0.8,-0.75},{0.65,0.8,-1.125},{0.8,0.8,-1.5}}
};
GLfloat backAxis[2][5][3] = {
{{0.0,0.8,-0.0},{-0.1,0.8,-0.375},{-0.2,0.8,-0.75},{-0.1,0.8,-1.125},{0.0,0.8,-1.5}},
{{0.4,0.8,-0.0},{0.2,0.8,-0.375},{0.0,0.8,-0.75},{0.2,0.8,-1.125},{0.4,0.8,-1.5}}
};
//the part left of door
GLfloat frontDoor[5][5][3] = {
{{0.0,0.0,0.0},{0.2,0.0,0.0},{0.4,0.0,0.0},{0.6,0.0,0.0},{0.8,0.0,0.0}},
{{0.0,0.2,0.0},{0.2,0.2,0.0},{0.4,0.2,0.0},{0.6,0.2,0.0},{0.8,0.2,0.0}},
{{0.0,0.4,0.0},{0.2,0.4,0.0},{0.4,0.4,0.0},{0.6,0.4,0.0},{0.8,0.4,0.0}},
{{0.0,0.7,0.0},{0.2,0.7,0.0},{0.4,0.7,0.0},{0.6,0.7,0.0},{0.8,0.7,0.0}},
{{0.0,0.8,-0.2},{0.2,0.8,-0.2},{0.4,0.8,-0.15},{0.6,0.8,-0.1},{0.8,0.8,0.0}}
};
//door part
GLfloat frontDoorSecond[5][5][3] = {
{{0.0,0.0,0.0},{0.2,0.0,0.0},{0.4,0.0,0.0},{0.6,0.0,0.0},{0.8,0.0,0.0}},
{{0.0,0.2,0.0},{0.2,0.2,0.0},{0.4,0.2,0.0},{0.6,0.2,0.0},{0.8,0.2,0.0}},
{{0.0,0.4,0.0},{0.2,0.4,0.0},{0.4,0.4,0.0},{0.6,0.4,0.0},{0.8,0.4,0.0}},
{{0.0,0.7,0.0},{0.2,0.7,0.0},{0.4,0.7,0.0},{0.6,0.7,0.0},{0.8,0.7,0.0}},
{{0.0,0.8,-0.2},{0.2,0.8,-0.2},{0.4,0.8,-0.2},{0.6,0.8,-0.2},{0.8,0.8,-0.2}}
};
GLfloat frontDoorSecondBack[5][5][3] = {
{{0.0,0.0,-0.2},{0.2,0.0,-0.2},{0.4,0.0,-0.2},{0.6,0.0,-0.2},{0.8,0.0,-0.0}},
{{0.0,0.2,-0.2},{0.2,0.2,-0.2},{0.4,0.2,-0.2},{0.6,0.2,-0.2},{0.8,0.2,-0.0}},
{{0.0,0.4,-0.2},{0.2,0.4,-0.2},{0.4,0.4,-0.2},{0.6,0.4,-0.2},{0.8,0.4,-0.0}},
{{0.0,0.7,-0.2},{0.2,0.7,-0.2},{0.4,0.7,-0.2},{0.6,0.7,-0.2},{0.8,0.7,-0.0}},
{{0.0,0.8,-0.2},{0.2,0.8,-0.2},{0.4,0.8,-0.2},{0.6,0.8,-0.2},{0.8,0.8,-0.2}}
};
GLfloat frontDoorSide[5][2][3] = {
{{0.0,0.0,-0.0},{0.0,0.0,-0.2}},
{{0.0,0.2,-0.0},{0.0,0.2,-0.2}},
{{0.0,0.4,-0.0},{0.0,0.4,-0.2}},
{{0.0,0.7,-0.0},{0.0,0.7,-0.2}},
{{0.0,0.8,-0.0},{0.0,0.8,-0.0}}
};
GLfloat frontDoorBottom[2][5][3] = {
{{0.0,0.0,-0.0},{0.2,0.0,-0.0},{0.4,0.0,-0.0},{0.6,0.0,-0.0},{0.8,0.0,-0.0}},
{{0.0,0.0,-0.2},{0.2,0.0,-0.2},{0.4,0.0,-0.2},{0.6,0.0,-0.2},{0.8,0.0,-0.0}}
};
//the part left behind door
GLfloat behindDoor[5][5][3] = {
{{0.0,0.0,0.0},{0.2,0.0,0.0},{0.4,0.0,0.0},{0.6,0.0,0.0},{0.8,0.0,0.0}},
{{0.0,0.2,0.0},{0.2,0.2,0.0},{0.4,0.2,0.0},{0.6,0.2,0.0},{0.8,0.2,0.0}},
{{0.0,0.4,0.0},{0.2,0.4,0.0},{0.4,0.4,0.0},{0.6,0.4,0.0},{0.8,0.4,0.0}},
{{0.0,0.7,0.0},{0.2,0.7,0.0},{0.4,0.7,0.0},{0.6,0.7,0.0},{0.8,0.7,0.0}},
{{0.0,0.8,0.2},{0.2,0.8,0.2},{0.4,0.8,0.15},{0.6,0.8,0.1},{0.8,0.8,0.0}}
};
//behind door
GLfloat behindDoorSecond[5][5][3] = {
{{0.0,0.0,0.0},{0.2,0.0,0.0},{0.4,0.0,0.0},{0.6,0.0,0.0},{0.8,0.0,0.0}},
{{0.0,0.2,0.0},{0.2,0.2,0.0},{0.4,0.2,0.0},{0.6,0.2,0.0},{0.8,0.2,0.0}},
{{0.0,0.4,0.0},{0.2,0.4,0.0},{0.4,0.4,0.0},{0.6,0.4,0.0},{0.8,0.4,0.0}},
{{0.0,0.7,0.0},{0.2,0.7,0.0},{0.4,0.7,0.0},{0.6,0.7,0.0},{0.8,0.7,0.0}},
{{0.0,0.8,0.2},{0.2,0.8,0.2},{0.4,0.8,0.2},{0.6,0.8,0.2},{0.8,0.8,0.2}}
};
GLfloat behindDoorSecondBack[5][5][3] = {
{{0.0,0.0,0.2},{0.2,0.0,0.2},{0.4,0.0,0.2},{0.6,0.0,0.2},{0.8,0.0,0.0}},
{{0.0,0.2,0.2},{0.2,0.2,0.2},{0.4,0.2,0.2},{0.6,0.2,0.2},{0.8,0.2,0.0}},
{{0.0,0.4,0.2},{0.2,0.4,0.2},{0.4,0.4,0.2},{0.6,0.4,0.2},{0.8,0.4,0.0}},
{{0.0,0.7,0.2},{0.2,0.7,0.2},{0.4,0.7,0.2},{0.6,0.7,0.2},{0.8,0.7,0.0}},
{{0.0,0.8,0.2},{0.2,0.8,0.2},{0.4,0.8,0.2},{0.6,0.8,0.2},{0.8,0.8,0.2}}
};
GLfloat behindDoorSide[5][2][3] = {
{{0.0,0.0,-0.0},{0.0,0.0,0.2}},
{{0.0,0.2,-0.0},{0.0,0.2,0.2}},
{{0.0,0.4,-0.0},{0.0,0.4,0.2}},
{{0.0,0.7,-0.0},{0.0,0.7,0.2}},
{{0.0,0.8,-0.0},{0.0,0.8,0.0}}
};
GLfloat behindDoorBottom[2][5][3] = {
{{0.0,0.0,-0.0},{0.2,0.0,-0.0},{0.4,0.0,-0.0},{0.6,0.0,-0.0},{0.8,0.0,-0.0}},
{{0.0,0.0,0.2},{0.2,0.0,0.2},{0.4,0.0,0.2},{0.6,0.0,0.2},{0.8,0.0,0.0}}
};
GLfloat innerRadius,outerRadius;
int nsides,rings;
bool left= false,right=false;
static GLdouble viewer[]= {0.0, 0.0, 2.0}; /* initial viewer location */
//车头部分右侧面
void init(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,4,
0,1,12,4,&forepoints[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
//glEvalMesh2(GL_FILL,0,20,0,20);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
//glMap1f(GL_MAP1_VERTEX_3,0.0,1.0,3,4,&ctrlpoints[0][0]);
//glEnable(GL_MAP1_VERTEX_3);
}
//车头前面的部分
void foreCover(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,4,
0,1,12,4,&frontPoints[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
//glEvalMesh2(GL_FILL,0,20,0,20);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void depthCover(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,4,
0,1,12,4,&depthPoints[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
//glEvalMesh2(GL_FILL,0,20,0,20);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void topCover(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,4,
0,1,12,4,&topPoints[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
//glEvalMesh2(GL_FILL,0,20,0,20);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void foreGlass(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,4,
0,1,12,6,&windGlass[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void backFront(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,5,
0,1,15,5,&backOne[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void backDepth(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,5,
0,1,15,5,&backTwo[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void backBack(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,5,
0,1,15,5,&backThree[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void backCover(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,5,
0,1,15,5,&backFour[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void DoorFront(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,5,
0,1,15,5,&frontDoor[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void DoorFrontSecond(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,5,
0,1,15,5,&frontDoorSecond[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void DoorFrontSecondBack(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,5,
0,1,15,5,&frontDoorSecondBack[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void DoorFrontBottom(void){
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,5,
0,1,15,2,&frontDoorBottom[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void DoorFrontSide(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,2,
0,1,6,5,&frontDoorSide[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void DoorBehind(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,5,
0,1,15,5,&behindDoor[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void DoorBehindSecond(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,5,
0,1,15,5,&behindDoorSecond[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void DoorBehindSecondBack(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,5,
0,1,15,5,&behindDoorSecondBack[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void DoorBehindBottom(void){
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,5,
0,1,15,2,&behindDoorBottom[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void DoorBehindSide(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,2,
0,1,6,5,&behindDoorSide[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
void AxisBack(void){
glClearColor(0.0,0.0,0.0,0.0);
glMap2f(GL_MAP2_VERTEX_3,0,1,3,5,
0,1,15,2,&backAxis[0][0][0]);
glEnable(GL_MAP2_VERTEX_3);
glMapGrid2f(20,0.0,1.0,20,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
}
static GLfloat lightPosition[4]; //position for light0
GLfloat light_position[] = { 2.0, 2.0, 0.0, 1.0 };
static float lightangle_X = 0.0, lightHeight = 1;
void lightInit(void)
{
//Initialize material property
GLfloat mat_specular[] = { 3000.0, 3000.0, 3000.0, 3000.0 };
GLfloat mat_shininess[] = { 100.0 };
GLfloat mat_ambient[] = { 1.0, 1.0, 0.0, 0.0 };
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
//Initialize light source
GLfloat white_light[] = { 1.0, 1.0, 1.0, 1.0 };
glLightfv(GL_LIGHT1, GL_DIFFUSE, white_light);
glLightfv(GL_LIGHT1, GL_SPECULAR, white_light);
glEnable(GL_LIGHTING);
glDepthFunc(GL_LESS);
glEnable(GL_DEPTH_TEST);
}
//加载图片的方法
void LoadTex()
{
unsigned int Texture;
FILE* img = NULL;
img = fopen("headfront.bmp","rb");
int size = 0;
fseek(img,18,SEEK_SET);
fread(&checkImageWidth,4,1,img);
fread(&checkImageHeight,4,1,img);
fseek(img,0,SEEK_END);
size = ftell(img) - 54;
unsigned char *data = (unsigned char*)malloc(size);
fseek(img,54,SEEK_SET); // image data
fread(data,size,1,img);
fclose(img);
glGenTextures(1, &Texture);
glBindTexture(GL_TEXTURE_2D, Texture);
gluBuild2DMipmaps(GL_TEXTURE_2D, 3, checkImageWidth, checkImageHeight, GL_BGR_EXT, GL_UNSIGNED_BYTE, data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
if (data)
free(data);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
innerRadius = 0.1;
outerRadius = 0.5;
nsides = 18;
rings = 18;
int i,n = 300;
GLfloat Pi = 3.1415,R = 0.1;
glClear(GL_COLOR_BUFFER_BIT);
//New position for light0 changed by mouse motion
lightPosition[0] = 2*cos(lightangle_X);
lightPosition[1] = lightHeight;
lightPosition[2] = 2*sin(lightangle_X);
lightPosition[3] = 1;
glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
glEnable(GL_LIGHT0);
glPushMatrix();
gluLookAt(viewer[0],viewer[1],viewer[2], 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glTranslatef(0.0,-1.0,0.0);
glRotatef(shoulder,0.0,1.0,0.0);
//glutSolidTeapot (1.00);
//glutWireTeapot(1.0);
//forward back tyre,前端里面的轮胎
glPushMatrix();
glTranslatef(-1.5,0.15,0.0);
glutSolidTorus(innerRadius,outerRadius,nsides,rings);
glBegin(GL_LINE_STRIP);
for(i=0; i<n; ++i)
glVertex2f(R*cos(2*Pi/n*i), R*sin(2*Pi/n*i));
glEnd();
glPopMatrix();
//forward head tyre,radius of circle is 0.1, 前端外面的轮胎
glPushMatrix();
glTranslatef(1.5,0.15,0.0);
glutSolidTorus(innerRadius,outerRadius,nsides,rings);
//画一个圆,盖住内胎
glBegin(GL_LINE_STRIP);
for(i=0; i<n; ++i)
glVertex2f(R*cos(2*Pi/n*i), R*sin(2*Pi/n*i));
glEnd();
glPopMatrix();
//backward back tyre , 后端里面的轮胎
glPushMatrix();
glTranslatef(-1.5,0.15,-1.5);
glutSolidTorus(innerRadius,outerRadius,nsides,rings);
glBegin(GL_LINE_STRIP);
for(i=0; i<n; ++i)
glVertex2f(R*cos(2*Pi/n*i), R*sin(2*Pi/n*i));
glEnd();
glPopMatrix();
//backward head tyre, 后端外面的轮胎
glPushMatrix();
glTranslatef(1.5,0.15,-1.5);
glutSolidTorus(innerRadius,outerRadius,nsides,rings);
glBegin(GL_LINE_STRIP);
for(i=0; i<n; ++i)
glVertex2f(R*cos(2*Pi/n*i), R*sin(2*Pi/n*i));
glEnd();
glPopMatrix();
//back bearing , 后轴承
glPushMatrix();
GLUquadricObj *backBearing;
backBearing = gluNewQuadric();
glTranslatef(-1.5,0.15,-1.5);
gluCylinder(backBearing,0.1,0.1,1.5,18,4);
glPopMatrix();
//forward bearing, 前轴承
glPushMatrix();
GLUquadricObj *forwardBearing;
forwardBearing = gluNewQuadric();
glTranslatef(1.5,0.15,-1.5);
gluCylinder(forwardBearing,0.1,0.1,1.5,18,4);
glPopMatrix();
//forward bottom of the whole car
glPushMatrix();
glTranslatef(-2.5,0.0,0.0);
//back part from 0 point is 2.5, front part is 1.5, forward convex is 1.3
glScalef((2.5+1.5+1.3)/0.8,1.0,1.0);
//glutWireCube(1.0);
glBegin(GL_LINE_LOOP);
glVertex3f(0.0,0.0,0.0);
glVertex3f(0.8,0.0,0.0);
glVertex3f(0.0,0.0,-1.5);
glVertex3f(0.8,0.0,-1.5);
glEnd();
glPopMatrix();
//开始贝塞尔曲线部分
// 车前半部分
glPushMatrix();
glTranslatef(1.5,0.0,0.0);
glScalef(1.3,1.0,1.0);
//curves
int iCurve,jCurve;
//glTranslatef(3.0,0.0,0.0);
//glRotatef(90,0.0,1.0,0.0);
//车头部分右侧面
init();
glPushMatrix();
//glEvalMesh2(GL_FILL,0,20,0,20);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glDisable(GL_DEPTH_TEST);
//车头部分前面
foreCover();
glPushMatrix();
//glEvalMesh2(GL_FILL,0,20,0,20);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glDisable(GL_TEXTURE_2D);
//glDisable(GL_MAP2_VERTEX_3);
glDisable(GL_MAP2_TEXTURE_COORD_1);
glDisable(GL_MAP2_TEXTURE_COORD_2);
glDisable(GL_DEPTH_TEST);
//depth , inside cover
depthCover();
glPushMatrix();
glTranslatef(0.0,0.0,-1.5);
//glRotatef(85.0,1.0,1.0,1.0);
//glEvalMesh2(GL_FILL,0,20,0,20);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glDisable(GL_DEPTH_TEST);
//top cover
topCover();
glPushMatrix();
//glTranslatef(1.5,0.0,0.0);
//glRotatef(85.0,1.0,1.0,1.0);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glDisable(GL_DEPTH_TEST);
glPopMatrix();
//wind glasses
foreGlass();
glPushMatrix();
glTranslatef(1.5,0.8,0.0);
glRotatef(15.0,0.0,0.0,1.0);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glDisable(GL_DEPTH_TEST);
//the back of the car
glPushMatrix();
glTranslatef(-2.5,0.0,0.0);
glScalef(2.0,1.0,1.0);
//backFront
backFront();
glPushMatrix();
//glTranslatef(1.5,0.8,0.0);
//glRotatef(15.0,0.0,0.0,1.0);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glDisable(GL_DEPTH_TEST);
//backDepth
backDepth();
glPushMatrix();
glTranslatef(0.0,0.0,-1.5);
//glRotatef(15.0,0.0,0.0,1.0);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glDisable(GL_DEPTH_TEST);
//backBack
backBack();
glPushMatrix();
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glDisable(GL_DEPTH_TEST);
//backCover
backCover();
glPushMatrix();
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glDisable(GL_DEPTH_TEST);
glPopMatrix();
AxisBack();
glPushMatrix();
glTranslatef(-2.5,0.2,0.0);
glRotatef(-10.0,0.0,0.0,1.0);
glScalef(1.0,1.0,1.0);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glDisable(GL_DEPTH_TEST);
//front Door the width of door is 3.2, for the front part is 1.5 x and the back part is 2.5 - 0.8 = 1.7
glPushMatrix();
DoorFront();
glTranslatef(0.8,0.0,0.0);
glScalef(0.9,1.0,1.0);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glPushMatrix();
if(right == true)
{
glTranslatef(1.15/2,0.0,1.15*1.73/2);
glRotatef(60.0,0.0,1.0,0.0);
}
glPushMatrix();
DoorFrontSecond();
glTranslatef(-0.9,0.0,0.0);
glScalef(2.3,1.0,1.0);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glPushMatrix();
DoorFrontSecondBack();
glTranslatef(-0.9,0.0,0.0);
glScalef(2.3,1.0,1.0);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glPushMatrix();
DoorFrontSide();
glTranslatef(-0.9,0.0,-0.2);
//glScalef(2.3,1.0,1.0);
glRotatef(180.0,0.0,1.0,0.0);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glPushMatrix();
DoorFrontBottom();
glTranslatef(-0.9,0.0,-0.0);
glScalef(2.3,1.0,1.0);
//glRotatef(180.0,0.0,1.0,0.0);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glPopMatrix();
//behind Door the width of door is 3.2, for the front part is 1.5 x and the back part is 2.5 - 0.8 = 1.7
glPushMatrix();
DoorBehind();
glTranslatef(0.8,0.0,-1.5);
glScalef(0.9,1.0,1.0);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glPushMatrix();
glTranslatef(0.0,0.0,-1.5);
if(left == true)
{
glTranslatef(1.15/2,0.0,-1.15*1.73/2);
glRotatef(-60.0,0.0,1.0,0.0);
}
glPushMatrix();
DoorBehindSecond();
glTranslatef(-0.9,0.0,0.0);
glScalef(2.3,1.0,1.0);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glPushMatrix();
DoorBehindSecondBack();
glTranslatef(-0.9,0.0,0.0);
glScalef(2.3,1.0,1.0);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glPushMatrix();
DoorBehindSide();
glTranslatef(-0.9,0.0,0.2);
//glScalef(2.3,1.0,1.0);
glRotatef(180.0,0.0,1.0,0.0);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glPushMatrix();
DoorBehindBottom();
glTranslatef(-0.9,0.0,-0.0);
glScalef(2.3,1.0,1.0);
//glRotatef(180.0,0.0,1.0,0.0);
for(jCurve=0; jCurve<=8; jCurve++)
{
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve<= 30;iCurve++)
glEvalCoord2f((GLfloat)iCurve/30.0,(GLfloat)jCurve/8.0);
glEnd();
glBegin(GL_LINE_STRIP);
for(iCurve = 0; iCurve <= 30;iCurve++)
glEvalCoord2f((GLfloat)jCurve/8.0,(GLfloat)iCurve/30.0);
glEnd();
}
glPopMatrix();
glPopMatrix();
glPopMatrix();
glutSwapBuffers();
}
void reshape(int w, int h)
{
glViewport(0,0,(GLsizei)w,(GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(65.0,(GLfloat)w/(GLfloat)h,1.0,20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0,0.0,-5.0);
}
void keyboard(unsigned char key, int x, int y)
{
switch(key){
case 'w': /*s key rotates ar shoulder*/
shoulder = (shoulder+5)%360;
glutPostRedisplay();
break;
case 's':
shoulder = (shoulder-5)%360;
glutPostRedisplay();
break;
case 'd':/*e key rotate at elbow*/
elbow = (elbow+5)%360;
glutPostRedisplay();
break;
case 'a':
elbow = (elbow - 5)%360;
glutPostRedisplay();
break;
case 'l':
if(left == false)
left = true;
else
left = false;
break;
case 'r':
if(right == false)
right = true;
else
right = false;
break;
default:
break;
}
if(key == 'x') viewer[0]-= 1.0;
if(key == 'X') viewer[0]+= 1.0;
if(key == 'y') viewer[1]-= 1.0;
if(key == 'Y') viewer[1]+= 1.0;
if(key == 'z') viewer[2]-= 1.0;
if(key == 'Z') viewer[2]+= 1.0;
display();
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowPosition(100, 100);
glutInitWindowSize(500, 500);
glutCreateWindow("Robot Arms");
lightInit();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
|
#include "FoundationPch.h"
#include "Foundation/Reflect/Version.h"
#include "Foundation/Reflect/Data/DataDeduction.h"
REFLECT_DEFINE_OBJECT( Helium::Reflect::Version );
using namespace Helium;
using namespace Helium::Reflect;
void Version::PopulateComposite( Reflect::Composite& comp )
{
comp.AddField( &Version::m_Source, TXT( "m_Source" ) );
comp.AddField( &Version::m_SourceVersion, TXT( "m_SourceVersion" ) );
}
Reflect::Version::Version()
{
}
Reflect::Version::Version(const tchar_t* source, const tchar_t* sourceVersion)
: m_Source (source)
, m_SourceVersion (sourceVersion)
{
}
bool Reflect::Version::IsCurrent()
{
return true;
}
|
#include "mydataobject.h"
#include <QDebug>
MyDataObject::MyDataObject(QObject *parent)
:QObject(parent)
{
}
MyDataObject::MyDataObject(const QString &name, const QString &color, QObject *parent)
:QObject(parent)
,m_name(name)
,m_color(color)
{
}
QString MyDataObject::getName() const
{
return m_name;
}
void MyDataObject::setName(const QString &name)
{
if(name != m_name){
m_name = name;
emit nameChanged();
}
}
QString MyDataObject::getColor() const
{
return m_color;
}
void MyDataObject::setColor(const QString &color)
{
if(color != m_color){
m_color = color;
emit colorChanged();
}
}
|
#ifndef DETAILSDOCKWIDGET_H
#define DETAILSDOCKWIDGET_H
#include <QDockWidget>
#include <detailsviewmodel.h>
namespace Ui {
class DetailsDockWidget;
}
class DetailsDockWidget : public QDockWidget
{
Q_OBJECT
public:
Q_INVOKABLE DetailsDockWidget(QtMvvm::ViewModel *viewModel, QWidget *parent = nullptr);
~DetailsDockWidget() override;
protected:
void closeEvent(QCloseEvent *event) override;
private slots:
void updateInfo();
void imageLoaded(int id, const QImage &image);
void imageLoadFailed(int id, const QString &error);
private:
DetailsViewModel *_viewModel;
Ui::DetailsDockWidget *_ui;
};
#endif // DETAILSDOCKWIDGET_H
|
// Swap two variables in a function called swap. Make two versions
// void swap (int& a int& b)
// void swap (int* a, int*b)
#include <iostream>
void swap(int& a, int& b)
{
std::cout << "Swapping reference variables" << std::endl;
printf("Start - A: %i, B: %i \n", a, b);
int temp = a;
a = b;
b = temp;
printf("End - A: %i, B: %i \n", a, b);
}
void swap(int* a, int* b)
{
// Here I'm choosing to swap the values of a and b rather than swapping the memory addresses
// check that the pointers are not null!
if (a && b)
{
std::cout << "Swapping pointer variables" << std::endl;
printf("Start - A: %i, B: %i \n", *a, *b);
int temp = *a;
*a = *b;
*b = temp;
printf("End - A: %i, B: %i \n", *a, *b);
}
}
int main()
{
// declare two ints on the stack
int a = 1;
int b = 43;
// Swap a and b by reference
swap(a, b);
// Declare c and d on the heap
int* c = new int(22);
int* d = new int(400);
// Swap c and d as pointers
swap(c, d);
// Pointers are just memory addresses
swap(&a, &b);
// and references are just aliases for existing variables
swap(*c, *d);
// Free our dynamically allocated memory
delete c;
delete d;
return 0;
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CHASTESYSCALLS_HPP_
#define CHASTESYSCALLS_HPP_
/**
* @file
* This file provides access to some 'system calls' in a cross-platform manner.
* It provides the normal Linux names, even on Windows.
* Functions provided: chdir, getpid, chmod, setenv.
*/
#ifdef _MSC_VER
#include <direct.h>
#define chdir _chdir
#include <process.h>
#define getpid _getpid
#include <io.h>
#define chmod _chmod
#include <sys/stat.h>
#define CHASTE_READONLY _S_IREAD
#define CHASTE_READ_EXECUTE _S_IREAD | _S_IEXEC
#define CHASTE_READ_WRITE _S_IREAD | _S_IWRITE
#define CHASTE_READ_WRITE_EXECUTE _S_IREAD | _S_IWRITE | _S_IEXEC
/**
* Windows version of setenv call. Note that under Linux we always pass 1 (overwrite) for the third arg.
* @param name environment variable to set
* @param value value to give the variable
* @param mode not used on Windows
*/
#define setenv(name, value, mode) _putenv_s(name, value)
#else
#include <unistd.h> // For chdir() and getpid()
#include <sys/stat.h> // For chmod()
/** Mode for chmod() to set readonly permissions for everyone. */
#define CHASTE_READONLY 0444
/** Mode for chmod() to set read & execute permissions for everyone. */
#define CHASTE_READ_EXECUTE 0555
/** Mode for chmod() to set read-write permissions for owner, and readonly for group. */
#define CHASTE_READ_WRITE 0640
/** Mode for chmod() to set full permissions for owner, and read-execute for everyone else. */
#define CHASTE_READ_WRITE_EXECUTE 0755
#endif // _MSC_VER
#endif // CHASTESYSCALLS_HPP_
|
#include <stdlib.h>
#include <iostream>
#include <vector>
#include "TFile.h"
#include "TTree.h"
#include "TStopwatch.h"
#include "TString.h"
#include "AngraMCPulse.h"
#include "PulseTree.h"
#include "AngraMCMixer.h"
using namespace std;
int main(int argc, char **argv)
{
std::cout << "Hello Mixer!" << std::endl;
TString outFileName = "mixed.root";
TString prefix = "./";
TString sSeed, sTime;
int seed = 20142015;
double mixTime = 3600.;
if(argc>=2){
// arg 1 must be SEED
sSeed = argv[1];
seed=sSeed.Atoi();
// arg 2 must be Output File Name
if (argc>=3) {
outFileName = argv[2];
if (argc>=4) {
prefix = argv[3];
if(argc>=5){
sTime = argv[4];
mixTime = sTime.Atoi();
}
}
}
}
cout << "Using "<< seed << " as random seed" << endl;
cout << "Prefix "<< prefix << endl;
cout << "File "<< outFileName << endl;
cout << "Time "<< mixTime << endl;
//load first tree
TStopwatch aWatch;
aWatch.Start();
TFile f1("/home/drc01/kemp/angra/data/Pulses/000001.photons_v1_1M_20131000_PULSES.root");
TTree* pulseTreeP1;
f1.GetObject("PulseTree;2",pulseTreeP1);
PulseTree pt1(pulseTreeP1);
AngraMCMixer aMixer;
aMixer.AddPrimary(&pt1,1./855.);
f1.Close();
TFile f2("/home/drc01/kemp/angra/data/Pulses/000002.electrons_v1_1M_20131000_PULSES.root");
TTree* pulseTreeP2;
f2.GetObject("PulseTree;2",pulseTreeP2);
PulseTree pt2(pulseTreeP2);
aMixer.AddPrimary(&pt2,1./71.0);
f2.Close();
TFile f3("/home/drc01/kemp/angra/data/Pulses/000003.positrons_v1_621000_20131000_PULSES.root");
TTree* pulseTreeP3;
f3.GetObject("PulseTree;2",pulseTreeP3);
PulseTree pt3(pulseTreeP3);
aMixer.AddPrimary(&pt3,1./68.4);
f3.Close();
// TFile f4("/home/drc01/kemp/angra/data/Pulses/000004.muons_v1_143100_20131000_PULSES.root");
// TTree* pulseTreeP4;
// f4.GetObject("PulseTree;2",pulseTreeP4);
// PulseTree pt4(pulseTreeP4);
// aMixer.AddPrimary(&pt4,1./3);
// f4.Close();
TFile f5("/home/drc01/kemp/angra/data/Pulses/000005.protons_v1_20k_20131000_PULSES.root");
TTree* pulseTreeP5;
f5.GetObject("PulseTree;2",pulseTreeP5);
PulseTree pt5(pulseTreeP5);
aMixer.AddPrimary(&pt5,1./6.38);
f5.Close();
TFile f6("/home/drc01/kemp/angra/data/Pulses/000006.pions_v1_10300_20131000_PULSES.root");
TTree* pulseTreeP6;
f6.GetObject("PulseTree;2",pulseTreeP6);
PulseTree pt6(pulseTreeP6);
aMixer.AddPrimary(&pt6,1./0.962);
f6.Close();
TFile f7("/home/drc01/kemp/angra/data/Pulses/000007.neutrons_v1_50k_20131000_PULSES.root");
TTree* pulseTreeP7;
f7.GetObject("PulseTree;2",pulseTreeP7);
PulseTree pt7(pulseTreeP7);
aMixer.AddPrimary(&pt7,1./112.9);
f7.Close();
/* TFile f9("/home/drc01/kemp/angra/data/Pulses/000009.neutrinos_v1_71800_20131000_PULSES.root");
TTree* pulseTreeP9;
f9.GetObject("PulseTree;2",pulseTreeP9);
PulseTree pt9(pulseTreeP9);
aMixer.AddPrimary(&pt9,1./0.053);
f9.Close();
*/
TFile f11("/home/drc01/kemp/angra/data/Pulses/000011.muons_v1_250k_20131001_PULSES.root");
TTree* pulseTreeP11;
f11.GetObject("PulseTree;2",pulseTreeP11);
PulseTree pt11(pulseTreeP11);
aMixer.AddPrimary(&pt11,1./76.14);
f11.Close();
TFile f12("/home/drc01/kemp/angra/data/Pulses/000012.muons_v1_250k_20131002_PULSES.root");
TTree* pulseTreeP12;
f12.GetObject("PulseTree;2",pulseTreeP12);
PulseTree pt12(pulseTreeP12);
aMixer.AddPrimary(&pt12,1./76.14);
f12.Close();
TFile f13("/home/drc01/kemp/angra/data/Pulses/000013.muons_v1_250k_20131003_PULSES.root");
TTree* pulseTreeP13;
f13.GetObject("PulseTree;2",pulseTreeP13);
PulseTree pt13(pulseTreeP13);
aMixer.AddPrimary(&pt13,1./76.14);
f13.Close();
TFile f14("/home/drc01/kemp/angra/data/Pulses/000014.muons_v1_250k_20131004_PULSES.root");
TTree* pulseTreeP14;
f14.GetObject("PulseTree;2",pulseTreeP14);
PulseTree pt14(pulseTreeP14);
aMixer.AddPrimary(&pt14,1./75.87);
f14.Close();
aWatch.Print();
aWatch.Continue();
std::cout << " sizes " << aMixer.GetNPrimaries() << " " //
<< aMixer.GetNEvents(1) << " " //
<< aMixer.GetNPulses(1,10) << std::endl;
std::cout << " a pulse from db " << aMixer.GetAPulse(1,2,0).run1 //
<< " " << aMixer.GetAPulse(1,2,0).event1 << std::endl;
TString fName = prefix + outFileName;
aMixer.Init(fName.Data(),seed);
//aMixer.FillSequentially();
aWatch.Print();
aWatch.Continue();
aMixer.Fill(mixTime);
aWatch.Print();
aWatch.Continue();
aMixer.Finalize();
aWatch.Print();
return 0;
}
|
#ifndef BOARD_HPP
#define BOARD_HPP
#include "NumberTile.hpp"
#include <Godot.hpp>
#include <Node2D.hpp>
#include <PackedScene.hpp>
#include <vector>
#include <InputEvent.hpp>
#include <RandomNumberGenerator.hpp>
using std::vector;
namespace godot
{
class PackedScene;
class Panel;
class MatrixIndex;
class Global;
class Timer;
class Game;
/* Enum variable showing board stat */
enum class BoardState: int
{
IDLE,
TOUCH,
SWIP,
UPDATE_BOARD
};
class Board : public Node2D
{
GODOT_CLASS(Board, Node2D);
private:
const float c_DRAG_THRESHOLD = 32. * 32.;
Ref<PackedScene> m_bg_tile_scn;
Ref<PackedScene> m_num_tile_scn;
Ref<PackedScene> m_player_lost_scn;
Vector2 m_tile_start_pos;
Vector2 m_board_size;
vector<vector<NumberTile*>> m_board_mat;
Node *m_bg_tiles_root;
Node *m_num_tiles_root;
BoardState m_curr_board_st = BoardState::IDLE;
/* Stores total drag by user, which shows which way to swip. */
Vector2 m_total_drag = Vector2(0, -1);
/* Holds the number of moving tiles, so to track if moving is finished*/
int m_moving_tiles = 0;
/* Stores which tiles to free inf UPDATE_BOARD state */
vector<NumberTile*> m_tiles_to_free;
/* Stroes which tiles to set to increase number in UPDATE_BOARD state */
vector<NumberTile*> m_tiles_to_update;
/* Stores touch index of first touch */
int m_touch_indx = -1;
/* A RandomNumberGenerator object to generate random numbers */
Ref<RandomNumberGenerator> m_rand_gen;
/* Delay time to change to Idle state reference */
Timer *m_to_idle_delay;
/* A reference to current Game object (Board parent).*/
Game *m_game;
private:
void create_num_tile_at_index(const MatrixIndex &index, int which_num);
void change_state_to(BoardState __new_sate);
void swipe_up();
void swipe_down();
void swipe_right();
void swipe_left();
void set_item_move_to_indx(const MatrixIndex &indx,
const MatrixIndex &to_indx);
void check_if_player_lost();
bool can_tile_move(const NumberTile &tile) const;
void print_board_matrix(); /* For debug purposes. */
public:
static void _register_methods();
void _init();
void _ready();
void _input(const Ref<InputEvent> event);
/* m_board_size setter and getter*/
void set_board_size(Vector2 __board_size);
Vector2 get_board_size() const;
void create_random_tile_with_num(int which_num);
void decrease_moving_tiles();
/* Method that is connected to timer used for resetting to idle state*/
void _on_ToIdleTmr_timeout();
};
}; // namespace godot
#endif
|
#include <iostream>
#include <cmath>
// Pn=n(3n−1)/2 - pentagonal number
using namespace std;
//this function test if number is pentagonal
int pentagonal (int a)
{
int test=sqrt(2*a/3);
int T[3];
for (int i=0;i<3;i++) {
T[i]=(test-1+i)*(3*(test-1+i)-1)/2;
}
if (a!=T[0] && a!=T[1] && a!=T[2]) return 0;
else return 1;
}
int modul (int a)
{
if (a>=0) return a;
else return -a;
}
int main()
{
for(int i=1;i<=10000;i++)
{
int P1=i*(3*i-1)/2;
for (int j=1;j<=10000;j++) {
int P2=j*(3*j-1)/2;
if (pentagonal(P1+P2))
{
if( i!=j && pentagonal(modul(P1-P2)))
{
cout << "Pentagonal number " << i << " is " << P1 << " and Pentagonal number " << j << " is " << P2 << " give difference " << modul(P1-P2) << endl;
}
}
}
}
cout << "Hello World!" << endl;
return 0;
}
|
#include "CYdLidar.h"
#include <iostream>
#include <string>
#include <signal.h>
#include <memory>
#include <unistd.h>
#include <thread>
#include <GL/glut.h>
#include <cmath>
//using namespace std;
using namespace ydlidar;
CYdLidar laser;
static bool stopPlease = false;
struct ViewData
{
LaserScan scan;
};
ViewData vd;
void initRanges(std::vector<float> &ranges, float val = 1.0)
{
std::cout << "dummy ranges values" << std::endl;
ranges.clear();
for (int i = 0; i < 360; ++i)
{
ranges.push_back(val);
}
}
static void Stop(int signo)
{
printf("Received exit signal\n");
stopPlease = true;
}
int runLidar(int argc, char *argv[])
{
printf(" YDLIDAR C++ TEST\n");
const std::string port = string("/dev/ttyUSB0");
const int baud = 125200;
const int intensities = 0;
signal(SIGINT, Stop);
signal(SIGTERM, Stop);
laser.setSerialPort(port);
laser.setSerialBaudrate(baud);
laser.setIntensities(intensities);
laser.initialize();
while (!stopPlease)
{
bool hardError;
LaserScan scan;
if (laser.doProcessSimple(scan, hardError))
{
//printf("\033c");
//printf("Scan received: %i ranges\n", scan.ranges.size());
//std::cout<<".";
//std::cout.flush();
vd.scan = scan;
}
else
{
initRanges(vd.scan.ranges, 0.5);
break;
}
usleep(50 * 1000);
}
laser.turnOff();
laser.disconnecting();
return 0;
}
void filter(std::vector<float> &out, std::vector<float> const &in, int const b, float const threshold)
{
out.clear();
for (int i = 0; i < in.size(); ++i)
{
int begin = i - b;
int end = i + b;
float suml = 0.0;
for (int j = begin; j < i; ++j)
{
suml += in.at(j % in.size());
}
float avgl = suml / (float)b;
float sumr = 0.0;
for (int j = i + 1; j <= end; ++j)
{
sumr += in.at(j % in.size());
}
float avgr = sumr / (float)b;
if ((abs(avgl - in.at(i)) < threshold) || (abs(avgr - in.at(i)) < threshold))
{
out.push_back(in.at(i));
}
else
{
out.push_back((avgl + avgr) / 2.0);
}
}
}
class vec
{
public:
vec(float x_, float y_)
: x(x_), y(y_)
{
}
vec(vec const &v)
: x(v.x), y(v.y)
{
}
float normsq()
{
return x * x + y * y;
}
vec &operator-=(vec const &v)
{
x -= v.x;
y -= v.y;
return *this;
}
vec &operator=(vec const &v)
{
x = v.x;
y = v.y;
return *this;
}
float x;
float y;
};
struct Segments
{
std::vector<float> ranges;
std::vector<float> angles;
std::vector<vec> points;
std::vector<int> parts;
};
void findSegments(Segments &seg, std::vector<float> const &in,
float const threshold, float const threshold2)
{
seg.ranges.clear();
seg.angles.clear();
seg.points.clear();
seg.parts.clear();
for (int i = 0; i < in.size(); ++i)
{
float r = in.at(i);
if (r > threshold)
{
float alpha = ((float)i) / ((float)in.size()) * 2 * 3.1415926;
seg.ranges.push_back(r);
seg.angles.push_back(alpha);
}
}
seg.parts.push_back(0);
float r0 = seg.ranges.at(0);
float alpha0 = seg.angles.at(0);
vec v0(-sin(alpha0) * r0, cos(alpha0) * r0);
seg.points.push_back(v0);
for (int i = 1; i < seg.ranges.size(); ++i)
{
float r1 = seg.ranges.at(i - 1);
float r2 = seg.ranges.at(i);
float alpha1 = seg.angles.at(i - 1);
float alpha2 = seg.angles.at(i);
vec v1(-sin(alpha1) * r1, cos(alpha1) * r1);
vec v2(-sin(alpha2) * r2, cos(alpha2) * r2);
seg.points.push_back(v2);
v1 -= v2;
// point distance too large -> new segment starts
if (v1.normsq() > threshold2 * threshold2)
{
seg.parts.push_back(i);
}
}
seg.parts.push_back(seg.ranges.size());
}
void displayMe(void)
{
glClear(GL_COLOR_BUFFER_BIT);
std::cout << vd.scan.ranges.size() << '\r' << std::flush;
int n = vd.scan.ranges.size();
if (n > 3)
{
Segments seg;
findSegments(seg, vd.scan.ranges, 0.01, 0.01);
for (int s = 0; s < seg.parts.size() - 1; ++s)
{
glBegin(GL_LINE_STRIP);
for (int i = seg.parts.at(s); i < seg.parts.at(s + 1); ++i)
{
glVertex3f(seg.points.at(i).x, seg.points.at(i).y, 0.0);
}
glEnd();
}
}
glFlush();
usleep(1000000 / 60);
glutPostRedisplay();
}
int main(int argc, char *argv[])
{
std::thread t(runLidar, argc, argv);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(800, 800);
glutInitWindowPosition(100, 100);
glutCreateWindow("Lidar measure");
glutDisplayFunc(displayMe);
glutMainLoop();
}
|
#include<iostream>
#include<algorithm>
#include<functional>
#include<set>
#include<vector>
#include<queue>
using namespace std;
const int MAX_POINT_NUMBER=100000;
class edge
{
public:
int dest,ori;
int length;
}edge;
bool operator> (const edge &a,const edge &b) const
{
return a.length<b.length;
}
vector<edge>g[MAX_POINT_NUMBER];
priority_queue<edge>GraphSet;
int m,n;
int prim()
{
return 0;
}
int main()
{
cin >>n>>m;
for(int i=0;i<m;i++)
{
int a,b,v;
cin >>a>>b>>v;
edge e;e.
}
}
|
#pragma once
#include <iostream>
int readIntFromConsole(std::string message) {
int number;
std::cout << message;
std::cin >> number;
return number;
}
double readDoubleFromConsole(std::string message) {
double number;
std::cout << message;
std::cin >> number;
return number;
}
|
#include "datastore.h"
#include "mydatastore.h"
#include "product.h"
#include "user.h"
#include "util.h"
#include <string>
#include <set>
#include <vector>
#include <map>
#include <sstream>
#include <iostream>
using namespace std;
MyDataStore::MyDataStore()
{
}
MyDataStore::~MyDataStore()
{
std::map<std::string, User*>::iterator user_it;
for (user_it = users_.begin(); user_it != users_.end(); ++user_it) {
delete user_it->second;
}
std::vector<Product*>::iterator prod_it;
for (prod_it = products_.begin(); prod_it != products_.end(); ++prod_it) {
delete *prod_it;
}
}
/**
* Adds a product to the data store
*/
void MyDataStore::addProduct(Product* p) {
products_.push_back(p);
std::set<std::string> keywords = p->keywords();
std::set<std::string>::iterator key_it;
std::map<std::string, std::set<Product*> >::iterator map_it;
for (key_it = keywords.begin(); key_it != keywords.end(); ++key_it) {
if (keys_.find(*key_it) == keys_.end()) {
std::set<Product*> new_set;
new_set.insert(p);
keys_.insert( make_pair(*key_it, new_set) );
}
else {
for (map_it = keys_.begin(); map_it != keys_.end(); ++map_it) {
if (*key_it == map_it->first) {
map_it->second.insert(p);
}
}
}
}
}
/**
* Adds a user to the data store
*/
void MyDataStore::addUser(User* u) {
std::vector<Product*> empty_cart;
users_.insert( make_pair(u->getName(), u) );
carts_.insert( make_pair(u->getName(), empty_cart) );
}
/**
* Performs a search of products whose keywords match the given "terms"
* type 0 = AND search (intersection of results for each term) while
* type 1 = OR search (union of results for each term)
*/
std::vector<Product*> MyDataStore::search(std::vector<std::string>& terms, int type) {
std::set<Product*> hits;
std::map<std::string, std::set<Product*> >::iterator map_it;
if (type == 1) {
for (unsigned int i = 0; i < terms.size(); i++) {
for (map_it = keys_.begin(); map_it != keys_.end(); ++map_it) {
std::set<Product*> set2;
if (map_it->first == terms[i]) {
set2 = map_it->second;
}
hits = setUnion(hits, set2);
}
}
}
if (type == 0) {
for (unsigned int i = 0; i < terms.size(); i++) {
for (map_it = keys_.begin(); map_it != keys_.end(); ++map_it) {
std::set<Product*> set2;
if (map_it->first == terms[i]) {
set2 = map_it->second;
if (i == 0) {
hits = setIntersection(set2, set2);
}
else {
hits = setIntersection(hits, set2);
}
}
}
}
}
std::set<Product*>::iterator hit_it;
std::vector<Product*> hits_vec;
for (hit_it = hits.begin(); hit_it != hits.end(); ++hit_it) {
hits_vec.push_back(*hit_it);
}
return hits_vec;
}
/**
* Reproduce the database file from the current Products and User values
*/
void MyDataStore::dump(std::ostream& ofile) {
ofile << "<products>" << endl;
for (unsigned int i = 0; i < products_.size(); i++) {
products_[i]->dump(ofile);
}
ofile << "</products>" << endl;
ofile << "<users>" << endl;
std::map<std::string, User*>::iterator it;
for (it = users_.begin(); it != users_.end(); ++it) {
it->second->dump(ofile);
}
ofile << "</users>" << endl;
}
/**
* Allows user to add to cart
*/
void MyDataStore::AddtoCart(std::string username, Product* p) {
std::map<std::string, std::vector<Product*> >::iterator it;
it = carts_.find(username);
if (it == carts_.end()) {
cout << "Invalid request" << endl;
return;
}
it->second.push_back(p);
}
/**
* Allows user to view cart
*/
void MyDataStore::ViewCart(std::string username) {
std::map<std::string, std::vector<Product*> >::iterator it;
it = carts_.find(username);
if (it == carts_.end()) {
cout << "Invalid username" << endl;
return;
}
else {
std::vector<Product*>::iterator vec;
int count = 1;
for (vec = it->second.begin(); vec != it->second.end(); ++vec) {
cout << "Item " << count << endl;
cout << (*vec)->displayString() << endl;
count++;
}
}
}
/**
* Allows user to buy all available products in cart
*/
void MyDataStore::BuyCart(std::string username) {
std::map<std::string, User*>::iterator user;
user = users_.find(username);
std::map<std::string, std::vector<Product*> >::iterator it;
it = carts_.find(username);
if (it == carts_.end()) {
cout << "Invalid username" << endl;
return;
}
vector<Product*>::iterator pro = it->second.begin();
while (pro != it->second.end()) {
if ((*pro)->getQty() > 0 && user->second->getBalance() >= (*pro)->getPrice()) {
user->second->deductAmount((*pro)->getPrice());
(*pro)->subtractQty(1);
pro = it->second.erase(pro);
// iterator now positioned at the item after the deleted item
}
else {
pro++;
}
}
}
|
#ifndef __FILE_VECN_INTERFACE__
#define __FILE_VECN_INTERFACE__
#include "logging.h"
#include "static_check.h"
#include "vecn_interface_base.h"
namespace Common
{
template <typename T, int d>
class ele_set : public ele_set_base<T>
{
public:
virtual T &at(int i) = 0;
virtual T const &at(int i) const = 0;
virtual inline int dim() const final { return d; }
constexpr static int const num_elements = d;
inline ele_set<T, d> &operator=(ele_set<T, d> const &r)
{
for (int i = 0; i < d; ++i)
{
at(i) = r.at(i);
}
return *this;
}
inline ele_set<T, d> &operator=(T const &f)
{
for (int i = 0; i < d; ++i)
{
at(i) = f;
}
return *this;
}
inline ele_set<T, d> &set(T const &f)
{
for (int i = 0; i < d; ++i)
{
at(i) = f;
}
return *this;
}
};
template <typename T, int r, int c>
class mat_interface;
class blablub
{
};
template <typename T, int d>
class vec_interface : public ele_set<T, d>, public mat_interface<T, d, 1>
{
public:
virtual T &at(int i) override = 0;
virtual T const &at(int i) const override = 0;
inline T &at(int i, int j) override
{
CHECK(0 == j);
return at(i);
}
inline T const &at(int i, int j) const override
{
CHECK(0 == j);
return at(i);
}
};
template <typename T, int r, int c>
class mat_interface : public mat_interface_base<T>
{
public:
virtual T &at(int i, int j) override = 0;
virtual T const &at(int i, int j) const override = 0;
virtual T &at(vec_interface<int, 2> const &ij) final {return at(ij.at(0), ij.at(1));}
virtual T const &at(vec_interface<int, 2> const &ij) const final {return at(ij.at(0), ij.at(1));}
virtual inline int dimr() const final { return r; }
virtual inline int dimc() const final { return c; }
constexpr static int const num_rows = r;
constexpr static int const num_columns = c;
};
// ******* elementwise operations *******
#define VECN_INTERFACE_IMPL_OPERATOR_ELE_ELE(FCT_NAME, OPERATOR) \
template <typename S, typename T, int d> \
inline S &FCT_NAME(S &x, ele_set<T, d> const &r) \
{ \
STATIC_CHECK((true == is_base_of<ele_set<T, d>, S>::value)); \
for (int i = 0; i < d; ++i) \
{ \
x.at(i) OPERATOR r.at(i); \
} \
return x; \
}
VECN_INTERFACE_IMPL_OPERATOR_ELE_ELE(operator+=, +=)
VECN_INTERFACE_IMPL_OPERATOR_ELE_ELE(operator-=, -=)
VECN_INTERFACE_IMPL_OPERATOR_ELE_ELE(operator*=, *=)
VECN_INTERFACE_IMPL_OPERATOR_ELE_ELE(operator/=, /=)
// --- vec <-> T ---
#define VECN_INTERFACE_IMPL_OPERATOR_ELE_T(FCT_NAME, OPERATOR) \
template <typename T, int d> \
inline ele_set<T, d> &FCT_NAME(ele_set<T, d> &x, T const &f) \
{ \
for (int i = 0; i < d; ++i) \
{ \
x.at(i) OPERATOR f; \
} \
return x; \
}
VECN_INTERFACE_IMPL_OPERATOR_ELE_T(operator+=, +=)
VECN_INTERFACE_IMPL_OPERATOR_ELE_T(operator-=, -=)
VECN_INTERFACE_IMPL_OPERATOR_ELE_T(operator*=, *=)
VECN_INTERFACE_IMPL_OPERATOR_ELE_T(operator/=, /=)
// ****** matrix multiplications *********
template <typename T, typename T2, int d>
inline T &atb(T &s, vec_interface<T2, d> const &a, vec_interface<T, d> const &b)
{
s = 0.0;
T tmp;
for (int i = 0; i < d; ++i)
{
tmp = a.at(i);
tmp *= b.at(i);
s += tmp;
}
return s;
}
template <typename T, typename T2, int r, int c>
inline vec_interface<T, r> &Ab(vec_interface<T, r> &x, mat_interface<T2, r, c> const &A, vec_interface<T, c> const &b)
{
for (int i = 0; i < r; ++i)
{
x.at(i) = 0.0;
}
T bj;
T Aijbj;
for (int j = 0; j < c; ++j)
{
bj = b.at(j);
for (int i = 0; i < r; ++i)
{
Aijbj = bj;
Aijbj *= A.at(i, j);
x.at(i) += Aijbj;
}
}
return x;
}
template <typename T, typename T2, int r, int c>
inline vec_interface<T, c> &Atb(vec_interface<T, c> &x, mat_interface<T2, r, c> const &A, vec_interface<T, r> const &b)
{
for (int i = 0; i < c; ++i)
{
x.at(i) = 0.0;
}
T bj;
T Ajibj;
for (int j = 0; j < r; ++j)
{
bj = b.at(j);
for (int i = 0; i < c; ++i)
{
Ajibj = bj;
Ajibj *= A.at(j, i);
x.at(i) += Ajibj;
}
}
return x;
}
template <typename T, typename T2, int r, int l, int c>
inline mat_interface<T, r, c> &AB(mat_interface<T, r, c> &X, mat_interface<T2, r, l> const &A, mat_interface<T, l, c> const &B)
{
T tmp;
for (int i = 0; i < r; ++i)
{
for (int j = 0; j < c; ++j)
{
X.m[i][j] = 0.0;
for (int k = 0; k < l; ++k)
{
tmp = B.at(k, j);
tmp *= A.at(i, k);
X.at(i, j) += tmp;
}
}
}
return X;
}
template <typename T, typename T2, int r, int l, int c>
inline mat_interface<T, r, c> &AtB(mat_interface<T, r, c> &X, mat_interface<T2, l, r> const &A, mat_interface<T, l, c> const &B)
{
T tmp;
for (int i = 0; i < r; ++i)
{
for (int j = 0; j < c; ++j)
{
X.m[i][j] = 0.0;
for (int k = 0; k < l; ++k)
{
tmp = B.at(k, j);
tmp *= A.at(k, i);
X.at(i, j) += tmp;
}
}
}
return X;
}
// ***********************************+
// transpose matrix
template <typename T, int r, int c>
class matT : public mat_interface<T, r, c>
{
public:
matT(mat_interface<T, c, r> &mat_) : mat(mat_)
{
}
virtual inline T &at(int i, int j) final
{
return mat.at(j, i);
}
virtual inline T const &at(int i, int j) const final
{
return mat.at(j, i);
}
private:
mat_interface<T, c, r> &mat;
};
template <typename T, int r, int c>
matT<T, c, r> transposed(mat_interface<T, r, c> &mat_)
{
return matT<T, c, r>(mat_);
}
template <typename T, int r, int c>
matT<T, c, r> const transposed(mat_interface<T, r, c> const &mat_)
{
return matT<T, c, r>(mat_);
}
} // namespace Common
#endif
|
#include "RegisterDialog.h"
#include <QMessageBox>
#include <QBuffer>
#include <QMouseEvent>
#include <QLayout>
#include <QDataStream>
#include <QRegExp>
#include <QDebug>
#include <QTcpSocket>
#include <QUdpSocket>
#include <QCryptographicHash>
#include <QTimer>
#include <qmath.h>
RegisterDialog::RegisterDialog(QWidget *parent) :
QDialog(parent)
{
setupUi(this);
initData();
initGui();
initSetting();
initNetWork();
}
void RegisterDialog::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
pointOffset = event->globalPos() - frameGeometry().topLeft();
}
else
{
QDialog::mousePressEvent(event);
}
}
void RegisterDialog::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() == Qt::LeftButton)
{
move(event->globalPos() - pointOffset);
if(NULL != regMoreInforForm)
{
int y = this->y() + OFFSET; //加31像素的话就证号从titelBar的下面出来
regMoreInforForm->move(this->x() + this->width(), y);
}
if(NULL != passwdProtectForm)
{
int x = regMoreInforForm->x() + regMoreInforForm->width() - passwdProtectForm->width();
int y = regMoreInforForm->y() + regMoreInforForm->height();
passwdProtectForm->move(x, y);
}
}
else
{
QDialog::mouseMoveEvent(event);
}
}
void RegisterDialog::isCanRegister()
{//这个函数是判断注册按钮是否可以按下的
if(name.length() && passwd.length() && sex.length())
{
if(lineEditPasswd->text() == lineEditPasswdConfirm->text())
{
pushButtonRegister->setEnabled(true);
labelTip->setText(QString::fromUtf8("注册信息已填写完整,可以注册"));
}
else
{
pushButtonRegister->setEnabled(false);
labelTip->setText(QString::fromUtf8("注册信息还未填写完整,请补完!"));
}
}
else
{
pushButtonRegister->setEnabled(false);
labelTip->setText(QString::fromUtf8("注册信息还未填写完整,请补完!"));
}
}
void RegisterDialog::resultForRegister(const QString &str)
{
int pressed = QMessageBox::information(0, QString::fromUtf8("注册结果"), QString::fromUtf8(str.toAscii().data()), QMessageBox::Ok, QMessageBox::Cancel);
if(QMessageBox::Ok == pressed)
{//如果用户选择OK则保留当前注册界面
}
else
{//如果用户选择cancel则关闭注册界面
this->close();
}
}
void RegisterDialog::on_pushButtonClose_clicked()
{
if(NULL != regMoreInforForm)
{
regMoreInforForm->close();
}
if(NULL != passwdProtectForm)
{
passwdProtectForm->close();
}
close();
}
void RegisterDialog::on_pushButtonRegister_clicked()
{//注册按钮被按下
registerTcpSocket->connectToHost(QHostAddress("127.0.0.1"),8888);
}
void RegisterDialog::on_lineEditPasswd_textEdited(const QString &arg1)
{
passwd = arg1;
passwdConfirm = lineEditPasswdConfirm->text();
passwdMatch(passwd, passwdConfirm);
isCanRegister();
}
void RegisterDialog::on_lineEditPasswdConfirm_textEdited(const QString &arg1)
{
passwd = lineEditPasswd->text();
passwdConfirm = arg1;
passwdMatch(passwd, passwdConfirm);
isCanRegister();
}
void RegisterDialog::passwdMatch(const QString &passwd, const QString &passwdConfirm)
{
if(passwd.length() > 0 && passwdConfirm.length() > 0)
{//说明了密码还有密码确认都是有值的
if(passwd != passwdConfirm)
{
qDebug()<<"no match"<<endl;
labelPasswdError->setText(QString::fromUtf8("两次输入的密码不匹配!"));
}
else
{
qDebug()<<"match two string!"<<endl;
labelPasswdError->setText(QString::fromUtf8("两次输入的密码匹配!"));
}
}
else
{
if(passwd.length() > 0)
{
passPart(passwd);
}
else if(passwdConfirm.length() > 0)
{
passPart(passwdConfirm);
}
}
}
void RegisterDialog::slotSelectDate()
{
birthday = dataWidget->selectedDate();
labelDate->setText(birthday.toString("yyyy.MM.dd"));
dataWidget->close();
isCanRegister();
}
void RegisterDialog::on_lineEditName_textChanged(const QString &arg1)
{
name = arg1;
isCanRegister();
}
void RegisterDialog::on_radioMan_clicked()
{
sex = "M";
isCanRegister();
}
void RegisterDialog::on_radioWomem_clicked()
{
sex = "F";
isCanRegister();
}
void RegisterDialog::slotReadUdpDatagramFromServer()
{
qDebug()<<"readUdpDatagramFromServer"<<endl;
QString strRegisterResult;
while(registerUdpSocket->hasPendingDatagrams())
{
QByteArray data;
data.resize(registerUdpSocket->size());
registerUdpSocket->readDatagram(data.data(), data.size());
strRegisterResult = data.data();
}
//////根据服务端的返回信息做下一步回应
//
if(strRegisterResult == QString("REGISTER_SUCCESS"))
{//注册成功则提示注册成功,并询问用户是否继续注册
resultForRegister(QString("注册成功,是否继续注册?"));
}
else if(strRegisterResult == QString("REGISTER_FALSE"))
{//注册成功则提示注册成功,并询问用户是否继续注册
resultForRegister(QString("注册失败,该账户名已经被占用! 是否继续注册?"));
}
}
void RegisterDialog::slotConnectToServerReady()
{
QByteArray bytes;
QDataStream out(&bytes, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_7);
out << (qint32)0;
out << (qint32)1;
out << (qint32)0;
passwd = QCryptographicHash::hash(passwd.toAscii(), QCryptographicHash::Md5).toHex();
//qDebug()<<QString::fromUtf8("注册时候的密码MD5加密值是:")<<passwd<<endl;
out << name << nickName << passwd << sex << birthday << mail
<< question1 << question2 << question3 << answer1 << answer2 << answer3;
///////下面是图片存储传送
out << headImageByte;
///////////////////////////////
//好吧把后面的数据添加在图片的后面
out << animalYears << constellation << blood << province << city << phone;
//////////////////////////////////
out.device()->seek(0);
//out << (qint32)(bytes.size() - (int)sizeof(QString::number(0,10)));
out << (qint32)(bytes.size() - (int)sizeof(qint32));
registerTcpSocket->write(bytes);
qDebug()<<QString::fromUtf8("client send message to server !! ");
//this->close();
}
void RegisterDialog::slotProtectInfor(QByteArray &data)
{//收回密保界面的槽
qDebug()<<QString::fromUtf8("收到密码保护的信号,现在进行处理");
QDataStream in(&data, QIODevice::ReadOnly);
in >> question1 >> question2 >> question3 >> answer1 >> answer2 >> answer3;
//qDebug()<<question1<<question2<<question3<<answer1<<answer2<<answer3<<endl;
//nice之后就开始让密保界面缩回去
if(NULL != passwdProtectForm && NULL != regMoreInforForm)
{//详细界面和密保界面都要存在
QPoint end;
end.setX(passwdProtectForm->x());
end.setY(passwdProtectForm->y() - passwdProtectForm->height());
moveAnimation(passwdProtectForm, passwdProtectForm->pos(), end);
QTimer::singleShot(800, this, SLOT(slotCloseProtectForm()));
}
else
{
qDebug()<<QString::fromUtf8("不满足密保界面回收条件");
}
}
void RegisterDialog::slotShowProtectInfor()
{//弹出密保界面的槽
if(NULL != regMoreInforForm && NULL == passwdProtectForm)
{// 详细信息界面存在 且 密保界面不存在
passwdProtectForm = new PasswdProtectForm;
connect(passwdProtectForm, SIGNAL(signalProtectinfor(QByteArray&)), this, SLOT(slotProtectInfor(QByteArray&)));
QPoint start;
start.setX(regMoreInforForm->x() + regMoreInforForm->width() - passwdProtectForm->width());
start.setY(regMoreInforForm->y());
passwdProtectForm->show();
QPoint end;
end.setX(start.x());
end.setY(regMoreInforForm->y() + regMoreInforForm->height());
moveAnimation(passwdProtectForm, start, end);
}
else
{
qDebug()<<QString::fromUtf8("不满足密保界面弹出条件");
}
}
void RegisterDialog::slotCloseProtectForm()
{//计时器超时响应
//完成密保界面的关闭
if(NULL != passwdProtectForm)
{
passwdProtectForm->close();
}
passwdProtectForm = NULL;
}
void RegisterDialog::slotMoreInfor(QByteArray &data)
{
///先处理详细界面发来的详细注册信息
QDataStream in(&data, QIODevice::ReadOnly);
in >> nickName >> animalYears >> constellation >> blood >> province >> city >> phone >> mail >> headImageByte;
headImagePix.loadFromData(headImageByte, "JPEG");
qDebug()<<QString::fromUtf8("验证以下数据先");
qDebug()<< nickName << animalYears << constellation << blood << province << city << phone << mail;
//在处理详细界面收回的问题
if(NULL != regMoreInforForm)
{//如果详细界面存在才可以收回
QPoint end;
end.setX(regMoreInforForm->x() - regMoreInforForm->width());
end.setY(regMoreInforForm->y());
moveAnimation(regMoreInforForm, regMoreInforForm->pos(), end);
QTimer::singleShot(800, this, SLOT(slotCloseRegMoreForm()));
}
}
void RegisterDialog::slotCloseRegMoreForm()
{
if(NULL != regMoreInforForm)
{
regMoreInforForm->close();
}
regMoreInforForm = NULL;
}
void RegisterDialog::passPlexity(int result, int length)
{//恩阿...这里如此繁杂...有时间我应该把这里改成表驱动
switch(result)
{
case EXITS_NUMBER:
{//1 要#include <qmath.h>
allTime = pow(10, length);
passwdConstTime();
break;
}
case EXITS_LOWER:
{//2
allTime = pow(26, length);
passwdConstTime();
break;
}
case EXITS_NUMBER_LOWER:
{//3
allTime = pow((10+26), length);
passwdConstTime();
break;
}
case EXITS_UPPER:
{//4
allTime = pow(26, length);
passwdConstTime();
break;
}
case EXITS_NUMBER_UPPER:
{//5
allTime = pow((10+26), length);
passwdConstTime();
break;
}
case EXITS_LOWER_UPPER:
{//6
allTime = pow((26+26), length);
passwdConstTime();
break;
}
case EXITS_NUMBER_LOWER_UPPER:
{//7
allTime = pow((10+26+26), length);
passwdConstTime();
break;
}
case EXITS_SIGN:
{//8
allTime = pow(32, length);
passwdConstTime();
break;
}
case EXITS_NUMBER_SIGN:
{//9
allTime = pow((10+32), length);
passwdConstTime();
break;
}
case EXITS_LOWER_SIGN:
{//10
allTime = pow((26+32), length);
passwdConstTime();
break;
}
case EXITS_NUMBER_LOWER_SIGN:
{//11
allTime = pow((10+26+32), length);
passwdConstTime();
break;
}
case EXITS_UPPER_SIGN:
{//12
allTime = pow((26+32), length);
passwdConstTime();
break;
}
case EXITS_NUMBER_UPPER_SIGN:
{//13
allTime = pow((10+26+32), length);
passwdConstTime();
break;
}
case EXITS_LOWER_UPPER_SIGN:
{//14
allTime = pow((26+26+32), length);
passwdConstTime();
break;
}
case EXITS_NUMBER_LOWER_UPPER_SIGN:
{//15
allTime = pow((10+26+26+32), length);
passwdConstTime();
break;
}
default:
{
// qDebug()<<QString::fromUtf8("在分析成分的时候出现了其他的情况");
}
}
// qDebug()<<"allTime "<<allTime;
}
void RegisterDialog::passwdConstTime()
{
if(allTime > 63072000000000)
{
qDebug()<<QString::fromUtf8("人类已经无法破解你的密码了~~");
labelPasswdComplex->setText(QString::fromUtf8("人类已经无法破解你的密码了~~"));
}
else
{
year = allTime / YEAR;
mon = allTime % YEAR / MONTH;
day = allTime % YEAR % MONTH / DAY;
hour = allTime % YEAR % MONTH% DAY / HOUR;
min = allTime % YEAR % MONTH% DAY % HOUR / MINUTE;
sec = allTime % YEAR % MONTH% DAY % HOUR % MINUTE / 20000;
labelPasswdComplex->setText(QString::fromUtf8("穷举此密码大概需要耗时%1年%2月%3天%4小时%5分钟%6秒")
.arg(QString::number(year)).arg(QString::number(mon)).arg(QString::number(day)).arg(QString::number(hour))
.arg(QString::number(min)).arg(QString::number(sec)));
}
}
void RegisterDialog::passPart(const QString &str)
{
int result = 0;
for(int i = 0; i < str.length(); ++i)
{
qDebug()<<"p["<<i<<"] = "<<str[i];
if(str[i].isDigit())
{
qDebug()<<"number";
result |= EXITS_NUMBER;
}
else if(str[i].isLower())
{
qDebug()<<"lower";
result |= EXITS_LOWER;
}
else if(str[i].isUpper())
{
qDebug()<<"upper";
result |= EXITS_UPPER;
}
else
{
qDebug()<<"sign";
result |= EXITS_SIGN;
}
}
qDebug()<<result;
//分析完组成成分之后就可以计算破解所需的理论耗时了
passPlexity(result, str.length());
}
void RegisterDialog::initGui()
{
lineEditPasswd->setEchoMode(QLineEdit::Password);
lineEditPasswdConfirm->setEchoMode(QLineEdit::Password);
pushButtonRegister->setEnabled(false);
labelPasswdError->setText("");
dataWidget = new QCalendarWidget;
labelPasswdComplex->setWordWrap(true);
}
void RegisterDialog::initNetWork()
{
registerUdpSocket = new QUdpSocket(this);
if(!(registerUdpSocket->bind(8000, QUdpSocket::ShareAddress)))
{
qDebug()<<"register dialog has error"<<endl;
qDebug()<<registerUdpSocket->errorString()<<endl;
return;
}
connect(registerUdpSocket, SIGNAL(readyRead()), this, SLOT(slotReadUdpDatagramFromServer()));
registerTcpSocket = new QTcpSocket(this);
connect(registerTcpSocket, SIGNAL(connected()), this, SLOT(slotConnectToServerReady()));
connect(dataWidget, SIGNAL(selectionChanged()), this, SLOT(slotSelectDate()));
}
void RegisterDialog::initData()
{
regMoreInforForm = NULL;
passwdProtectForm = NULL;
///////////////////////////
nickName = "";
animalYears = "";
constellation = "";
blood = "";
province = "";
city = "";
phone = "";
mail = "";
headImagePix = QPixmap();
///////////////////////////
question1 = "";
question2 = "";
question3 = "";
answer1 = "";
answer2 = "";
answer3 = "";
}
void RegisterDialog::initSetting()
{
this->setWindowFlags(Qt::FramelessWindowHint);
this->setAttribute(Qt::WA_TranslucentBackground, true);
this->move(0, 0);
}
void RegisterDialog::moveAnimation(QWidget *widget, QPoint start, QPoint end)
{
if(widget == regMoreInforForm)
{
this->raise();
}
else if(widget == passwdProtectForm)
{
regMoreInforForm->raise();
}
else
{
qDebug()<<QString::fromUtf8("判断widget是regMoreInforForm还是passwdProtectForm出现了问题");
}
QPropertyAnimation *animation = new QPropertyAnimation(widget, "pos");
animation->setDuration(600); //时间
animation->setStartValue(start);
animation->setEndValue(end);
//animation->setEasingCurve(QEasingCurve::OutBounce); //这里是变化的形式
animation->start();
}
void RegisterDialog::on_pushButtonSetDate_clicked()
{
dataWidget->setMinimumDate(QDate(1900, 1, 1));
dataWidget->setMaximumDate(QDate::currentDate());
dataWidget->show();
}
void RegisterDialog::on_pushButtonPasswdProcect_clicked()
{//这里要弹出详细界面了
if(NULL == regMoreInforForm)
{
regMoreInforForm = new RegisterMoreInforForm(birthday);
connect(regMoreInforForm, SIGNAL(signalShowProcect()), this, SLOT(slotShowProtectInfor()));
connect(regMoreInforForm, SIGNAL(signalRegInfor(QByteArray&)), this, SLOT(slotMoreInfor(QByteArray&)));
regMoreInforForm->show();
QPoint start;
start.setX(this->x() + this->width() - regMoreInforForm->width());
start.setY(this->y() + OFFSET);
QPoint end;
end.setX(this->x()+ this->width());
end.setY(start.y());
moveAnimation(regMoreInforForm, start, end);
}
else
{
qDebug()<<"NULL != regMoreInforForm";
}
}
|
#pragma once
//----------------------------------------------------------------------------------------//
//struct
struct _DROP_CHAOS
{
BYTE index[6];
BYTE id[6];
BYTE level[6];
BYTE skill[6];
BYTE luck[6];
BYTE addopt[6];
BYTE addoptex[6];
BYTE addoptanc[6];
};
//----------------------------------------------------------------------------------------//
class _chaos_castle
{
public:
//----------- variavel
int chaos[6];
//----------- struct
_DROP_CHAOS drop[255];
//----------- configurações
void _iniciar_chaos_castle(char * filename);
//----------- funções
void _chaos_drop(LPOBJ lpObj, char vector);
private:
void _reload();
};
//----------------------------------------------------------------------------------------//
//extern
extern _chaos_castle _chaos;
//----------------------------------------------------------------------------------------//
//hook original função
void _chaos_castle_hook(int iChaosCastleIndex, int iWinnerIndex);
|
#include "Helper.h"
#include <fstream>
#include <cassert>
std::vector<char> readFile(const std::string& filename)
{
std::ifstream file(filename, std::ios::ate | std::ios::binary); //ate makes it so you start reading at the end of the file handy for knowing filesize.
if (!file.is_open())
{
assert(0 && "Failed to open file!");
std::exit(-1);
}
size_t fileSize = (size_t)file.tellg();
std::vector<char> buffer(fileSize);
file.seekg(0);
file.read(buffer.data(), fileSize);
file.close();
return buffer;
}
std::string GetFilePath(const std::string& str)
{
size_t found = str.find_last_of("/\\");
return str.substr(0, found);
}
std::string GetSuffix(const std::string& filepath)
{
const size_t pos = filepath.rfind('.');
return (pos == std::string::npos) ? "" : filepath.substr(filepath.rfind('.') + 1);
}
std::string GetFileName(const std::string& filepath, bool removeExtension)
{
std::string fileName = filepath.substr(filepath.find_last_of("/\\") + 1);
if(removeExtension)
{
std::string::size_type const pos(fileName.find_last_of('.'));
fileName = fileName.substr(0, pos);
}
return fileName;
}
|
#include "StdAfx.h"
#include "FrmExitConf.h"
|
class Solution {
public:
vector<int> singleNumbers(vector<int>& nums) { // 位运算
int x = 0, y = 0, n = 0, m = 1;
for (int num : nums) // 遍历异或。我们需要的是结果的第一个不为零的数字在第几位。这代表着两个不同数字在哪一位开始是不同的
// 注:位数是从右往左数的
n ^= num;
while ((n & m) == 0) // 循环左移,计算 m。这个数值就代表了第一个不为0的位数对应的数值。
m <<= 1;
for (int num : nums) { // 遍历,对 nums 进行分组。分成m位置为0和为1的两组数。
if(num & m) x ^= num; // 当 num & m != 0
else y ^= num; // 当 num & m == 0
}
return vector<int> {x, y}; // 返回出现一次的数字。这是因为分组之后,各自组里面相同数字成对出现。对于两个落单的
// 不同数字,一定会分在不同组里面。这时候各自组内异或,即可得到最终结果。
}
};
// reference 《剑指offer》
|
#ifndef CONSOLE_H
#define CONSOLE_H
#include <method.h>
#include <QString>
#include <QFileDialog>
class console{
public:
console();
void Console(bool flagCase_1, bool flagCase_2,int *flagError,string *result, string *analize, QString data);
method *Method;
};
#endif // CONSOLE_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.