blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
807847aa6fc72b4126c842c6d8859df603694063 | 07e21eb8770e719a7cad01a7f376a53d85d9090c | /include/shan/net/context_base.h | 7cdf36b2c49c438c66552e245a9296c5e05ec61b | [
"BSD-2-Clause"
] | permissive | shanpark/Shan.Lib | 8d4b304f53ef9748af4fc5072005e976be84d3b8 | a57de39a026788ddf67e5c2dbb4cae2f3ec62396 | refs/heads/master | 2021-01-17T16:02:05.317128 | 2017-05-17T06:50:05 | 2017-05-17T06:50:05 | 83,308,963 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,200 | h | context_base.h | //
// context_base.h
// Shan.Net
//
// Created by Sung Han Park on 2017. 3. 14..
// Copyright © 2017 Sung Han Park. All rights reserved.
//
#ifndef shan_net_context_base_h
#define shan_net_context_base_h
namespace shan {
namespace net {
// ongoing tasks on channel
using channel_task = uint8_t;
enum : uint8_t {
T_NONE = 0,
T_CONNECT = (1 << 0),
T_HANDSHAKE = (1 << 1),
T_READ = (1 << 2),
T_WRITE = (1 << 3),
T_SHUTDOWN = (1 << 4),
T_BUSY = (T_CONNECT | T_HANDSHAKE | T_READ | T_WRITE)
};
// state of context. The state proceeds only downward, and the context that reached the last state is not reusable.
enum context_stat : uint8_t {
CREATED = 0,
OPEN, // all
STARTED, // acceptor
BOUND, // udp_channel
CONNECTED, // tcp_channel, udp_channel
REQ_CLOSE, // tcp_channel, udp_channel
DISCONNECTED, // tcp_channel, udp_channel
CLOSED // all
};
class context_base : public object, public std::enable_shared_from_this<context_base> {
public:
context_base()
: _done(false), _connected(false), _task_in_progress(T_NONE), _stat(CREATED) {}
void done(bool done) {
_done = done;
}
bool done() {
return _done;
}
object_ptr param() {
return _param;
}
void param(object_ptr p) {
_param = p;
}
protected:
bool connected() {
return _connected;
}
void connected(bool c) {
_connected = c;
}
void set_task_in_progress(channel_task task) {
_task_in_progress |= task;
}
void clear_task_in_progress(channel_task task) {
_task_in_progress &= (~task);
}
bool is_task_in_progress(channel_task task) {
return static_cast<bool>(_task_in_progress | task);
}
bool is_channel_busy() {
return static_cast<bool>(_task_in_progress & T_BUSY);
}
bool settable_stat(context_stat s) {
if (_stat < s) // the state can not proceed reverse direction.
return true;
return false;
}
context_stat stat() {
return _stat;
}
void stat(context_stat s) {
_stat = s;
}
protected:
bool _done;
bool _connected;
channel_task _task_in_progress;
context_stat _stat;
object_ptr _param;
};
} // namespace net
} // namespace shan
#include <shan/net/channel_context.h>
#include <shan/net/acceptor_context.h>
#endif /* shan_net_context_base_h */
|
00f5f8eb210e348e6a318a44a48dce41475c906b | 4338722c4e18133d2ada68b950057072446a4e91 | /DTO/NewGameDTO.h | 6be0fd161be267fa4f8771f39435edc60c70dfa3 | [] | no_license | M2GIL/IataaCppIA | c09d1742b007dd149cb3497d667a123d8f0aab16 | f3f3d5ee749867f79a5c8b28d1a7c6f0d42be7af | refs/heads/master | 2020-06-13T18:35:11.957320 | 2017-01-21T21:58:20 | 2017-01-21T21:58:20 | 75,568,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 724 | h | NewGameDTO.h | #ifndef CHECKERS_REST_IA_C_NEWGAMEDTO_H
#define CHECKERS_REST_IA_C_NEWGAMEDTO_H
#include "AbstractDTO.h"
#include "StatusDTO.h"
#include "../domain/enumeration/Status.h"
using std::string;
namespace Dto {
/**
* Encapsulates a new game response.
*/
class NewGameDTO : public AbstractDTO {
public:
NewGameDTO(Status state, string token, string gameID)
: m_statusDTO(state, token), m_gameID(gameID) {}
virtual ~NewGameDTO() {}
public:
virtual void serialize(PrettyWriter<StringBuffer>&) const;
private:
/**
* Status.
*/
StatusDTO m_statusDTO;
/**
* GameID.
*/
string m_gameID;
};
}
#endif
|
ed9ca0818b1f39d04407cd0af8a48ed33374a0bf | 924780c7e078a900f2f472710a1274a0b11bfe67 | /components/plunFaceDetect/facedetectOpenCV.cpp | eaa6a9249144581d7ab2e2764ea4f779244527be | [
"MIT"
] | permissive | bhlee420/plun | b536dcc6cafb33b1a6ce560851d87befe159ee89 | a79dc160a301eae198ec9983829e0e3d1d280757 | refs/heads/master | 2021-01-23T13:37:37.599592 | 2014-11-10T05:36:14 | 2014-11-10T05:36:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 525 | cpp | facedetectOpenCV.cpp | /*
* facedetectOpenCV.cpp
*
* Created on: 2014. 8. 20.
* Author: hwang-linux
*/
#include "facedetectOpenCV.h"
namespace plun {
facedetectOpenCV::facedetectOpenCV() {
// TODO Auto-generated constructor stub
}
facedetectOpenCV::~facedetectOpenCV() {
// TODO Auto-generated destructor stub
}
void facedetectOpenCV::init()
{
}
vector<Rectangle> facedetectOpenCV::detect(unsigned char* image, unsigned int width, unsigned height)
{
vector<Rectangle> _detected;
return _detected;
}
} /* namespace plun */
|
a4b5f2ff4da4c628ae84a312056acfce9eead0fe | 771b38103191ed8aedaac18e60a2943d33a2e748 | /dowork.h | e3cf5284d6b014f82032f502604ee86446e30f13 | [] | no_license | horvathzoltan/httpapi1 | fe087b2c70525a97dcc49791197fe9a02a4b08c2 | b5c63df04959064b24cc626e2b6d6efb9ec24a63 | refs/heads/master | 2020-04-22T16:03:47.992325 | 2019-03-03T21:12:51 | 2019-03-03T21:12:51 | 170,496,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 741 | h | dowork.h | #ifndef DOWORK_H
#define DOWORK_H
#include "zaction.h"
class doWork
{
public:
doWork();
static zActionResult dolgoz1(const QUrlQuery& param, const QByteArray& content);
static zActionResult dolgoz2(const QUrlQuery& param, const QByteArray& content);
static zActionResult getNextNumber(const QUrlQuery& param, const QByteArray& content);
static zActionResult getHeaderUCtr1(const QUrlQuery& param, const QByteArray& content);
static zActionResult getMainPagetr1(const QUrlQuery& param, const QByteArray& content);
static zActionResult testconnection(const QUrlQuery& param, const QByteArray& content);
static zActionResult login(const QUrlQuery& param, const QByteArray& content);
};
#endif // DOWORK_H
|
a67ff8c9e8d8fb8639c039dccf7f84dbd1fec6a8 | c4165e745412ade20a59bbaad5755ed8f1f54c6a | /Code/Core/include/mapRegistrationKernelInverterBase.h | 9aab73051d6bb239dec51104734070dddd7cab3b | [] | no_license | MIC-DKFZ/MatchPoint | e0e3fb45a274a6de4b6c49397ea1e9b5bbed4620 | a45efdf977418305039df6a4f98efe6e7ed1f578 | refs/heads/master | 2023-06-22T07:52:46.870768 | 2023-06-17T07:43:48 | 2023-06-17T07:43:48 | 186,114,444 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,697 | h | mapRegistrationKernelInverterBase.h | // -----------------------------------------------------------------------
// MatchPoint - DKFZ translational registration framework
//
// Copyright (c) German Cancer Research Center (DKFZ),
// Software development for Integrated Diagnostics and Therapy (SIDT).
// ALL RIGHTS RESERVED.
// See mapCopyright.txt or
// http://www.dkfz.de/en/sidt/projects/MatchPoint/copyright.html
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notices for more information.
//
//------------------------------------------------------------------------
/*!
// @file
// @version $Revision$ (last changed revision)
// @date $Date$ (last change date)
// @author $Author$ (last changed by)
// Subversion HeadURL: $HeadURL$
*/
#ifndef __MAP_REGISTRATION_KERNEL_INVERTER_BASE_H
#define __MAP_REGISTRATION_KERNEL_INVERTER_BASE_H
#include "mapServiceProvider.h"
#include "mapRegistrationKernelBase.h"
namespace map
{
namespace core
{
/*! @class RegistrationKernelInverterBase
* @brief Base class for any instance in MatchPoint that provides kernel inversion services
*
* @ingroup RegOperation
* @tparam VInputDimensions Dimensions of the input space of the kernel that should be inverted.
* @tparam VOutputDimensions Dimensions of the output space of the kernel that should be inverted.
*/
template <unsigned int VInputDimensions, unsigned int VOutputDimensions>
class RegistrationKernelInverterBase : public
services::ServiceProvider< RegistrationKernelBase<VInputDimensions, VOutputDimensions> >
{
public:
typedef RegistrationKernelBase<VInputDimensions, VOutputDimensions> KernelBaseType;
using KernelBasePointer = typename KernelBaseType::Pointer;
typedef RegistrationKernelBase<VOutputDimensions, VInputDimensions> InverseKernelBaseType;
using InverseKernelBasePointer = typename InverseKernelBaseType::Pointer;
using FieldRepresentationType = FieldRepresentationDescriptor<VInputDimensions>;
using InverseFieldRepresentationType = FieldRepresentationDescriptor<VOutputDimensions>;
using RequestType = KernelBaseType;
using NullPointType = typename InverseKernelBaseType::OutputPointType;
/*! Standard class typedefs. */
typedef RegistrationKernelInverterBase<VInputDimensions, VOutputDimensions> Self;
using Superclass = services::ServiceProvider<RequestType>;
using Pointer = itk::SmartPointer<Self>;
using ConstPointer = itk::SmartPointer<const Self>;
itkTypeMacro(RegistrationKernelInverterBase, ServiceProvider);
/*! Generates the inverse kernel.
* Returns a smpart pointer to an inverted version of the kernel.
* @eguarantee strong
* @param [in] request Referenz to the kernel that should be inverted
* @param [in] pFieldRepresentation Pointer to the field representation of the kernel.
* @param [in] pInverseFieldRepresentation Pointer to the field representation of the inverse kernel.
* @return Smart pointer to the inverse kernel.
* @pre The inverter service provider may require the field representation, depending on the kernel.
* e.g. if the kernel cannot be inverted analyticaly the inverse field representation descriptor is
* needed in order to generate a prober field for the inverse kernel.
* To avoid any exceptions always provide the field representation descriptors unless you are sure they
* won't be needed.
* The kernel must be the right type for a concrete inverter. Thus only call this method for kernels for wich
* canHandleRequest returned true.
* @post If the method returns with no exception, there is always an inverse kernel (smart pointer is not NULL)
* @remark This function might cause an exception/assertion if the responsible service provider needs
* a missing field representation descriptor. Also if no suitable provider is available an exception will be thrown.
*/
virtual InverseKernelBasePointer invertKernel(const KernelBaseType& kernel,
const FieldRepresentationType* pFieldRepresentation,
const InverseFieldRepresentationType* pInverseFieldRepresentation, bool useNullPoint = false,
NullPointType nullPoint = NullPointType(itk::NumericTraits< ::map::core::continuous::ScalarType>::NonpositiveMin()))
const = 0;
protected:
RegistrationKernelInverterBase()
{
};
virtual ~RegistrationKernelInverterBase() {};
private:
RegistrationKernelInverterBase(const Self&); //purposely not implemented
void operator=(const Self&); //purposely not implemented
};
} // end namespace core
} // end namespace map
#endif
|
920efb874ff363397a0a12362fca5b7e586e2298 | c5a1dd3ecb89498ca98e49889b1a50be5ff8be5e | /core/api/dut.h | 3d4be173ff987694a3b6dafc1b23c0f90d4d48b5 | [] | no_license | psi46/pxar | c31f14dd2ada1b56ab65ad63dda51b6b2f4a965f | 71ebc53d78589d0ab89be1aad0125549a19ee9b5 | refs/heads/master | 2021-07-25T16:56:05.426288 | 2021-06-10T14:26:01 | 2021-06-10T14:26:01 | 14,920,729 | 22 | 31 | null | 2016-11-15T16:40:39 | 2013-12-04T10:21:12 | C++ | UTF-8 | C++ | false | false | 7,827 | h | dut.h | /**
* pxar DUT class header
* to be included by any executable linking to libpxar
*/
#ifndef PXAR_DUT_H
#define PXAR_DUT_H
/** Declare all classes that need to be included in shared libraries on Windows
* as class DLLEXPORT className
*/
#include "pxardllexport.h"
/** Cannot use stdint.h when running rootcint on WIN32 */
#if ((defined WIN32) && (defined __CINT__))
typedef int int32_t;
typedef short int int16_t;
typedef unsigned int uint32_t;
typedef unsigned short int uint16_t;
typedef unsigned char uint8_t;
#else
#include <stdint.h>
#endif
#include <string>
#include <vector>
#include <map>
#include "datatypes.h"
#include "exceptions.h"
namespace pxar {
class DLLEXPORT dut {
/** Allow the API class to access private members of the DUT - noone else
* should be able to access them!
*/
friend class pxarCore;
public:
/** Default DUT constructor
*/
dut() : _initialized(false), _programmed(false), roc(), tbm(), sig_delays(),
va(0), vd(0), ia(0), id(0), pg_setup(), pg_sum(0), trigger_source(TRG_SEL_PG_DIR) {}
// GET functions to read information
/** Info function printing a listing of the current DUT objects and their states
*/
void info();
/** Function returning the number of enabled pixels on a specific ROC:
*/
size_t getNEnabledPixels(uint8_t rocid);
/** Function returning the number of enabled pixels on all ROCs:
*/
size_t getNEnabledPixels();
/** Function returning the number of masked pixels on a specific ROC:
*/
size_t getNMaskedPixels(uint8_t rocid);
/** Function returning the number of masked pixels on all ROCs:
*/
size_t getNMaskedPixels();
/** Function returning the number of enabled TBMs:
*/
size_t getNEnabledTbms();
/** Function returning the number of TBMs:
*/
size_t getNTbms();
/** Function returning the TBM type programmed:
*/
std::string getTbmType();
/** Function returning the number of enabled ROCs:
*/
size_t getNEnabledRocs();
/** Function returning the number of ROCs:
*/
size_t getNRocs();
/** Function returning the ROC type programmed:
*/
std::string getRocType();
/** Function returning the enabled pixels configs for a specific ROC ID:
*/
std::vector< pixelConfig > getEnabledPixels(size_t rocid);
/** Function returning the enabled pixels configs for a ROC with given I2C address:
*/
std::vector< pixelConfig > getEnabledPixelsI2C(size_t roci2c);
/** Function returning the enabled pixels configs for all ROCs:
*/
std::vector< pixelConfig > getEnabledPixels();
/** Function returning all masked pixels configs for a specific ROC:
*/
std::vector< pixelConfig > getMaskedPixels(size_t rocid);
/** Function returning all masked pixels configs for all ROCs:
*/
std::vector< pixelConfig > getMaskedPixels();
/** Function returning the enabled ROC configs
*/
std::vector< rocConfig > getEnabledRocs();
/** Function returning the Ids of all enabled ROCs in a uint8_t vector:
*/
std::vector< uint8_t > getEnabledRocIDs();
/** Function returning the I2C addresses of all enabled ROCs in a uint8_t vector:
*/
std::vector< uint8_t > getEnabledRocI2Caddr();
/** Function returning the I2C addresses of all ROCs in a uint8_t vector:
*/
std::vector< uint8_t > getRocI2Caddr();
/** Function returning the enabled TBM configs
*/
std::vector< tbmConfig > getEnabledTbms();
/** Function returning the status of a given pixel:
*/
bool getPixelEnabled(uint8_t column, uint8_t row);
/** Function to check if all pixels on all ROCs are enabled:
*/
bool getAllPixelEnable();
/** Function to check if all ROCs of a module are enabled:
*/
bool getModuleEnable();
/** Function returning the configuration of a given pixel:
*/
pixelConfig getPixelConfig(size_t rocid, uint8_t column, uint8_t row);
/** Function to read the current value from a DAC on ROC rocId
*/
uint8_t getDAC(size_t rocId, std::string dacName);
/** Function to read current values from all DAC on ROC rocId
*/
std::vector<std::pair<std::string,uint8_t> > getDACs(size_t rocId);
/** Function to read current values from all DAC on TBM tbmId
*/
std::vector< std::pair<std::string,uint8_t> > getTbmDACs(size_t tbmId);
/** Function returning the token chain lengths:
*/
std::vector<uint8_t> getTbmChainLengths(size_t tbmId);
/** Helper function to print current values from all DAC on ROC rocId
* to stdout
*/
void printDACs(size_t rocId);
/** SET functions to allow enabling and disabling from the outside **/
/** Function to enable the given ROC:
*/
void setROCEnable(size_t rocId, bool enable);
/** Function to enable the given TBM:
*/
void setTBMEnable(size_t tbmId, bool enable);
/** Function to enable the given pixel on all ROCs:
*/
void testPixel(uint8_t column, uint8_t row, bool enable);
/** Function to enable the given pixel on the specified ROC:
*/
void testPixel(uint8_t column, uint8_t row, bool enable, uint8_t rocid);
/** Function to mask the given pixel on all ROCs:
*/
void maskPixel(uint8_t column, uint8_t row, bool mask);
/** Function to mask the given pixel on a specific ROC
*/
void maskPixel(uint8_t column, uint8_t row, bool mask, uint8_t rocid);
/** Function to enable all pixels on all ROCs:
*/
void testAllPixels(bool enable);
/** Function to enable all pixels on a specific ROC "rocid":
*/
void testAllPixels(bool enable, uint8_t rocid);
/** Function to enable all pixels on a specific ROC "rocid":
*/
void maskAllPixels(bool mask, uint8_t rocid);
/** Function to enable all pixels on all ROCs:
*/
void maskAllPixels(bool mask);
/** Function to update all trim bits of a given ROC.
*/
bool updateTrimBits(std::vector<pixelConfig> trimming, uint8_t rocid);
/** Function to update trim bits for one particular pixel on a given ROC.
*/
bool updateTrimBits(uint8_t column, uint8_t row, uint8_t trim, uint8_t rocid);
/** Function to update trim bits for one particular pixel on a given ROC.
*/
bool updateTrimBits(pixelConfig trim, uint8_t rocid);
/** Function to check the status of the DUT
*/
bool status();
private:
/** Initialization status of the DUT instance, marks the "ready for
* operations" status
*/
bool _initialized;
/** Initialization status of the DUT devices, true when successfully
* programmed and ready for operations
*/
bool _programmed;
/** Function returning for every column if it includes an enabled pixel
* for a specific ROC selected by its I2C address:
*/
std::vector< bool > getEnabledColumns(size_t roci2c);
/** DUT member to hold all ROC configurations
*/
std::vector< rocConfig > roc;
/** DUT member to hold all TBM configurations
*/
std::vector< tbmConfig > tbm;
/** DUT member to hold all DTB signal delay configurations
*/
std::map<uint8_t,uint8_t> sig_delays;
/** Variables to store the DTB power limit settings
*/
double va, vd, ia, id;
/** DUT member to store the current Pattern Generator command list
*/
std::vector<std::pair<uint16_t,uint8_t> > pg_setup;
/** DUT member to store the delay sum of the full Pattern Generator
* command list
*/
uint32_t pg_sum;
/** DUT member to store the selected trigger source to be activated
*/
uint16_t trigger_source;
}; //class DUT
} //namespace pxar
#endif /* PXAR_DUT_H */
|
c62ce5e929061ffa83e679e493987b3429c2ef29 | a5edb9bc455f8e1e4cb7e20842ab0eeb8f602049 | /include/lwiot/device/dhtsensor.h | 47c780174c6283c79448e1518eecd27a84d83732 | [
"Apache-2.0"
] | permissive | lwIoT/lwiot-core | 32d148b4527c9ca9f4b9716bd89ae10d4a99030e | 07d2a3ba962aef508911e453268427b006c57701 | refs/heads/master | 2020-03-13T06:47:44.493308 | 2019-08-30T15:15:21 | 2019-08-30T15:15:21 | 131,012,032 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 707 | h | dhtsensor.h | /*
* DHT sensor definition.
*
* @author Michel Megens
* @email dev@bietje.net
*/
#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <lwiot.h>
#include <lwiot/io/gpiopin.h>
#include <lwiot/io/dhtbus.h>
namespace lwiot
{
typedef enum {
DHT11,
DHT22
} dht_type_t;
class DhtSensor {
public:
explicit DhtSensor(const GpioPin& pin, dht_type_t type = DHT22);
virtual ~DhtSensor() = default;
bool read(float& humidity, float& temperature);
const dht_type_t& type() const;
private:
DhtBus _io;
dht_type_t _type;
/* Methods */
int16_t convert(uint8_t msb, uint8_t lsb);
bool read(int16_t& humid, int16_t& temperature);
};
}
|
cbd05ae0bfc4cc532d761cce3a1eee83f79d9706 | defe9bd7e4da966552279ca1a7fe8c1a7c77aa31 | /_memoria_.h | ad47d950f283f781ab3de2482e67fbcf8dafecbd | [] | no_license | jPAREb/PdS | a2f82439f304a7fccad23b8827acbe4aab316d76 | 4b93721455062d7ab1e0d2f2f1652f7c7d408682 | refs/heads/master | 2022-11-18T09:09:20.953611 | 2020-07-01T00:03:32 | 2020-07-01T00:03:32 | 275,794,411 | 0 | 1 | null | 2021-06-27T09:20:41 | 2020-06-29T11:30:34 | C++ | ISO-8859-2 | C++ | false | false | 666 | h | _memoria_.h | #pragma once
#include <iostream>
#include <windows.h>
#include <vector>
using namespace std;
vector<ULARGE_INTEGER> _memoria_() {
ULARGE_INTEGER bits_lliures_cridar, bits_total, bits_lliure;
GetDiskFreeSpaceEx(L".", &bits_lliures_cridar, &bits_total, &bits_lliure);
vector <ULARGE_INTEGER> memoria;
memoria.push_back(bits_total);
memoria.push_back(bits_lliure);
//ALTRE OPCIÓ PER VEURE LA MEMORIA
//MEMORYSTATUSEX statex;
//statex.dwLength = sizeof(statex);
//GlobalMemoryStatusEx(&statex);
//cout << "Total System Memory: " << (statex.ullTotalPhys / 1024) / 1024 << "MB" << endl;
return memoria;
} |
8450b2479cfbd527e88875ee76659097577bcd3d | 44a17902fe132720dc71ee0b02dae6a388f36df4 | /2021/Final/F.cpp | 6c893e0c1caf8e83e9d7b146f7ec83ee8d5b9e99 | [] | no_license | wupsi/PP1_2021_Spring | 3ac83b090dc19ae35d28a73659624fb16f1566ef | 914acb647fec29a78bd8bc6ac91cff6c861396ae | refs/heads/main | 2023-07-28T21:25:35.297747 | 2021-09-14T01:17:25 | 2021-09-14T01:17:25 | 406,180,042 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 181 | cpp | F.cpp | #include <iostream>
using namespace std;
int main(){
string str; cin >> str;
sub = "abcdefghijklmnopqrstuvwxyz";
for(int i = 0; i < str.size(); i++){
}
} |
2c51c356aff2e5a314ee3f8d256abc4de5a85516 | a214b27b156c24f0e19fe16622f3bd4692cd5332 | /Ejemplo/v11/Mensaje.cpp | 173dac4e7bab110285d909a8dced142e11db30dd | [] | no_license | Drolegc/EjemploLab | c05b7f381b5382f4069e307213ca72c78b7ebaf9 | 9e4340ab2e612dcd9dbeb37e4279e57f73891cb7 | refs/heads/master | 2020-06-03T05:14:05.833620 | 2019-06-12T03:34:04 | 2019-06-12T03:34:04 | 191,455,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 495 | cpp | Mensaje.cpp | // Mensaje.cpp
#include "Mensaje.h"
#include "HoraSistema.h"
Mensaje::Mensaje(string texto, string email)
: t {texto}, emailEmisor {email}
{
HoraSistema* hs = HoraSistema::getInstance();
fyh = hs->darFechaYHora();
}
FechaYHora Mensaje::darFechaYHora()
{
return fyh;
}
string Mensaje::darTexto()
{
return t;
}
DtMensaje Mensaje::darDtMensaje()
{
DtMensaje res {fyh, t, emailEmisor};
return res;
}
string Mensaje::darEmailEmisor()
{
return emailEmisor;
}
|
332b7e68a9b72ad15c72649d78db5aab69f0dd68 | cf7a6b56e58c52c9eb23164db743a1af2c047514 | /impl/json_array.cpp | f1d7d8c1aca8c2ced96d560054dead80447e434e | [] | no_license | tigerinsky/json | 20fc1d4e07d35956ab8d14349d235268fbdfda7c | 2514454e7ddc0f4f3e34949b6229125074ac1d0a | refs/heads/master | 2020-05-31T13:00:37.164856 | 2015-05-29T02:56:47 | 2015-05-29T02:56:47 | 35,756,095 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 632 | cpp | json_array.cpp | #include "../json_obj.h"
namespace tis {
namespace json {
size_t JsonArray::size() const {
return _vector.size();
}
JsonObj*& JsonArray::operator[](size_t idx){
return _vector[idx];
}
JsonObj* JsonArray::get(size_t idx) const {
return _vector[idx];
}
void JsonArray::push_back(JsonObj* obj) {
_vector.push_back(obj);
}
std::ostream& operator<<(std::ostream& os, const JsonArray& arr) {
os << '[';
for (size_t i = 0; i < arr.size() - 1; ++i) {
os << *(arr.get(i));
os << ", ";
}
if (arr.size() > 0) {
os << *(arr.get(arr.size() - 1));
}
return os << ']';
}
}
}
|
cc9368328e83ea55df8e413d0e833784e5ceac2c | ddf4fe5a0d37cee6c5c7122454497e3e378989fb | /src/base/WCSimTrajectory.cc | c941eab039a00b0db5b34cb1e480ce0723720377 | [
"MIT"
] | permissive | chipsneutrino/chips-sim | 83e9b1f7639f2f2cfb61350dca5878aec1dc173c | 19d3f2d75c674c06d2f27b9a344b70ca53e672c5 | refs/heads/master | 2022-11-25T16:14:27.887589 | 2020-07-27T16:43:36 | 2020-07-27T16:43:36 | 266,086,454 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,044 | cc | WCSimTrajectory.cc | #include "WCSimTrajectory.hh"
#include "G4TrajectoryPoint.hh"
#include "G4ParticleTypes.hh"
#include "G4ParticleTable.hh"
#include "G4AttDefStore.hh"
#include "G4AttDef.hh"
#include "G4AttValue.hh"
#include "G4UnitsTable.hh"
#include "G4VProcess.hh"
#include <sstream>
//G4Allocator<WCSimTrajectory> aTrajectoryAllocator;
G4Allocator<WCSimTrajectory> myTrajectoryAllocator;
WCSimTrajectory::WCSimTrajectory() : positionRecord(0), fTrackID(0), fParentID(0), fProcessID(0), PDGEncoding(0), PDGCharge(0.0), ParticleName(""), initialMomentum(
G4ThreeVector()),
fEnergy(0.0), fParticleDirection(G4ThreeVector()), fParticlePosition(G4ThreeVector()), fVtxX(
0.0),
fVtxY(0.0), fVtxZ(0.0), fVtxDirX(0.0), fVtxDirY(0.0), fVtxDirZ(0.0), fIsOpticalPhoton(false), fIsScatteredPhoton(
false),
SaveIt(false), creatorProcess(""), globalTime(0.0)
{
;
}
WCSimTrajectory::WCSimTrajectory(const G4Track *aTrack)
{
G4ParticleDefinition *fpParticleDefinition = aTrack->GetDefinition();
ParticleName = fpParticleDefinition->GetParticleName();
PDGCharge = fpParticleDefinition->GetPDGCharge();
PDGEncoding = fpParticleDefinition->GetPDGEncoding();
fTrackID = aTrack->GetTrackID();
fParentID = aTrack->GetParentID();
if (aTrack->GetCreatorProcess())
{
G4VProcess *theCreatorProcess = (G4VProcess *)(aTrack->GetCreatorProcess());
fProcessID = theCreatorProcess->GetProcessType();
}
initialMomentum = aTrack->GetMomentum();
fParticlePosition = aTrack->GetPosition();
fParticleDirection = initialMomentum.unit();
fVtxX = fParticlePosition.x();
fVtxY = fParticlePosition.y();
fVtxZ = fParticlePosition.z();
fVtxTime = aTrack->GetGlobalTime();
fVtxDirX = fParticleDirection.x();
fVtxDirY = fParticleDirection.y();
fVtxDirZ = fParticleDirection.z();
fEnergy = aTrack->GetKineticEnergy();
positionRecord = new TrajectoryPointContainer();
// Following is for the first trajectory point
positionRecord->push_back(new G4TrajectoryPoint(aTrack->GetPosition()));
stoppingPoint = aTrack->GetPosition();
stoppingVolume = aTrack->GetVolume();
if (aTrack->GetUserInformation() != 0)
SaveIt = true;
else
SaveIt = false;
globalTime = aTrack->GetGlobalTime();
if (aTrack->GetCreatorProcess() != 0)
{
const G4VProcess *tempproc = aTrack->GetCreatorProcess();
creatorProcess = tempproc->GetProcessName();
}
else
creatorProcess = "";
fIsOpticalPhoton = 0;
fIsScatteredPhoton = 0;
if (fpParticleDefinition && fpParticleDefinition == G4OpticalPhoton::OpticalPhotonDefinition())
{
fIsOpticalPhoton = 1;
if (fProcessID == 3)
fIsScatteredPhoton = 1;
}
}
WCSimTrajectory::WCSimTrajectory(WCSimTrajectory &right) : G4VTrajectory()
{
ParticleName = right.ParticleName;
PDGCharge = right.PDGCharge;
PDGEncoding = right.PDGEncoding;
fTrackID = right.fTrackID;
fParentID = right.fParentID;
fProcessID = right.fProcessID;
initialMomentum = right.initialMomentum;
positionRecord = new TrajectoryPointContainer();
fVtxX = right.fVtxX;
fVtxY = right.fVtxY;
fVtxZ = right.fVtxZ;
fVtxTime = right.fVtxTime;
fVtxDirX = right.fVtxDirX;
fVtxDirY = right.fVtxDirY;
fVtxDirZ = right.fVtxDirZ;
stoppingPoint = right.stoppingPoint;
stoppingVolume = right.stoppingVolume;
fEndTime = right.fEndTime;
SaveIt = right.SaveIt;
creatorProcess = right.creatorProcess;
for (size_t i = 0; i < right.positionRecord->size(); i++)
{
G4TrajectoryPoint *rightPoint = (G4TrajectoryPoint *)((*(right.positionRecord))[i]);
positionRecord->push_back(new G4TrajectoryPoint(*rightPoint));
}
globalTime = right.globalTime;
}
WCSimTrajectory::~WCSimTrajectory()
{
// positionRecord->clearAndDestroy();
size_t i;
for (i = 0; i < positionRecord->size(); i++)
{
delete (*positionRecord)[i];
}
positionRecord->clear();
delete positionRecord;
}
void WCSimTrajectory::ShowTrajectory(std::ostream &os) const
{
// Invoke the default implementation in G4VTrajectory...
G4VTrajectory::ShowTrajectory(os);
// ... or override with your own code here.
}
void WCSimTrajectory::DrawTrajectory(G4int i_mode) const
{
// Invoke the default implementation in G4VTrajectory...
G4VTrajectory::DrawTrajectory();
// ... or override with your own code here.
}
const std::map<G4String, G4AttDef> *WCSimTrajectory::GetAttDefs() const
{
G4bool isNew;
std::map<G4String, G4AttDef> *store = G4AttDefStore::GetInstance("WCSimTrajectory", isNew);
if (isNew)
{
G4String ID("ID");
(*store)[ID] = G4AttDef(ID, "Track ID", "Bookkeeping", "", "G4int");
G4String PID("PID");
(*store)[PID] = G4AttDef(PID, "Parent ID", "Bookkeeping", "", "G4int");
G4String PN("PN");
(*store)[PN] = G4AttDef(PN, "Particle Name", "Physics", "", "G4String");
G4String Ch("Ch");
(*store)[Ch] = G4AttDef(Ch, "Charge", "Physics", "", "G4double");
G4String PDG("PDG");
(*store)[PDG] = G4AttDef(PDG, "PDG Encoding", "Physics", "", "G4int");
G4String IMom("IMom");
(*store)[IMom] = G4AttDef(IMom, "Momentum of track at start of trajectory", "Physics", "", "G4ThreeVector");
G4String NTP("NTP");
(*store)[NTP] = G4AttDef(NTP, "No. of points", "Physics", "", "G4int");
}
return store;
}
std::vector<G4AttValue> *WCSimTrajectory::CreateAttValues() const
{
char c[100];
//std::ostrstream s(c,100);
std::ostringstream s(c);
std::vector<G4AttValue> *values = new std::vector<G4AttValue>;
s.seekp(std::ios::beg);
s << fTrackID << std::ends;
values->push_back(G4AttValue("ID", c, ""));
s.seekp(std::ios::beg);
s << fParentID << std::ends;
values->push_back(G4AttValue("PID", c, ""));
values->push_back(G4AttValue("PN", ParticleName, ""));
s.seekp(std::ios::beg);
s << PDGCharge << std::ends;
values->push_back(G4AttValue("Ch", c, ""));
s.seekp(std::ios::beg);
s << PDGEncoding << std::ends;
values->push_back(G4AttValue("PDG", c, ""));
s.seekp(std::ios::beg);
s << G4BestUnit(initialMomentum, "Energy") << std::ends;
values->push_back(G4AttValue("IMom", c, ""));
s.seekp(std::ios::beg);
s << GetPointEntries() << std::ends;
values->push_back(G4AttValue("NTP", c, ""));
return values;
}
void WCSimTrajectory::AppendStep(const G4Step *aStep)
{
positionRecord->push_back(new G4TrajectoryPoint(aStep->GetPostStepPoint()->GetPosition()));
}
G4ParticleDefinition *WCSimTrajectory::GetParticleDefinition()
{
return (G4ParticleTable::GetParticleTable()->FindParticle(ParticleName));
}
void WCSimTrajectory::MergeTrajectory(G4VTrajectory *secondTrajectory)
{
if (!secondTrajectory)
return;
WCSimTrajectory *seco = (WCSimTrajectory *)secondTrajectory;
stoppingPoint = seco->stoppingPoint;
stoppingVolume = seco->stoppingVolume;
G4int ent = seco->GetPointEntries();
for (G4int i = 1; i < ent; i++) // initial point of the second trajectory should not be merged
{
positionRecord->push_back((*(seco->positionRecord))[i]);
// positionRecord->push_back(seco->positionRecord->removeAt(1));
}
delete (*seco->positionRecord)[0];
seco->positionRecord->clear();
}
|
db75caaff3a1405d8aa52918a9f21c10aee21e73 | 0d802f71dfeb703f3e20c4091cbcf583a48bc8c9 | /main-2.cpp | fcd566db639e65ae66da2b1d0e8cb47cf7486a7a | [] | no_license | finaldestroyer/Cs1 | 4f6c67e5d5efffcaea8c4b8b279e9dfca92ec8db | 0a2df61c7c99f0f06464a65a500f715a13fbe519 | refs/heads/main | 2023-02-09T14:00:41.397078 | 2020-12-29T15:04:41 | 2020-12-29T15:04:41 | 325,315,366 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,755 | cpp | main-2.cpp | #include <iostream>
using namespace std;
int
main ()
{
string ok = "";
string character = "";
string poke = "";
string monster = "";
cout << "What is your favorite anime? Pokemon or Naruto or Yugioh?" << endl;
cin >> ok;
if (ok == "pokemon" || ok == "Pokemon")
{
cout << "Oh that's cool." << endl;
cout << "What's your favorite pokemon? Pikachu or Charmander?" << endl;
cin >> poke;
if (poke == "pikachu" || poke == "Pikachu")
{
cout << "Pikachu use thunderbolt" << endl;
}
else if (poke == "Charmander" || poke == "charmander")
{
cout << "Charmander use Fire Blast" << endl;
}
else
{
cout << "You have failed to answer my question" << endl;
return 0;
}
}
if (ok == "Naruto" || ok == "naruto")
{
cout << "Oh that's cool." << endl;
cout << "Who is your favorite character? Naruto or Sasuke?" << endl;
cin >> character;
if (character == "naruto" || character == "Naruto")
{
cout << "Rasengan" << endl;
}
else if (character == "sasuke" || character == "sasuke")
{
cout << "Chidori" << endl;
}
else
{
cout << "You have failed to answer my question" << endl;
return 0;
}
}
if (ok == "yugioh" || ok == "Yugioh")
{
cout <<
"Who's you favorite monster? Dark Magician or Blue-eyes White Dragon? Please spell it how I spelled it."
<< endl;
cin >> monster;
if (monster == "Dark Magician" || monster == "Blue-eyes White Dragon")
{
cout << "DU DU DU DU DUUUUUUEEEEELLLL!!!! " << endl;
}
else
{
cout << "You have failed to answer my question" << endl;
return 0;
}
}
else
{
cout << "You have failed to answer my question" << endl;
return 0;
}
return 0;
}
|
6b11433a14030cfba463ecb6b45692314b8d21ee | 881a20a31c85f04f81a32957b9522022c47f1c20 | /02_Fraction/test.cpp | e05b82d8c9052d038b3ca4ead987ad8cda15af99 | [] | no_license | Hfdxbr/Tasks_for_Bogdan | eab5eb6bc4c2c35b4c9adcfcf1580c4ae3701ce6 | ef44209cccd37f9dead23ee0899c6c7ac5e23bc7 | refs/heads/master | 2020-12-20T17:15:17.539031 | 2020-06-28T19:59:12 | 2020-06-28T19:59:25 | 236,151,445 | 0 | 0 | null | 2020-06-28T20:17:22 | 2020-01-25T09:47:44 | C++ | UTF-8 | C++ | false | false | 761 | cpp | test.cpp | #include "../test_runner.h"
#include "fraction.h"
void Test_addition() {
for (int i = -99; i < 100; ++i)
for (int j = -99; j < 100; ++j)
ASSERT_EQUAL(Fraction(i) + Fraction(j), Fraction(i + j));
for (int i = -99; i < 100; ++i)
for (int j = -99; j < 100; ++j) {
Fraction x(i);
x += Fraction(j);
ASSERT_EQUAL(x, Fraction(i + j));
}
for (int n1 = -99; n1 < 100; ++n1)
for (int d1 = 1; d1 < 100; ++d1)
for (int n2 = -99; n2 < 100; ++n2)
for (int d2 = 1; d2 < 100; ++d2) {
Fraction x(n1, d1);
Fraction y(n2, d2);
ASSERT_EQUAL(x + y, Fraction(n1 * d2 + n2 * d1, d1 * d2));
}
}
int main() {
TestRunner tr;
RUN_TEST(tr, Test_addition);
/* Tests */
return 0;
}
|
61b47b11c3a4d59c390130d1fdf911b779b29371 | fae677f03642eb13ab0dce406295c10ec8f31def | /tsc_globaldata.h | 0b71f1aeea10361d95dde844dc2277b83b1843bf | [] | no_license | bobthepiman/TwoStepperControl | b9985afec100a0b60b6d7c35f1e82900d708fe3c | a67e0aec034c05a2620e326c577f7fbee240630f | refs/heads/master | 2020-12-30T16:27:07.500211 | 2017-05-07T22:26:39 | 2017-05-07T22:26:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,767 | h | tsc_globaldata.h | #ifndef TSC_GLOBALDATA_H
#define TSC_GLOBALDATA_H
#include <QElapsedTimer>
#include <QImage>
#include <fstream>
#include <string>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <sstream>
class TSC_GlobalData {
public:
TSC_GlobalData(void);
~TSC_GlobalData(void);
void storeGlobalData(void);
bool loadGlobalData(void); // trying to load a "TSC_Preferences.tsc" datafile in the home directory
void setINDIState(bool); // true if INDI-Server is connected
bool getINDIState(void);
void setInitialStarPosition(float, float); // store the coordinates of the last click - the routine converts it also to ccd-coordinates
float getInitialStarPosition(short); // 0 is screen x, 1 is screen y, 2 is ccd x and 3 is ccd y
void setCameraDisplaySize(int, int); // set the size of the widget that displays the camera image
int getCameraDisplaySize(short);
float getCameraImageScalingFactor(void); // get the factor that is used to scale the CCD image to the widget size
void setCameraImageScalingFactor(float);
void setCameraParameters(float, float, int, int); // set ccd pixelsize x, y and ccd chip width and height in pixels
float getCameraPixelSize(short); // 0 for width in microns in x, 1 for y
int getCameraChipPixels(short); // get ccd width and height, 0 for x and 1 for y
void setSyncPosition(float, float); // when syncing, set RA and decl in decimal format (degrees)
float getSyncPositionCoords(short); // 0 for decimal RA, 1 for declination- the monotonic timer "monotonicGlobalTimer" starts
bool wasMountSynced(void); // get the sync-state ...
qint64 getTimeSinceLastSync(void); // get time in milliseconds since last sync
void setGearData(float,float,float,float,float,float,float,float,float); // store data on stepper gears and stepsize
float getGearData(short); //0 for planetary ratio for RA, 1 for other in RA, 2 for # of wormwheels, 3 for stepsize in RA, 4,5,6 and 7 for declination, 8 for microstep-resolution
void setDriveData(short, int); // 0 for controller ID of RA, 1 for ID of Decl
int getDriveID(short); // 0 for controller ID of RA, 1 for ID of Decl
void setDriveParams(short, short, double); // 0 for RA, 1 for decl, 0 for speed, 1 for Acc, 2 for Current, and the value
double getDriveParams(short, short); // 0 for RA, 1 for decl and 0 for speed, 1, for Acc and 2 for current
double getActualScopePosition(short); // 0 for hour angle, 1 for decl, 2 for RA
void incrementActualScopePosition(double, double); // add hour angle and decl increments
void storeCameraImage(QImage);
void setGuideScopeFocalLength(int); // FL of guidescope in mm
int getGuideScopeFocalLength(void);
bool getGuidingState(void); // check if system is in autoguiding state
void setGuidingState(bool);
bool getTrackingMode(void); // a global variable checking if the mount is tracking or slewing
void setTrackingMode(bool);
void setSiteParams(double, double, double); // latitude, longitude and UTC offset of site
void setSiteParams(QString); // set the name of the site
double getSiteCoords(short); // get coordinates of site
QString getSiteName(void); // get name of site
QImage* getCameraImage(void); // retrieve the topical image from the guiding camera
QString* getBTMACAddress(void); // get the MAC address of the BT-adapter
void setLX200IPAddress(QString); // store the IP address for LX200
QString* getLX200IPAddress(void); // get IP address for LX200
void setLocalSTime(double);
double getLocalSTime(void);
void setCelestialSpeed(short);
double getCelestialSpeed(void);
private:
QElapsedTimer *monotonicGlobalTimer;
double localSiderealTime;
bool INDIServerIsConnected;
bool guidingState;
bool isInTrackingMode;
QImage *currentCameraImage;
int guideScopeFocalLength;
QString *BTMACAddress;
QString *LX200IPAddress;
double celestialSpeed;
struct initialStarPosStruct {
float screenx;
float screeny;
float ccdx;
float ccdy;
};
struct cameraDisplaySizeStruct {
int width;
int height;
float scalingFactor;
};
struct cameraParametersStruct {
float pixelSizeMicronsX;
float pixelSizeMicronsY;
int chipWidth;
int chipHeight;
};
struct syncPositionStruct {
float rightAscension;
float declination;
qint64 timeSinceSyncInMS;
bool mountWasSynced;
};
struct gearDataStruct {
float planetaryRatioRA;
float gearRatioRA;
float wormSizeRA;
float stepSizeRA;
float planetaryRatioDecl;
float gearRatioDecl;
float wormSizeDecl;
float stepSizeDecl;
float microsteps;
};
struct driveDataStruct {
int RAControllerID;
int DeclControllerID;
double actualRASpeed;
double actualDeclSpeed;
double driveAccRA;
double driveAccDecl;
double driveCurrRA;
double driveCurrDecl;
};
struct actualScopePositionStruct {
double actualHA;
double actualDecl;
double actualRA;
};
struct siteParamsStruct {
double longitude;
double latitude;
QString siteName;
double UTCOffset;
};
struct initialStarPosStruct initialStarPos;
struct cameraDisplaySizeStruct cameraDisplaySize;
struct cameraParametersStruct cameraParameters;
struct syncPositionStruct syncPosition;
struct gearDataStruct gearData;
struct driveDataStruct driveData;
struct actualScopePositionStruct actualScopePosition;
struct siteParamsStruct siteParams;
};
#endif // TSC_GLOBALDATA_H
|
f7ede688c9b6d6519b5a67085f6863b394742bf8 | e36e49d2cd31a28097fa1f066b5e65915c19e858 | /lib/Gfx/Texture.cpp | 1f80ec30a8b0aebde91fd5235b72428e07ab98f8 | [
"Zlib",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | axia-sw/Doll | 9074e8a4b3dfcc6c02ea9abd78c2ae5f33f0da75 | a5846a6553d9809e9a0ea50db2dc18b95eb21921 | refs/heads/master | 2021-06-28T13:22:16.857790 | 2020-12-18T12:35:14 | 2020-12-18T12:35:14 | 74,479,497 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,170 | cpp | Texture.cpp | #define DOLL_TRACE_FACILITY doll::kLog_GfxTexture
#include "../BuildSettings.hpp"
#include "doll/Gfx/Texture.hpp"
#include "doll/Gfx/API-GL.hpp"
#include "doll/IO/File.hpp"
#include "doll/Core/Logger.hpp"
#include "doll/Core/Memory.hpp"
#include "doll/Core/MemoryTags.hpp"
#include "doll/Math/Math.hpp"
#include <png.h>
static void *doll__stbi_malloc( size_t n, const char *f, unsigned l, const char *fn )
{
AX_ASSERT_NOT_NULL( doll::gDefaultAllocator );
doll::IAllocator &a = *doll::gDefaultAllocator;
void *const p = a.alloc( n + sizeof( size_t ), doll::kTag_Texture, f, l, fn );
if( !p ) {
return ( void * )0;
}
size_t *const pn = ( size_t * )p;
*pn = n;
return ( void * )( pn + 1 );
}
static void *doll__stbi_realloc( void *p, size_t n, const char *f, unsigned l, const char *fn )
{
AX_ASSERT_NOT_NULL( doll::gDefaultAllocator );
doll::IAllocator &a = *doll::gDefaultAllocator;
void *const q = a.alloc( n + sizeof( size_t ), doll::kTag_Texture, f, l, fn );
if( !q ) {
return ( void * )0;
}
if( p != ( void * )0 ) {
const size_t *pn = ( ( const size_t * )p ) - 1;
const size_t oldn = *pn;
const size_t cpyn = oldn < n ? oldn : n;
doll::Mem::copy( q, p, cpyn );
a.dealloc( ( void * )pn, f, l, fn );
}
size_t *const qn = ( size_t * )q;
*qn = n;
return ( void * )( qn + 1 );
}
static void doll__stbi_free( void *p, const char *f, unsigned l, const char *fn )
{
AX_ASSERT_NOT_NULL( doll::gDefaultAllocator );
doll::IAllocator &a = *doll::gDefaultAllocator;
if( !p ) {
return;
}
size_t *const pn = ( ( size_t * )p ) - 1;
a.dealloc( ( void * )pn, f, l, fn );
}
#define STB_IMAGE_IMPLEMENTATION
#define STBI_NO_STDIO
#define STBI_NO_HDR
#define STBI_NO_LINEAR
#define STBI_ASSERT\
AX_ASSERT
#define STBI_MALLOC(N_)\
doll__stbi_malloc((size_t)(N_),__FILE__,__LINE__,AX_FUNCTION)
#define STBI_REALLOC(P_,N_)\
doll__stbi_realloc((void*)(P_),(size_t)(N_),__FILE__,__LINE__,AX_FUNCTION)
#define STBI_FREE(P_)\
doll__stbi_free((void*)(P_),__FILE__,__LINE__,AX_FUNCTION)
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4312)
# pragma warning(disable:4456)
# pragma warning(disable:4457)
# pragma warning(disable:6001)
# pragma warning(disable:6011)
# pragma warning(disable:6246)
# pragma warning(disable:6262)
# pragma warning(disable:6385)
#endif
#ifdef __GNUC__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wunused-function"
# pragma GCC diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wint-to-pointer-cast"
#endif
#include <stb_image.h>
#ifdef __clang__
# pragma clang diagnostic pop
#endif
#ifdef __GNUC__
//# pragma GCC diagnostic pop
#endif
#ifdef _MSC_VER
# pragma warning(pop)
#endif
namespace doll
{
MTextures MTextures::instance;
MTextures &g_textureMgr = MTextures::instance;
DOLL_FUNC Bool DOLL_API gfx_isTextureResolutionValid( U16 resX, U16 resY )
{
// must be square
if( resX!=resY ) {
return false;
}
// must be in range
if( !resX || resX>16384 ) {
return false;
}
// must be a power of two
if( !bitIsPowerOfTwo( resX ) ) {
return false;
}
// meets requirements; this is valid
return true;
}
class LoadingTexture {
enum class ELoadResult {
success,
failure,
keepSearching
};
enum class ELoadType {
none,
png,
stb
};
ELoadResult loadPNG( const Str &filename, const TArr<U8> &data );
ELoadResult loadViaSTB( const Str &filename, const TArr<U8> &data );
U32 m_res_x, m_res_y;
U8 *m_data;
ELoadType m_loadedType;
TMutArr<U8> m_ownedBuffer;
ETextureFormat m_format;
U32 m_channels;
struct LibpngReadData {
TArr<U8> data;
UPtr offset;
};
static void libpngRead_f( png_structp pngptr, png_bytep data, png_size_t length ) {
LibpngReadData *const io = reinterpret_cast< LibpngReadData * >( png_get_io_ptr( pngptr ) );
AX_ASSERT_NOT_NULL( io );
AX_ASSERT( io->data.isUsed() );
if( io->offset + length > io->data.num() || io->offset + length < io->offset ) {
png_error( pngptr, "Read error" );
}
memcpy( data, io->data.get() + io->offset, length );
io->offset += length;
}
struct LibpngMessageData {
const LoadingTexture *loading;
Str filename;
};
static void libpngError_f( png_structp pngptr, png_const_charp message ) {
const LibpngMessageData *const data = reinterpret_cast< LibpngMessageData * >( png_get_error_ptr( pngptr ) );
AX_ASSERT_NOT_NULL( data );
g_ErrorLog( data->filename ) += Str( message );
longjmp( png_jmpbuf( pngptr ), 1 );
}
static void libpngWarning_f( png_structp pngptr, png_const_charp message ) {
const LibpngMessageData *const data = reinterpret_cast< LibpngMessageData * >( png_get_error_ptr( pngptr ) );
AX_ASSERT_NOT_NULL( data );
g_WarningLog( data->filename ) += Str( message );
}
public:
LoadingTexture()
: m_res_x( 0 )
, m_res_y( 0 )
, m_data( nullptr )
, m_loadedType( ELoadType::none )
, m_ownedBuffer()
, m_format( kTexFmtRGB8 )
, m_channels( 0 )
{
}
~LoadingTexture() {
fini();
}
Bool load( Str filename, TArr<U8> data ) {
ELoadResult r;
AX_ASSERT_MSG( m_loadedType == ELoadType::none, "Already initialized" );
if( ( r = loadPNG( filename, data ) ) != ELoadResult::keepSearching ) {
AX_ASSERT( r == ELoadResult::failure || m_loadedType == ELoadType::png );
return r == ELoadResult::success;
}
if( ( r = loadViaSTB( filename, data ) ) != ELoadResult::keepSearching ) {
AX_ASSERT( r == ELoadResult::failure || m_loadedType == ELoadType::stb );
return r == ELoadResult::success;
}
return false;
}
Void fini() {
switch( m_loadedType ) {
case ELoadType::none:
break;
case ELoadType::png:
m_ownedBuffer.clear();
m_data = nullptr;
break;
case ELoadType::stb:
AX_ASSERT_NOT_NULL( m_data );
m_data = ( stbi_image_free( m_data ), nullptr );
break;
}
m_loadedType = ELoadType::none;
m_res_x = 0;
m_res_y = 0;
}
U32 res_x() const { return m_res_x; }
U32 res_y() const { return m_res_y; }
ETextureFormat format() const { return kTexFmtRGBA8; }
U32 channels() const { return 4; }
U8 *data() const { AX_ASSERT_NOT_NULL( m_data ); return m_data; }
};
LoadingTexture::ELoadResult LoadingTexture::loadPNG( const Str &filename, const TArr<U8> &data ) {
static const U32 kMaxPNGRes = 16384;
static const UPtr kPNGSigSize = 8;
if( data.num() < kPNGSigSize ) {
if( filename.getExtension().caseCmp( ".png" ) ) {
g_WarningLog( filename ) += "PNG file is too small";
}
return ELoadResult::keepSearching;
}
if( !png_check_sig( ( const png_byte * )data.get(), kPNGSigSize ) ) {
if( filename.getExtension().caseCmp( ".png" ) ) {
g_WarningLog( filename ) += "Has '.png' extension, but not a valid PNG file";
}
return ELoadResult::keepSearching;
}
LibpngMessageData msgdata;
msgdata.loading = this;
msgdata.filename = filename;
png_structp pngptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, (png_voidp)&msgdata, &libpngError_f, &libpngWarning_f );
if( !pngptr ) {
g_ErrorLog( filename ) += "Failed to create PNG read struct";
return ELoadResult::failure;
}
png_infop infoptr = png_create_info_struct( pngptr );
if( !infoptr ) {
g_ErrorLog( filename ) += "Failed to create PNG info struct";
png_destroy_read_struct( &pngptr, nullptr, nullptr );
return ELoadResult::failure;
}
png_set_user_limits( pngptr, kMaxPNGRes, kMaxPNGRes );
LibpngReadData iodata;
iodata.data = data;
iodata.offset = 0;
png_set_read_fn( pngptr, &iodata, &libpngRead_f );
TMutArr<png_bytep> rows;
if( setjmp( png_jmpbuf( pngptr ) ) ) {
png_destroy_read_struct( &pngptr, &infoptr, nullptr );
m_ownedBuffer.purge();
return ELoadResult::failure;
}
png_set_sig_bytes( pngptr, 0 );
png_read_info( pngptr, infoptr );
const int pngbitdepth = png_get_bit_depth( pngptr, infoptr );
const int pngcolortype = png_get_color_type( pngptr, infoptr );
if( pngcolortype == PNG_COLOR_TYPE_PALETTE ) {
png_set_palette_to_rgb( pngptr );
} else if( pngcolortype == PNG_COLOR_TYPE_GRAY && pngbitdepth < 8 ) {
png_set_expand_gray_1_2_4_to_8( pngptr );
}
png_set_gray_to_rgb( pngptr );
if( png_get_valid( pngptr, infoptr, PNG_INFO_tRNS ) ) {
png_set_tRNS_to_alpha( pngptr );
}
if( pngbitdepth == 16 ) {
png_set_strip_16( pngptr );
} else if( pngbitdepth < 8 ) {
png_set_packing( pngptr );
}
png_read_update_info( pngptr, infoptr );
char buf[ 128 ];
const U32 pngresx = png_get_image_width( pngptr, infoptr );
const U32 pngresy = png_get_image_height( pngptr, infoptr );
switch( png_get_color_type( pngptr, infoptr ) ) {
case PNG_COLOR_TYPE_GRAY:
m_format = kTexFmtRGB8;
m_channels = 3;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
m_format = kTexFmtRGBA8;
m_channels = 4;
break;
case PNG_COLOR_TYPE_RGB:
m_format = kTexFmtRGB8;
m_channels = 3;
break;
case PNG_COLOR_TYPE_RGB_ALPHA:
m_format = kTexFmtRGBA8;
m_channels = 4;
break;
default:
g_ErrorLog( filename ) += ( axspf( buf, "Unknown color type: %i", int( png_get_color_type( pngptr, infoptr ) ) ), buf );
longjmp( png_jmpbuf( pngptr ), 1 );
}
g_VerboseLog( filename ) += ( axspf( buf, "PNG resolution: %ux%u", pngresx, pngresy ), buf );
g_DebugLog += buf;
if( pngresx > kMaxPNGRes || pngresy > kMaxPNGRes ) {
g_ErrorLog( filename ) += ( axspf( buf, "PNG is too large (%ux%u exceeds maximum of %u on any axis)", pngresx, pngresy, kMaxPNGRes ), buf );
longjmp( png_jmpbuf( pngptr ), 1 );
}
if( !rows.reserve( axarr_size_t( pngresy ) ) ) {
g_ErrorLog( filename ) += "Failed to allocate PNG row pointers";
longjmp( png_jmpbuf( pngptr ), 1 );
}
if( !m_ownedBuffer.resize( pngresx*pngresy*m_channels ) ) {
g_ErrorLog( filename ) += "Failed to allocate PNG image data";
longjmp( png_jmpbuf( pngptr ), 1 );
}
do {
const U32 stride = pngresx*m_channels;
rows.resize( pngresy );
for( U32 y = 0; y < pngresy; ++y ) {
rows[ pngresy - ( y + 1 ) ] = m_ownedBuffer.pointer( y*stride );
}
} while( false );
png_set_rows( pngptr, infoptr, rows.pointer() );
png_read_image( pngptr, rows.pointer() );
png_read_end( pngptr, nullptr );
png_destroy_read_struct( &pngptr, &infoptr, nullptr );
m_res_x = pngresx;
m_res_y = pngresy;
m_data = m_ownedBuffer.pointer();
// Done
m_loadedType = ELoadType::png;
return ELoadResult::success;
}
LoadingTexture::ELoadResult LoadingTexture::loadViaSTB( const Str &filename, const TArr<U8> &data ) {
// Check if it's a known extension
do {
static const Str knownexts[] = {
".png", ".jpg", ".bmp", ".tga", ".psd", ".dds"
};
const Str fileext( filename.getExtension() );
Bool found = false;
for( const Str &testext : knownexts ) {
if( fileext.caseCmp( testext ) ) {
found = true;
break;
}
}
if( !found ) {
return ELoadResult::keepSearching;
}
} while( false );
stbi_set_flip_vertically_on_load( 1 );
// Try loading the data into memory
do {
int w = 0, h = 0, c = 0;
auto *image = stbi_load_from_memory( ( const stbi_uc * )data.get(), int(ptrdiff_t(data.num())), &w, &h, &c, STBI_rgb_alpha );
if( !image ) {
return ELoadResult::failure;
}
m_data = reinterpret_cast< U8 * >( image );
m_res_x = static_cast< U32 >( w );
m_res_y = static_cast< U32 >( h );
} while( false );
// Done
m_loadedType = ELoadType::stb;
return ELoadResult::success;
}
/*
===============================================================================
RECTANGLE ALLOCATOR
For a given rectangular region, this manages the possible allocations
within it.
===============================================================================
*/
// constructor
CRectangleAllocator::CRectangleAllocator()
: head( nullptr )
, tail( nullptr )
{
resolution.x = 0;
resolution.y = 0;
}
// destructor
CRectangleAllocator::~CRectangleAllocator()
{
fini();
}
// initialize
Bool CRectangleAllocator::init( const SPixelVec2 &res )
{
// already initialized?
if( head!=nullptr ) {
return true;
}
// register the total resolution (must be done before allocating free space
// node; otherwise the asserts will fail)
resolution.x = res.x;
resolution.y = res.y;
// create the initial free space node
SNode *const p = allocateNode( 0, 0, res.x, res.y );
if( !p ) {
return false;
}
// the system is in the valid initial state
return true;
}
// finish
Void CRectangleAllocator::fini()
{
// don't waste time doing proper unlinks
#if _MSC_VER
# pragma warning(push)
# pragma warning(disable:6001) //... false positive? "uninitialized memory"
#endif
while( head!=nullptr ) {
SNode *next = head->next;
free( ( Void * )head );
head = next;
}
#if _MSC_VER
# pragma warning(pop)
#endif
// nullify this setting so it's not accidentally used
tail = nullptr;
// there's no resolution anymore
resolution.x = 0;
resolution.y = 0;
}
// allocate an identifier, returning a token
Void *CRectangleAllocator::allocateId( SPixelRect &rect, U16 textureId, const SPixelVec2 &res )
{
AX_ASSERT_MSG( textureId>0, "textureId is required" );
AX_ASSERT_MSG( res.x>0, "resolution must be specified" );
AX_ASSERT_MSG( res.y>0, "resolution must be specified" );
SNode *const best = findBestFitNode( res.x, res.y );
if( !best ) {
return nullptr;
}
if( best->rect.res.x > res.x + 2 || best->rect.res.y > res.y + 2 ) {
if( !splitNode( best, textureId, res.x, res.y ) ) {
return nullptr;
}
}
rect = best->rect;
return ( Void * )best;
}
// deallocate a previously allocated identifier
Void CRectangleAllocator::freeId( Void *p )
{
if( !p ) {
return;
}
#if AX_DEBUG_ENABLED
// ensure the passed node was allocated in here
SNode *test;
for( test=head; test!=nullptr; test=test->next ) {
if( test==( SNode * )p ) {
break;
}
}
// if this is nullptr it means we exhausted the whole list without finding the
// node; therefore the pointer passed is invalid either because it was
// already removed from the list -or- it was never in this list to begin
// with
AX_ASSERT_MSG( test!=nullptr, "node must exist in this allocator" );
#endif
SNode *node = ( SNode * )p;
node->textureId = 0;
mergeAdjacentFreeNodes( node );
}
// allocate a free-space node
CRectangleAllocator::SNode *CRectangleAllocator::allocateNode( U16 offX, U16 offY, U16 resX, U16 resY )
{
SNode *node;
// verify parameters
AX_ASSERT_MSG( resX>0, "resolution must be specified" );
AX_ASSERT_MSG( resY>0, "resolution must be specified" );
AX_ASSERT_MSG( ( offX + resX )<=resolution.x, "node must fit" );
AX_ASSERT_MSG( ( offY + resY )<=resolution.y, "node must fit" );
// NOTE: we don't check for intersections because when a split occurs it
// has to operate without altering the existing node
// allocate
node = ( SNode * )malloc( sizeof( *node ) );
if( !node ) {
return nullptr;
}
// default settings (free space)
node->textureId = 0;
node->rect.off.x = offX;
node->rect.off.y = offY;
node->rect.res.x = resX;
node->rect.res.y = resY;
// link
node->next = nullptr;
node->prev = tail;
if( node->prev!=nullptr ) {
node->prev->next = node;
} else {
head = node;
}
tail = node;
g_DebugLog += axf( "Allocated %ux%u node at (%u,%u -> %u,%u)", +resX, +resY, +offX, +offY, offX+resX, offY+resY );
// node is ready now
return node;
}
// deallocate a node (it's okay to pass nullptr in)
Void CRectangleAllocator::freeNode( SNode *node )
{
// accept nullptr input; we need to manually unlink so we can't just pass to
// free
if( !node ) {
return;
}
// unlink
if( node->prev!=nullptr ) {
node->prev->next = node->next;
} else {
head = node->next;
}
if( node->next!=nullptr ) {
node->next->prev = node->prev;
} else {
tail = node->prev;
}
// now deallocate the memory
free( ( Void * )node );
}
// find the node which has the best fit for this
CRectangleAllocator::SNode *CRectangleAllocator::findBestFitNode( U16 resX, U16 resY ) const
{
// ensure parameters match
AX_ASSERT_MSG( resX>0, "resolution must be specified" );
AX_ASSERT_MSG( resY>0, "resolution must be specified" );
// early exit for nodes that would be too big
if( resX>resolution.x || resY>resolution.y ) {
return nullptr;
}
// scoring system
struct SScoredNode
{
SNode *node;
U32 score;
};
SScoredNode best = { nullptr, ~0U };
// find the node with the least wasted space
for( SNode *node=head; node!=nullptr; node=node->next ) {
// skip if minimum requirements aren't met
if( node->textureId!=0 ) {
continue;
}
if( node->rect.res.x<resX || node->rect.res.y<resY ) {
continue;
}
// construct the test object
SScoredNode test = {
node,
( ( U32 )node->rect.res.x )*( ( U32 )node->rect.res.y )
};
// test against the current high score and keep the better of the two
if( test.score<best.score ) {
best = test;
}
}
// return the currently selected node (nullptr if none met minimum reqs)
return best.node;
}
// split a node into one-to-three nodes, marking one as used
Bool CRectangleAllocator::splitNode( SNode *node, U16 textureId, U16 resX, U16 resY )
{
// ensure all the parameters match
AX_ASSERT_MSG( node!=nullptr, "node is required" );
AX_ASSERT_MSG( node->textureId==0, "node must be free" ); //must be a free node
AX_ASSERT_MSG( textureId>0, "must specify texture" );
AX_ASSERT_MSG( resX>0, "resolution is required" );
AX_ASSERT_MSG( resY>0, "resolution is required" );
AX_ASSERT_MSG( resX<=node->rect.res.x, "resolution must fit" );
AX_ASSERT_MSG( resY<=node->rect.res.y, "resolution must fit" );
// figure out the remaining space
U16 splitRes[ 2 ] = {
( U16 )( node->rect.res.x - resX ),
( U16 )( node->rect.res.y - resY )
};
U32 bestSplit = splitRes[ 0 ]>splitRes[ 1 ] ? 0 : 1;
// select the offsets of each remaining point
SPixelVec2 splitPoints[ 2 ] = {
{ ( U16 )( node->rect.off.x + resX ), node->rect.off.y },
{ node->rect.off.x, ( U16 )( node->rect.off.y + resY ) }
};
SPixelVec2 splitExtents[ 2 ] = {
{ splitRes[ 0 ], bestSplit==0 ? node->rect.res.y : resY },
{ bestSplit==1 ? node->rect.res.x : resX, splitRes[ 1 ] }
};
// splits
SNode *splits[ 2 ] = { nullptr, nullptr };
// make each split
for( U32 i=0; i<2; ++i ) {
// don't make a split here if there's no space
if( splitRes[ i ]==0 ) {
continue;
}
// there's space for the split; allocate
splits[ i ] = allocateNode( splitPoints[ i ].x, splitPoints[ i ].y, splitExtents[ i ].x, splitExtents[ i ].y );
if( !splits[ i ] ) {
// ... clean up (don't leave false free nodes!)
if( i==1 ) {
freeNode( splits[ 0 ] );
}
// we could not allocate
return false;
}
}
// list this node as an allocated texture (with the specified resolution)
node->textureId = textureId;
node->rect.res.x = resX;
node->rect.res.y = resY;
g_DebugLog += axf( "Marked %ux%u node at (%u,%u -> %u,%u)", resX, resY, node->rect.off.x, node->rect.off.y, node->rect.off.x+resX, node->rect.off.y+resY );
// the node now marked and the partitions are in a valid state
return true;
}
static Bool isAdjacent( const SPixelRect &a, const SPixelRect &b )
{
if( a.off.x + a.res.x == b.off.x || a.off.x == b.off.x + b.res.x ) {
return a.off.y == b.off.y && a.res.y == b.res.y;
}
if( a.off.y + a.res.y == b.off.y || a.off.y == b.off.y + b.res.y ) {
return a.off.x == b.off.x && a.res.x == b.res.x;
}
return false;
}
UPtr CRectangleAllocator::findAdjacentFreeNodes( SNode **out_nodes, UPtr maxOutNodes, SNode *node ) const
{
AX_ASSERT_NOT_NULL( out_nodes );
AX_ASSERT( maxOutNodes >= 4 );
AX_ASSERT_NOT_NULL( node );
UPtr cAdjNodes = 0;
const SPixelRect &mainRect = node->rect;
for( SNode *p = head; p != nullptr; p = p->next ) {
if( p == node || p->textureId != 0 || !isAdjacent( p->rect, mainRect ) ) {
continue;
}
out_nodes[ cAdjNodes++ ] = p;
if( cAdjNodes == maxOutNodes ) {
break;
}
}
return cAdjNodes;
}
Void CRectangleAllocator::mergeAdjacentFreeNodes( SNode *node )
{
static const UPtr kMaxAdjNodes = 4;
SNode *pAdjNodes[ kMaxAdjNodes ];
const UPtr cAdjNodes = findAdjacentFreeNodes( pAdjNodes, kMaxAdjNodes, node );
for( UPtr i = 0; i < cAdjNodes; ++i ) {
AX_ASSERT_NOT_NULL( pAdjNodes[ i ] );
SNode &adj = *pAdjNodes[ i ];
SPixelRect &rc = adj.rect;
if( rc.off.x < node->rect.off.x ) {
//AX_ASSERT( rc.off.y == node->rect.off.y );
node->rect.off.x = rc.off.x;
node->rect.res.x += rc.res.x;
} else if( rc.off.x > node->rect.off.x ) {
//AX_ASSERT( rc.off.y == node->rect.off.y );
node->rect.res.x += rc.res.x;
} else if( rc.off.y < node->rect.off.y ) {
//AX_ASSERT( rc.off.x == node->rect.off.x );
node->rect.off.y = rc.off.y;
node->rect.res.y += rc.res.y;
} else if( rc.off.y > node->rect.off.y ) {
//AX_ASSERT( rc.off.x == node->rect.off.x );
node->rect.res.y += rc.res.y;
}
freeNode( pAdjNodes[ i ] );
pAdjNodes[ i ] = nullptr;
}
}
/*
===============================================================================
TEXTURE MANAGER
Controls all of the texture atlases, which in turn control all of the
textures.
===============================================================================
*/
// constructor
MTextures::MTextures()
: textures()
, freeIds()
, freeIds_sp(0)
, defAtlasRes(0)
, mgrAtlas_list()
, mgrTex_list()
{
for( freeIds_sp=0; freeIds_sp<0xFFFF; ++freeIds_sp ) {
freeIds[ freeIds_sp ] = 0xFFFF - freeIds_sp;
}
defAtlasRes = 1024;
}
// destructor
MTextures::~MTextures()
{
}
// pushes an "available for use" (free) texture identifier to the internal stack
Void MTextures::pushFreeTextureId( U16 textureId )
{
AX_ASSERT_MSG( textureId>0, "Should not be pushing the nullptr id" );
AX_ASSERT_MSG( freeIds_sp<MAX_TEXTURES - 1, "Should not have a full stack" );
freeIds[ freeIds_sp++ ] = textureId;
}
// pops a free texture identifier from the internal stack
U16 MTextures::popFreeTextureId()
{
if( freeIds_sp==0 ) {
return 0;
}
return freeIds[ --freeIds_sp ];
}
// make a new texture
RTexture *MTextures::makeTexture( U16 width, U16 height, const Void *data, ETextureFormat format, CTextureAtlas *specificAtlas )
{
CTextureAtlas *atlas = nullptr;
RTexture *tex = nullptr;
Bool atlasWasFound = false;
// check the parameters
if( !AX_VERIFY_NOT_NULL( data ) ) {
return nullptr;
}
if( !AX_VERIFY_MSG( width > 0 && height > 0, "Invalid resolution" ) ) {
return nullptr;
}
// try to allocate from an existing atlas first
if( specificAtlas != nullptr ) {
if( !AX_VERIFY_MSG( specificAtlas->getFormat() == format, "Invalid format for atlas" ) ) {
return nullptr;
}
atlasWasFound = true;
atlas = specificAtlas;
tex = atlas->reserveTexture( width, height );
if( !AX_VERIFY_MSG( tex != nullptr, "Atlas can't fit texture" ) ) {
return nullptr;
}
} else {
for( atlas = mgrAtlas_list.head(); atlas != nullptr; atlas = atlas->mgrAtlas_link.next() ) {
if( atlas->getFormat() != format ) {
continue;
}
tex = atlas->reserveTexture( width, height );
if( tex!=nullptr ) {
atlasWasFound = true;
break;
}
}
}
// if we couldn't allocate the texture through an existing atlas, allocate
// a new atlas altogether
if( !tex ) {
const U16 res = g_textureMgr.getDefaultAtlasResolution();
atlas = allocateAtlas( format, res, res );
if( !AX_VERIFY_MSG( atlas!=nullptr, "Atlas allocate failed" ) ) {
return nullptr;
}
tex = atlas->reserveTexture( width, height );
if( !AX_VERIFY_MSG( tex!=nullptr, "Reserve texture failed" ) ) {
delete atlas;
return nullptr;
}
}
#if DOLL_TEXTURE_MEMORY_ENABLED
const UPtr totalSize = width*height*gfx_getTexelByteSize( format );
if( !AX_VERIFY_MSG( tex->copyMemory( data, totalSize ), "Copy memory failed" ) ) {
goto fail;
}
//
// TODO: Optimize the updates so it's done before the texture is needed
// - automatically, with an optional `flushTextureUpdates` command or
// - something like that to do it before then.
//
// update the atlas
if( !AX_VERIFY_MSG( atlas->updateTextures( 1, &tex ), "Textures failed to update" ) ) {
goto fail;
}
#else
if( !atlas->updateTexture( tex, format, data ) ) {
goto fail;
}
#endif
// done
return tex;
fail:
delete tex;
tex = nullptr;
if( atlasWasFound ) {
delete atlas;
atlas = nullptr;
}
return nullptr;
}
// load up a new texture
RTexture *MTextures::loadTexture( Str filename, CTextureAtlas *specificAtlas )
{
//
// XXX: This needs to be fixed to support RGB8 too
//
LoadingTexture loading;
// load the file
do {
U8 *filedata = nullptr;
UPtr filesize = 0;
if( !core_loadFile( filename, filedata, filesize, kTag_Texture ) ) {
return nullptr;
}
// try to load up the image
const Bool didLoad = loading.load( filename, TArr<U8>(filedata, filesize) );
core_freeFile( filedata );
if( !didLoad ) {
g_DebugLog( filename ) += "Failed to load image.";
return nullptr;
}
} while( false );
const U32 width = loading.res_x();
const U32 height = loading.res_y();
const ETextureFormat format = loading.format();
const U32 channels = loading.channels();
U8 *const data = loading.data();
// swap colors then copy the memory over
for( U32 y=0; y<height; ++y ) {
for( U32 x=0; x<width; ++x ) {
U8 *const off = &data[ ( y*width + x )*channels ];
const U8 tmp = off[ 2 ];
off[ 2 ] = off[ 0 ];
off[ 0 ] = tmp;
}
}
// load the image as an actual texture
RTexture *const tex = makeTexture( width, height, ( Void * )data, format, specificAtlas );
// done
return tex;
}
// allocate a texture atlas with the properties given
CTextureAtlas *MTextures::allocateAtlas( ETextureFormat fmt, U16 resX, U16 resY )
{
CTextureAtlas *const atlas = new CTextureAtlas();
if( !AX_VERIFY_MEMORY( atlas ) ) {
return nullptr;
}
mgrAtlas_list.addTail( atlas->mgrAtlas_link );
if( !AX_VERIFY_MSG( atlas->init( fmt, resX, resY ), "Init failed" ) ) {
delete atlas;
return nullptr;
}
return atlas;
}
// retrieve the texture handle from the identifier given
RTexture *MTextures::getTextureById( U16 textureId ) const
{
return textures[ textureId ];
}
// retrieve the number of textures allocated
U16 MTextures::getAllocatedTexturesCount() const
{
return ( MAX_TEXTURES - 1 ) - freeIds_sp;
}
// register a texture with a system returning its internal identifier
U16 MTextures::procureTextureId()
{
return popFreeTextureId();
}
// store the value of a registered texture
Void MTextures::setHandleForTextureId( U16 textureId, RTexture *handle )
{
AX_ASSERT_MSG( textureId!=0, "Invalid texture identifier" );
AX_ASSERT_MSG( handle!=nullptr, "Invalid texture handle" );
AX_ASSERT_MSG( textures[ textureId ]==nullptr, "RTexture already set" );
textures[ textureId ] = handle;
}
// unregister a texture from the system, nullifying the internal pointer
Void MTextures::nullifyTextureId( U16 textureId )
{
AX_ASSERT_MSG( textures[ textureId ]!=nullptr, "RTexture not set" );
textures[ textureId ] = nullptr;
pushFreeTextureId( textureId );
}
/*
===============================================================================
TEXTURE ATLAS
===============================================================================
*/
// constructor
CTextureAtlas::CTextureAtlas()
: mgrAtlas_link( this )
, texture( 0 )
, resolution()
, format( kTexFmtRGBA8 )
, allocator()
, atlas_list()
{
resolution.x = 0;
resolution.y = 0;
}
// destructor
CTextureAtlas::~CTextureAtlas()
{
fini();
mgrAtlas_link.unlink();
}
// initialize the atlas with the given format and resolution
Bool CTextureAtlas::init( ETextureFormat fmt, U16 resX, U16 resY )
{
AX_ASSERT_MSG( texture == 0, "RTexture already initialized" );
AX_ASSERT_MSG( gfx_isTextureResolutionValid( resX, resY ), "Invalid resolution" );
// set the resolution
resolution.x = resX;
resolution.y = resY;
// must initialize the rectangle allocator
if( !AX_VERIFY_MSG( allocator.init( resolution ), "allocator init failed" ) ) {
return false;
}
// allocate the texture
if( !AX_VERIFY_MSG( ( texture = gfx_r_createTexture( fmt, resX, resY, nullptr ) ) != 0, "Failed to create texture" ) ) {
allocator.fini();
return false;
}
// set the format
format = fmt;
// done
return true;
}
// finish the atlas
Void CTextureAtlas::fini()
{
if( !texture ) {
return;
}
TIntrLink< RTexture > *link, *next;
for( link=atlas_list.headLink(); link!=nullptr; link=next ) {
next = link->nextLink();
RTexture *const tex = link->node();
AX_ASSERT_NOT_NULL( tex );
tex->fini();
}
allocator.fini();
gfx_r_destroyTexture( texture );
texture = 0;
}
#if DOLL_TEXTURE_MEMORY_ENABLED
// supply a list of updates to the atlas
Bool CTextureAtlas::updateTextures( UPtr numTextures, const RTexture *const *textures )
{
AX_ASSERT_MSG( textures!=nullptr, "Need the texture array" );
if( !numTextures ) {
return true;
}
for( UPtr i=0; i<numTextures; ++i ) {
const RTexture *const src = textures[ i ];
AX_ASSERT_NOT_NULL( src );
const U8 *const mem = ( const U8 * )src->getMemoryPointer();
if( !mem ) {
continue;
}
const SPixelRect srcRect = src->getAtlasRectangle();
const SPixelVec2 srcRes = src->getResolution();
gfx_r_updateTexture( texture, srcRect.off.x, srcRect.off.y, srcRes.x, srcRes.y, mem );
}
return true;
}
#else
// update a texture in the atlas
Bool CTextureAtlas::updateTexture( const RTexture *tex, ETextureFormat fmt, const Void *data )
{
AX_ASSERT_NOT_NULL( tex );
AX_ASSERT( tex->atlas == this );
const SPixelRect rc = tex->getAtlasRectangle();
const SPixelVec2 sz = tex->getResolution();
( void )fmt;
gfx_r_updateTexture( texture, rc.off.x, rc.off.y, sz.x, sz.y, ( const U8 * )data );
return true;
}
#endif
// allocate a texture within this system
RTexture *CTextureAtlas::reserveTexture( U16 width, U16 height )
{
SPixelRect texRect;
SPixelVec2 texRes;
U16 texId;
texId = g_textureMgr.procureTextureId();
if( !AX_VERIFY_MSG( texId!=0, "No more textures available" ) ) {
return nullptr;
}
texRes.x = width;
texRes.y = height;
Void *const texNode = allocator.allocateId( texRect, texId, texRes );
if( !texNode ) {
return nullptr;
}
RTexture *const texPtr = new RTexture( this, texRect, texNode, texId );
if( !AX_VERIFY_MEMORY( texPtr ) ) {
return nullptr;
}
g_textureMgr.setHandleForTextureId( texId, texPtr );
atlas_list.addTail( texPtr->atlas_link );
g_textureMgr.mgrTex_list.addTail( texPtr->mgrTex_link );
return texPtr;
}
/*
===============================================================================
TEXTURE
===============================================================================
*/
// constructor
RTexture::RTexture( CTextureAtlas *mainAtlas, const SPixelRect &rect, Void *allocNode, U16 textureId )
: atlas( mainAtlas )
, texRect( rect )
, allocNode( allocNode )
, ident( textureId )
, name( nullptr )
#if DOLL_TEXTURE_MEMORY_ENABLED
, memory( nullptr )
#endif
{
AX_ASSERT_MSG( mainAtlas!=nullptr, "Cannot pass nullptr for the atlas" );
AX_ASSERT_MSG( allocNode!=nullptr, "You need a valid allocation node" );
}
// destructor
RTexture::~RTexture()
{
fini();
}
// translate coordinates of this texture into the texture atlas
Void RTexture::translateCoordinates( STextureRect &dst, const SPixelRect &src ) const
{
static const int negateAmount = 1;
SPixelRect adjSrc;
SPixelRect atlasCoords;
adjSrc.off.x = src.off.x >= texRect.res.x ? 0 : src.off.x;
adjSrc.off.y = src.off.y >= texRect.res.y ? 0 : src.off.y;
adjSrc.res.x = adjSrc.off.x + src.res.x > texRect.res.x ? texRect.res.x : src.res.x;
adjSrc.res.y = adjSrc.off.y + src.res.y > texRect.res.y ? texRect.res.y : src.res.y;
atlasCoords.res.x = ( adjSrc.res.x - negateAmount );
atlasCoords.res.y = ( adjSrc.res.y - negateAmount );
atlasCoords.off.x = texRect.off.x + adjSrc.off.x;
atlasCoords.off.y = texRect.off.y + adjSrc.off.y;
const SPixelVec2 atlasRes = atlas->getResolution();
const Vec2f texOff = Vec2f( 1.0f/F32( atlasRes.x ), 1.0f/F32( atlasRes.y ) );
//const Vec2f texOff( 0.0f, 0.0f );
dst.pos[ 0 ] = texOff.x/2 + ( F32 )atlasCoords.off.x/( F32 )atlasRes.x;
dst.pos[ 1 ] = texOff.y/2 + ( F32 )atlasCoords.off.y/( F32 )atlasRes.y;
dst.res[ 0 ] = texOff.x/2 + ( F32 )atlasCoords.res.x/( F32 )atlasRes.x;
dst.res[ 1 ] = texOff.y/2 + ( F32 )atlasCoords.res.y/( F32 )atlasRes.y;
#if 0
static int iDebugCount = 0;
if( iDebugCount == 2 ) {
return;
}
++iDebugCount;
g_DebugLog += axf( "%ux%u block at (%u,%u) becomes %.4fx%.4f units at (%.4f,%.4f)", src.res.x, src.res.y, atlasCoords.off.x, atlasCoords.off.y, dst.res[0], dst.res[1], dst.pos[0], dst.pos[1] );
#endif
}
// set the name of this texture
Bool RTexture::setName( Str newName )
{
if( newName.isEmpty() ) {
name.purge();
return true;
}
name.clear();
return AX_VERIFY_MEMORY( name.tryAssign( newName ) );
}
// retrieve the name of this texture
Str RTexture::getName() const
{
return name;
}
// finish
Void RTexture::fini()
{
if( !atlas ) {
return;
}
AX_ASSERT_MSG( allocNode!=nullptr, "Invalid texture object" );
#if DOLL_TEXTURE_MEMORY_ENABLED
delete [] memory;
memory = nullptr;
#endif
atlas->freeNode( allocNode );
allocNode = nullptr;
atlas_link.unlink();
atlas = nullptr;
if( ident!=0 ) {
g_textureMgr.nullifyTextureId( ident );
}
texRect.off.x = 0;
texRect.off.y = 0;
texRect.res.x = 0;
texRect.res.y = 0;
name.purge();
}
DOLL_FUNC CTextureAtlas *DOLL_API gfx_newTextureAtlas( U16 resX, U16 resY, U16 format )
{
return g_textureMgr.allocateAtlas( ( ETextureFormat )format, resX, resY );
}
DOLL_FUNC CTextureAtlas *DOLL_API gfx_deleteTextureAtlas( CTextureAtlas *atlas )
{
delete atlas;
return nullptr;
}
DOLL_FUNC RTexture *DOLL_API gfx_newTexture( U16 width, U16 height, const void *data, ETextureFormat format )
{
return g_textureMgr.makeTexture( width, height, data, format );
}
DOLL_FUNC RTexture *DOLL_API gfx_newTextureInAtlas( U16 width, U16 height, const void *data, ETextureFormat format, CTextureAtlas *atlas )
{
AX_ASSERT_NOT_NULL( atlas );
return g_textureMgr.makeTexture( width, height, data, format, atlas );
}
DOLL_FUNC RTexture *DOLL_API gfx_loadTexture( Str filename )
{
AX_ASSERT( filename.isUsed() );
return g_textureMgr.loadTexture( filename );
}
DOLL_FUNC RTexture *DOLL_API gfx_loadTextureInAtlas( Str filename, CTextureAtlas *atlas )
{
AX_ASSERT( filename.isUsed() );
AX_ASSERT_NOT_NULL( atlas );
return g_textureMgr.loadTexture( filename, atlas );
}
DOLL_FUNC RTexture *DOLL_API gfx_deleteTexture( RTexture *texture )
{
if( texture != nullptr ) {
delete texture;
}
return nullptr;
}
DOLL_FUNC U32 DOLL_API gfx_getTextureResX( const RTexture *texture )
{
AX_ASSERT_NOT_NULL( texture );
return ( U32 )texture->getResolution().x;
}
DOLL_FUNC U32 DOLL_API gfx_getTextureResY( const RTexture *texture )
{
AX_ASSERT_NOT_NULL( texture );
return ( U32 )texture->getResolution().y;
}
}
|
d7902012165b8f7c7d13ddf459a38df6abc3d5c6 | 6d9cca2871d12565cfca8f0305a1a990aec71ee4 | /src/core/model/light/Sun.h | b4e0ecddc9d0e703ced246ea189c8de2ab5cbb3b | [
"Apache-2.0"
] | permissive | Pro1d/proXo | 9491b03a688b3af8f8988af818889da042d9d574 | 90fe95bd80a413487a3d36714c957747433a08f9 | refs/heads/master | 2020-07-03T17:50:09.590721 | 2018-10-27T19:14:58 | 2018-10-29T12:07:41 | 67,033,140 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 424 | h | Sun.h | #ifndef __SUN_H__
#define __SUN_H__
#include "core/math/type.h"
#include "core/model/Light.h"
namespace proxo {
class SunLight : public Light {
public:
SunLight();
void lighting(vec4 color, vec4 normal, vec4 point, real ambient,
real diffuse, real specular, real shininess, vec4 colorOut);
real getDirectionToSource(vec4 point, vec4 directionOut);
};
} // namespace proxo
#endif // __SUN_H__
|
ce1e6b229afe21f70725a40210e1bce6b1be6faf | 39b51aad9e36c6d3da9d510bde9eb950c8bdd73e | /BundlerTrackViewer/Parser/BundlerOutputParser.h | fca72c2114ea3b15782eabfa7f79d32472375703 | [] | no_license | duyguceylan/MySFM | db7014979e1fbfb2e9d7fcb0eb763fc85387f6a7 | 27c58e6406b0843fca1dc5721e47542270e91c5f | refs/heads/master | 2021-01-11T19:42:21.528092 | 2016-09-25T18:44:37 | 2016-09-25T18:44:37 | 69,182,365 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,245 | h | BundlerOutputParser.h | /*
* BundlerOutputParser.h
* BundlerTrackViewer
*
* Created by Duygu Ceylan on 11/8/11.
* Copyright 2011 __MyCompanyName__. All rights reserved.
*
*/
#include <vector>
#include "sfm-driver/sfm.h"
#include "PerspectiveCamera.h"
#include "Image.h"
#include "Common.h"
using namespace std;
class BundlerOutputParser
{
private:
int noCameras;
int noTracks;
std::vector<camera_params_t> cameraParams;
std::vector<CorrespondenceTrack> tracks;
public:
BundlerOutputParser() {}
~BundlerOutputParser() {}
void readBundlerOutputFile(const char* filename, int width, int height);
void writeCamAndImage(const char *outputPath, std::vector<string> &imagePaths, std::vector<PerspectiveCamera> &cameras);
void readCalibration(const char *outputPath, int noImages, std::vector<PerspectiveCamera> &cameras);
void undistortImage(Img &img, int w, int h, const std::string &out, const camera_params_t &camera);
int getNoOfTrack() {return tracks.size();}
int getNoOfCorrespondencesInTrack(int index){return tracks[index].correspondences.size(); }
Correspondence getCorrespondenceInTrack(int trackIndex, int corrIndex) {return tracks[trackIndex].correspondences[corrIndex]; }
void convertSfMOutputToPMVS(const char *input);
}; |
d49010f07bd161136eeecbadbe0fb5d9c156d79b | 7e1107c4995489a26c4007e41b53ea8d00ab2134 | /game/code/mission/objectives/gotoobjective.cpp | 99828015778f49ef15db662f9a4b07c15754222e | [] | no_license | Svxy/The-Simpsons-Hit-and-Run | 83837eb2bfb79d5ddb008346313aad42cd39f10d | eb4b3404aa00220d659e532151dab13d642c17a3 | refs/heads/main | 2023-07-14T07:19:13.324803 | 2023-05-31T21:31:32 | 2023-05-31T21:31:32 | 647,840,572 | 591 | 45 | null | null | null | null | UTF-8 | C++ | false | false | 15,702 | cpp | gotoobjective.cpp | //=============================================================================
// Copyright (C) 2002 Radical Entertainment Ltd. All rights reserved.
//
// File: gotoobjective.cpp
//
// Description: Implement GoToObjective
//
// History: 16/04/2002 + Created -- NAME
//
//=============================================================================
//========================================
// System Includes
//========================================
// Foundation Tech
#include <raddebug.hpp>
#include <p3d/utility.hpp>
//========================================
// Project Includes
//========================================
#include <events/eventmanager.h>
#include <input/inputmanager.h>
#include <meta/eventlocator.h>
#include <meta/spheretriggervolume.h>
#include <meta/triggervolumetracker.h>
#include <mission/objectives/gotoobjective.h>
#include <mission/animatedicon.h>
#include <mission/gameplaymanager.h>
#include <mission/missionmanager.h>
#include <render/dsg/inststatentitydsg.h>
#include <ai/actionbuttonhandler.h>
#include <ai/actionbuttonmanager.h>
#include <worldsim/character/charactermanager.h>
#include <worldsim/character/character.h>
#include <memory/srrmemory.h>
#include <interiors/interiormanager.h>
#include <camera/supercammanager.h>
#include <camera/supercamcentral.h>
#include <camera/walkercam.h>
//******************************************************************************
//
// Global Data, Local Data, Local Classes
//
//******************************************************************************
//******************************************************************************
//
// Public Member Functions
//
//******************************************************************************
//==============================================================================
// GoToObjective::GoToObjective
//==============================================================================
// Description: Constructor.
//
// Parameters: None.
//
// Return: N/A.
//
//==============================================================================
GoToObjective::GoToObjective() :
mDestinationLocator( NULL ),
mAnimatedIcon( NULL ),
mScaleFactor( 1.0f ),
mHudMapIconID( -1 ),
mCollectEffect( NULL ),
mWaitingForEffect( false ),
mGotoDialogOn( true ),
mActionTrigger( false ),
mOldEvent( LocatorEvent::NUM_EVENTS ),
mOldData( -1 )
{
mArrowPath.mPathRoute.Allocate( RoadManager::GetInstance()->GetNumRoads() );
mEffectName[0] = '\0';
}
//==============================================================================
// GoToObjective::~GoToObjective
//==============================================================================
// Description: Destructor.
//
// Parameters: None.
//
// Return: N/A.
//
//==============================================================================
GoToObjective::~GoToObjective()
{
if ( mAnimatedIcon )
{
delete mAnimatedIcon;
mAnimatedIcon = NULL;
UnregisterLocator( mHudMapIconID );
//Alert the walkercam that there is a drawable.
WalkerCam* wc = static_cast<WalkerCam*>(GetSuperCamManager()->GetSCC( 0 )->GetSuperCam( SuperCam::WALKER_CAM ));
if ( wc )
{
wc->SetCollectibleLocation( mAnimatedIcon );
}
}
if ( mCollectEffect )
{
delete mCollectEffect;
mCollectEffect = NULL;
}
}
//=============================================================================
// GoToObjective::OnInitalize
//=============================================================================
// Description: Comment
//
// Parameters: ()
//
// Return: void
//
//=============================================================================
void GoToObjective::OnInitialize()
{
MEMTRACK_PUSH_GROUP( "Mission - GoToObjective" );
GameMemoryAllocator gma = GetGameplayManager()->GetCurrentMissionHeap();
rAssert( mDestinationLocator == NULL );
mDestinationLocator = p3d::find<Locator>( mDestinationLocatorName );
rAssert( mDestinationLocator != NULL );
//mDestinationLocator->AddRef();
mDestinationLocator->SetFlag( Locator::ACTIVE, true );
//mDestinationLocator->SetFlag( Locator::DRAWN, true );
EventLocator* eventLocator = dynamic_cast<EventLocator*>( mDestinationLocator );
if( eventLocator != NULL )
{
GetEventManager()->AddListener( this, (EventEnum)(EVENT_LOCATOR + eventLocator->GetEventType()));
}
if ( mActionTrigger )
{
//Swap the settings of the event locator to make it go through the action button
//handing system.
mOldEvent = eventLocator->GetEventType();
eventLocator->SetEventType( LocatorEvent::GENERIC_BUTTON_HANDLER_EVENT );
ActionButton::GenericEventButtonHandler* pABHandler = dynamic_cast<ActionButton::GenericEventButtonHandler*>( ActionButton::GenericEventButtonHandler::NewAction( eventLocator, (EventEnum)(EVENT_LOCATOR + mOldEvent), gma ) );
rAssert( pABHandler );
pABHandler->SetEventData( static_cast<void*>(eventLocator) );
int id = 0;
bool bResult = GetActionButtonManager()->AddAction( pABHandler, id );
rAssert( bResult );
mOldData = eventLocator->GetData();
eventLocator->SetData( id );
}
if( strcmp( mDestinationDrawableName, "" ) != 0 )
{
rmt::Vector pos;
mDestinationLocator->GetLocation( &pos );
mAnimatedIcon = new AnimatedIcon();
mAnimatedIcon->Init( mDestinationDrawableName, pos );
SphereTriggerVolume* sphTrig = dynamic_cast<SphereTriggerVolume*>(eventLocator->GetTriggerVolume(0));
//rAssertMsg( sphTrig != NULL, "GOTO objectives should only use sphere triggers." );
if ( sphTrig )
{
if ( mScaleFactor != 0.0f )
{
sphTrig->SetSphereRadius( mScaleFactor );
}
}
//Only put up an icon in the HUD if there is a drawable in the world.
RegisterLocator( mDestinationLocator, mHudMapIconID, true, HudMapIcon::ICON_MISSION );
//Alert the walkercam that there is a drawable.
WalkerCam* wc = static_cast<WalkerCam*>(GetSuperCamManager()->GetSCC( 0 )->GetSuperCam( SuperCam::WALKER_CAM ));
if ( wc )
{
wc->SetCollectibleLocation( mAnimatedIcon );
}
}
else
{
// mDestinationLocator->SetFlag( Locator::DRAWN, true );
}
if ( strcmp( mEffectName, "" ) != 0 && strcmp( mEffectName, "none" ) != 0 )
{
mCollectEffect = new AnimatedIcon();
mCollectEffect->Init( mEffectName, rmt::Vector( 0.0f, 0.0f, 0.0f ), false, true );
}
mWaitingForEffect = false;
rmt::Vector targetPosn;
mDestinationLocator->GetLocation(&targetPosn);
LightPath( targetPosn, mArrowPath );
// if the goto objective is near the entrance of our current interior,
// lets assume that we don't need to do it
if(GetInteriorManager()->IsInside())
{
Locator* entrance = p3d::find<Locator>(GetInteriorManager()->GetInterior());
if(entrance)
{
rmt::Vector e, d, dist;
entrance->GetLocation(&e);
mDestinationLocator->GetLocation(&d);
dist.Sub(d,e);
if(dist.Magnitude() < 20.0f)
{
SetFinished( true );
// don't wan't to show stage complete for doing nothing
GetGameplayManager()->GetCurrentMission()->GetCurrentStage()->ShowStageComplete(false);
}
}
}
MEMTRACK_POP_GROUP("Mission - GoToObjective");
}
//=============================================================================
// GoToObjective::OnFinalize
//=============================================================================
// Description: Comment
//
// Parameters: ()
//
// Return: void
//
//=============================================================================
void GoToObjective::OnFinalize()
{
//
// Disable the controller
//
GetInputManager()->SetGameState( Input::ACTIVE_GAMEPLAY );
rAssert( mDestinationLocator != NULL );
mDestinationLocator->SetFlag( Locator::ACTIVE, false );
EventLocator* eventLocator = dynamic_cast<EventLocator*>( mDestinationLocator );
if( eventLocator != NULL )
{
GetEventManager()->RemoveListener( this, (EventEnum)(EVENT_LOCATOR + eventLocator->GetEventType()));
//This is to make sure that the exit volume triggers to kill characters hanging on
//to action button handlers. Semi-hack
unsigned int i;
for ( i = 0; i < eventLocator->GetNumTriggers(); ++i )
{
GetTriggerVolumeTracker()->RemoveTrigger( eventLocator->GetTriggerVolume( i ) );
GetTriggerVolumeTracker()->AddTrigger( eventLocator->GetTriggerVolume( i ) );
}
}
//Redundant if the old data is -1
if ( mActionTrigger && mOldData != -1 )
{
int id = eventLocator->GetData();
GetActionButtonManager()->RemoveActionByIndex( id );
eventLocator->SetData( mOldData );
eventLocator->SetEventType( mOldEvent );
//reset the old data
mOldData = -1;
}
//mDestinationLocator->Release();
mDestinationLocator = NULL;
if ( mAnimatedIcon )
{
delete mAnimatedIcon;
mAnimatedIcon = NULL;
UnregisterLocator( mHudMapIconID );
//Alert the walkercam that there is a drawable.
WalkerCam* wc = static_cast<WalkerCam*>(GetSuperCamManager()->GetSCC( 0 )->GetSuperCam( SuperCam::WALKER_CAM ));
if ( wc )
{
wc->SetCollectibleLocation( NULL );
}
}
if ( mCollectEffect )
{
delete mCollectEffect;
mCollectEffect = NULL;
}
UnlightPath( mArrowPath.mPathRoute );
}
//=============================================================================
// GoToObjective::OnUpdate
//=============================================================================
// Description: Comment
//
// Parameters: ( unsigned int elapsedTime )
//
// Return: void
//
//=============================================================================
void GoToObjective::OnUpdate( unsigned int elapsedTime )
{
if ( mAnimatedIcon )
{
mAnimatedIcon->Update( elapsedTime );
}
if ( mCollectEffect )
{
mCollectEffect->Update( elapsedTime );
}
//This is so that we can see the effect finish before we blow it away.
if ( mWaitingForEffect )
{
if ( !mCollectEffect->IsRendering() )
{
//The effect is finished rendering.
SetFinished( true );
}
}
UpdateLightPath(mArrowPath);
//Hard-code a test to see if we're already in the volume. This will correct if
//We're starting a mission inside it.
if ( !GetFinished() && mDestinationLocator && !mActionTrigger )
{
unsigned int i;
for ( i = 0; i < mDestinationLocator->GetNumTriggers(); ++i )
{
if ( reinterpret_cast<TriggerLocator*>(mDestinationLocator)->GetTriggerVolume( i )->IsPlayerTracking( 0 ) )
{
SetFinished( true );
}
}
}
}
//=============================================================================
// GoToObjective::HandleEvent
//=============================================================================
// Description: Comment
//
// Parameters: ( EventEnum id, void* pEventData )
//
// Return: void
//
//=============================================================================
void GoToObjective::HandleEvent( EventEnum id, void* pEventData )
{
switch( id )
{
case EVENT_LOCATOR + LocatorEvent::CHECK_POINT:
{
Locator* locator = static_cast<Locator*>( pEventData );
if( locator == mDestinationLocator && !mWaitingForEffect )
{
if ( mActionTrigger && mOldData != -1 )
{
//This is a hack for if the Effect takes too long, we need
//to get rid of the frickin' button in the screen
int id = locator->GetData();
GetCharacterManager()->GetCharacter( 0 )->RemoveActionButtonHandler( GetActionButtonManager()->GetActionByIndex( id ) );
}
if( mGotoDialogOn )
{
GetEventManager()->TriggerEvent( EVENT_DESTINATION_REACHED );
}
if ( IsFinished() == false )
{
//
// Disable the controller
//
GetInputManager()->SetGameState( Input::ACTIVE_NONE );
if ( mAnimatedIcon )
{
//Put the collection effect here and hit start.
rmt::Vector pos;
locator->GetLocation( &pos );
if ( mCollectEffect )
{
mCollectEffect->Reset();
mCollectEffect->Move( pos );
mCollectEffect->ShouldRender( true );
mWaitingForEffect = true;
}
else if ( strcmp( mEffectName, "none" ) != 0 )
{
//Only show the effect if there is a drawable.
if ( strcmp( mDestinationDrawableName, "" ) != 0 )
{
//USe the default one from the mission manager
GetMissionManager()->PutEffectHere( pos );
}
}
//Also, get rid of the old one.
mAnimatedIcon->ShouldRender( false );
}
}
if ( !mWaitingForEffect )
{
SetFinished( true );
}
}
break;
}
default:
{
// this isn't a "real" event listener so it may get events
// it doesn't care about
break;
}
}
}
//=============================================================================
// GoToObjective::SetDestinationLocatorName
//=============================================================================
// Description: Comment
//
// Parameters: ( char* locatorname, char* p3dname, float scale )
//
// Return: void
//
//=============================================================================
void GoToObjective::SetDestinationNames( char* locatorname, char* p3dname, float scale )
{
strcpy( mDestinationLocatorName, locatorname );
strcpy( mDestinationDrawableName, p3dname );
mScaleFactor = scale;
}
//=============================================================================
// GoToObjective::SetCollectEffectName
//=============================================================================
// Description: Comment
//
// Parameters: ( char* name )
//
// Return: void
//
//=============================================================================
void GoToObjective::SetCollectEffectName( char* name )
{
rAssert( name );
strcpy( mEffectName, name );
}
//******************************************************************************
//
// Private Member Functions
//
//******************************************************************************
|
e44da5a260b63135d8bc0589ecf806adf1c8aae3 | dcadc09210647c07bd4b216b9da7b85482045953 | /src/process.hh | 797639cdd042bf4da846e5c2e7495b22fdee9b3f | [] | no_license | Kuree/hermes | 3e59f972f1ba02e7f72b504e29ccd00d90694d8d | c856124a4cbfaed6b7d4af1479daf9582b1111f2 | refs/heads/master | 2023-04-23T03:42:28.361814 | 2021-05-06T00:55:08 | 2021-05-06T00:55:08 | 348,496,435 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,295 | hh | process.hh | #ifndef HERMES_PROCESS_HH
#define HERMES_PROCESS_HH
#include <condition_variable>
#include <cstdio>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <utility>
#include <vector>
// forward declare
namespace subprocess {
class Popen;
}
namespace hermes {
class Process {
public:
explicit Process(const std::vector<std::string> &commands);
Process(const std::vector<std::string> &commands, const std::string &cwd);
void wait();
~Process();
private:
std::unique_ptr<subprocess::Popen> process_;
};
class Dispatcher {
public:
void dispatch(const std::function<void()> &task);
static Dispatcher *get_default_dispatcher() {
static Dispatcher instance;
return &instance;
}
void finish();
~Dispatcher() { finish(); }
private:
std::mutex threads_lock_;
std::queue<std::thread> threads_;
void clean_up();
};
// code from https://github.com/progschj/ThreadPool
class ThreadPool {
public:
explicit ThreadPool(size_t);
template <class F, class... Args>
auto enqueue(F &&f, Args &&...args) -> std::future<typename std::result_of<F(Args...)>::type>;
~ThreadPool();
private:
// need to keep track of threads so we can join them
std::vector<std::thread> workers;
// the task queue
std::queue<std::function<void()> > tasks;
// synchronization
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads) : stop(false) {
for (size_t i = 0; i < threads; ++i)
workers.emplace_back([this] {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock,
[this] { return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty()) return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
// add new work item to the pool
template <class F, class... Args>
auto ThreadPool::enqueue(F &&f, Args &&...args)
-> std::future<typename std::result_of<F(Args...)>::type> {
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared<std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...));
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if (stop) throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace([task]() { (*task)(); });
}
condition.notify_one();
return res;
}
// the destructor joins all threads
inline ThreadPool::~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker : workers) worker.join();
}
} // namespace hermes
#endif // HERMES_PROCESS_HH
|
e49afa551482f18cf860428fc41148ed0297be77 | 7fa105ff31703145bf4839f074c0cc48f66de59e | /src/StringAlgorithm/SAM.cpp | dd8151c14c2e6f9b779987a7b52e8fd4ad8fc0a7 | [] | no_license | UPCACM/DuckKnowNothing | 44237120378c01a8c08af5562fc01a5e130d1b68 | 85417049c8f7612a0fcb08f0edc846295e476e0d | refs/heads/master | 2021-07-21T18:34:03.239649 | 2020-07-23T08:48:21 | 2020-07-23T08:48:21 | 197,498,250 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,425 | cpp | SAM.cpp | const int maxn = int(1e5) + 7;
struct SAM {
struct Node {
int len, pre; // 到达当前状态的最大步, 当前状态的父亲
std::map<int, int> next;
void init(int _len, int _pre) { // 状态节点初始化
len = _len, pre = _pre;
next.clear();
}
} node[maxn << 1];
int size, last;
void init() { // sam初始化
for (int i = 1; i < size; i++) node[i].next.clear();
node[0].init(0, -1);
size = 1, last = 0;
}
void extend(int ch) {
int cur = size++, u = last;
node[cur].len = node[last].len + 1;
while (u != -1 && !node[u].next.count(ch)) {
node[u].next[ch] = cur;
u = node[u].pre;
}
if (u == -1) node[cur].pre = 0; // 到达虚拟节点
else {
int v = node[u].next[ch];
if (node[v].len == node[u].len + 1) node[cur].pre = v; // 状态连续
else {
int clone = size++; // 拷贝
node[clone] = node[v];
node[clone].len = node[u].len + 1;
while (u != -1 && node[u].next[ch] == v) {
node[u].next[ch] = clone; // 把指向v的全部替换为指向clone
u = node[u].pre;
}
node[v].pre = node[cur].pre = clone;
}
}
last = cur; // 更新last
}
} sam; |
dab0fab716164177df902acc81f00918b2396098 | bffd46830acda1b96dc9df5fdbdecc67650d4e20 | /homework8/test/ut_filesystem.h | c3581c00996731c268ceb0773b926d24c50d0a23 | [] | no_license | RoJeA/courseProject_PatternOrientedSoftwareDevelopment | 005e158d1f2ff60b84e742f0d0a0a1d928c6a3bb | 8e1e63572cdb997e62a9b923784eee6a380968a7 | refs/heads/master | 2020-09-23T23:28:49.463329 | 2020-01-04T08:24:24 | 2020-01-04T08:24:24 | 225,614,854 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,046 | h | ut_filesystem.h | #ifndef UT_FILESYSTEM_H
#define UT_FILESYSTEM_H
#include <sys/stat.h>
#include "../src/file.h"
#include "../src/folder.h"
#include "../src/utilities.h"
#include "../src/iterator.h"
#include "../src/null_iterator.h"
#include "../src/node.h"
#include "../src/link.h"
#include "../src/find_visitor.cpp"
#include "../src/update_path_visitor.cpp"
class FSTest : public ::testing::Test{
protected:
void SetUp() {
try{
hw = new Folder("test/test_folder/hw");
a_out = new File("test/test_folder/hw/a.out");
hw1_cpp = new File("test/test_folder/hw/hw1.cpp");
hello_txt = new File("test/test_folder/hello.txt");
test_folder = new Folder("test/test_folder");
TA_folder = new Folder("test/test_folder/hw/TA_folder");
TA_folder_a_out = new File("test/test_folder/hw/TA_folder/a.out");
link = new Link("./junklink");
}catch(string str){
cout<<"SetUp(): "<<str<<endl;
}
test_folder->addChild(hello_txt);
test_folder->addChild(hw);
TA_folder->addChild(TA_folder_a_out);
hw->addChild(TA_folder);
hw->addChild(a_out);
hw->addChild(hw1_cpp);
link->addLink(a_out);
}
void TearDown() {
delete hw;
delete a_out;
delete hw1_cpp;
delete hello_txt;
delete test_folder;
delete TA_folder;
delete TA_folder_a_out;
delete link;
}
Folder* hw;
Node* a_out;
Node* hw1_cpp;
File* hello_txt;
Node* test_folder;
Node* TA_folder;
Node* TA_folder_a_out;
Link* link;
};
TEST(StatApi, GetSize) {
struct stat st;
ASSERT_EQ(0, stat("test/test_folder/hello.txt", &st));
int size = st.st_size;
// ASSERT_EQ(14, size);
}
TEST_F(FSTest, AddException){
ASSERT_ANY_THROW(hello_txt->addChild(test_folder));
}
TEST_F(FSTest, CatchException){
try{
hello_txt->addChild(test_folder);
ASSERT_EQ(true, false);
} catch(std::string s){
ASSERT_EQ("Invalid add!", s);
}
}
TEST_F(FSTest, InfoByteFunctionOnFile){
// ASSERT_EQ(14, infoByte(hello_txt));
}
TEST_F(FSTest, InfoByteFunctionOnFolder){
// ASSERT_EQ(19027, infoByte(hw));
}
TEST_F(FSTest, ExistanceInfoNode){
try{
Node* a_out = new File("test/test_folder/hw/aw.out");
ASSERT_EQ(true, false);
} catch(std::string s){
ASSERT_EQ("Node is not exist!", s);
}
try{
Node* a_out = new Folder("test/test_folder/hww");
ASSERT_EQ(true, false);
} catch(std::string s){
ASSERT_EQ("Node is not exist!", s);
}
}
TEST_F(FSTest, IteratorFromFolder) {
Iterator * it = hw->createIterator();
it->first(); // Initialize
ASSERT_EQ(TA_folder, it->currentItem());
it->next();
ASSERT_EQ(a_out, it->currentItem());
it->next();
ASSERT_EQ(hw1_cpp, it->currentItem());
it->next();
ASSERT_TRUE(it->isDone());
try{
it->currentItem();
ASSERT_TRUE(false);
}
catch(string s){
ASSERT_EQ(s,"No current item!");
}
try{
it->next();
}
catch(string s){
ASSERT_EQ(s,"Moving past the end!");
}
}
TEST_F(FSTest,createNullIterator){
try{
Iterator * it = a_out->createIterator();
it->first(); // Initialize
}
catch(string s){
ASSERT_EQ(s,"no child member");
}
try{
Iterator * it = a_out->createIterator();
it->currentItem(); // Initialize
}
catch(string s){
ASSERT_EQ(s,"no child member");
}
try{
Iterator * it = a_out->createIterator();
it->next(); // Initialize
}
catch(string s){
ASSERT_EQ(s,"no child member");
}
}
TEST_F(FSTest,WrongTypeFile){
try{
Node* hw = new File("test/test_folder/hw");
ASSERT_EQ(true, false);
} catch(std::string s){
ASSERT_EQ("It is not File!", s);
}
}
TEST_F(FSTest, WrongTypeFolder){
try{
Node* a_out = new Folder("test/test_folder/hw/a.out");
ASSERT_EQ(true, false);
} catch(std::string s){
ASSERT_EQ("It is not Folder!", s);
}
}
TEST_F(FSTest, NameInfoNode){
ASSERT_EQ("a.out", a_out->name());
ASSERT_EQ("hw", hw->name());
}
TEST_F(FSTest, IteratorFromFile){
Iterator* it= hello_txt->createIterator();
ASSERT_TRUE(it->isDone());
try{
it->first();
ASSERT_EQ(true,false);
}
catch(string s){
ASSERT_EQ(s,"no child member");
}
}
TEST_F(FSTest, ListNode){
Utilities list;
try{
list.listNode(a_out);
ASSERT_EQ(true, false);
} catch(std::string s){
ASSERT_EQ("Not a directory", s);
}
ASSERT_EQ("TA_folder a.out hw1.cpp", list.listNode(hw));
}
TEST_F(FSTest, FindNode){
Utilities bla;
ASSERT_EQ("a.out", bla.findNode(a_out,"a.out"));
ASSERT_EQ("./TA_folder/a.out\n./a.out", bla.findNode(hw,"a.out"));
ASSERT_EQ("",bla.findNode(hw,"hw"));
}
//HW6
TEST_F(FSTest, NodeTypeError){
//file
try{
Link* a_out = new Link("test/test_folder/hw/a.out");
ASSERT_EQ(true, false);
} catch(std::string s){
ASSERT_EQ("It is not Link!", s);
}
//folder
try{
Link* a_out = new Link("./test/test_folder", a_out);
ASSERT_EQ(true, false);
} catch(std::string s){
ASSERT_EQ("It is not Link!", s);
}
ASSERT_ANY_THROW(new File("./123")); //If the node doesn't exist, you should throw string "Node is not exist!"
ASSERT_ANY_THROW(new File("./test_data/folder")); //If the File doesn't exist, you should throw string "It is not File!"
ASSERT_ANY_THROW(new Folder("./test_data/hello")); //If the Folder doesn't exist, you should throw string "It is not Folder!"
ASSERT_ANY_THROW(new Link("./test_data/test", a_out)); //If the Link doesn't exist, you should throw string "It is not Link!"
}
TEST_F(FSTest, FindVisitor){
FindVisitor * fvf = new FindVisitor("TA_folder");
hw->accept(fvf);
ASSERT_EQ("./TA_folder",fvf->findResult());
FindVisitor * fv = new FindVisitor("a.out");
hw->accept(fv);
ASSERT_EQ("./TA_folder/a.out\n./a.out",fv->findResult());
//reuse + find file
TA_folder->accept(fv);
ASSERT_EQ("./a.out",fv->findResult());
a_out->accept(fv);
ASSERT_EQ("a.out",fv->findResult());
FindVisitor * fl = new FindVisitor("junklink");
link->accept(fl);
ASSERT_EQ("junklink",fl->findResult());
}
TEST_F(FSTest,link){
link->addLink(a_out);
ASSERT_EQ(a_out,link->getSource());
}
TEST_F(FSTest,RenameNode){
struct stat _st;
UpdatePathVisitor * upv = new UpdatePathVisitor();
a_out->renameNode("TA_file");
a_out->accept(upv);
ASSERT_EQ("TA_file", a_out->name()); // Check the node name in your own file system!
if (lstat("test/test_folder/hw/TA_file", &_st) != 0)
FAIL(); // Check the physical node name!
a_out->renameNode("a.out");
}
TEST_F(FSTest,UpdatePathVisitor){
struct stat _st;
UpdatePathVisitor * upv = new UpdatePathVisitor();
TA_folder->renameNode("TA_folder1");
TA_folder->accept(upv);
ASSERT_EQ("TA_folder1", TA_folder->name()); // Check the node name in your own file system!
ASSERT_EQ("test/test_folder/hw/TA_folder1", TA_folder->getPath()); // Check the path of itself!
ASSERT_EQ("test/test_folder/hw/TA_folder1/a.out", TA_folder_a_out->getPath()); // Check the path of child node!
if (lstat("test/test_folder/hw/TA_folder1", &_st) != 0)
FAIL(); // Check the physical node name!
TA_folder->renameNode("TA_folder");
}
#endif
|
e81c113bfaa4d56352056897a942b024635c8b4c | a5d82d37eea9a0eecc3161b9798c6b90ce5c4802 | /UVALive/6948.cpp | fe3c7c2bd13f2ee07e36a8616a4b1c1abd78cc91 | [] | no_license | suvrajitkarmaker/competitive_programming | f9fd914818352121107c483058ec7bc9d1f030de | a65eb91c98bf69313c72d8a7cde117f0072ccbc6 | refs/heads/master | 2021-05-26T07:47:19.915618 | 2020-11-04T06:58:21 | 2020-11-04T06:58:21 | 127,952,877 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,747 | cpp | 6948.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define gcd3(x,y,z) __gcd(__gcd(x,y),z)
#define INF LLONG_MAX
#define inf LONG_MAX
#define PI (2.0*acos(0.0))
#define Log(b,x) (log(x)/log(b))
#define all(x) (x).begin(), (x).end()
#define Unique(x) sort(all(x)); x.erase(unique(all(x)), x.end());
#define inttostring(x) to_string(x)
#define stringtoint(x) stoll(x)
#define valid(nx,ny,row,col) nx>0 && nx<=row && ny>0 && ny<=col
#define CLR(x,y) memset(x,y,sizeof(x));
#define MAX 105
#define eps 1e-9
string s;
int le,num,mark[150],str[150],f=0;
void BT(int po,int ct)
{
if(f==1)
return;
if(po>=num)
{
f=1;
return;
}
int tmp=s[ct]-48;
if(mark[tmp]==0 && tmp>=1 && tmp<=num)
{
mark[tmp]=1;
str[po]=tmp;
BT(po+1,ct+1);
mark[tmp]=0;
}
if(f==1)
return;
if(ct+1<le)
{
tmp*=10;
tmp+=s[ct+1]-48;
if(mark[tmp]==0 && tmp>=1 && tmp<=num)
{
mark[tmp]=1;
str[po]=tmp;
BT(po+1,ct+2);
mark[tmp]=0;
}
}
}
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
while(cin>>s)
{
CLR(str,0);
CLR(mark,0);
f=0;
le=s.size();
if(le<=9)
num=le;
else
{
num=le-9;
num/=2;
num+=9;
}
BT(0,0);
for(int i=0; i<num-1; i++)
{
printf("%d ",str[i]);
}
printf("%d\n",str[num-1]);
}
}
|
6de3f1f50b04ca58f59fb00b333d3451ba6cd817 | c20c4812ac0164c8ec2434e1126c1fdb1a2cc09e | /Source/Source/KG3DEngine/KG3DEngine/Helpers/KGStringFunctionsBase.cpp | 976212ca91c7ead561d8ccba2e51ee554af0f2f5 | [
"MIT"
] | permissive | uvbs/FullSource | f8673b02e10c8c749b9b88bf18018a69158e8cb9 | 07601c5f18d243fb478735b7bdcb8955598b9a90 | refs/heads/master | 2020-03-24T03:11:13.148940 | 2018-07-25T18:30:25 | 2018-07-25T18:30:25 | 142,408,505 | 2 | 2 | null | 2018-07-26T07:58:12 | 2018-07-26T07:58:12 | null | GB18030 | C++ | false | false | 5,091 | cpp | KGStringFunctionsBase.cpp | ////////////////////////////////////////////////////////////////////////////////
//
// FileName : KGStringFunctionsBase.cpp
// Version : 1.0
// Creator : Chen Tianhong
// Create Date : 2008-9-1 17:24:34
// Comment :
//
////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "KGStringFunctionsBase.h"
////////////////////////////////////////////////////////////////////////////////
KG_CUSTOM_HELPERS::UnicodeConvertor::UnicodeConvertor()
:m_uWideCharBufferSize(0)
, m_uCharBufferSize(0)
, m_uCodePage(special_code)
, m_dwFlag(0)
{
}
KG_CUSTOM_HELPERS::UnicodeConvertor::~UnicodeConvertor()
{
m_uWideCharBufferSize = 0;
m_uCharBufferSize = 0;
}
WCHAR* KG_CUSTOM_HELPERS::UnicodeConvertor::ToWHelper( const CHAR* lpChar, size_t uCharSize
, WCHAR* lpWBuffer, size_t uBufferSizeInWChar
, UINT CodePage /*= special_code*/
, DWORD dwFlag /*= 0 /*MB_PRECOMPOSED也是可以的*/ )
{
_ASSERTE((void*)lpChar != (void*)lpWBuffer);
_ASSERTE(lpChar && lpWBuffer);
UINT uCodePageUse = CodePage == special_code ? Private::uCodePage : CodePage;
int nReturn = MultiByteToWideChar(uCodePageUse, dwFlag, lpChar, (int)uCharSize, lpWBuffer, (int)uBufferSizeInWChar);
if (nReturn <= 0/* || nReturn == (int)ERROR_NO_UNICODE_TRANSLATION*/)
{
#if defined(_DEBUG) | defined(DEBUG)
DWORD dwErrorCode = ::GetLastError();
_KG3D_DEBUG_OUTPUT1("ToWHelper Error:%d", dwErrorCode);
#endif
return NULL;
}
return lpWBuffer;
}
CHAR* KG_CUSTOM_HELPERS::UnicodeConvertor::ToAHelper( const WCHAR* lpWChar, size_t uWCharSize
, CHAR* lpABuffer, size_t uBufferSize
, UINT CodePage /*= special_code*/
, DWORD dwFlag /*= 0/*WC_COMPOSITECHECK*/ )
{
_ASSERTE((void*)lpWChar != (void*)lpABuffer);
_ASSERTE(lpWChar && lpABuffer);
UINT uCodePageUse = CodePage == special_code ? Private::uCodePage : CodePage;
int nReturn = WideCharToMultiByte(uCodePageUse, dwFlag, lpWChar, (int)uWCharSize, lpABuffer, (int)uBufferSize, NULL, NULL);
if (nReturn <= 0)
{
#if defined(_DEBUG) | defined(DEBUG)
DWORD dwErrorCode = ::GetLastError();
_KG3D_DEBUG_OUTPUT1("ToAHelper Error:%d", dwErrorCode);
#endif
return NULL;
}
return lpABuffer;
}
CHAR* KG_CUSTOM_HELPERS::UnicodeConvertor::CreateCharBuffer( size_t uSize )
{
if(uSize > max_size)
return NULL;
m_uCharBufferSize = uSize;
ZeroMemory(m_CBuffer, sizeof(CHAR)*_countof(m_CBuffer));
return m_CBuffer;
}
WCHAR* KG_CUSTOM_HELPERS::UnicodeConvertor::CreateWCharBuffer( size_t uSize )
{
if(uSize > max_size)
return NULL;
m_uWideCharBufferSize = uSize;
ZeroMemory(m_WBuffer, sizeof(WCHAR)*_countof(m_WBuffer));
return m_WBuffer;
}
WCHAR* KG_CUSTOM_HELPERS::UnicodeConvertor::ToW( const CHAR* lpChar )
{
if(! lpChar)
return NULL;
size_t uSize = strlen(lpChar) + 1; ///注意下面的MultiByteToWideChar的Size是要求计入'\0'的
if (uSize <= 0 || uSize > max_size)
return NULL;
WCHAR* lpWideCharBuffer = this->CreateWCharBuffer(uSize);
if(! lpWideCharBuffer || lpWideCharBuffer == (WCHAR*)lpChar)
return NULL;
_ASSERTE(m_uWideCharBufferSize == uSize);
_ASSERTE(m_uWideCharBufferSize > 0);
if(! this->ToWHelper(lpChar, uSize, lpWideCharBuffer, m_uWideCharBufferSize, m_uCodePage, m_dwFlag))
{
ClearWCharBuffer();
return NULL;
}
return lpWideCharBuffer;
}
CHAR* KG_CUSTOM_HELPERS::UnicodeConvertor::ToA( const WCHAR* lpWChar )
{
if(! lpWChar)
return NULL;
size_t uSize = wcslen(lpWChar)+1; ///注意下面的WideCharToMultiByte的Size是要求计入'\0'的
if (uSize <= 0 || uSize > max_size)
return NULL;
CHAR* lpCharBuffer = CreateCharBuffer(uSize*2);
if(! lpCharBuffer)
return NULL;
_ASSERTE(m_uCharBufferSize == uSize*2);
_ASSERTE(m_uCharBufferSize > 0);
if(! this->ToAHelper(lpWChar, uSize, lpCharBuffer, m_uCharBufferSize, m_uCodePage, m_dwFlag))
{
ClearCharBuffer();
return NULL;
}
return lpCharBuffer;
}
TCHAR* KG_CUSTOM_HELPERS::UnicodeConvertor::ToT( const WCHAR* lpWChar, size_t uWCharSize, TCHAR* lpTChar, size_t uTCharSize )
{
#if defined(_UNICODE) | defined(UNICODE)
if(! lpWChar || ! lpTChar)
return NULL;
if (0 == wcscpy_s(lpTChar, uTCharSize, lpWChar))
{
return lpTChar;
}
return NULL;
#else
return this->ToAHelper(lpWChar, uWCharSize, lpTChar, uTCharSize);
#endif
}
TCHAR* KG_CUSTOM_HELPERS::UnicodeConvertor::ToT( const char* lpChar, size_t uCharSize, TCHAR* lpTChar, size_t uTCharSize )
{
#if defined(_UNICODE) | defined(UNICODE)
return this->ToWHelper(lpChar, uCharSize, lpTChar, uTCharSize);
#else
if(! lpChar || !lpTChar)
return NULL;
if (0 == strcpy_s(lpTChar, uTCharSize, lpChar))
{
return lpTChar;
}
return NULL;
#endif
}
const TCHAR* KG_CUSTOM_HELPERS::UnicodeConvertor::ToT( const WCHAR* lpWChar )
{
#if defined(_UNICODE) | defined(UNICODE)
return lpWChar;
#else
return this->ToA(lpWChar);
#endif
}
const TCHAR* KG_CUSTOM_HELPERS::UnicodeConvertor::ToT( const char* lpChar )
{
#if defined(_UNICODE) | defined(UNICODE)
return this->ToW(lpChar);
#else
return lpChar;
#endif
} |
6676d501fe8a4e75683e62d1a17cfa4afb842546 | 105e7eb0da72185990e940f289b4acccdcba4b5e | /algo/cpp/longest_substring_without_repeating_characters.cc | 4026ed079ee087f9447a105d3aa7684f4230251b | [] | no_license | waveform/leetcode | c748ae3efbc907d6588ed2f2d20370ddd9f05401 | 0ac39d45f0e90c79ecc67b8375aca2ad6c79f965 | refs/heads/master | 2021-01-19T21:02:39.227990 | 2019-06-06T22:59:12 | 2019-06-06T22:59:12 | 101,244,106 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 743 | cc | longest_substring_without_repeating_characters.cc | class Solution {
public:
// solution #1: O(n)
/*
int lengthOfLongestSubstring(string s) {
int lut[256] = {0};
int b = 0, e = 0, ans = 0, n = s.size();
while(1) {
while(e<n && !lut[s[e]]) { lut[s[e++]] = 1; }
ans = max(ans, e - b);
if (e>=n) break;
while(lut[s[e]]) lut[s[b++]] = 0;
}
return ans;
}
*/
// solution #2: O(n)
int lengthOfLongestSubstring(string s) {
vector<int> lut(256, -1);
int ans = 0, start = -1, n = s.size();
for (int i=0; i<n; i++) {
start = max(start, lut[s[i]]);
lut[s[i]] = i;
ans = max(ans, i - start);
}
return ans;
}
};
|
c92e88d1adde228d73f608d608b4aeb7aeaa12c0 | 820b6af9fd43b270749224bb278e5f714f655ac9 | /Filters/HyperTree/vtkHyperTreeGridGeometry1DImpl.h | c2b9a75c12924de5bfcf69d159efc4d27b29fc22 | [
"BSD-3-Clause"
] | permissive | Kitware/VTK | 49dee7d4f83401efce8826f1759cd5d9caa281d1 | dd4138e17f1ed5dfe6ef1eab0ff6643fdc07e271 | refs/heads/master | 2023-09-01T10:21:57.496189 | 2023-09-01T08:20:15 | 2023-09-01T08:21:05 | 631,615 | 2,253 | 1,243 | NOASSERTION | 2023-09-14T07:53:03 | 2010-04-27T15:12:58 | C++ | UTF-8 | C++ | false | false | 2,182 | h | vtkHyperTreeGridGeometry1DImpl.h | // SPDX-FileCopyrightText: Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
// SPDX-License-Identifier: BSD-3-Clause
/**
* @class vtkHyperTreeGridGeometry1DImpl
* @brief vtkHyperTreeGridGeometry internal classes for 1D vtkHyperTreeGrid
*
* This class is an internal class used in by the vtkHyperTreeGridGeometry filter
* to generate the HTG surface in the 1D case.
*/
#ifndef vtkHyperTreeGridGeometry1DImpl_h
#define vtkHyperTreeGridGeometry1DImpl_h
#include "vtkHyperTreeGridGeometrySmallDimensionsImpl.h"
#include <vector> // For std::vector
VTK_ABI_NAMESPACE_BEGIN
class vtkHyperTreeGridGeometry1DImpl : public vtkHyperTreeGridGeometrySmallDimensionsImpl
{
public:
vtkHyperTreeGridGeometry1DImpl(vtkHyperTreeGrid* input, vtkPoints* outPoints,
vtkCellArray* outCells, vtkDataSetAttributes* inCellDataAttributes,
vtkDataSetAttributes* outCellDataAttributes, bool passThroughCellIds,
const std::string& originalCellIdArrayName);
~vtkHyperTreeGridGeometry1DImpl() override = default;
protected:
/**
* Generate the surface for a leaf cell cutted by one interface.
* Called by ProcessLeafCellWithInterface.
*/
void ProcessLeafCellWithOneInterface(vtkHyperTreeGridNonOrientedGeometryCursor* cursor,
double signe, const std::vector<double>& distancesToInterface) override;
/**
* Generate the surface for a leaf cell cutted by two interfaces.
* Called by ProcessLeafCellWithInterface.
*/
void ProcessLeafCellWithDoubleInterface(vtkHyperTreeGridNonOrientedGeometryCursor* cursor,
const std::vector<double>& distancesToInterfaceA,
const std::vector<double>& distancesToInterfaceB) override;
/**
* Compute the point coordinates of the surface of the current cell, independently
* of the fact that the current cell has a defined interface or not.
*
* Used as a pre-process in ProcessLeafCellWithInterface.
*/
void BuildCellPoints(vtkHyperTreeGridNonOrientedGeometryCursor* cursor) override;
private:
/**
* Denotes the oriention of the 1D HTG
* 0, 1, 2 = aligned along the X, Y, Z axis
*/
unsigned int Axis = 0;
};
VTK_ABI_NAMESPACE_END
#endif /* vtkHyperTreeGridGeometry1DImpl_h */
|
d5d56eecb1fe369c84ab1b27e3745f60fad1c2a7 | b0dd7779c225971e71ae12c1093dc75ed9889921 | /libs/mpi/src/environment.cpp | 8a19439c65ca32f8e95ef07dfd767384f4ab175c | [
"LicenseRef-scancode-warranty-disclaimer",
"BSL-1.0"
] | permissive | blackberry/Boost | 6e653cd91a7806855a162347a5aeebd2a8c055a2 | fc90c3fde129c62565c023f091eddc4a7ed9902b | refs/heads/1_48_0-gnu | 2021-01-15T14:31:33.706351 | 2013-06-25T16:02:41 | 2013-06-25T16:02:41 | 2,599,411 | 244 | 154 | BSL-1.0 | 2018-10-13T18:35:09 | 2011-10-18T14:25:18 | C++ | UTF-8 | C++ | false | false | 3,009 | cpp | environment.cpp | // Copyright (C) 2005-2006 Douglas Gregor <doug.gregor@gmail.com>
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Message Passing Interface 1.1 -- 7.1.1. Environmental Inquiries
#include <boost/mpi/environment.hpp>
#include <boost/mpi/exception.hpp>
#include <boost/mpi/detail/mpi_datatype_cache.hpp>
#include <cassert>
#include <exception>
#include <stdexcept>
namespace boost { namespace mpi {
#ifdef BOOST_MPI_HAS_NOARG_INITIALIZATION
environment::environment(bool abort_on_exception)
: i_initialized(false),
abort_on_exception(abort_on_exception)
{
if (!initialized()) {
BOOST_MPI_CHECK_RESULT(MPI_Init, (0, 0));
i_initialized = true;
}
MPI_Errhandler_set(MPI_COMM_WORLD, MPI_ERRORS_RETURN);
}
#endif
environment::environment(int& argc, char** &argv, bool abort_on_exception)
: i_initialized(false),
abort_on_exception(abort_on_exception)
{
if (!initialized()) {
BOOST_MPI_CHECK_RESULT(MPI_Init, (&argc, &argv));
i_initialized = true;
}
MPI_Errhandler_set(MPI_COMM_WORLD, MPI_ERRORS_RETURN);
}
environment::~environment()
{
if (i_initialized) {
if (std::uncaught_exception() && abort_on_exception) {
abort(-1);
} else if (!finalized()) {
detail::mpi_datatype_cache().clear();
BOOST_MPI_CHECK_RESULT(MPI_Finalize, ());
}
}
}
void environment::abort(int errcode)
{
BOOST_MPI_CHECK_RESULT(MPI_Abort, (MPI_COMM_WORLD, errcode));
}
bool environment::initialized()
{
int flag;
BOOST_MPI_CHECK_RESULT(MPI_Initialized, (&flag));
return flag != 0;
}
bool environment::finalized()
{
int flag;
BOOST_MPI_CHECK_RESULT(MPI_Finalized, (&flag));
return flag != 0;
}
int environment::max_tag()
{
int* max_tag_value;
int found = 0;
BOOST_MPI_CHECK_RESULT(MPI_Attr_get,
(MPI_COMM_WORLD, MPI_TAG_UB, &max_tag_value, &found));
assert(found != 0);
return *max_tag_value - num_reserved_tags;
}
int environment::collectives_tag()
{
return max_tag() + 1;
}
optional<int> environment::host_rank()
{
int* host;
int found = 0;
BOOST_MPI_CHECK_RESULT(MPI_Attr_get,
(MPI_COMM_WORLD, MPI_HOST, &host, &found));
if (!found || *host == MPI_PROC_NULL)
return optional<int>();
else
return *host;
}
optional<int> environment::io_rank()
{
int* io;
int found = 0;
BOOST_MPI_CHECK_RESULT(MPI_Attr_get,
(MPI_COMM_WORLD, MPI_IO, &io, &found));
if (!found || *io == MPI_PROC_NULL)
return optional<int>();
else
return *io;
}
std::string environment::processor_name()
{
char name[MPI_MAX_PROCESSOR_NAME];
int len;
BOOST_MPI_CHECK_RESULT(MPI_Get_processor_name, (name, &len));
return std::string(name, len);
}
} } // end namespace boost::mpi
|
39c02c9b9689aa8773f6f0748af2a06f75019ef8 | edc3f27cc4d8076a57d14f49b9664c5486c72c35 | /ortc/windows/org/ortc/RTCDtmfSender.h | 1bb55614dcb77c9224d1811f77780f1bb14e2f44 | [] | no_license | jacano/ortc.UWP | b9cc8dc2802081ea9872eb96a92e3568ad8a3aaf | 0a717049f7b0970eea8d9939756c3e752a1e2478 | refs/heads/master | 2022-11-27T06:47:04.065612 | 2017-09-08T12:38:34 | 2017-09-08T12:38:34 | 102,836,778 | 1 | 1 | null | 2022-11-19T03:09:22 | 2017-09-08T08:16:17 | C++ | UTF-8 | C++ | false | false | 5,255 | h | RTCDtmfSender.h | #pragma once
#include <ortc/IDTMFSender.h>
namespace Org
{
namespace Ortc
{
ZS_DECLARE_TYPEDEF_PTR(::ortc::IDTMFSender, IDTMFSender)
ZS_DECLARE_TYPEDEF_PTR(::ortc::IDTMFSenderDelegate, IDTMFSenderDelegate)
ZS_DECLARE_TYPEDEF_PTR(::ortc::IDTMFSenderSubscription, IDTMFSenderSubscription)
ref class RTCDtmfSender;
ref class RTCRtpSender;
namespace Internal
{
ZS_DECLARE_CLASS_PTR(RTCDtmfSenderDelegate)
} // namespace internal
/// <summary>
/// The OnToneChange event uses the RTCDTMFToneChangeEvent interface.
/// </summary>
public ref struct RTCDTMFToneChangeEvent sealed
{
friend class Internal::RTCDtmfSenderDelegate;
/// <summary>
/// Gets the tone attribute contains the character for the tone that has
/// just begun playout (see InsertDTMF()). If the value is the empty
/// string, it indicates that the previous tone has completed playback.
/// </summary>
property Platform::String^ Tone
{
Platform::String^ get() { return _tone; }
}
private:
Platform::String^ _tone;
};
public delegate void RTCDtmfSenderOnToneChangeDelegate(RTCDTMFToneChangeEvent^ evt);
/// <summary>
/// An RTCDtmfSender instance allows sending DTMF tones to/from the remote
/// peer, as per [RFC4733].
/// </summary>
public ref class RTCDtmfSender sealed
{
friend class Internal::RTCDtmfSenderDelegate;
private:
public:
/// <summary>
/// Construct an instance of the RTCDtmfSender associated to an
/// RTCRtpSender.
/// </summary>
RTCDtmfSender(RTCRtpSender^ sender);
/// <summary>
/// The InsertDTMF() method is used to send DTMF tones. Since DTMF tones
/// cannot be sent without configuring the DTMF codec, if InsertDTMF()
/// is called prior to sender.Send(parameters), or if
/// sender.Send(parameters) was called but parameters did not include
/// the DTMF codec, throw an InvalidStateError exception.
/// </summary>
[Windows::Foundation::Metadata::DefaultOverloadAttribute]
void InsertDtmf(Platform::String^ tones);
/// <summary>
/// The InsertDTMF() method is used to send DTMF tones. Since DTMF tones
/// cannot be sent without configuring the DTMF codec, if InsertDTMF()
/// is called prior to sender.Send(parameters), or if
/// sender.Send(parameters) was called but parameters did not include
/// the DTMF codec, throw an InvalidStateError exception.
/// </summary>
[Windows::Foundation::Metadata::OverloadAttribute("InsertDtmfWithDuration")]
void InsertDtmf(Platform::String^ tones, uint64 duration);
/// <summary>
/// The InsertDTMF() method is used to send DTMF tones. Since DTMF tones
/// cannot be sent without configuring the DTMF codec, if InsertDTMF()
/// is called prior to sender.Send(parameters), or if
/// sender.Send(parameters) was called but parameters did not include
/// the DTMF codec, throw an InvalidStateError exception.
/// </summary>
[Windows::Foundation::Metadata::OverloadAttribute("InsertDtmfWithDurationAndGap")]
void InsertDtmf(Platform::String^ tones, uint64 duration, uint64 interToneGap);
/// <summary>
/// Gets whether the RTCDtmfSender is capable of sending DTMF.
/// </summary>
property Platform::Boolean CanInsertDtmf
{
Platform::Boolean get();
}
/// <summary>
/// Gets the RTCRtpSender instance.
/// </summary>
property RTCRtpSender^ Sender
{
RTCRtpSender^ get();
}
/// <summary>
/// Gets the toneBuffer attribute returns a list of the tones remaining
/// to be played out.
/// </summary>
property Platform::String^ ToneBuffer
{
Platform::String^ get();
}
/// <summary>
/// Get the duration attribute returns the current tone duration value
/// in milliseconds. This value will be the value last set via the
/// InsertDTMF() method, or the default value of 100 ms if
/// InsertDTMF() was called without specifying the duration.
/// </summary>
property uint64 Duration
{
uint64 get();
}
/// <summary>
/// Gets the interToneGap attribute returns the current value of the
/// between-tone gap. This value will be the value last set via the
/// InsertDTMF() method, or the default value of 70 ms if InsertDTMF()
/// was called without specifying the interToneGap.
/// </summary>
property uint64 InterToneGap
{
uint64 get();
}
/// <summary>
/// The OnToneChange event handler uses the RTCDTMFToneChangeEvent
/// interface to return the character for each tone as it is played out.
/// </summary>
event RTCDtmfSenderOnToneChangeDelegate^ OnToneChange;
private:
IDTMFSenderPtr _nativePointer;
Internal::RTCDtmfSenderDelegatePtr _nativeDelegatePointer;
IDTMFSenderSubscriptionPtr _nativeSubscriptionPointer;
};
} // namespace ortc
} // namespace org
|
42b01eaa93acda4e1c05b018eed65d26ca056ce6 | 308f5596f1c7d382520cfce13ceaa5dff6f4f783 | /hphp/hhbbc/optimize.h | 901fcfb18aed3744f6b1a12e9e0495bc2def44dc | [
"PHP-3.01",
"Zend-2.0",
"MIT"
] | permissive | facebook/hhvm | 7e200a309a1cad5304621b0516f781c689d07a13 | d8203129dc7e7bf8639a2b99db596baad3d56b46 | refs/heads/master | 2023-09-04T04:44:12.892628 | 2023-09-04T00:43:05 | 2023-09-04T00:43:05 | 455,600 | 10,335 | 2,326 | NOASSERTION | 2023-09-14T21:24:04 | 2010-01-02T01:17:06 | C++ | UTF-8 | C++ | false | false | 2,012 | h | optimize.h | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#pragma once
#include "hphp/hhbbc/context.h"
namespace HPHP::HHBBC {
//////////////////////////////////////////////////////////////////////
struct Index;
struct FuncAnalysis;
struct Bytecode;
struct BlockUpdateInfo;
using BlockUpdates = CompactVector<std::pair<BlockId, CompressedBlockUpdate>>;
/*
* Use information from an analyze call to perform various
* optimizations on a function.
*
* The Index should be unchanged since the one that was provided to
* the corresponding analyze_func call.
*
* This routine may modify the php::Blocks attached to the passed-in
* php::Func, and may renumber the php::Func's locals, but won't update
* any of the func's other metadata.
*/
void optimize_func(const Index&, FuncAnalysis&&, php::WideFunc&);
void update_bytecode(php::WideFunc&, BlockUpdates&&, FuncAnalysis* = nullptr);
/*
* Return a bytecode to generate the value in cell
*/
Bytecode gen_constant(const TypedValue& cell);
//////////////////////////////////////////////////////////////////////
}
|
4c2c9b4db770b2a67228f34a543dc7c2eedc7e4b | bc1a5f0821df7c2d94880f5110543f1c033f35e7 | /solutions/6-连续子数组的最大和/main_1.cpp | 95218921de5cd05d186b6036672e15e6e76d2598 | [] | no_license | biechuyangwang/nowcoder | 293bec55df017c59208d86cfc2aa5569284b67c1 | 556803af3cc230ddaf5eb0543fe0626490617997 | refs/heads/master | 2023-02-09T22:42:38.250933 | 2021-01-04T02:23:30 | 2021-01-04T02:23:30 | 319,267,501 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,259 | cpp | main_1.cpp | /*
* author: 李俊
* time:2020/12/11
*
* 动态规划
*/
/*
* 注意事项
*/
/*
* 动归方程
* f(x) = max{a(x),f(x-1)+a(x)}
* f(x)表示以a(x)结尾的子数组的最大和。子数组不能为空。
*/
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e9+7;
class Solution {
public: // 动态规划
int FindGreatestSumOfSubArray_1(vector<int> array) {
int res = array[0];
int len = array.size();
vector<int>dp(len);
dp[0] = array[0];
for(int i=0;i<len;++i){
dp[i] = max(array[i], dp[i-1]+array[i]);
res = res < dp[i] ? dp[i] : res;
}
return res;
}
int FindGreatestSumOfSubArray_2(vector<int> array) {
int res = array[0];
int x,x_1=array[0];
for(int i=1;i<array.size();++i){
x = max(array[i], x_1+array[i]);
res = max(res, x);
x_1 = x;
}
return res;
}
};
int main(){
vector<int>input = {1,-2,3,10,-4,7,2,-5};
// vector<int>input = {-11,-2,-3,-10,-4,-7,-2,-5};
int res;
Solution s;
// res = s.FindGreatestSumOfSubArray_1(input);
res = s.FindGreatestSumOfSubArray_2(input);
cout << res << endl;
return 0;
}
/*
* output 1:
* 18
*
* output 2:
* -2
*/ |
3fa3e42538da7c86f63089049a616b9d9274fb7d | 3319bc8ed103ed5a7c7b3470c3ec3db5e9d0f716 | /Code/main.cpp | e1c74b84c150d62f8a94b9e2e3e907affd177e49 | [] | no_license | dshmul/DSA_Project3 | b1489c27c8656bb19e653b36cd2aa7b27f3b4577 | f07bcc75d6c7961361a44069a688ab05bb532953 | refs/heads/master | 2023-04-18T13:55:14.460064 | 2021-04-18T23:15:22 | 2021-04-18T23:15:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,116 | cpp | main.cpp | #include "odom.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <chrono>
#include <cfloat>
#include "avl.h"
#include "hashMap.h"
#include "windows.h"
using namespace std;
//Helper function: Returns the updated root of the tree
Node* callInsert(Node* root, Odom* name, int id);
void findMin(Node* root, hashMap* u_map, string option, int max_time_);
void findMax(Node* root, hashMap* u_map, string option, int max_time_);
void findAverage(Node* root, hashMap* u_map, string option, int max_time_);
int main()
{
Node* root = nullptr; //avl tree root node
hashMap u_map; //hashmap
vector<Odom*> listOdom;
string operation;
while (true)
{
cout << "\nWhat would you wish to do? Please select a number." << endl;
cout << "0. Stop Program" << endl;
cout << "1. Load Data" << endl;
cout << "2. Find Min of a value" << endl;
cout << "3. Find Max of a value" << endl;
cout << "4. Find Average of a value" << endl;
cout << "5. Find Data at a specific time" << endl;
cout << endl << "Selection: ";
cin >> operation;
if (operation == "0") {
cout << "Thank you!" << endl;
break;
}
else if (operation == "1") //load data into data structures
{
ifstream ifs;
string file;
cout << "\nWhat file would you like to load?" << endl;
cin >> file;
cout << endl;
ifs.open(file);
if (!ifs) {
cout << "\nInvalid file" << endl << endl;
}
else {
string lineFromFile;
istringstream line;
double px, py, pz, lvx, lvy, lvz, avx, avy, avz;
double maxlvx = 0;
int t = 0; // time variable
// gets column titles
getline(ifs, lineFromFile);
//obtain all values from csv and push them to a vector to avoid file reading in timing
while (getline(ifs, lineFromFile))
{
line.str(lineFromFile);
string temp;
getline(line, temp, ',');
px = stod(temp);
getline(line, temp, ',');
py = stod(temp);
getline(line, temp, ',');
pz = stod(temp);
getline(line, temp, ',');
lvx = stod(temp);
getline(line, temp, ',');
lvy = stod(temp);
getline(line, temp, ',');
lvz = stod(temp);
getline(line, temp, ',');
avx = stod(temp);
getline(line, temp, ',');
avy = stod(temp);
getline(line, temp, ',');
avz = stod(temp);
Odom* point = new Odom(px, py, pz, lvx, lvy, lvz, avx, avy, avz, t);
listOdom.push_back(point);
t += 10;
}
cout << "\nThe number of elements in this dataset: " << listOdom.size() << endl;
ifs.close();
//----------------------insert elements into avl tree----------------------//
auto o_map_start = chrono::system_clock::now();
for (int i = 0; i < listOdom.size(); i++) {
root = callInsert(root, listOdom[i], listOdom[i]->t_());
}
auto o_map_stop = chrono::system_clock::now();
double o_map_duration = chrono::duration_cast<chrono::milliseconds>(o_map_stop - o_map_start).count();
cout << "\nAVL Tree load duration: " << o_map_duration << " ms" << endl;
//----------------------insert elements into unordered map (hashMap)-----------------------//
auto u_map_start = chrono::system_clock::now();
for (int i = 0; i < listOdom.size(); i++) {
u_map.insert(listOdom[i]);
}
auto u_map_stop = chrono::system_clock::now();
double u_map_duration = chrono::duration_cast<chrono::milliseconds>(u_map_stop - u_map_start).count();
cout << "\nHashmap load duration: " << u_map_duration << " ms" << endl << endl;
}
}
else if (operation == "2" && listOdom.size() != 0) { //find the min
int min_time = 0;
int max_time = listOdom.size() * 10;
cout << endl;
cout << "Which value would you like to find the minimum for?" << endl;
cout << "1. Position X (m)" << endl;
cout << "2. Position Y (m)" << endl;
cout << "3. Position Z (m)" << endl;
cout << "4. Linear Velocity X (m/s)" << endl;
cout << "5. Linear Velocity Y (m/s)" << endl;
cout << "6. Linear Velocity Z (m/s)" << endl;
cout << "7. Angular Velocity X (rad/s)" << endl;
cout << "8. Angular Velocity Y (rad/s)" << endl;
cout << "9. Angular Velocity Z (rad/s)" << endl;
cin >> operation;
findMin(root, &u_map, operation, listOdom.size() * 10);
}
else if (operation == "3" && listOdom.size() != 0) { //find the max
int min_time = 0;
int max_time = listOdom.size() * 10;
cout << endl;
cout << "Which value would you like to find the maximum for?" << endl;
cout << "1. Position X (m)" << endl;
cout << "2. Position Y (m)" << endl;
cout << "3. Position Z (m)" << endl;
cout << "4. Linear Velocity X (m/s)" << endl;
cout << "5. Linear Velocity Y (m/s)" << endl;
cout << "6. Linear Velocity Z (m/s)" << endl;
cout << "7. Angular Velocity X (rad/s)" << endl;
cout << "8. Angular Velocity Y (rad/s)" << endl;
cout << "9. Angular Velocity Z (rad/s)" << endl;
cin >> operation;
findMax(root, &u_map, operation, listOdom.size() * 10);
}
else if (operation == "4" && listOdom.size() != 0) { //find the average
int min_time = 0;
int max_time = listOdom.size() * 10;
cout << endl;
cout << "Which value would you like to find the average for?" << endl;
cout << "1. Position X (m)" << endl;
cout << "2. Position Y (m)" << endl;
cout << "3. Position Z (m)" << endl;
cout << "4. Linear Velocity X (m/s)" << endl;
cout << "5. Linear Velocity Y (m/s)" << endl;
cout << "6. Linear Velocity Z (m/s)" << endl;
cout << "7. Angular Velocity X (rad/s)" << endl;
cout << "8. Angular Velocity Y (rad/s)" << endl;
cout << "9. Angular Velocity Z (rad/s)" << endl;
cin >> operation;
findAverage(root, &u_map, operation, listOdom.size() * 10);
}
else if (operation == "5" && listOdom.size() != 0) { //find values at time t
int time;
cout << "\nEnter time:" << endl;
cin >> time;
auto avl_start = std::chrono::high_resolution_clock::now();
Odom* avl_data = root->search(root, time);
auto avl_stop = std::chrono::high_resolution_clock::now();
double avl_duration = std::chrono::duration_cast<chrono::milliseconds>(avl_stop - avl_start).count();
cout << "\nPosition X (m): " << avl_data->px_() << "\tLinear Velocity X (m/s): " << avl_data->lvx_() << "\tAngular Velocity X (rad/s): " << avl_data->avx_() << endl;
cout << "Position Y (m): " << avl_data->py_() << "\tLinear Velocity Y (m/s): " << avl_data->lvy_() << "\tAngular Velocity Y (rad/s): " << avl_data->avy_() << endl;
cout << "Position Z (m): " << avl_data->pz_() << "\tLinear Velocity Z (m/s): " << avl_data->lvz_() << "\tAngular Velocity Z (rad/s): " << avl_data->avz_() << endl;
cout << "\nAVL Tree search duration: " << avl_duration << " ms" << endl;
auto hash_start = chrono::high_resolution_clock::now();
Odom* hash_data = u_map.get(time);
auto hash_stop = chrono::high_resolution_clock::now();
double hash_duration = chrono::duration_cast<chrono::milliseconds>(hash_stop - hash_start).count();
cout << "\nPosition X (m): " << hash_data->px_() << "\tLinear Velocity X (m/s): " << hash_data->lvx_() << "\tAngular Velocity X (rad/s): " << hash_data->avx_() << endl;
cout << "Position Y (m): " << hash_data->py_() << "\tLinear Velocity Y (m/s): " << hash_data->lvy_() << "\tAngular Velocity Y (rad/s): " << hash_data->avy_() << endl;
cout << "Position Z (m): " << hash_data->pz_() << "\tLinear Velocity Z (m/s): " << hash_data->lvz_() << "\tAngular Velocity Z (rad/s): " << hash_data->avz_() << endl;
cout << "\nHashmap search duration: " << hash_duration << " ms" << endl << endl;
}
else {
cout << "Invalid Option. Please Try Again." << endl << endl;
}
}
return 0;
}
Node* callInsert(Node* root, Odom* name, int id) {
if (!root) { //If the root is null, create the node outside of the insert function
return new Node(name, id);
}
//Finally, call the function
//O(logN)
return root->insert(name, id);
}
void findMin(Node* root, hashMap* u_map, string option, int max_time_) {
int min_time = 0;
int max_time = 0;
cout << endl << "How many milliseconds into the simulation would you like to start?" << endl;
cin >> min_time;
cout << endl << "How many milliseconds into the simulation would you like to start? (Select -1 for end of simulation)" << endl;
cin >> max_time;
min_time = (min_time / 10) * 10; //allows us to truncate any value not divisible by ten
if (max_time != -1 && max_time <= max_time_)
max_time = (max_time / 10) * 10; //allows us to truncate any value not divisible by ten
else
max_time = max_time_;
//Option is based on which physics value we want to find the min of
if (option == "1" || option == "2" || option == "3" || option == "4" ||
option == "5" || option == "6" || option == "7" || option == "8" || option == "9") {
auto min_start = chrono::system_clock::now();
cout << "\nThe min value for the avl tree is: " << root->minInorder(DBL_MAX, option, min_time, max_time) << endl;
auto min_stop = chrono::system_clock::now();
double min_duration = chrono::duration_cast<chrono::milliseconds>(min_stop - min_start).count();
cout << "\nAVL Tree finding minimum duration: " << min_duration << " ms" << endl;
auto min_start2 = chrono::system_clock::now();
double min = DBL_MAX;
double val = 0;
for (int i = min_time; i < max_time; i += 10) {
if (option == "1") {
val = u_map->get(i)->px_();
}
else if (option == "2") {
val = u_map->get(i)->py_();
}
else if (option == "3") {
val = u_map->get(i)->pz_();
}
else if (option == "4") {
val = u_map->get(i)->lvx_();
}
else if (option == "5") {
val = u_map->get(i)->lvy_();
}
else if (option == "6") {
val = u_map->get(i)->lvz_();
}
else if (option == "7") {
val = u_map->get(i)->avx_();
}
else if (option == "8") {
val = u_map->get(i)->avy_();
}
else if (option == "9") {
val = u_map->get(i)->avz_();
}
if (val < min)
min = val;
}
cout << "\nThe min value for the hashmap is: " << min << endl;
auto min_stop2 = chrono::system_clock::now();
double min_duration2 = chrono::duration_cast<chrono::milliseconds>(min_stop2 - min_start2).count();
cout << "\nHashmap finding minimum duration: " << min_duration2 << " ms" << endl << endl;
}
else {
cout << "Invalid Selection" << endl << endl;
}
}
void findMax(Node* root, hashMap* u_map, string option, int max_time_) {
int min_time = 0;
int max_time = 0;
cout << endl << "How many milliseconds into the simulation would you like to start?" << endl;
cin >> min_time;
cout << endl << "How many milliseconds into the simulation would you like to start? (Select -1 for end of simulation)" << endl;
cin >> max_time;
min_time = (min_time / 10) * 10; //allows us to truncate any value not divisible by ten
if (max_time != -1 && max_time <= max_time_)
max_time = (max_time / 10) * 10; //allows us to truncate any value not divisible by ten
else
max_time = max_time_;
//Option is based on which physics value we want to find the min of
if (option == "1" || option == "2" || option == "3" || option == "4" ||
option == "5" || option == "6" || option == "7" || option == "8" || option == "9") {
auto max_start = chrono::system_clock::now();
cout << "\nThe max value for the avl tree is: " << root->maxInorder(0, option, min_time, max_time) << endl;
auto max_stop = chrono::system_clock::now();
double max_duration = chrono::duration_cast<chrono::milliseconds>(max_stop - max_start).count();
cout << "\nAVL Tree finding maximum duration: " << max_duration << " ms" << endl;
auto max_start2 = chrono::system_clock::now();
double max = 0;
double val = 0;
for (int i = min_time; i < max_time; i += 10) {
if (option == "1") {
val = u_map->get(i)->px_();
}
else if (option == "2") {
val = u_map->get(i)->py_();
}
else if (option == "3") {
val = u_map->get(i)->pz_();
}
else if (option == "4") {
val = u_map->get(i)->lvx_();
}
else if (option == "5") {
val = u_map->get(i)->lvy_();
}
else if (option == "6") {
val = u_map->get(i)->lvz_();
}
else if (option == "7") {
val = u_map->get(i)->avx_();
}
else if (option == "8") {
val = u_map->get(i)->avy_();
}
else if (option == "9") {
val = u_map->get(i)->avz_();
}
if (val > max) {
max = val;
}
}
cout << "\nThe max value for the hashmap is: " << max << endl;
auto max_stop2 = chrono::system_clock::now();
double max_duration2 = chrono::duration_cast<chrono::milliseconds>(max_stop2 - max_start2).count();
cout << "\nHashmap finding max duration: " << max_duration2 << " ms" << endl << endl;
}
else {
cout << "Invalid Selection" << endl << endl;
}
}
void findAverage(Node* root, hashMap* u_map, string option, int max_time_) {
int min_time = 0;
int max_time = 0;
cout << endl << "How many milliseconds into the simulation would you like to start?" << endl;
cin >> min_time;
cout << endl << "How many milliseconds into the simulation would you like to start? (Select -1 for end of simulation)" << endl;
cin >> max_time;
min_time = (min_time / 10) * 10; //allows us to truncate any value not divisible by ten
if (max_time != -1 && max_time <= max_time_)
max_time = (max_time / 10) * 10; //allows us to truncate any value not divisible by ten
else
max_time = max_time_;
//Option is based on which physics value we want to find the min of
if (option == "1" || option == "2" || option == "3" || option == "4" ||
option == "5" || option == "6" || option == "7" || option == "8" || option == "9") {
auto average_start = chrono::system_clock::now();
cout << "\nThe average value for the avl tree is: " << root->sumInorder(0, option, min_time, max_time) / (1 + (max_time - min_time) / 10) << endl;
auto average_stop = chrono::system_clock::now();
double average_duration = chrono::duration_cast<chrono::milliseconds>(average_stop - average_start).count();
cout << "\nAVL Tree finding average duration: " << average_duration << " ms" << endl;
auto average_start2 = chrono::system_clock::now();
double sum = 0;
double val = 0;
for (int i = min_time; i < max_time; i += 10) {
if (option == "1") {
sum += u_map->get(i)->px_();
}
else if (option == "2") {
sum += u_map->get(i)->py_();
}
else if (option == "3") {
sum += u_map->get(i)->pz_();
}
else if (option == "4") {
sum += u_map->get(i)->lvx_();
}
else if (option == "5") {
sum += u_map->get(i)->lvy_();
}
else if (option == "6") {
sum += u_map->get(i)->lvz_();
}
else if (option == "7") {
sum += u_map->get(i)->avx_();
}
else if (option == "8") {
sum += u_map->get(i)->avy_();
}
else if (option == "9") {
sum += u_map->get(i)->avz_();
}
}
auto average_stop2 = chrono::system_clock::now();
cout << "\nThe average value for the hashmap is: " << sum / (1 + (max_time - min_time)/10) << endl;
double average_duration2 = chrono::duration_cast<chrono::milliseconds>(average_stop2 - average_start2).count();
cout << "\nHashmap finding average duration: " << average_duration2 << " ms" << endl << endl;
}
else {
cout << "Invalid Selection" << endl << endl;
}
} |
8ffb41e6f9dd1111db62df5befb7c4157d7cd293 | ac914a40dccfc860baba59cc569a00acf31779eb | /src/external_interface/CExternalInterface.cpp | 7fb2e28f000df37b850e72fc4d8723d8533b3e39 | [] | no_license | baaaab/unusual-object-detector | a45ebad93bc5df6991deac71643d02b2fbe6913f | 8d4447a1bcf1211592b4c5b2aca91b7652f434ac | refs/heads/master | 2020-05-20T17:22:45.786474 | 2019-05-08T22:26:13 | 2019-05-08T22:26:13 | 185,686,164 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,537 | cpp | CExternalInterface.cpp | #include "CExternalInterface.h"
#include "../core/CUnusualObjectDetector.h"
#include "../core/CImageStore.h"
#include "../core/CHog.h"
#include "../core/CModel.h"
#include <settings.h>
CExternalInterface::CExternalInterface(CUnusualObjectDetector* unusualObjectDetector) :
_unusualObjectDetector( unusualObjectDetector )
{
}
CExternalInterface::~CExternalInterface()
{
}
uint32_t CExternalInterface::getImageWidth()
{
return IMAGE_WIDTH;
}
uint32_t CExternalInterface::getImageHeight()
{
return IMAGE_HEIGHT;
}
uint32_t CExternalInterface::getMaxNumCellsPerSide()
{
return HOG_NUM_CELLS;
}
std::vector<float> CExternalInterface::getScoreDistribution()
{
return _unusualObjectDetector->getScoreDistribution();
}
std::vector<std::vector<bool> > CExternalInterface::getModel()
{
return _unusualObjectDetector->getModel()->getModel();
}
std::vector<uint16_t> CExternalInterface::getHog(uint32_t imageId)
{
CImageStore* imageStore = _unusualObjectDetector->getImageStore();
cv::Mat im = imageStore->fetchImage(imageId);
CHog hog(im, imageId);
return hog.getHOG();
}
std::vector<float> CExternalInterface::getRCH(uint32_t imageId)
{
CImageStore* imageStore = _unusualObjectDetector->getImageStore();
cv::Mat im = imageStore->fetchImage(imageId);
CHog hog(im, imageId);
CModel* model = _unusualObjectDetector->getModel();
hog.computeRCH(model);
return hog.getRCH();
}
std::vector<uint32_t>CExternalInterface::getUnusualImageList() const
{
return _unusualObjectDetector->getImageStore()->getUnusualImageList();
}
|
3fa70425aae762bca44147f6109013bed1dd6512 | e923e77ae54e721e3a606aea44e92fba46459e61 | /src/abstract_vm/inc/error.hpp | 3f3df072bf1cf60cd95e6c6fd7454104f60c1f3c | [] | no_license | gbersac/abstract_vm_42 | d066f2a6d0d9fc93faad79486d9ce325eed50c21 | 486cc995fd84aecb748e8aa6fdf71c5c1ae413ea | refs/heads/master | 2020-05-17T22:30:21.400041 | 2015-10-29T14:49:04 | 2015-10-29T14:49:04 | 42,865,441 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,094 | hpp | error.hpp | #ifndef ERROR_H
# define ERROR_H
#include <exception>
#include <sstream>
#include <string>
class IOperand;
typedef IOperand const* Oper;
/******************************************************************************/
/* Base Class */
/******************************************************************************/
class VMError: public std::exception
{
public:
virtual std::string msg() const = 0;
virtual char const * what() const throw() = 0;
};
class ParseError: public VMError
{
virtual std::string msg() const = 0;
char const * what() const throw();
};
class ExecutionError: public VMError
{
virtual std::string msg() const = 0;
char const * what() const throw();
};
/******************************************************************************/
/* Execution Error */
/******************************************************************************/
class AssertError: public ExecutionError
{
public:
AssertError(Oper expected, Oper real);
std::string msg() const;
private:
Oper _expected;
Oper _real;
};
class EmptyStackError: public ExecutionError
{
public:
EmptyStackError();
std::string msg() const;
};
class Not8bitIntError: public ExecutionError
{
public:
Not8bitIntError();
std::string msg() const;
};
class RvalueZeroError: public ExecutionError
{
public:
RvalueZeroError();
std::string msg() const;
};
/******************************************************************************/
/* Parsing Error */
/******************************************************************************/
class InvalidInstructionError: public ParseError
{
public:
InvalidInstructionError();
~InvalidInstructionError() throw();
std::string msg() const;
};
class OverflowError: public ParseError
{
public:
OverflowError();
~OverflowError() throw();
std::string msg() const;
};
class NoExitError: public ParseError
{
public:
NoExitError();
std::string msg() const;
};
#endif
|
4d92923aac767e775b152e514421b160e084bab6 | ea1a2d7323f0d8ae8126a2edf821b691af98083e | /src/symbol/const.cpp | 723bb1f95ab2042bdcdeb8adb855e0313a9ed330 | [] | no_license | smagnan/Lutin | 918c6e3f83e3187eed35468c94105037b17184fc | bb5ac72d5ab729f2699ab6e09e0a0ef6f1ec7a05 | refs/heads/master | 2021-01-13T02:11:33.069605 | 2015-03-31T09:25:51 | 2015-03-31T09:25:51 | 31,362,467 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 306 | cpp | const.cpp | // ---------------------------------------------
// const.cpp
//
// Created :
// by : Pierre GODARD
//
// ---------------------------------------------
#include "const.h"
S_Const::S_Const()
: Symbol(CONST)
{
}
S_Const::~S_Const()
{
}
std::string S_Const::print() const
{
return "const";
}
|
1baccd5bfc00c4cb921ed9ca53f87703f025494f | 44957500406858a0ef206e8f0bd6bcaee01fc90c | /pulsadorLedRGB_092021.ino | 54d507a3cf15e06c8a8b75b6d20d165623a58dd1 | [] | no_license | YazefVE/EjerciciosArduino | ad1ccfdc6740a27810f7db2792e33d30f239b09d | ce1896e20467d9e0f874a4acc92b15e79c60f417 | refs/heads/main | 2023-08-19T14:38:50.814503 | 2021-10-10T06:02:30 | 2021-10-10T06:02:30 | 415,491,957 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,142 | ino | pulsadorLedRGB_092021.ino | /****************************************************************
DEtectar moviemnto con ultrasonido y activar buzzer y led
Materiales:
led RGB
buzzer
ultrasonido
1 resistencias 220 omh (led)
Arduino UNO
Resistencias de 220omh
*****************************************************************/
/*Variables para guardar velocidad, distancia y tiempo*/
float velocidad = 0.01716, distancia = 0, tiempo = 0;
/*Variables para pines echo y trigger del ultrasonido, buzzer y led*/
int trigger = 2, echo = A5, buzzer = 4, led = 5;
void setup()
{
Serial.begin(9600);
pinMode(trigger, OUTPUT);
pinMode(echo, INPUT);
pinMode(buzzer, OUTPUT);
pinMode(led, OUTPUT);
}
void loop()
{
digitalWrite(trigger,LOW);
delayMicroseconds(20);
digitalWrite(trigger,HIGH);
delayMicroseconds(10);
digitalWrite(trigger,LOW);
tiempo = pulseIn(echo,HIGH);
distancia = velocidad * tiempo;
if(distancia < 100){
digitalWrite(buzzer, HIGH);
digitalWrite(led, HIGH);
delay(distancia*10);
digitalWrite(buzzer, LOW);
digitalWrite(led, LOW);
delay(distancia*10);
}
Serial.println(distancia);
} |
09de4ddd465b1e8b8a77f1ca0aa9c64d302c448b | 3e110416778b12752ab8703015a165c8c971e9a3 | /2020/2020_Pot_III_4/main.cpp | aacf7f50e7669e95386f54d0a4cd146f0d3d53ee | [] | no_license | sboda1985/erettsegi | 67fd8e337e85561041d24e52ad4e5e988dd42363 | ff15e6bf81e93b3027b0f03240baf6b96fc880b7 | refs/heads/master | 2023-09-02T21:07:33.032793 | 2023-05-19T04:42:02 | 2023-05-19T04:42:02 | 119,490,959 | 1 | 10 | null | 2023-02-19T14:13:26 | 2018-01-30T06:10:36 | C++ | UTF-8 | C++ | false | false | 440 | cpp | main.cpp | #include <iostream>
#include <fstream>
using namespace std;
int main()
{
int x, y, prev3;
ofstream out("bac.txt");
cout << "x = ";
cin >> x;
cout << "y = ";
cin >> y;
int prev1 = y;
int prev2 = x;
prev3 = prev2;
while (prev3>0){
out << prev1 << " ";
prev3 = 2*prev2 - prev1 + 2;
prev1 = prev2;
prev2 = prev3;
}
out << prev1 << " " << prev2 ;
return 0;
}
|
b1b4129bcfd5f4ca9cea0b29486fad8016df1444 | aaf03e46ce124856baea665233b6a76254f01b78 | /CppPrimer/Chapter16/16_28/Unique_ptr.h | 94c8961c9bb124bbe5e0a6f80fa244c3e2411ece | [] | no_license | MisLink/CppPrimer | 06b40255cfdce84c20a473b310bcc469426643ec | dd67b60fca6868110cc190990b1f92b4badfa108 | refs/heads/master | 2020-05-18T02:52:01.723400 | 2017-03-02T16:29:01 | 2017-03-02T16:29:01 | 27,751,475 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 308 | h | Unique_ptr.h | #ifndef UNIQUEPTR_H
#define UNIQUEPTR_H
#include"DebugDelete.h"
template<typename T, typename D = DebugDelete>
class Unique_ptr {
public:
Unique_ptr( ) = default;
Unique_ptr(D d) :del(d) { }
~Unique_ptr( ) { del(ptr); }
private:
T *ptr = nullptr;
D del = D( );
};
#endif // !UNIQUEPTR_H
|
32bdfcfdf0532b986a6ec2fb569c781d3c33d57e | 0afe19dc19d0646271aab90596a3617d749e6786 | /ares/ms/cpu/cpu.cpp | acc5c3f86ddd7ffab6026a4813af73318605ca69 | [
"ISC"
] | permissive | byuubackup/ares | 8654d8d39a9b2cc75e1cc030fd70b6854ac0cd1f | b6e807b54f69ad18a4788868b9de33a752ea7458 | refs/heads/master | 2022-12-04T18:12:38.720148 | 2020-07-25T02:06:51 | 2020-07-25T02:06:51 | 282,349,863 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,072 | cpp | cpu.cpp | #include <ms/ms.hpp>
namespace ares::MasterSystem {
CPU cpu;
#include "memory.cpp"
#include "debugger.cpp"
#include "serialization.cpp"
auto CPU::load(Node::Object parent) -> void {
ram.allocate(8_KiB);
node = parent->append<Node::Component>("CPU");
debugger.load(node);
}
auto CPU::unload() -> void {
ram.reset();
node = {};
debugger = {};
}
auto CPU::main() -> void {
if(state.nmiLine) {
state.nmiLine = 0; //edge-sensitive
debugger.interrupt("NMI");
irq(0, 0x0066, 0xff);
}
if(state.irqLine) {
//level-sensitive
debugger.interrupt("IRQ");
irq(1, 0x0038, 0xff);
}
debugger.instruction();
instruction();
}
auto CPU::step(uint clocks) -> void {
Thread::step(clocks);
Thread::synchronize();
}
auto CPU::setNMI(bool value) -> void {
state.nmiLine = value;
}
auto CPU::setIRQ(bool value) -> void {
state.irqLine = value;
}
auto CPU::power() -> void {
Z80::bus = this;
Z80::power();
Thread::create(system.colorburst(), {&CPU::main, this});
r.pc = 0x0000; //reset vector address
state = {};
}
}
|
906ccecca49763ad6262f6afa35e793c0409b078 | d52ecc1a4f57702ab703f8a6ccb42f77463458ff | /pca/src/data_handler.h | 742b6743f2d7750b767693a02fc2d6118e0dea52 | [] | no_license | gianluca-capelo/numerical_analysis | 120c7279dc2ad7997594e0e28c61e620e7663b2b | 0510c036ea82841fc31eb75b06e08c332c4089c3 | refs/heads/main | 2023-02-09T11:32:11.788289 | 2021-01-02T21:10:57 | 2021-01-02T21:10:57 | 326,269,612 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 523 | h | data_handler.h | #ifndef DATA_HANDLER_H
#define DATA_HANDLER_H
#include "types.h"
class DataHandler {
public:
DataHandler();
DataHandler(char* train_set_file, char* test_set_file);
void load_train_set(char* train_set_file);
Matrix& train_data();
Matrix& train_label();
void load_test_set(char* test_set_file);
Matrix& test_data();
Vector& classif();
void export_classif(char* out_file);
private:
Matrix _train_data;
Matrix _train_label;
Matrix _test_data;
Vector _classif;
};
#endif /* DATA_HANDLER_H */ |
487f734ddde6a7cdc0725abbca25847eaeb97bf1 | 0b96060d8445e6917663e74efdecb5aadbd08a43 | /myclient.h | 77b5cffbadcc2c949793068cd1e020c5b87fbe8d | [] | no_license | Mihailus2000/Server-for-XO | 06f0822d5bbb8e41aab905634ccb1987d7f76d36 | 1771dcfb570e3f0c12f6c0f2b489676fdcb44441 | refs/heads/master | 2020-06-04T21:02:07.106140 | 2019-06-16T12:53:46 | 2019-06-16T12:53:46 | 192,190,586 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 684 | h | myclient.h | #ifndef MYCLIENT_H
#define MYCLIENT_H
#include <QObject>
#include <QTcpSocket>
#include <QDebug>
#include <QByteArray>
#include <QDataStream>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
class MyClient : public QObject
{
Q_OBJECT
public:
explicit MyClient(int socketDescriptor,QTcpSocket* socket,QObject *parent = nullptr);
QTcpSocket* getSocket();
signals:
public slots:
void sockDisk();
void sockReady();
private:
QTcpSocket* _sok; //сокет пользователя
int sok_desck;
QByteArray Data;
QJsonDocument doc;
QJsonParseError docError;
signals:
void startGame();
};
#endif // MYCLIENT_H
|
c0aa0ecea65911acdf79cb29dcbb3ae6c3f307eb | f9ebf1a1c0ec436e2580875cd61b1dd028022c6d | /src/tools.hpp | fdaa22caad1347fbada00c998c430c0a5a19853f | [
"MIT"
] | permissive | aboutNisblee/MineSweeperMatrix | ba6ba3663468d718c3e001a5410d420ce2fac162 | 786415cc02333528f02cf452e048036854152f19 | refs/heads/master | 2021-05-28T01:51:40.246456 | 2014-11-28T08:39:09 | 2014-11-28T08:39:35 | 27,181,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,013 | hpp | tools.hpp | /**
* \addtogroup tools
* \{
*
* \file tools.hpp
*
* \date 18.11.2012
* \author Moritz Nisblé moritz.nisble@gmx.de
*/
#ifndef SRC_TOOLS_HPP_
#define SRC_TOOLS_HPP_
#include <stdint.h>
#include <exception>
#include <sstream>
#include "field.hpp"
namespace msm
{
template<class T>
struct compare_address
{
explicit compare_address(T const* p) :
p(p)
{
}
bool operator()(T const* rhs)
{
return (p == rhs);
}
T const* p;
};
///Exception that is throw when the Matrix is accessed at an invalid position.
class IndexOutOfBoundsException: public std::exception
{
public:
/// Constructor.
IndexOutOfBoundsException() throw ();
/** Constructor.
* \param index The index that was illegal accessed.
* \param length The length of the array.
* \param dimension A char describing the dimension in the Matrix (e.g. 'X'). */
IndexOutOfBoundsException(uint16_t index, uint16_t length, char dimension) throw ()
{
idx = index;
len = length;
dim = dimension;
}
/// Destructor.
virtual ~IndexOutOfBoundsException() throw ()
{
}
/** What message.
* \return A c-style string with the error message. */
virtual const char* what() const throw ()
{
std::stringstream ss;
ss << "Matrix index out of bounds. Index: " << idx << " exceeding array length of: " << len << " in dimension: "
<< dim;
return ss.str().c_str();
}
uint16_t idx;
uint16_t len;
char dim;
};
/// Helper class to enable overloading of the 2-dimensional array operator.
class Proxy
{
public:
Proxy(Field** x, uint16_t maxY) :
x(x), maxY(maxY)
{
}
/** Field-access-operator for the vertical dimension.
* \param y The Y-coordinate inside the matrix.
* \return Reference to the \ref Field "field" at the given coordinates.
*/
Field& operator[](uint16_t y) const throw (IndexOutOfBoundsException)
{
if (y >= maxY)
throw IndexOutOfBoundsException(y, maxY, 'Y');
else
return *x[y];
}
private:
Field** x;
uint16_t maxY;
};
} // namespace msm
#endif /* SRC_TOOLS_HPP_ */
///\}
|
1663e098420ef0929d28b19e8bb07a0a0cb7e9c5 | d973af5e5aea21d8b206cf9f9fe2193fc7dc43cc | /include/phd/base/base.hpp | a9e137871a59418c1fc738153c73eefb7c5a0c6e | [] | no_license | blockspacer/phd | f2d97a1c5093b2c695e4cc0db066d3d495656710 | 9c3ada84dbf23a2964b6e654d550191815bf5f30 | refs/heads/main | 2022-12-02T23:38:43.787826 | 2020-08-21T07:39:26 | 2020-08-21T07:39:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 133 | hpp | base.hpp | #pragma once
#ifndef PHD_BASE_BASE_HPP
#define PHD_BASE_BASE_HPP
#include <phd/base/ebco.hpp>
#endif // PHD_BASE_BASE_HPP
|
e1c528581c06ce75ec917a7baeae6020d27864bf | a5a99f646e371b45974a6fb6ccc06b0a674818f2 | /RecoBTag/SecondaryVertex/plugins/BoostedDoubleSVProducer.cc | c903c83cd4713e01fac9a9b698901a73c0a3d8ac | [
"Apache-2.0"
] | permissive | cms-sw/cmssw | 4ecd2c1105d59c66d385551230542c6615b9ab58 | 19c178740257eb48367778593da55dcad08b7a4f | refs/heads/master | 2023-08-23T21:57:42.491143 | 2023-08-22T20:22:40 | 2023-08-22T20:22:40 | 10,969,551 | 1,006 | 3,696 | Apache-2.0 | 2023-09-14T19:14:28 | 2013-06-26T14:09:07 | C++ | UTF-8 | C++ | false | false | 30,962 | cc | BoostedDoubleSVProducer.cc | // -*- C++ -*-
//
// Package: RecoBTag/SecondaryVertex
// Class: BoostedDoubleSVProducer
//
/**\class BoostedDoubleSVProducer BoostedDoubleSVProducer.cc RecoBTag/SecondaryVertex/plugins/BoostedDoubleSVProducer.cc
*
* Description: EDProducer that produces collection of BoostedDoubleSVTagInfos
*
* Implementation:
* A collection of SecondaryVertexTagInfos is taken as input and a collection of BoostedDoubleSVTagInfos
* is produced as output.
*/
//
// Original Author: Dinko Ferencek
// Created: Thu, 06 Oct 2016 14:02:30 GMT
//
//
// system include files
#include <memory>
// user include files
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/stream/EDProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Utilities/interface/StreamID.h"
#include "FWCore/Utilities/interface/isFinite.h"
#include "FWCore/Utilities/interface/ESGetToken.h"
#include "DataFormats/BTauReco/interface/CandIPTagInfo.h"
#include "DataFormats/BTauReco/interface/CandSecondaryVertexTagInfo.h"
#include "DataFormats/BTauReco/interface/BoostedDoubleSVTagInfo.h"
#include "DataFormats/BTauReco/interface/TaggingVariable.h"
#include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h"
#include "DataFormats/PatCandidates/interface/PackedCandidate.h"
#include "DataFormats/VertexReco/interface/Vertex.h"
#include "DataFormats/VertexReco/interface/VertexFwd.h"
#include "DataFormats/Candidate/interface/VertexCompositePtrCandidate.h"
#include "RecoBTag/SecondaryVertex/interface/TrackKinematics.h"
#include "RecoBTag/SecondaryVertex/interface/V0Filter.h"
#include "RecoBTag/SecondaryVertex/interface/TrackSelector.h"
#include "RecoVertex/VertexPrimitives/interface/ConvertToFromReco.h"
#include "TrackingTools/Records/interface/TransientTrackRecord.h"
#include "TrackingTools/IPTools/interface/IPTools.h"
#include "TrackingTools/TransientTrack/interface/TransientTrackBuilder.h"
#include "fastjet/PseudoJet.hh"
#include "fastjet/contrib/Njettiness.hh"
#include <map>
//
// class declaration
//
class BoostedDoubleSVProducer : public edm::stream::EDProducer<> {
public:
explicit BoostedDoubleSVProducer(const edm::ParameterSet&);
~BoostedDoubleSVProducer() override;
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
private:
void beginStream(edm::StreamID) override;
void produce(edm::Event&, const edm::EventSetup&) override;
void endStream() override;
void calcNsubjettiness(const reco::JetBaseRef& jet,
float& tau1,
float& tau2,
std::vector<fastjet::PseudoJet>& currentAxes) const;
void setTracksPVBase(const reco::TrackRef& trackRef, const reco::VertexRef& vertexRef, float& PVweight) const;
void setTracksPV(const reco::CandidatePtr& trackRef, const reco::VertexRef& vertexRef, float& PVweight) const;
void etaRelToTauAxis(const reco::VertexCompositePtrCandidate& vertex,
const fastjet::PseudoJet& tauAxis,
std::vector<float>& tau_trackEtaRel) const;
// ----------member data ---------------------------
const edm::EDGetTokenT<std::vector<reco::CandSecondaryVertexTagInfo>> svTagInfos_;
const double beta_;
const double R0_;
const double maxSVDeltaRToJet_;
const double maxDistToAxis_;
const double maxDecayLen_;
reco::V0Filter trackPairV0Filter;
reco::TrackSelector trackSelector;
edm::EDGetTokenT<edm::ValueMap<float>> weightsToken_;
edm::ESGetToken<TransientTrackBuilder, TransientTrackRecord> trackBuilderToken_;
edm::Handle<edm::ValueMap<float>> weightsHandle_;
// static variables
static constexpr float dummyZ_ratio = -3.0f;
static constexpr float dummyTrackSip3dSig = -50.0f;
static constexpr float dummyTrackSip2dSigAbove = -19.0f;
static constexpr float dummyTrackEtaRel = -1.0f;
static constexpr float dummyVertexMass = -1.0f;
static constexpr float dummyVertexEnergyRatio = -1.0f;
static constexpr float dummyVertexDeltaR = -1.0f;
static constexpr float dummyFlightDistance2dSig = -1.0f;
static constexpr float charmThreshold = 1.5f;
static constexpr float bottomThreshold = 5.2f;
};
//
// constants, enums and typedefs
//
//
// static data member definitions
//
//
// constructors and destructor
//
BoostedDoubleSVProducer::BoostedDoubleSVProducer(const edm::ParameterSet& iConfig)
: svTagInfos_(
consumes<std::vector<reco::CandSecondaryVertexTagInfo>>(iConfig.getParameter<edm::InputTag>("svTagInfos"))),
beta_(iConfig.getParameter<double>("beta")),
R0_(iConfig.getParameter<double>("R0")),
maxSVDeltaRToJet_(iConfig.getParameter<double>("maxSVDeltaRToJet")),
maxDistToAxis_(iConfig.getParameter<edm::ParameterSet>("trackSelection").getParameter<double>("maxDistToAxis")),
maxDecayLen_(iConfig.getParameter<edm::ParameterSet>("trackSelection").getParameter<double>("maxDecayLen")),
trackPairV0Filter(iConfig.getParameter<edm::ParameterSet>("trackPairV0Filter")),
trackSelector(iConfig.getParameter<edm::ParameterSet>("trackSelection")) {
edm::InputTag srcWeights = iConfig.getParameter<edm::InputTag>("weights");
trackBuilderToken_ =
esConsumes<TransientTrackBuilder, TransientTrackRecord>(edm::ESInputTag("", "TransientTrackBuilder"));
if (!srcWeights.label().empty())
weightsToken_ = consumes<edm::ValueMap<float>>(srcWeights);
produces<std::vector<reco::BoostedDoubleSVTagInfo>>();
}
BoostedDoubleSVProducer::~BoostedDoubleSVProducer() {
// do anything here that needs to be done at destruction time
// (e.g. close files, deallocate resources etc.)
}
//
// member functions
//
// ------------ method called to produce the data ------------
void BoostedDoubleSVProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) {
// get the track builder
edm::ESHandle<TransientTrackBuilder> trackBuilder = iSetup.getHandle(trackBuilderToken_);
// get input secondary vertex TagInfos
edm::Handle<std::vector<reco::CandSecondaryVertexTagInfo>> svTagInfos;
iEvent.getByToken(svTagInfos_, svTagInfos);
if (!weightsToken_.isUninitialized())
iEvent.getByToken(weightsToken_, weightsHandle_);
// create the output collection
auto tagInfos = std::make_unique<std::vector<reco::BoostedDoubleSVTagInfo>>();
// loop over TagInfos
for (std::vector<reco::CandSecondaryVertexTagInfo>::const_iterator iterTI = svTagInfos->begin();
iterTI != svTagInfos->end();
++iterTI) {
// get TagInfos
const reco::CandIPTagInfo& ipTagInfo = *(iterTI->trackIPTagInfoRef().get());
const reco::CandSecondaryVertexTagInfo& svTagInfo = *(iterTI);
// default variable values
float z_ratio = dummyZ_ratio;
float trackSip3dSig_3 = dummyTrackSip3dSig, trackSip3dSig_2 = dummyTrackSip3dSig,
trackSip3dSig_1 = dummyTrackSip3dSig, trackSip3dSig_0 = dummyTrackSip3dSig;
float tau2_trackSip3dSig_0 = dummyTrackSip3dSig, tau1_trackSip3dSig_0 = dummyTrackSip3dSig,
tau2_trackSip3dSig_1 = dummyTrackSip3dSig, tau1_trackSip3dSig_1 = dummyTrackSip3dSig;
float trackSip2dSigAboveCharm_0 = dummyTrackSip2dSigAbove, trackSip2dSigAboveBottom_0 = dummyTrackSip2dSigAbove,
trackSip2dSigAboveBottom_1 = dummyTrackSip2dSigAbove;
float tau1_trackEtaRel_0 = dummyTrackEtaRel, tau1_trackEtaRel_1 = dummyTrackEtaRel,
tau1_trackEtaRel_2 = dummyTrackEtaRel;
float tau2_trackEtaRel_0 = dummyTrackEtaRel, tau2_trackEtaRel_1 = dummyTrackEtaRel,
tau2_trackEtaRel_2 = dummyTrackEtaRel;
float tau1_vertexMass = dummyVertexMass, tau1_vertexEnergyRatio = dummyVertexEnergyRatio,
tau1_vertexDeltaR = dummyVertexDeltaR, tau1_flightDistance2dSig = dummyFlightDistance2dSig;
float tau2_vertexMass = dummyVertexMass, tau2_vertexEnergyRatio = dummyVertexEnergyRatio,
tau2_vertexDeltaR = dummyVertexDeltaR, tau2_flightDistance2dSig = dummyFlightDistance2dSig;
float jetNTracks = 0, nSV = 0, tau1_nSecondaryVertices = 0, tau2_nSecondaryVertices = 0;
// get the jet reference
const reco::JetBaseRef jet = svTagInfo.jet();
std::vector<fastjet::PseudoJet> currentAxes;
float tau2, tau1;
// calculate N-subjettiness
calcNsubjettiness(jet, tau1, tau2, currentAxes);
const reco::VertexRef& vertexRef = ipTagInfo.primaryVertex();
GlobalPoint pv(0., 0., 0.);
if (ipTagInfo.primaryVertex().isNonnull())
pv = GlobalPoint(vertexRef->x(), vertexRef->y(), vertexRef->z());
const std::vector<reco::CandidatePtr>& selectedTracks = ipTagInfo.selectedTracks();
const std::vector<reco::btag::TrackIPData>& ipData = ipTagInfo.impactParameterData();
size_t trackSize = selectedTracks.size();
reco::TrackKinematics allKinematics;
std::vector<float> IP3Ds, IP3Ds_1, IP3Ds_2;
int contTrk = 0;
// loop over tracks associated to the jet
for (size_t itt = 0; itt < trackSize; ++itt) {
const reco::CandidatePtr trackRef = selectedTracks[itt];
float track_PVweight = 0.;
setTracksPV(trackRef, vertexRef, track_PVweight);
if (track_PVweight > 0.5)
allKinematics.add(trackRef);
const reco::btag::TrackIPData& data = ipData[itt];
bool isSelected = false;
if (trackSelector(trackRef, data, *jet, pv))
isSelected = true;
// check if the track is from V0
bool isfromV0 = false, isfromV0Tight = false;
std::vector<reco::CandidatePtr> trackPairV0Test(2);
trackPairV0Test[0] = trackRef;
for (size_t jtt = 0; jtt < trackSize; ++jtt) {
if (itt == jtt)
continue;
const reco::btag::TrackIPData& pairTrackData = ipData[jtt];
const reco::CandidatePtr pairTrackRef = selectedTracks[jtt];
trackPairV0Test[1] = pairTrackRef;
if (!trackPairV0Filter(trackPairV0Test)) {
isfromV0 = true;
if (trackSelector(pairTrackRef, pairTrackData, *jet, pv))
isfromV0Tight = true;
}
if (isfromV0 && isfromV0Tight)
break;
}
if (isSelected && !isfromV0Tight)
jetNTracks += 1.;
reco::TransientTrack transientTrack = trackBuilder->build(trackRef);
GlobalVector direction(jet->px(), jet->py(), jet->pz());
int index = 0;
if (currentAxes.size() > 1 &&
reco::deltaR2(trackRef->momentum(), currentAxes[1]) < reco::deltaR2(trackRef->momentum(), currentAxes[0]))
index = 1;
direction = GlobalVector(currentAxes[index].px(), currentAxes[index].py(), currentAxes[index].pz());
// decay distance and track distance wrt to the closest tau axis
float decayLengthTau = -1;
float distTauAxis = -1;
TrajectoryStateOnSurface closest = IPTools::closestApproachToJet(
transientTrack.impactPointState(), *vertexRef, direction, transientTrack.field());
if (closest.isValid())
decayLengthTau = (closest.globalPosition() - RecoVertex::convertPos(vertexRef->position())).mag();
distTauAxis = std::abs(IPTools::jetTrackDistance(transientTrack, direction, *vertexRef).second.value());
float IP3Dsig = ipTagInfo.impactParameterData()[itt].ip3d.significance();
if (!isfromV0 && decayLengthTau < maxDecayLen_ && distTauAxis < maxDistToAxis_) {
IP3Ds.push_back(IP3Dsig < -50. ? -50. : IP3Dsig);
++contTrk;
if (currentAxes.size() > 1) {
if (reco::deltaR2(trackRef->momentum(), currentAxes[0]) < reco::deltaR2(trackRef->momentum(), currentAxes[1]))
IP3Ds_1.push_back(IP3Dsig < -50. ? -50. : IP3Dsig);
else
IP3Ds_2.push_back(IP3Dsig < -50. ? -50. : IP3Dsig);
} else
IP3Ds_1.push_back(IP3Dsig < -50. ? -50. : IP3Dsig);
}
}
std::vector<size_t> indices = ipTagInfo.sortedIndexes(reco::btag::IP2DSig);
bool charmThreshSet = false;
reco::TrackKinematics kin;
for (size_t i = 0; i < indices.size(); ++i) {
size_t idx = indices[i];
const reco::btag::TrackIPData& data = ipData[idx];
const reco::CandidatePtr trackRef = selectedTracks[idx];
kin.add(trackRef);
if (kin.vectorSum().M() > charmThreshold // charm cut
&& !charmThreshSet) {
trackSip2dSigAboveCharm_0 = data.ip2d.significance();
charmThreshSet = true;
}
if (kin.vectorSum().M() > bottomThreshold) // bottom cut
{
trackSip2dSigAboveBottom_0 = data.ip2d.significance();
if ((i + 1) < indices.size())
trackSip2dSigAboveBottom_1 = (ipData[indices[i + 1]]).ip2d.significance();
break;
}
}
float dummyTrack = -50.;
std::sort(IP3Ds.begin(), IP3Ds.end(), std::greater<float>());
std::sort(IP3Ds_1.begin(), IP3Ds_1.end(), std::greater<float>());
std::sort(IP3Ds_2.begin(), IP3Ds_2.end(), std::greater<float>());
int num_1 = IP3Ds_1.size();
int num_2 = IP3Ds_2.size();
switch (contTrk) {
case 0:
trackSip3dSig_0 = dummyTrack;
trackSip3dSig_1 = dummyTrack;
trackSip3dSig_2 = dummyTrack;
trackSip3dSig_3 = dummyTrack;
break;
case 1:
trackSip3dSig_0 = IP3Ds.at(0);
trackSip3dSig_1 = dummyTrack;
trackSip3dSig_2 = dummyTrack;
trackSip3dSig_3 = dummyTrack;
break;
case 2:
trackSip3dSig_0 = IP3Ds.at(0);
trackSip3dSig_1 = IP3Ds.at(1);
trackSip3dSig_2 = dummyTrack;
trackSip3dSig_3 = dummyTrack;
break;
case 3:
trackSip3dSig_0 = IP3Ds.at(0);
trackSip3dSig_1 = IP3Ds.at(1);
trackSip3dSig_2 = IP3Ds.at(2);
trackSip3dSig_3 = dummyTrack;
break;
default:
trackSip3dSig_0 = IP3Ds.at(0);
trackSip3dSig_1 = IP3Ds.at(1);
trackSip3dSig_2 = IP3Ds.at(2);
trackSip3dSig_3 = IP3Ds.at(3);
}
switch (num_1) {
case 0:
tau1_trackSip3dSig_0 = dummyTrack;
tau1_trackSip3dSig_1 = dummyTrack;
break;
case 1:
tau1_trackSip3dSig_0 = IP3Ds_1.at(0);
tau1_trackSip3dSig_1 = dummyTrack;
break;
default:
tau1_trackSip3dSig_0 = IP3Ds_1.at(0);
tau1_trackSip3dSig_1 = IP3Ds_1.at(1);
}
switch (num_2) {
case 0:
tau2_trackSip3dSig_0 = dummyTrack;
tau2_trackSip3dSig_1 = dummyTrack;
break;
case 1:
tau2_trackSip3dSig_0 = IP3Ds_2.at(0);
tau2_trackSip3dSig_1 = dummyTrack;
break;
default:
tau2_trackSip3dSig_0 = IP3Ds_2.at(0);
tau2_trackSip3dSig_1 = IP3Ds_2.at(1);
}
math::XYZVector jetDir = jet->momentum().Unit();
reco::TrackKinematics tau1Kinematics;
reco::TrackKinematics tau2Kinematics;
std::vector<float> tau1_trackEtaRels, tau2_trackEtaRels;
std::map<double, size_t> VTXmap;
for (size_t vtx = 0; vtx < svTagInfo.nVertices(); ++vtx) {
const reco::VertexCompositePtrCandidate& vertex = svTagInfo.secondaryVertex(vtx);
// get the vertex kinematics
reco::TrackKinematics vertexKinematic(vertex);
if (currentAxes.size() > 1) {
if (reco::deltaR2(svTagInfo.flightDirection(vtx), currentAxes[1]) <
reco::deltaR2(svTagInfo.flightDirection(vtx), currentAxes[0])) {
tau2Kinematics = tau2Kinematics + vertexKinematic;
if (tau2_flightDistance2dSig < 0) {
tau2_flightDistance2dSig = svTagInfo.flightDistance(vtx, true).significance();
tau2_vertexDeltaR = reco::deltaR(svTagInfo.flightDirection(vtx), currentAxes[1]);
}
etaRelToTauAxis(vertex, currentAxes[1], tau2_trackEtaRels);
tau2_nSecondaryVertices += 1.;
} else {
tau1Kinematics = tau1Kinematics + vertexKinematic;
if (tau1_flightDistance2dSig < 0) {
tau1_flightDistance2dSig = svTagInfo.flightDistance(vtx, true).significance();
tau1_vertexDeltaR = reco::deltaR(svTagInfo.flightDirection(vtx), currentAxes[0]);
}
etaRelToTauAxis(vertex, currentAxes[0], tau1_trackEtaRels);
tau1_nSecondaryVertices += 1.;
}
} else if (!currentAxes.empty()) {
tau1Kinematics = tau1Kinematics + vertexKinematic;
if (tau1_flightDistance2dSig < 0) {
tau1_flightDistance2dSig = svTagInfo.flightDistance(vtx, true).significance();
tau1_vertexDeltaR = reco::deltaR(svTagInfo.flightDirection(vtx), currentAxes[0]);
}
etaRelToTauAxis(vertex, currentAxes[0], tau1_trackEtaRels);
tau1_nSecondaryVertices += 1.;
}
const GlobalVector& flightDir = svTagInfo.flightDirection(vtx);
if (reco::deltaR2(flightDir, jetDir) < (maxSVDeltaRToJet_ * maxSVDeltaRToJet_))
VTXmap[svTagInfo.flightDistance(vtx).error()] = vtx;
}
nSV = VTXmap.size();
math::XYZTLorentzVector allSum = allKinematics.weightedVectorSum();
if (tau1_nSecondaryVertices > 0.) {
const math::XYZTLorentzVector& tau1_vertexSum = tau1Kinematics.weightedVectorSum();
if (allSum.E() > 0.)
tau1_vertexEnergyRatio = tau1_vertexSum.E() / allSum.E();
if (tau1_vertexEnergyRatio > 50.)
tau1_vertexEnergyRatio = 50.;
tau1_vertexMass = tau1_vertexSum.M();
}
if (tau2_nSecondaryVertices > 0.) {
const math::XYZTLorentzVector& tau2_vertexSum = tau2Kinematics.weightedVectorSum();
if (allSum.E() > 0.)
tau2_vertexEnergyRatio = tau2_vertexSum.E() / allSum.E();
if (tau2_vertexEnergyRatio > 50.)
tau2_vertexEnergyRatio = 50.;
tau2_vertexMass = tau2_vertexSum.M();
}
float dummyEtaRel = -1.;
std::sort(tau1_trackEtaRels.begin(), tau1_trackEtaRels.end());
std::sort(tau2_trackEtaRels.begin(), tau2_trackEtaRels.end());
switch (tau2_trackEtaRels.size()) {
case 0:
tau2_trackEtaRel_0 = dummyEtaRel;
tau2_trackEtaRel_1 = dummyEtaRel;
tau2_trackEtaRel_2 = dummyEtaRel;
break;
case 1:
tau2_trackEtaRel_0 = tau2_trackEtaRels.at(0);
tau2_trackEtaRel_1 = dummyEtaRel;
tau2_trackEtaRel_2 = dummyEtaRel;
break;
case 2:
tau2_trackEtaRel_0 = tau2_trackEtaRels.at(0);
tau2_trackEtaRel_1 = tau2_trackEtaRels.at(1);
tau2_trackEtaRel_2 = dummyEtaRel;
break;
default:
tau2_trackEtaRel_0 = tau2_trackEtaRels.at(0);
tau2_trackEtaRel_1 = tau2_trackEtaRels.at(1);
tau2_trackEtaRel_2 = tau2_trackEtaRels.at(2);
}
switch (tau1_trackEtaRels.size()) {
case 0:
tau1_trackEtaRel_0 = dummyEtaRel;
tau1_trackEtaRel_1 = dummyEtaRel;
tau1_trackEtaRel_2 = dummyEtaRel;
break;
case 1:
tau1_trackEtaRel_0 = tau1_trackEtaRels.at(0);
tau1_trackEtaRel_1 = dummyEtaRel;
tau1_trackEtaRel_2 = dummyEtaRel;
break;
case 2:
tau1_trackEtaRel_0 = tau1_trackEtaRels.at(0);
tau1_trackEtaRel_1 = tau1_trackEtaRels.at(1);
tau1_trackEtaRel_2 = dummyEtaRel;
break;
default:
tau1_trackEtaRel_0 = tau1_trackEtaRels.at(0);
tau1_trackEtaRel_1 = tau1_trackEtaRels.at(1);
tau1_trackEtaRel_2 = tau1_trackEtaRels.at(2);
}
int cont = 0;
GlobalVector flightDir_0, flightDir_1;
reco::Candidate::LorentzVector SV_p4_0, SV_p4_1;
double vtxMass = 0.;
for (std::map<double, size_t>::iterator iVtx = VTXmap.begin(); iVtx != VTXmap.end(); ++iVtx) {
++cont;
const reco::VertexCompositePtrCandidate& vertex = svTagInfo.secondaryVertex(iVtx->second);
if (cont == 1) {
flightDir_0 = svTagInfo.flightDirection(iVtx->second);
SV_p4_0 = vertex.p4();
vtxMass = SV_p4_0.mass();
if (vtxMass > 0.)
z_ratio = reco::deltaR(currentAxes[1], currentAxes[0]) * SV_p4_0.pt() / vtxMass;
}
if (cont == 2) {
flightDir_1 = svTagInfo.flightDirection(iVtx->second);
SV_p4_1 = vertex.p4();
vtxMass = (SV_p4_1 + SV_p4_0).mass();
if (vtxMass > 0.)
z_ratio = reco::deltaR(flightDir_0, flightDir_1) * SV_p4_1.pt() / vtxMass;
break;
}
}
// when only one tau axis has SVs assigned, they are all assigned to the 1st tau axis
// in the special case below need to swap values
if ((tau1_vertexMass < 0 && tau2_vertexMass > 0)) {
float temp = tau1_trackEtaRel_0;
tau1_trackEtaRel_0 = tau2_trackEtaRel_0;
tau2_trackEtaRel_0 = temp;
temp = tau1_trackEtaRel_1;
tau1_trackEtaRel_1 = tau2_trackEtaRel_1;
tau2_trackEtaRel_1 = temp;
temp = tau1_trackEtaRel_2;
tau1_trackEtaRel_2 = tau2_trackEtaRel_2;
tau2_trackEtaRel_2 = temp;
temp = tau1_flightDistance2dSig;
tau1_flightDistance2dSig = tau2_flightDistance2dSig;
tau2_flightDistance2dSig = temp;
tau1_vertexDeltaR = tau2_vertexDeltaR;
temp = tau1_vertexEnergyRatio;
tau1_vertexEnergyRatio = tau2_vertexEnergyRatio;
tau2_vertexEnergyRatio = temp;
temp = tau1_vertexMass;
tau1_vertexMass = tau2_vertexMass;
tau2_vertexMass = temp;
}
reco::TaggingVariableList vars;
vars.insert(reco::btau::jetNTracks, jetNTracks, true);
vars.insert(reco::btau::jetNSecondaryVertices, nSV, true);
vars.insert(reco::btau::trackSip3dSig_0, trackSip3dSig_0, true);
vars.insert(reco::btau::trackSip3dSig_1, trackSip3dSig_1, true);
vars.insert(reco::btau::trackSip3dSig_2, trackSip3dSig_2, true);
vars.insert(reco::btau::trackSip3dSig_3, trackSip3dSig_3, true);
vars.insert(reco::btau::tau1_trackSip3dSig_0, tau1_trackSip3dSig_0, true);
vars.insert(reco::btau::tau1_trackSip3dSig_1, tau1_trackSip3dSig_1, true);
vars.insert(reco::btau::tau2_trackSip3dSig_0, tau2_trackSip3dSig_0, true);
vars.insert(reco::btau::tau2_trackSip3dSig_1, tau2_trackSip3dSig_1, true);
vars.insert(reco::btau::trackSip2dSigAboveCharm, trackSip2dSigAboveCharm_0, true);
vars.insert(reco::btau::trackSip2dSigAboveBottom_0, trackSip2dSigAboveBottom_0, true);
vars.insert(reco::btau::trackSip2dSigAboveBottom_1, trackSip2dSigAboveBottom_1, true);
vars.insert(reco::btau::tau1_trackEtaRel_0, tau1_trackEtaRel_0, true);
vars.insert(reco::btau::tau1_trackEtaRel_1, tau1_trackEtaRel_1, true);
vars.insert(reco::btau::tau1_trackEtaRel_2, tau1_trackEtaRel_2, true);
vars.insert(reco::btau::tau2_trackEtaRel_0, tau2_trackEtaRel_0, true);
vars.insert(reco::btau::tau2_trackEtaRel_1, tau2_trackEtaRel_1, true);
vars.insert(reco::btau::tau2_trackEtaRel_2, tau2_trackEtaRel_2, true);
vars.insert(reco::btau::tau1_vertexMass, tau1_vertexMass, true);
vars.insert(reco::btau::tau1_vertexEnergyRatio, tau1_vertexEnergyRatio, true);
vars.insert(reco::btau::tau1_flightDistance2dSig, tau1_flightDistance2dSig, true);
vars.insert(reco::btau::tau1_vertexDeltaR, tau1_vertexDeltaR, true);
vars.insert(reco::btau::tau2_vertexMass, tau2_vertexMass, true);
vars.insert(reco::btau::tau2_vertexEnergyRatio, tau2_vertexEnergyRatio, true);
vars.insert(reco::btau::tau2_flightDistance2dSig, tau2_flightDistance2dSig, true);
vars.insert(reco::btau::z_ratio, z_ratio, true);
vars.finalize();
tagInfos->push_back(reco::BoostedDoubleSVTagInfo(
vars, edm::Ref<std::vector<reco::CandSecondaryVertexTagInfo>>(svTagInfos, iterTI - svTagInfos->begin())));
}
// put the output in the event
iEvent.put(std::move(tagInfos));
}
void BoostedDoubleSVProducer::calcNsubjettiness(const reco::JetBaseRef& jet,
float& tau1,
float& tau2,
std::vector<fastjet::PseudoJet>& currentAxes) const {
std::vector<fastjet::PseudoJet> fjParticles;
// loop over jet constituents and push them in the vector of FastJet constituents
for (const reco::CandidatePtr& daughter : jet->daughterPtrVector()) {
if (daughter.isNonnull() && daughter.isAvailable()) {
const reco::Jet* subjet = dynamic_cast<const reco::Jet*>(daughter.get());
// if the daughter is actually a subjet
if (subjet && daughter->numberOfDaughters() > 1) {
// loop over subjet constituents and push them in the vector of FastJet constituents
for (size_t i = 0; i < daughter->numberOfDaughters(); ++i) {
const reco::CandidatePtr& constit = subjet->daughterPtr(i);
if (constit.isNonnull() && constit->pt() > std::numeric_limits<double>::epsilon()) {
// Check if any values were nan or inf
float valcheck = constit->px() + constit->py() + constit->pz() + constit->energy();
if (edm::isNotFinite(valcheck)) {
edm::LogWarning("FaultyJetConstituent")
<< "Jet constituent required for N-subjettiness computation contains Nan/Inf values!";
continue;
}
if (subjet->isWeighted()) {
float w = 0.0;
if (!weightsToken_.isUninitialized())
w = (*weightsHandle_)[constit];
else {
throw cms::Exception("MissingConstituentWeight")
<< "BoostedDoubleSVProducer: No weights (e.g. PUPPI) given for weighted jet collection"
<< std::endl;
}
if (w > 0) {
fjParticles.push_back(
fastjet::PseudoJet(constit->px() * w, constit->py() * w, constit->pz() * w, constit->energy() * w));
}
} else {
fjParticles.push_back(fastjet::PseudoJet(constit->px(), constit->py(), constit->pz(), constit->energy()));
}
} else
edm::LogWarning("MissingJetConstituent")
<< "Jet constituent required for N-subjettiness computation is missing!";
}
} else {
// Check if any values were nan or inf
float valcheck = daughter->px() + daughter->py() + daughter->pz() + daughter->energy();
if (edm::isNotFinite(valcheck)) {
edm::LogWarning("FaultyJetConstituent")
<< "Jet constituent required for N-subjettiness computation contains Nan/Inf values!";
continue;
}
if (jet->isWeighted()) {
float w = 0.0;
if (!weightsToken_.isUninitialized())
w = (*weightsHandle_)[daughter];
else {
throw cms::Exception("MissingConstituentWeight")
<< "BoostedDoubleSVProducer: No weights (e.g. PUPPI) given for weighted jet collection" << std::endl;
}
if (w > 0 && daughter->pt() > std::numeric_limits<double>::epsilon()) {
fjParticles.push_back(
fastjet::PseudoJet(daughter->px() * w, daughter->py() * w, daughter->pz() * w, daughter->energy() * w));
}
} else {
fjParticles.push_back(fastjet::PseudoJet(daughter->px(), daughter->py(), daughter->pz(), daughter->energy()));
}
}
} else
edm::LogWarning("MissingJetConstituent") << "Jet constituent required for N-subjettiness computation is missing!";
}
// N-subjettiness calculator
fastjet::contrib::Njettiness njettiness(fastjet::contrib::OnePass_KT_Axes(),
fastjet::contrib::NormalizedMeasure(beta_, R0_));
// calculate N-subjettiness
tau1 = njettiness.getTau(1, fjParticles);
tau2 = njettiness.getTau(2, fjParticles);
currentAxes = njettiness.currentAxes();
}
void BoostedDoubleSVProducer::setTracksPVBase(const reco::TrackRef& trackRef,
const reco::VertexRef& vertexRef,
float& PVweight) const {
PVweight = 0.;
const reco::TrackBaseRef trackBaseRef(trackRef);
typedef reco::Vertex::trackRef_iterator IT;
const reco::Vertex& vtx = *(vertexRef);
// loop over tracks in vertices
for (IT it = vtx.tracks_begin(); it != vtx.tracks_end(); ++it) {
const reco::TrackBaseRef& baseRef = *it;
// one of the tracks in the vertex is the same as the track considered in the function
if (baseRef == trackBaseRef) {
PVweight = vtx.trackWeight(baseRef);
break;
}
}
}
void BoostedDoubleSVProducer::setTracksPV(const reco::CandidatePtr& trackRef,
const reco::VertexRef& vertexRef,
float& PVweight) const {
PVweight = 0.;
const pat::PackedCandidate* pcand = dynamic_cast<const pat::PackedCandidate*>(trackRef.get());
if (pcand) // MiniAOD case
{
if (pcand->fromPV() == pat::PackedCandidate::PVUsedInFit) {
PVweight = 1.;
}
} else {
const reco::PFCandidate* pfcand = dynamic_cast<const reco::PFCandidate*>(trackRef.get());
setTracksPVBase(pfcand->trackRef(), vertexRef, PVweight);
}
}
void BoostedDoubleSVProducer::etaRelToTauAxis(const reco::VertexCompositePtrCandidate& vertex,
const fastjet::PseudoJet& tauAxis,
std::vector<float>& tau_trackEtaRel) const {
math::XYZVector direction(tauAxis.px(), tauAxis.py(), tauAxis.pz());
const std::vector<reco::CandidatePtr>& tracks = vertex.daughterPtrVector();
for (std::vector<reco::CandidatePtr>::const_iterator track = tracks.begin(); track != tracks.end(); ++track)
tau_trackEtaRel.push_back(std::abs(reco::btau::etaRel(direction.Unit(), (*track)->momentum())));
}
// ------------ method called once each stream before processing any runs, lumis or events ------------
void BoostedDoubleSVProducer::beginStream(edm::StreamID) {}
// ------------ method called once each stream after processing all runs, lumis and events ------------
void BoostedDoubleSVProducer::endStream() {}
// ------------ method fills 'descriptions' with the allowed parameters for the module ------------
void BoostedDoubleSVProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
edm::ParameterSetDescription desc;
desc.add<double>("beta", 1.0);
desc.add<double>("R0", 0.8);
desc.add<double>("maxSVDeltaRToJet", 0.7);
{
edm::ParameterSetDescription trackSelection;
trackSelection.setAllowAnything();
desc.add<edm::ParameterSetDescription>("trackSelection", trackSelection);
}
{
edm::ParameterSetDescription trackPairV0Filter;
trackPairV0Filter.add<double>("k0sMassWindow", 0.03);
desc.add<edm::ParameterSetDescription>("trackPairV0Filter", trackPairV0Filter);
}
desc.add<edm::InputTag>("svTagInfos", edm::InputTag("pfInclusiveSecondaryVertexFinderAK8TagInfos"));
desc.add<edm::InputTag>("weights", edm::InputTag(""));
descriptions.addDefault(desc);
}
//define this as a plug-in
DEFINE_FWK_MODULE(BoostedDoubleSVProducer);
|
fa795c49edbfdc14b38cde562c7ebc46f4e2b4ae | a5c20f27ac2991e42681f36874430007daaa8c9a | /1-100/94. Binary Tree Inorder Traversal.cpp | c1aa39c2ebb00f621fa5514e9dc53f2fc09417b9 | [] | no_license | tyq-1112/leetcode_note | 57f900f970f93c209b735b5e6da6916885eed96b | 6e000bb5c77946ba73bf6a02ecf5ff04cdf58252 | refs/heads/main | 2023-06-18T16:44:25.020076 | 2021-07-15T03:53:12 | 2021-07-15T03:53:12 | 374,507,476 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,206 | cpp | 94. Binary Tree Inorder Traversal.cpp | #include <bits/stdc++.h>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> ans;
vector<int> inorderTraversal(TreeNode* root) {
dfs(root);
return ans;
}
void dfs(TreeNode* root){
if(root){
dfs(root->left);
ans.push_back(root->val);
dfs(root->right);
}
}
};
/*
给定一个二叉树的根节点 root ,返回它的 中序 遍历。
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
示例 4:
输入:root = [1,2]
输出:[2,1]
示例 5:
输入:root = [1,null,2]
输出:[1,2]
提示:
树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
*/ |
9dd336b4a81c2309901d1d40a8deaae940a7534e | d37298735bf83f1dcbc39daea78ac84c9321a42d | /2017_GameServer/IOCPServer/IOCPServer.cpp | fae3a821d9b723e6bfad6f07e430683dd604d1a2 | [] | no_license | on1659/KPU_IOCP_GameServer_2017_ | e9912a766c589a3c2495ab872abcda5f1f121fef | c0c34f9f6ce4f1597801a1426451f6f64ec85feb | refs/heads/master | 2021-06-16T08:24:08.135722 | 2017-05-29T05:23:48 | 2017-05-29T05:23:48 | 88,931,959 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 155 | cpp | IOCPServer.cpp |
#include "../header.h"
#include "IOCPServer.h"
CIOCPServer::CIOCPServer()
{
CMiniDump::Start();
}
CIOCPServer::~CIOCPServer()
{
CMiniDump::End();
}
|
62229186bc6891641d99a66fe0ef8ea71339f8e1 | e21f322152c75f3541301a3df01d24fdc5370535 | /containers/MultiSpecialization/NoHostallocator.hpp | 81686e221655827edb23943c094711ef4202757c | [] | no_license | QMCPACK/cxx_prototype | b38dca72fcdd9071816805f72e239aeb74488e93 | 5c78bbd5ee40bab26c1c7ca39a484255f28ef92e | refs/heads/master | 2020-05-27T04:49:49.946010 | 2019-05-25T02:28:14 | 2019-05-25T02:28:35 | 188,489,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,672 | hpp | NoHostallocator.hpp | //////////////////////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source License.
// See LICENSE file in top directory for details.
//
// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
//
// File developed by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory
//
// File created by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory
//////////////////////////////////////////////////////////////////////////////////////
// -*- C++ -*-
/** @file NoHostallocator.hpp
*/
#ifndef QMCPLUSPLUS_NoHost_ALLOCATOR_H
#define QMCPLUSPLUS_NoHost_ALLOCATOR_H
#include <cstdlib>
#include <string>
#include <stdexcept>
#include <string>
namespace qmcplusplus
{
template<typename T, size_t ALIGN>
struct NoHostallocator
{
typedef T value_type;
typedef size_t size_type;
typedef T* pointer;
typedef const T* const_pointer;
NoHostallocator() = default;
template<class U>
NoHostallocator(const NoHostallocator<U, ALIGN>&)
{}
template<class U>
struct rebind
{
typedef NoHostallocator<U, ALIGN> other;
};
T* allocate(std::size_t n)
{
void* pt(nullptr);
std::size_t asize = n * sizeof(T);
std::size_t amod = asize % ALIGN;
if (amod != 0)
asize += ALIGN - amod;
#if __STDC_VERSION__ >= 201112L || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16)
// as per C11 standard asize must be an integral multiple of ALIGN
// or behavior is undefined. Some implementations support all positive
// values of asize but the standard has not been amended
// This is also not guaranteed threadsafe until it appeared in
// the C++17 standard.
pt = aligned_alloc(ALIGN, asize);
#else
// While posix memalign can deal with asize violating the C11 standard
// assumptions made later by our simd code namely copyn require allocation
// of the entire aligned block to avoid heap buffer read overflows later
posix_memalign(&pt, ALIGN, asize);
#endif
if (pt == nullptr)
throw std::runtime_error("Allocation failed in NoHostallocator, requested size in bytes = " +
std::to_string(n * sizeof(T)));
return static_cast<T*>(pt);
}
void deallocate(T* p, std::size_t) { free(p); }
};
template<class T1, size_t ALIGN1, class T2, size_t ALIGN2>
bool operator==(const NoHostallocator<T1, ALIGN1>&, const NoHostallocator<T2, ALIGN2>&)
{
return ALIGN1 == ALIGN2;
}
template<class T1, size_t ALIGN1, class T2, size_t ALIGN2>
bool operator!=(const NoHostallocator<T1, ALIGN1>&, const NoHostallocator<T2, ALIGN2>&)
{
return ALIGN1 != ALIGN2;
}
} // namespace qmcplusplus
#endif
|
c18ffe1ea381726f5699020ceb947a3a5b283f78 | 31475b58b676a174d89b3130f869656366dc3078 | /fm_game/scenemanager.h | 4bb82d3c3657cb239e357934e64af323168c758e | [] | no_license | cooper-zhzhang/engine | ed694d15b5d065d990828e43e499de9fa141fc47 | b19b45316220fae2a1d00052297957268c415045 | refs/heads/master | 2021-06-21T07:09:37.355174 | 2017-07-18T14:51:45 | 2017-07-18T14:51:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 394 | h | scenemanager.h |
#pragma once
#include "../public/i_entity.h"
#include <vector>
#include <string>
#include <map>
class SceneObjManager : public IEntity
{
private:
PERSISTID player;
public:
SceneObjManager();
~SceneObjManager();
virtual bool Init(const IVarList& args);
virtual bool Shut();
virtual void Execute(float seconds);
PERSISTID& GetPlayerId();
void SetPlayer(const PERSISTID& id);
}; |
d376e216f5202f58acb43faad35807ff45872da3 | 35f8e34dc8e7005551fa57b88f52c0b2581425ff | /src/core/robotInterface/XMLReader.cpp | dc900a8e341e03535d92c797dfce4ec0dba2cce7 | [] | no_license | warp1337/icub-main | 721cb1bbdf2a939ca9fecd329f07844935b138c2 | e7034ec500599db6dd92be4f25c3073ca0c6b957 | refs/heads/master | 2020-02-26T17:20:23.471478 | 2014-10-27T14:09:12 | 2014-10-27T14:09:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,318 | cpp | XMLReader.cpp | /*
* Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia
* Author: Daniele E. Domenichelli <daniele.domenichelli@iit.it>
*
* CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
*/
#include "XMLReader.h"
#include "Action.h"
#include "Device.h"
#include "Param.h"
#include "Robot.h"
#include "Types.h"
#include <yarp/os/LogStream.h>
#include <tinyxml.h>
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <yarp/os/Property.h>
#include <yarp/os/ResourceFinder.h>
#define SYNTAX_ERROR(line) yFatal() << "Syntax error while loading" << curr_filename << "at line" << line << "."
#define SYNTAX_WARNING(line) yWarning() << "Invalid syntax while loading" << curr_filename << "at line" << line << "."
// BUG in TinyXML, see
// https://sourceforge.net/tracker/?func=detail&aid=3567726&group_id=13559&atid=113559
// When this bug is fixed upstream we can enable this
#define TINYXML_UNSIGNED_INT_BUG 0
namespace {
// Represent something like this in the xml file
// <!DOCTYPE robot PUBLIC "-//YARP//DTD robotInterface 1.0//EN" "http://www.icub.org/DTD/robotInterfaceV1.0.dtd">
class RobotInterfaceDTD
{
public:
enum DocType {
DocTypeUnknown = 0,
DocTypeRobot,
DocTypeDevices,
DocTypeParams,
DocTypeActions,
};
RobotInterfaceDTD() :
type(DocTypeUnknown),
identifier(""),
uri(""),
majorVersion(0),
minorVersion(0) {}
bool parse(TiXmlUnknown* unknownNode, std::string curr_filename);
bool valid() { return type != DocTypeUnknown && majorVersion != 0;}
void setDefault() {
type = RobotInterfaceDTD::DocTypeUnknown;
identifier = "-//YARP//DTD robotInterface 1.0//EN";
uri = "http://www.icub.org/DTD/robotInterfaceV1.0.dtd";
majorVersion = 1;
minorVersion = 0;
}
DocType type;
std::string identifier;
std::string uri;
unsigned int majorVersion;
unsigned int minorVersion;
static const std::string baseUri;
static const std::string ext;
};
const std::string RobotInterfaceDTD::baseUri("http://www.icub.org/DTD/robotInterfaceV");
const std::string RobotInterfaceDTD::ext(".dtd");
RobotInterfaceDTD::DocType StringToDocType(const std::string &type) {
if (!type.compare("robot")) {
return RobotInterfaceDTD::DocTypeRobot;
} else if (!type.compare("devices")) {
return RobotInterfaceDTD::DocTypeDevices;
} else if (!type.compare("params")) {
return RobotInterfaceDTD::DocTypeParams;
} else if (!type.compare("actions")) {
return RobotInterfaceDTD::DocTypeActions;
}
return RobotInterfaceDTD::DocTypeUnknown;
}
std::string DocTypeToString(RobotInterfaceDTD::DocType doctype) {
switch (doctype) {
case RobotInterfaceDTD::DocTypeRobot:
return std::string("robot");
case RobotInterfaceDTD::DocTypeDevices:
return std::string("devices");
case RobotInterfaceDTD::DocTypeParams:
return std::string("params");
case RobotInterfaceDTD::DocTypeActions:
return std::string("actions");
default:
return std::string();
}
}
bool RobotInterfaceDTD::parse(TiXmlUnknown* unknownNode, std::string curr_filename) {
// Very basic and ugly DTD tag parsing as TinyXML does not support it
// We just need the version numbers.
// Split tag in token
std::istringstream iss(unknownNode->ValueStr());
std::vector<std::string> tokens;
std::copy(std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>(),
std::back_inserter<std::vector<std::string> >(tokens));
// Merge token in quotes (and remove quotes)
for (std::vector<std::string>::iterator it = tokens.begin(); it != tokens.end(); ++it) {
if(it->at(0) == '"' ) {
if (it->at(it->size() - 1) == '"') {
*it = it->substr(1, it->size() - 2);
} else {
std::string s = it->substr(1) + " ";
for (std::vector<std::string>::iterator cit = it + 1; cit != tokens.end(); ) {
if (cit->at(cit->size() - 1) == '"') {
s += cit->substr(0, cit->size() - 1);
cit = tokens.erase(cit);
break;
} else {
s += *cit + " ";
cit = tokens.erase(cit);
}
}
*it = s;
}
}
}
if(tokens.size() != 5) {
SYNTAX_WARNING(unknownNode->Row()) << "Unknown node found" << tokens.size();
}
if(tokens.at(0) != "!DOCTYPE") {
SYNTAX_WARNING(unknownNode->Row()) << "Unknown node found";
}
type = StringToDocType(tokens.at(1));
if(type == RobotInterfaceDTD::DocTypeUnknown)
{
SYNTAX_WARNING(unknownNode->Row()) << "Unknown document type. Supported document types are: \"robot\", \"devices\", \"params\"";
}
if(tokens.at(2) != "PUBLIC") {
SYNTAX_WARNING(unknownNode->Row()) << "Unknown document type. Expected \"PUBLIC\", found" << tokens.at(2);
}
identifier = tokens.at(3); // For now just skip checks on the identifier
uri = tokens.at(4);
// Extract version numbers from the URI
if (uri.find(RobotInterfaceDTD::baseUri) != 0) {
SYNTAX_WARNING(unknownNode->Row()) << "Unknown document type. Unknown url" << uri;
}
std::size_t start = RobotInterfaceDTD::baseUri.size();
std::size_t end = uri.find(RobotInterfaceDTD::ext, start);
if (end == std::string::npos) {
SYNTAX_WARNING(unknownNode->Row()) << "Unknown document type. Unknown url" << uri;
}
std::string versionString = uri.substr(start, end - start);
std::size_t dot = versionString.find('.');
if (dot == std::string::npos) {
SYNTAX_WARNING(unknownNode->Row()) << "Unknown document type. Unknown url" << uri;
}
std::string majorVersionString = versionString.substr(0, dot);
std::string minorVersionString = versionString.substr(dot + 1);
std::istringstream majiss(majorVersionString);
if ( !(majiss >> majorVersion) ) {
SYNTAX_WARNING(unknownNode->Row()) << "Unknown document type. Missing version in Url" << uri;
}
std::istringstream miniss(minorVersionString);
if ( !(miniss >> minorVersion) ) {
SYNTAX_WARNING(unknownNode->Row()) << "Unknown document type. Missing version in Url" << uri;
}
// If we got here, this is a valid DTD declaration
return true;
}
} // namespace
class RobotInterface::XMLReader::Private
{
public:
Private(XMLReader *parent);
~Private();
RobotInterface::Robot& readRobotFile(const std::string &fileName);
RobotInterface::Robot& readRobotTag(TiXmlElement *robotElem);
RobotInterface::DeviceList readDevices(TiXmlElement *devicesElem);
RobotInterface::Device readDeviceTag(TiXmlElement *deviceElem);
RobotInterface::DeviceList readDevicesTag(TiXmlElement *devicesElem);
RobotInterface::DeviceList readDevicesFile(const std::string &fileName);
RobotInterface::ParamList readParams(TiXmlElement *paramsElem);
RobotInterface::Param readParamTag(TiXmlElement *paramElem);
RobotInterface::Param readGroupTag(TiXmlElement *groupElem);
RobotInterface::ParamList readParamListTag(TiXmlElement *paramListElem);
RobotInterface::ParamList readSubDeviceTag(TiXmlElement *subDeviceElem);
RobotInterface::ParamList readParamsTag(TiXmlElement *paramsElem);
RobotInterface::ParamList readParamsFile(const std::string &fileName);
RobotInterface::ActionList readActions(TiXmlElement *actionsElem);
RobotInterface::Action readActionTag(TiXmlElement *actionElem);
RobotInterface::ActionList readActionsTag(TiXmlElement *actionsElem);
RobotInterface::ActionList readActionsFile(const std::string &fileName);
XMLReader * const parent;
std::string filename;
std::string path;
RobotInterfaceDTD dtd;
Robot robot;
yarp::os::ResourceFinder rf;
std::string curr_filename;
unsigned int minorVersion;
unsigned int majorVersion;
};
RobotInterface::XMLReader::Private::Private(XMLReader *p) :
parent(p)
{
rf.setVerbose();
}
RobotInterface::XMLReader::Private::~Private()
{
}
RobotInterface::Robot& RobotInterface::XMLReader::Private::readRobotFile(const std::string &fileName)
{
filename = fileName;
#ifdef WIN32
std::replace(filename.begin(), filename.end(), '/', '\\');
#endif
curr_filename = fileName;
#ifdef WIN32
path = filename.substr(0, filename.rfind("\\"));
#else // WIN32
path = filename.substr(0, filename.rfind("/"));
#endif //WIN32
TiXmlDocument *doc = new TiXmlDocument(filename.c_str());
if (!doc->LoadFile()) {
SYNTAX_ERROR(doc->ErrorRow()) << doc->ErrorDesc();
}
if (!doc->RootElement()) {
SYNTAX_ERROR(doc->Row()) << "No root element.";
}
for (TiXmlNode* childNode = doc->FirstChild(); childNode != 0; childNode = childNode->NextSibling()) {
if (childNode->Type() == TiXmlNode::TINYXML_UNKNOWN) {
if(dtd.parse(childNode->ToUnknown(), curr_filename)) {
break;
}
}
}
if (!dtd.valid()) {
SYNTAX_WARNING(doc->Row()) << "No DTD found. Assuming version robotInterfaceV1.0";
dtd.setDefault();
dtd.type = RobotInterfaceDTD::DocTypeRobot;
}
if(dtd.type != RobotInterfaceDTD::DocTypeRobot) {
SYNTAX_WARNING(doc->Row()) << "Expected document of type" << DocTypeToString(RobotInterfaceDTD::DocTypeRobot)
<< ". Found" << DocTypeToString(dtd.type);
}
if(dtd.majorVersion != 1 || dtd.minorVersion != 0) {
SYNTAX_WARNING(doc->Row()) << "Only robotInterface DTD version 1.0 is supported";
}
readRobotTag(doc->RootElement());
delete doc;
// yDebug() << robot;
return robot;
}
RobotInterface::Robot& RobotInterface::XMLReader::Private::readRobotTag(TiXmlElement *robotElem)
{
if (robotElem->ValueStr().compare("robot") != 0) {
SYNTAX_ERROR(robotElem->Row()) << "Root element should be \"robot\". Found" << robotElem->ValueStr();
}
if (robotElem->QueryStringAttribute("name", &robot.name()) != TIXML_SUCCESS) {
SYNTAX_ERROR(robotElem->Row()) << "\"robot\" element should contain the \"name\" attribute";
}
#if TINYXML_UNSIGNED_INT_BUG
if (robotElem->QueryUnsignedAttribute("build", &robot.build()) != TIXML_SUCCESS) {
// No build attribute. Assuming build="0"
SYNTAX_WARNING(robotElem->Row()) << "\"robot\" element should contain the \"build\" attribute [unsigned int]. Assuming 0";
}
#else
int tmp;
if (robotElem->QueryIntAttribute("build", &tmp) != TIXML_SUCCESS || tmp < 0) {
// No build attribute. Assuming build="0"
SYNTAX_WARNING(robotElem->Row()) << "\"robot\" element should contain the \"build\" attribute [unsigned int]. Assuming 0";
tmp = 0;
}
robot.build() = (unsigned)tmp;
#endif
if (robotElem->QueryStringAttribute("portprefix", &robot.portprefix()) != TIXML_SUCCESS) {
SYNTAX_WARNING(robotElem->Row()) << "\"robot\" element should contain the \"portprefix\" attribute. Using \"name\" attribute";
robot.portprefix() = robot.name();
}
// yDebug() << "Found robot [" << robot.name() << "] build [" << robot.build() << "] portprefix [" << robot.portprefix() << "]";
for (TiXmlElement* childElem = robotElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) {
if (childElem->ValueStr().compare("device") == 0 || childElem->ValueStr().compare("devices") == 0) {
DeviceList childDevices = readDevices(childElem);
for (DeviceList::const_iterator it = childDevices.begin(); it != childDevices.end(); ++it) {
robot.devices().push_back(*it);
}
} else {
ParamList childParams = readParams(childElem);
for (ParamList::const_iterator it = childParams.begin(); it != childParams.end(); ++it) {
robot.params().push_back(*it);
}
}
}
return robot;
}
RobotInterface::DeviceList RobotInterface::XMLReader::Private::readDevices(TiXmlElement *devicesElem)
{
const std::string &valueStr = devicesElem->ValueStr();
if (valueStr.compare("device") != 0 &&
valueStr.compare("devices") != 0)
{
SYNTAX_ERROR(devicesElem->Row()) << "Expected \"device\" or \"devices\". Found" << valueStr;
}
if (valueStr.compare("device") == 0) {
// yDebug() << valueStr;
DeviceList deviceList;
deviceList.push_back(readDeviceTag(devicesElem));
return deviceList;
}
// "devices"
return readDevicesTag(devicesElem);
}
RobotInterface::Device RobotInterface::XMLReader::Private::readDeviceTag(TiXmlElement *deviceElem)
{
const std::string &valueStr = deviceElem->ValueStr();
if (valueStr.compare("device") != 0) {
SYNTAX_ERROR(deviceElem->Row()) << "Expected \"device\". Found" << valueStr;
}
Device device;
if (deviceElem->QueryStringAttribute("name", &device.name()) != TIXML_SUCCESS) {
SYNTAX_ERROR(deviceElem->Row()) << "\"device\" element should contain the \"name\" attribute";
}
// yDebug() << "Found device [" << device.name() << "]";
if (deviceElem->QueryStringAttribute("type", &device.type()) != TIXML_SUCCESS) {
SYNTAX_ERROR(deviceElem->Row()) << "\"device\" element should contain the \"type\" attribute";
}
device.params().push_back(Param("robotName", robot.portprefix().c_str()));
for (TiXmlElement* childElem = deviceElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) {
if (childElem->ValueStr().compare("action") == 0 ||
childElem->ValueStr().compare("actions") == 0) {
ActionList childActions = readActions(childElem);
for (ActionList::const_iterator it = childActions.begin(); it != childActions.end(); ++it) {
device.actions().push_back(*it);
}
} else {
ParamList childParams = readParams(childElem);
for (ParamList::const_iterator it = childParams.begin(); it != childParams.end(); ++it) {
device.params().push_back(*it);
}
}
}
// yDebug() << device;
return device;
}
RobotInterface::DeviceList RobotInterface::XMLReader::Private::readDevicesTag(TiXmlElement *devicesElem)
{
const std::string &valueStr = devicesElem->ValueStr();
if (valueStr.compare("devices") != 0) {
SYNTAX_ERROR(devicesElem->Row()) << "Expected \"devices\". Found" << valueStr;
}
std::string filename;
if (devicesElem->QueryStringAttribute("file", &filename) == TIXML_SUCCESS) {
// yDebug() << "Found devices file [" << filename << "]";
filename=rf.findFileByName(filename);
return readDevicesFile(filename);
}
std::string robotName;
if (devicesElem->QueryStringAttribute("robot", &robotName) != TIXML_SUCCESS) {
SYNTAX_WARNING(devicesElem->Row()) << "\"devices\" element should contain the \"robot\" attribute";
}
if (robotName != robot.name()) {
SYNTAX_WARNING(devicesElem->Row()) << "Trying to import a file for the wrong robot. Found" << robotName << "instead of" << robot.name();
}
unsigned int build;
#if TINYXML_UNSIGNED_INT_BUG
if (devicesElem->QueryUnsignedAttribute("build", &build()) != TIXML_SUCCESS) {
// No build attribute. Assuming build="0"
SYNTAX_WARNING(devicesElem->Row()) << "\"devices\" element should contain the \"build\" attribute [unsigned int]. Assuming 0";
}
#else
int tmp;
if (devicesElem->QueryIntAttribute("build", &tmp) != TIXML_SUCCESS || tmp < 0) {
// No build attribute. Assuming build="0"
SYNTAX_WARNING(devicesElem->Row()) << "\"devices\" element should contain the \"build\" attribute [unsigned int]. Assuming 0";
tmp = 0;
}
build = (unsigned)tmp;
#endif
if (build != robot.build()) {
SYNTAX_WARNING(devicesElem->Row()) << "Import a file for a different robot build. Found" << build << "instead of" << robot.build();
}
DeviceList devices;
for (TiXmlElement* childElem = devicesElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) {
DeviceList childDevices = readDevices(childElem);
for (DeviceList::const_iterator it = childDevices.begin(); it != childDevices.end(); ++it) {
devices.push_back(*it);
}
}
return devices;
}
RobotInterface::DeviceList RobotInterface::XMLReader::Private::readDevicesFile(const std::string &fileName)
{
std::string old_filename = curr_filename;
curr_filename = fileName;
TiXmlDocument *doc = new TiXmlDocument(fileName.c_str());
if (!doc->LoadFile()) {
SYNTAX_ERROR(doc->ErrorRow()) << doc->ErrorDesc();
}
if (!doc->RootElement()) {
SYNTAX_ERROR(doc->Row()) << "No root element.";
}
RobotInterfaceDTD devicesFileDTD;
for (TiXmlNode* childNode = doc->FirstChild(); childNode != 0; childNode = childNode->NextSibling()) {
if (childNode->Type() == TiXmlNode::TINYXML_UNKNOWN) {
if(devicesFileDTD.parse(childNode->ToUnknown(), curr_filename)) {
break;
}
}
}
if (!devicesFileDTD.valid()) {
SYNTAX_WARNING(doc->Row()) << "No DTD found. Assuming version robotInterfaceV1.0";
devicesFileDTD.setDefault();
devicesFileDTD.type = RobotInterfaceDTD::DocTypeDevices;
}
if (devicesFileDTD.type != RobotInterfaceDTD::DocTypeDevices) {
SYNTAX_ERROR(doc->Row()) << "Expected document of type" << DocTypeToString(RobotInterfaceDTD::DocTypeDevices)
<< ". Found" << DocTypeToString(devicesFileDTD.type);
}
if (devicesFileDTD.majorVersion != dtd.majorVersion) {
SYNTAX_ERROR(doc->Row()) << "Trying to import a file with a different robotInterface DTD version";
}
RobotInterface::DeviceList devices = readDevicesTag(doc->RootElement());
delete doc;
curr_filename = old_filename;
return devices;
}
RobotInterface::ParamList RobotInterface::XMLReader::Private::readParams(TiXmlElement* paramsElem)
{
const std::string &valueStr = paramsElem->ValueStr();
if (valueStr.compare("param") != 0 &&
valueStr.compare("group") != 0 &&
valueStr.compare("paramlist") != 0 &&
valueStr.compare("subdevice") != 0 &&
valueStr.compare("params") != 0)
{
SYNTAX_ERROR(paramsElem->Row()) << "Expected \"param\", \"group\", \"paramlist\","
<< "\"subdevice\", or \"params\". Found" << valueStr;
}
if (valueStr.compare("param") == 0) {
ParamList params;
params.push_back(readParamTag(paramsElem));
return params;
} else if (valueStr.compare("group") == 0) {
ParamList params;
params.push_back(readGroupTag(paramsElem));
return params;
} else if (valueStr.compare("paramlist") == 0) {
return readParamListTag(paramsElem);
} else if (valueStr.compare("subdevice") == 0) {
return readSubDeviceTag(paramsElem);
}
// "params"
return readParamsTag(paramsElem);
}
RobotInterface::Param RobotInterface::XMLReader::Private::readParamTag(TiXmlElement *paramElem)
{
if (paramElem->ValueStr().compare("param") != 0) {
SYNTAX_ERROR(paramElem->Row()) << "Expected \"param\". Found" << paramElem->ValueStr();
}
Param param;
if (paramElem->QueryStringAttribute("name", ¶m.name()) != TIXML_SUCCESS) {
SYNTAX_ERROR(paramElem->Row()) << "\"param\" element should contain the \"name\" attribute";
}
// yDebug() << "Found param [" << param.name() << "]";
const char *valueText = paramElem->GetText();
if (!valueText) {
SYNTAX_ERROR(paramElem->Row()) << "\"param\" element should have a value [ \"name\" = " << param.name() << "]";
}
param.value() = valueText;
// yDebug() << param;
return param;
}
RobotInterface::Param RobotInterface::XMLReader::Private::readGroupTag(TiXmlElement* groupElem)
{
if (groupElem->ValueStr().compare("group") != 0) {
SYNTAX_ERROR(groupElem->Row()) << "Expected \"group\". Found" << groupElem->ValueStr();
}
Param group(true);
if (groupElem->QueryStringAttribute("name", &group.name()) != TIXML_SUCCESS) {
SYNTAX_ERROR(groupElem->Row()) << "\"group\" element should contain the \"name\" attribute";
}
// yDebug() << "Found group [" << group.name() << "]";
ParamList params;
for (TiXmlElement* childElem = groupElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) {
ParamList childParams = readParams(childElem);
for (ParamList::const_iterator it = childParams.begin(); it != childParams.end(); ++it) {
params.push_back(*it);
}
}
if (params.empty()) {
SYNTAX_ERROR(groupElem->Row()) << "\"group\" cannot be empty";
}
std::string groupString;
for (ParamList::iterator it = params.begin(); it != params.end(); ++it) {
if (!groupString.empty()) {
groupString += " ";
}
groupString += "(" + it->name() + " " + it->value() + ")";
}
group.value() = groupString;
return group;
}
RobotInterface::ParamList RobotInterface::XMLReader::Private::readParamListTag(TiXmlElement* paramListElem)
{
if (paramListElem->ValueStr().compare("paramlist") != 0) {
SYNTAX_ERROR(paramListElem->Row()) << "Expected \"paramlist\". Found" << paramListElem->ValueStr();
}
ParamList params;
Param mainparam;
if (paramListElem->QueryStringAttribute("name", &mainparam.name()) != TIXML_SUCCESS) {
SYNTAX_ERROR(paramListElem->Row()) << "\"paramlist\" element should contain the \"name\" attribute";
}
params.push_back(mainparam);
// yDebug() << "Found paramlist [" << params.at(0).name() << "]";
for (TiXmlElement* childElem = paramListElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) {
if (childElem->ValueStr().compare("elem") != 0) {
SYNTAX_ERROR(childElem->Row()) << "Expected \"elem\". Found" << childElem->ValueStr();
}
Param childParam;
if (childElem->QueryStringAttribute("name", &childParam.name()) != TIXML_SUCCESS) {
SYNTAX_ERROR(childElem->Row()) << "\"elem\" element should contain the \"name\" attribute";
}
const char *valueText = childElem->GetText();
if (!valueText) {
SYNTAX_ERROR(childElem->Row()) << "\"elem\" element should have a value [ \"name\" = " << childParam.name() << "]";
}
childParam.value() = valueText;
params.push_back(childParam);
}
if (params.empty()) {
SYNTAX_ERROR(paramListElem->Row()) << "\"paramlist\" cannot be empty";
}
// +1 skips the first element, that is the main param
for (ParamList::iterator it = params.begin() + 1; it != params.end(); ++it) {
Param ¶m = *it;
params.at(0).value() += (params.at(0).value().empty() ? "(" : " ") + param.name();
}
params.at(0).value() += ")";
// yDebug() << params;
return params;
}
RobotInterface::ParamList RobotInterface::XMLReader::Private::readSubDeviceTag(TiXmlElement *subDeviceElem)
{
if (subDeviceElem->ValueStr().compare("subdevice") != 0) {
SYNTAX_ERROR(subDeviceElem->Row()) << "Expected \"subdevice\". Found" << subDeviceElem->ValueStr();
}
ParamList params;
//FIXME Param featIdParam;
Param subDeviceParam;
//FIXME featIdParam.name() = "FeatId";
subDeviceParam.name() = "subdevice";
//FIXME if (subDeviceElem->QueryStringAttribute("name", &featIdParam.value()) != TIXML_SUCCESS) {
// SYNTAX_ERROR(subDeviceElem->Row()) << "\"subdevice\" element should contain the \"name\" attribute";
// }
if (subDeviceElem->QueryStringAttribute("type", &subDeviceParam.value()) != TIXML_SUCCESS) {
SYNTAX_ERROR(subDeviceElem->Row()) << "\"subdevice\" element should contain the \"type\" attribute";
}
//FIXME params.push_back(featIdParam);
params.push_back(subDeviceParam);
// yDebug() << "Found subdevice [" << params.at(0).value() << "]";
for (TiXmlElement* childElem = subDeviceElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) {
ParamList childParams = readParams(childElem);
for (ParamList::const_iterator it = childParams.begin(); it != childParams.end(); ++it) {
params.push_back(Param(it->name(), it->value()));
}
}
// yDebug() << params;
return params;
}
RobotInterface::ParamList RobotInterface::XMLReader::Private::readParamsTag(TiXmlElement *paramsElem)
{
const std::string &valueStr = paramsElem->ValueStr();
if (valueStr.compare("params") != 0) {
SYNTAX_ERROR(paramsElem->Row()) << "Expected \"params\". Found" << valueStr;
}
std::string filename;
if (paramsElem->QueryStringAttribute("file", &filename) == TIXML_SUCCESS) {
// yDebug() << "Found params file [" << filename << "]";
filename=rf.findFileByName(filename);
return readParamsFile(filename);
}
std::string robotName;
if (paramsElem->QueryStringAttribute("robot", &robotName) != TIXML_SUCCESS) {
SYNTAX_WARNING(paramsElem->Row()) << "\"params\" element should contain the \"robot\" attribute";
}
if (robotName != robot.name()) {
SYNTAX_WARNING(paramsElem->Row()) << "Trying to import a file for the wrong robot. Found" << robotName << "instead of" << robot.name();
}
unsigned int build;
#if TINYXML_UNSIGNED_INT_BUG
if (paramsElem->QueryUnsignedAttribute("build", &build()) != TIXML_SUCCESS) {
// No build attribute. Assuming build="0"
SYNTAX_WARNING(paramsElem->Row()) << "\"params\" element should contain the \"build\" attribute [unsigned int]. Assuming 0";
}
#else
int tmp;
if (paramsElem->QueryIntAttribute("build", &tmp) != TIXML_SUCCESS || tmp < 0) {
// No build attribute. Assuming build="0"
SYNTAX_WARNING(paramsElem->Row()) << "\"params\" element should contain the \"build\" attribute [unsigned int]. Assuming 0";
tmp = 0;
}
build = (unsigned)tmp;
#endif
if (build != robot.build()) {
SYNTAX_WARNING(paramsElem->Row()) << "Import a file for a different robot build. Found" << build << "instead of" << robot.build();
}
ParamList params;
for (TiXmlElement* childElem = paramsElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) {
ParamList childParams = readParams(childElem);
for (ParamList::const_iterator it = childParams.begin(); it != childParams.end(); ++it) {
params.push_back(*it);
}
}
return params;
}
RobotInterface::ParamList RobotInterface::XMLReader::Private::readParamsFile(const std::string &fileName)
{
std::string old_filename = curr_filename;
curr_filename = fileName;
TiXmlDocument *doc = new TiXmlDocument(fileName.c_str());
if (!doc->LoadFile()) {
SYNTAX_ERROR(doc->ErrorRow()) << doc->ErrorDesc();
}
if (!doc->RootElement()) {
SYNTAX_ERROR(doc->Row()) << "No root element.";
}
RobotInterfaceDTD paramsFileDTD;
for (TiXmlNode* childNode = doc->FirstChild(); childNode != 0; childNode = childNode->NextSibling()) {
if (childNode->Type() == TiXmlNode::TINYXML_UNKNOWN) {
if(paramsFileDTD.parse(childNode->ToUnknown(), curr_filename)) {
break;
}
}
}
if (!paramsFileDTD.valid()) {
SYNTAX_WARNING(doc->Row()) << "No DTD found. Assuming version robotInterfaceV1.0";
paramsFileDTD.setDefault();
paramsFileDTD.type = RobotInterfaceDTD::DocTypeParams;
}
if (paramsFileDTD.type != RobotInterfaceDTD::DocTypeParams) {
SYNTAX_ERROR(doc->Row()) << "Expected document of type" << DocTypeToString(RobotInterfaceDTD::DocTypeParams)
<< ". Found" << DocTypeToString(paramsFileDTD.type);
}
if (paramsFileDTD.majorVersion != dtd.majorVersion) {
SYNTAX_ERROR(doc->Row()) << "Trying to import a file with a different robotInterface DTD version";
}
RobotInterface::ParamList params = readParamsTag(doc->RootElement());
delete doc;
curr_filename = old_filename;
return params;
}
RobotInterface::ActionList RobotInterface::XMLReader::Private::readActions(TiXmlElement *actionsElem)
{
const std::string &valueStr = actionsElem->ValueStr();
if (valueStr.compare("action") != 0 &&
valueStr.compare("actions") != 0)
{
SYNTAX_ERROR(actionsElem->Row()) << "Expected \"action\" or \"actions\". Found" << valueStr;
}
if (valueStr.compare("action") == 0) {
ActionList actionList;
actionList.push_back(readActionTag(actionsElem));
return actionList;
}
// "actions"
return readActionsTag(actionsElem);
}
RobotInterface::Action RobotInterface::XMLReader::Private::readActionTag(TiXmlElement* actionElem)
{
if (actionElem->ValueStr().compare("action") != 0) {
SYNTAX_ERROR(actionElem->Row()) << "Expected \"action\". Found" << actionElem->ValueStr();
}
Action action;
if (actionElem->QueryValueAttribute<ActionPhase>("phase", &action.phase()) != TIXML_SUCCESS || action.phase() == ActionPhaseUnknown) {
SYNTAX_ERROR(actionElem->Row()) << "\"action\" element should contain the \"phase\" attribute [startup|interrupt{1,2,3}|shutdown]";
}
if (actionElem->QueryValueAttribute<ActionType>("type", &action.type()) != TIXML_SUCCESS || action.type() == ActionTypeUnknown) {
SYNTAX_ERROR(actionElem->Row()) << "\"action\" element should contain the \"type\" attribute [configure|calibrate|attach|abort|detach|park|custom]";
}
// yDebug() << "Found action [ ]";
#if TINYXML_UNSIGNED_INT_BUG
if (actionElem->QueryUnsignedAttribute("level", &action.level()) != TIXML_SUCCESS) {
SYNTAX_ERROR(actionElem->Row()) << "\"action\" element should contain the \"level\" attribute [unsigned int]";
}
#else
int tmp;
if (actionElem->QueryIntAttribute("level", &tmp) != TIXML_SUCCESS || tmp < 0) {
SYNTAX_ERROR(actionElem->Row()) << "\"action\" element should contain the \"level\" attribute [unsigned int]";
}
action.level() = (unsigned)tmp;
#endif
for (TiXmlElement* childElem = actionElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) {
ParamList childParams = readParams(childElem);
for (ParamList::const_iterator it = childParams.begin(); it != childParams.end(); ++it) {
action.params().push_back(*it);
}
}
// yDebug() << action;
return action;
}
RobotInterface::ActionList RobotInterface::XMLReader::Private::readActionsTag(TiXmlElement *actionsElem)
{
const std::string &valueStr = actionsElem->ValueStr();
if (valueStr.compare("actions") != 0) {
SYNTAX_ERROR(actionsElem->Row()) << "Expected \"actions\". Found" << valueStr;
}
std::string filename;
if (actionsElem->QueryStringAttribute("file", &filename) == TIXML_SUCCESS) {
// yDebug() << "Found actions file [" << filename << "]";
filename=rf.findFileByName(filename);
return readActionsFile(filename);
}
std::string robotName;
if (actionsElem->QueryStringAttribute("robot", &robotName) != TIXML_SUCCESS) {
SYNTAX_WARNING(actionsElem->Row()) << "\"actions\" element should contain the \"robot\" attribute";
}
if (robotName != robot.name()) {
SYNTAX_WARNING(actionsElem->Row()) << "Trying to import a file for the wrong robot. Found" << robotName << "instead of" << robot.name();
}
unsigned int build;
#if TINYXML_UNSIGNED_INT_BUG
if (actionsElem->QueryUnsignedAttribute("build", &build()) != TIXML_SUCCESS) {
// No build attribute. Assuming build="0"
SYNTAX_WARNING(actionsElem->Row()) << "\"actions\" element should contain the \"build\" attribute [unsigned int]. Assuming 0";
}
#else
int tmp;
if (actionsElem->QueryIntAttribute("build", &tmp) != TIXML_SUCCESS || tmp < 0) {
// No build attribute. Assuming build="0"
SYNTAX_WARNING(actionsElem->Row()) << "\"actions\" element should contain the \"build\" attribute [unsigned int]. Assuming 0";
tmp = 0;
}
build = (unsigned)tmp;
#endif
if (build != robot.build()) {
SYNTAX_WARNING(actionsElem->Row()) << "Import a file for a different robot build. Found" << build << "instead of" << robot.build();
}
ActionList actions;
for (TiXmlElement* childElem = actionsElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) {
ActionList childActions = readActions(childElem);
for (ActionList::const_iterator it = childActions.begin(); it != childActions.end(); ++it) {
actions.push_back(*it);
}
}
return actions;
}
RobotInterface::ActionList RobotInterface::XMLReader::Private::readActionsFile(const std::string &fileName)
{
std::string old_filename = curr_filename;
curr_filename = fileName;
TiXmlDocument *doc = new TiXmlDocument(fileName.c_str());
if (!doc->LoadFile()) {
SYNTAX_ERROR(doc->ErrorRow()) << doc->ErrorDesc();
}
if (!doc->RootElement()) {
SYNTAX_ERROR(doc->Row()) << "No root element.";
}
RobotInterfaceDTD actionsFileDTD;
for (TiXmlNode* childNode = doc->FirstChild(); childNode != 0; childNode = childNode->NextSibling()) {
if (childNode->Type() == TiXmlNode::TINYXML_UNKNOWN) {
if(actionsFileDTD.parse(childNode->ToUnknown(), curr_filename)) {
break;
}
}
}
if (!actionsFileDTD.valid()) {
SYNTAX_WARNING(doc->Row()) << "No DTD found. Assuming version robotInterfaceV1.0";
actionsFileDTD.setDefault();
actionsFileDTD.type = RobotInterfaceDTD::DocTypeActions;
}
if (actionsFileDTD.type != RobotInterfaceDTD::DocTypeActions) {
SYNTAX_ERROR(doc->Row()) << "Expected document of type" << DocTypeToString(RobotInterfaceDTD::DocTypeActions)
<< ". Found" << DocTypeToString(actionsFileDTD.type);
}
if (actionsFileDTD.majorVersion != dtd.majorVersion) {
SYNTAX_ERROR(doc->Row()) << "Trying to import a file with a different robotInterface DTD version";
}
RobotInterface::ActionList actions = readActionsTag(doc->RootElement());
delete doc;
curr_filename = old_filename;
return actions;
}
RobotInterface::XMLReader::XMLReader() :
mPriv(new Private(this))
{
}
RobotInterface::XMLReader::~XMLReader()
{
delete mPriv;
}
RobotInterface::Robot& RobotInterface::XMLReader::getRobot(const std::string& filename)
{
return mPriv->readRobotFile(filename);
}
|
c71e9ed6233705c6efffe173059458f4883f01cb | 699bf827a5cf9ea91d18dd544494e8466c9bf5c4 | /DoubleLinkedList.cpp | 9abb533931b649dc82c4c0c6988072bdba335f8a | [] | no_license | T1murKO/Cpp-Algorithms | 610a57fd2767e62e056fb0d3dd70a47f4d7bce29 | 6f642e47d205a0813e31d292f07ee06777c0e729 | refs/heads/main | 2023-03-20T03:48:04.021313 | 2021-03-15T08:27:46 | 2021-03-15T08:27:46 | 347,879,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,369 | cpp | DoubleLinkedList.cpp | #pragma once
#include <exception>
#include <iostream>
#include <List>
using namespace std;
template <typename T>
class DoubleLinkedList
{
public:
DoubleLinkedList() :head(new Node()), tail(head), size(0) {}
~DoubleLinkedList();
class Node
{
public:
T data;
Node* prevNode;
Node* nextNode;
Node() :prevNode(nullptr), nextNode(nullptr) {}
Node(const T& data, Node* tail)
{
tail->nextNode = this;
this->data = data;
this->prevNode = tail;
this->nextNode = nullptr;
}
};
bool add(const T& value);
bool remove(const size_t index);
bool insert(const size_t index, const T& value);
T get(const size_t);
size_t getSize();
bool isEmpty();
T operator [] (const size_t index);
private:
Node* head;
Node* tail;
size_t size;
Node* getNodeByIndex(size_t index)
{
if (index < 0 || index >= size)
throw out_of_range("Error: Out of range\n");
Node* currentNode;
if (index < size / 2)
{
currentNode = head;
size_t currentIndex = 0;
while (currentIndex != index)
{
currentNode = currentNode->nextNode;
currentIndex++;
}
}
else
{
currentNode = tail;
size_t currentIndex = size - 1;
while (currentIndex != index)
{
currentNode = currentNode->prevNode;
currentIndex--;
}
}
return currentNode;
}
};
template <typename T>
size_t DoubleLinkedList<T>::getSize()
{
return size;
}
template <typename T>
bool DoubleLinkedList<T>::isEmpty()
{
return (size == 0) ? true : false;
}
template <typename T>
bool DoubleLinkedList<T>::insert(const size_t index, const T& value)
{
try
{
if (index == size)
{
add(value);
return true;
}
Node* nodeToInsert = new Node();
nodeToInsert->data = value;
Node* nodeToShift = getNodeByIndex(index);
if (nodeToShift->prevNode == nullptr)
{
head = nodeToInsert;
}
else
{
nodeToInsert->prevNode = nodeToShift->prevNode;
nodeToShift->prevNode->nextNode = nodeToInsert;
tail = nodeToShift;
}
nodeToShift->prevNode = nodeToInsert;
nodeToInsert->nextNode = nodeToShift;
return true;
}
catch (exception& e)
{
cerr << e.what() << " in insert method\n";
return false;
}
}
template <typename T>
bool DoubleLinkedList<T>::add(const T& value)
{
try
{
if (isEmpty())
{
head->data = value;
size++;
}
else
{
tail = new Node(value, tail);
size++;
}
return true;
}
catch (exception& e)
{
cerr << e.what() << " in add method\n";
return false;
}
}
template <typename T>
T DoubleLinkedList<T>::get(const size_t index)
{
try
{
if (index < 0 || index >= size)
throw out_of_range("Error: Out of range\n");
Node* currentNode;
if (index < size / 2)
{
currentNode = head;
size_t currentIndex = 0;
while (currentIndex != index)
{
currentNode = currentNode->nextNode;
currentIndex++;
}
}
else
{
currentNode = tail;
size_t currentIndex = size - 1;
while (currentIndex != index)
{
currentNode = currentNode->prevNode;
currentIndex--;
}
}
return currentNode->data;
}
catch (exception& e)
{
cerr << e.what() << "in get method\n";
system("pause");
exit(0);
}
}
template <typename T>
T DoubleLinkedList<T>::operator [] (const size_t index)
{
try
{
return this->getNodeByIndex(index)->data;
}
catch (exception& e)
{
cerr << e.what() << "in get method\n";
system("pause");
}
}
template <typename T>
bool DoubleLinkedList<T>::remove(const size_t index)
{
try
{
Node* currentNode = getNodeByIndex(index);
if (currentNode->prevNode == nullptr)
head = currentNode->nextNode;
else if (currentNode->nextNode == nullptr)
tail = currentNode->prevNode;
else
{
currentNode->prevNode->nextNode = currentNode->nextNode;
currentNode->nextNode->prevNode = currentNode->prevNode;
}
size--;
return true;
}
catch (exception& e)
{
cerr << e.what() << "in remove method\n";
return false;
}
}
template <typename T>
DoubleLinkedList<T>::~DoubleLinkedList()
{
Node* nodeToDelete = head;
while (nodeToDelete->nextNode != nullptr)
{
Node* tmp = nodeToDelete;
nodeToDelete = nodeToDelete->nextNode;
delete tmp;
}
delete nodeToDelete;
} |
8baa118b93cd6cb937553915e2724f3f4e123506 | c5cce7b6f031440198fa7462e581c48cf1cfd0ee | /NANE/src/NES/APU/Sequencer.cpp | 9e0459bf7e2fd92733c3ed0976abeb2b1db72954 | [] | no_license | BlueSquid1/NANE | 34516c9568c0543df96caccd1072912d5762ae91 | 5bdc8b6702bfcb05b0a6e50bf8bd72a479c4b9d9 | refs/heads/master | 2021-11-27T14:57:38.637314 | 2021-11-22T10:07:40 | 2021-11-22T10:07:40 | 229,574,914 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,226 | cpp | Sequencer.cpp | #include "Sequencer.h"
Sequencer::Sequencer(int period, bool isLooping, std::function<void(void)> expireHandle)
{
this->counter = period;
this->period = period;
this->isLooping = isLooping;
this->expireHandle = expireHandle;
}
void Sequencer::Clock()
{
if(this->haltCounter == true)
{
return;
}
if(this->counter <= 0 && this->period >= 0)
{
//reset if needed
if(this->period >= 0 && this->isLooping)
{
this->counter = this->period;
}
//call expire handle
if(this->expireHandle != nullptr)
{
this->expireHandle();
}
return;
}
this->counter--;
}
int Sequencer::GetCounter() const
{
return this->counter;
}
int Sequencer::GetPeriod() const
{
return this->period;
}
void Sequencer::SetPeriod(int period, bool resetCounter)
{
this->period = period;
if(resetCounter)
{
this->ResetCounterToPeriod();
}
}
void Sequencer::ResetCounterToPeriod()
{
this->counter = this->period;
}
bool Sequencer::GetHaltCounter() const
{
return this->haltCounter;
}
void Sequencer::SetHaltCounter(bool haltCounter)
{
this->haltCounter = haltCounter;
} |
63eae5ac3a9d872243cbeba7ee2c700f18b79cf1 | a8761e3f96f7981fe42e28617c5d2eb0e3da3a08 | /crystal/serializer/record/test/AccessorTest.cpp | 6ec9e9b93def4de2826c897d9e96578e836fc283 | [
"Apache-2.0"
] | permissive | crystal-dataop/crystal | a1250ff03fcb4db9717d67bebd168536951a1a3a | 128e1dcde1ef68cabadab9b16d45f5199f0afe5c | refs/heads/master | 2023-07-05T06:23:42.149575 | 2021-08-10T14:08:33 | 2021-08-10T14:08:33 | 298,713,405 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,968 | cpp | AccessorTest.cpp | /*
* Copyright 2017-present Yeolar
*
* 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 <gtest/gtest.h>
#include <string>
#include "crystal/memory/SysAllocator.h"
#include "crystal/serializer/record/Accessor.h"
using namespace crystal;
TEST(Accessor, all) {
RecordMeta meta;
meta.addMeta(FieldMeta("field1", 1, DataType::BOOL, 1, 1));
meta.addMeta(FieldMeta("field2", 2, DataType::INT8, 8, 1, "50"));
meta.addMeta(FieldMeta("field3", 3, DataType::INT8, 4, 1));
meta.addMeta(FieldMeta("field4", 4, DataType::FLOAT, 32, 1));
meta.addMeta(FieldMeta("field5", 5, DataType::STRING, 0, 1, "default"));
meta.addMeta(FieldMeta("field6", 6, DataType::BOOL, 1, 10));
meta.addMeta(FieldMeta("field7", 7, DataType::INT8, 8, 10, "50"));
meta.addMeta(FieldMeta("field8", 8, DataType::INT8, 4, 10));
meta.addMeta(FieldMeta("field9", 9, DataType::FLOAT, 32, 10));
meta.addMeta(FieldMeta("field10", 10, DataType::STRING, 0, 10, "default"));
meta.addMeta(FieldMeta("field11", 11, DataType::BOOL, 1, 0));
meta.addMeta(FieldMeta("field12", 12, DataType::INT8, 8, 0, "50"));
meta.addMeta(FieldMeta("field13", 13, DataType::INT8, 4, 0));
meta.addMeta(FieldMeta("field14", 14, DataType::FLOAT, 32, 0));
meta.addMeta(FieldMeta("field15", 15, DataType::STRING, 0, 0, "default"));
Accessor accessor(meta);
EXPECT_EQ(183, accessor.bitOffset());
EXPECT_EQ(200, accessor.bufferSize());
SysAllocator allocator;
void* buf = allocator.address(allocator.allocate(accessor.bufferSize()));
memset(buf, 0, accessor.bufferSize());
accessor.reset(buf, &allocator, meta);
EXPECT_EQ(false, accessor.get<bool>(buf, &allocator, *meta.getMeta(1)));
EXPECT_EQ(50, accessor.get<int8_t>(buf, &allocator, *meta.getMeta(2)));
EXPECT_EQ(0, accessor.get<int8_t>(buf, &allocator, *meta.getMeta(3)));
EXPECT_FLOAT_EQ(0, accessor.get<float>(buf, &allocator, *meta.getMeta(4)));
EXPECT_STREQ("default", std::string(accessor.get<std::string_view>(
buf, &allocator, *meta.getMeta(5))).c_str());
EXPECT_TRUE(accessor.set<bool>(buf, &allocator, *meta.getMeta(1), true));
EXPECT_TRUE(accessor.set<int8_t>(buf, &allocator, *meta.getMeta(2), 100));
EXPECT_TRUE(accessor.set<int8_t>(buf, &allocator, *meta.getMeta(3), 10));
EXPECT_TRUE(accessor.set<float>(buf, &allocator, *meta.getMeta(4), 1.23));
EXPECT_TRUE(accessor.set<std::string_view>(buf, &allocator, *meta.getMeta(5),
"string"));
EXPECT_EQ(true, accessor.get<bool>(buf, &allocator, *meta.getMeta(1)));
EXPECT_EQ(100, accessor.get<int8_t>(buf, &allocator, *meta.getMeta(2)));
EXPECT_EQ(10, accessor.get<int8_t>(buf, &allocator, *meta.getMeta(3)));
EXPECT_FLOAT_EQ(1.23, accessor.get<float>(buf, &allocator, *meta.getMeta(4)));
EXPECT_STREQ("string", std::string(accessor.get<std::string_view>(
buf, &allocator, *meta.getMeta(5))).c_str());
Array<bool> a6 = accessor.mget<bool>(buf, &allocator, *meta.getMeta(6));
for (size_t i = 0; i < 10; i++) {
EXPECT_EQ(false, a6.get(i));
EXPECT_TRUE(a6.set(i, true));
EXPECT_EQ(true, a6.get(i));
}
Array<int8_t> a7 = accessor.mget<int8_t>(buf, &allocator, *meta.getMeta(7));
for (size_t i = 0; i < 10; i++) {
EXPECT_EQ(50, a7.get(i));
EXPECT_TRUE(a7.set(i, i));
EXPECT_EQ(i, a7.get(i));
}
Array<int8_t> a8 = accessor.mget<int8_t>(buf, &allocator, *meta.getMeta(8));
for (size_t i = 0; i < 10; i++) {
EXPECT_EQ(0, a8.get(i));
EXPECT_TRUE(a8.set(i, i));
EXPECT_EQ(i, a8.get(i));
}
Array<float> a9 = accessor.mget<float>(buf, &allocator, *meta.getMeta(9));
for (size_t i = 0; i < 10; i++) {
EXPECT_FLOAT_EQ(0, a9.get(i));
EXPECT_TRUE(a9.set(i, i * 0.1));
EXPECT_FLOAT_EQ(i * 0.1, a9.get(i));
}
Array<std::string_view> a10 =
accessor.mget<std::string_view>(buf, &allocator, *meta.getMeta(10));
for (size_t i = 0; i < 10; i++) {
EXPECT_STREQ("default", std::string(a10.get(i)).c_str());
EXPECT_TRUE(a10.set(i, "string"));
EXPECT_STREQ("string", std::string(a10.get(i)).c_str());
}
EXPECT_TRUE(accessor.rebuildVarArray(buf, &allocator, *meta.getMeta(11), 10));
Array<bool> a11 = accessor.mget<bool>(buf, &allocator, *meta.getMeta(11));
for (size_t i = 0; i < 10; i++) {
EXPECT_EQ(false, a11.get(i));
EXPECT_TRUE(a11.set(i, true));
EXPECT_EQ(true, a11.get(i));
}
EXPECT_TRUE(accessor.rebuildVarArray(buf, &allocator, *meta.getMeta(12), 10));
Array<int8_t> a12 = accessor.mget<int8_t>(buf, &allocator, *meta.getMeta(12));
for (size_t i = 0; i < 10; i++) {
EXPECT_EQ(50, a12.get(i));
EXPECT_TRUE(a12.set(i, i));
EXPECT_EQ(i, a12.get(i));
}
EXPECT_TRUE(accessor.rebuildVarArray(buf, &allocator, *meta.getMeta(13), 10));
Array<int8_t> a13 = accessor.mget<int8_t>(buf, &allocator, *meta.getMeta(13));
for (size_t i = 0; i < 10; i++) {
EXPECT_EQ(0, a13.get(i));
EXPECT_TRUE(a13.set(i, i));
EXPECT_EQ(i, a13.get(i));
}
EXPECT_TRUE(accessor.rebuildVarArray(buf, &allocator, *meta.getMeta(14), 10));
Array<float> a14 = accessor.mget<float>(buf, &allocator, *meta.getMeta(14));
for (size_t i = 0; i < 10; i++) {
EXPECT_FLOAT_EQ(0, a14.get(i));
EXPECT_TRUE(a14.set(i, i * 0.1));
EXPECT_FLOAT_EQ(i * 0.1, a14.get(i));
}
EXPECT_TRUE(accessor.rebuildVarArray(buf, &allocator, *meta.getMeta(15), 10));
Array<std::string_view> a15 =
accessor.mget<std::string_view>(buf, &allocator, *meta.getMeta(15));
for (size_t i = 0; i < 10; i++) {
EXPECT_STREQ("default", std::string(a15.get(i)).c_str());
EXPECT_TRUE(a15.set(i, "string"));
EXPECT_STREQ("string", std::string(a15.get(i)).c_str());
}
EXPECT_STREQ(
R"({bitOffset=183,blocks=)"
R"([{bitOffset=0,bitSize=1,byteOffset=0,byteSize=0,itemBitSize=1,itemByteSize=0,mask="63:8000000000000000:0",tag=1})"
R"(,{bitOffset=0,bitSize=0,byteOffset=0,byteSize=1,itemBitSize=0,itemByteSize=1,mask="0:0:0",tag=2})"
R"(,{bitOffset=1,bitSize=4,byteOffset=0,byteSize=0,itemBitSize=4,itemByteSize=0,mask="59:7800000000000000:0",tag=3})"
R"(,{bitOffset=0,bitSize=0,byteOffset=1,byteSize=4,itemBitSize=0,itemByteSize=4,mask="0:0:0",tag=4})"
R"(,{bitOffset=0,bitSize=0,byteOffset=5,byteSize=8,itemBitSize=0,itemByteSize=8,mask="0:0:0",tag=5})"
R"(,{bitOffset=5,bitSize=10,byteOffset=0,byteSize=0,itemBitSize=1,itemByteSize=0,mask="0:0:0",tag=6})"
R"(,{bitOffset=0,bitSize=0,byteOffset=13,byteSize=10,itemBitSize=0,itemByteSize=1,mask="0:0:0",tag=7})"
R"(,{bitOffset=15,bitSize=40,byteOffset=0,byteSize=0,itemBitSize=4,itemByteSize=0,mask="0:0:0",tag=8})"
R"(,{bitOffset=0,bitSize=0,byteOffset=23,byteSize=40,itemBitSize=0,itemByteSize=4,mask="0:0:0",tag=9})"
R"(,{bitOffset=0,bitSize=0,byteOffset=63,byteSize=80,itemBitSize=0,itemByteSize=8,mask="0:0:0",tag=10})"
R"(,{bitOffset=0,bitSize=0,byteOffset=143,byteSize=8,itemBitSize=1,itemByteSize=0,mask="0:0:0",tag=11})"
R"(,{bitOffset=0,bitSize=0,byteOffset=151,byteSize=8,itemBitSize=0,itemByteSize=1,mask="0:0:0",tag=12})"
R"(,{bitOffset=0,bitSize=0,byteOffset=159,byteSize=8,itemBitSize=4,itemByteSize=0,mask="0:0:0",tag=13})"
R"(,{bitOffset=0,bitSize=0,byteOffset=167,byteSize=8,itemBitSize=0,itemByteSize=4,mask="0:0:0",tag=14})"
R"(,{bitOffset=0,bitSize=0,byteOffset=175,byteSize=8,itemBitSize=0,itemByteSize=8,mask="0:0:0",tag=15}])"
R"(,bufferSize=200})",
accessor.toString().c_str());
}
|
b5df671e9dcb62ff9a69272d7863edfac4d97e2a | 1f13ce76e9e3a4437b47fa6bf730ad01b3245d35 | /src-qt5/core/lumina-desktop-unified/src-desktop/src-widgets/NativeWindow.h | 47699ae6c55ddaec51bb263ee160cb845706df9d | [
"BSD-3-Clause"
] | permissive | rodlie/lumina | 779400e2a03ae3857359d75b6f70cba85c2bc674 | a41dba4da23cc665072f157c71b3b0d1d5f639ec | refs/heads/master | 2020-03-10T15:26:06.354871 | 2018-05-02T18:48:53 | 2018-05-02T18:48:53 | 129,448,378 | 0 | 0 | BSD-3-Clause | 2018-04-13T20:07:36 | 2018-04-13T20:07:36 | null | UTF-8 | C++ | false | false | 1,192 | h | NativeWindow.h | //===========================================
// Lumina-desktop source code
// Copyright (c) 2018, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#ifndef _LUMINA_DESKTOP_NATIVE_WINDOW_WIDGET_H
#define _LUMINA_DESKTOP_NATIVE_WINDOW_WIDGET_H
#include <global-includes.h>
#include <NativeWindowObject.h>
#include "NativeEmbedWidget.h"
class NativeWindow : public QFrame{
Q_OBJECT
public:
NativeWindow(NativeWindowObject *obj);
~NativeWindow();
QPoint relativeOrigin(); //origin of the embedded window relative to the frame
public slots:
void initProperties();
private:
//Core object
NativeWindowObject *WIN;
// Interface items
void createFrame();
void loadIcons();
QToolButton *closeB, *minB, *maxB, *otherB;
QHBoxLayout *toolbarL;
QVBoxLayout *vlayout;
QLabel *titleLabel;
NativeEmbedWidget *container;
// Info cache variables
QRect oldgeom;
private slots:
//Property Change slots
void syncWinImage();
void syncName();
void syncTitle();
void syncIcon();
void syncSticky();
void syncVisibility(bool init = false);
void syncWinType();
void syncGeom();
};
#endif
|
cfc2ecb35d5b8e6154bccc6f66c4f3d1905bff7d | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /chrome/browser/web_applications/preinstalled_web_app_utils.cc | 0fc9e6daf8a685831b9636074dc554271ba3bce6 | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 28,982 | cc | preinstalled_web_app_utils.cc | // Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/web_applications/preinstalled_web_app_utils.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/types/expected_macros.h"
#include "base/values.h"
#include "chrome/browser/apps/user_type_filter.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/web_applications/file_utils_wrapper.h"
#include "chrome/browser/web_applications/mojom/user_display_mode.mojom.h"
#include "chrome/browser/web_applications/web_app_install_info.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/webapps/common/constants.h"
#include "third_party/blink/public/common/manifest/manifest_util.h"
#include "ui/events/devices/device_data_manager.h"
#include "ui/gfx/codec/png_codec.h"
namespace web_app {
namespace {
// kAppUrl is a required string specifying a URL inside the scope of the web
// app that contains a link to the app manifest.
constexpr char kAppUrl[] = "app_url";
// kHideFromUser is an optional boolean which controls whether we add
// a shortcut to the relevant OS surface i.e. Application folder on macOS, Start
// Menu on Windows and Linux, and launcher on Chrome OS. Defaults to false if
// missing. If true, we also don't show the app in search or in app management
// on Chrome OS.
constexpr char kHideFromUser[] = "hide_from_user";
// kOnlyForNewUsers is an optional boolean. If set and true we will not install
// the app for users that have already run Chrome before.
constexpr char kOnlyForNewUsers[] = "only_for_new_users";
// kOnlyIfPreviouslyPreinstalled is an optional boolean. If set and true we will
// not preinstall the app for new users.
constexpr char kOnlyIfPreviouslyPreinstalled[] =
"only_if_previously_preinstalled";
// kUserType is an allowlist of user types to install this app for. This must be
// populated otherwise the app won't ever be installed.
// Example: "user_type": ["unmanaged", "managed", "child"]
// See apps::DetermineUserType() for relevant string constants.
constexpr char kUserType[] = "user_type";
// kCreateShortcuts is an optional boolean which controls whether OS
// level shortcuts are created. On Chrome OS this controls whether the app is
// pinned to the shelf.
// The default value of kCreateShortcuts if false.
constexpr char kCreateShortcuts[] = "create_shortcuts";
// kFeatureName is an optional string parameter specifying a feature
// associated with this app. The feature must be present in
// |kPreinstalledAppInstallFeatures| to be applicable.
// If specified:
// - if the feature is enabled, the app will be installed
// - if the feature is not enabled, the app will be removed.
constexpr char kFeatureName[] = "feature_name";
// kFeatureNameOrInstalled is an optional string parameter specifying a feature
// associated with this app. The feature must be present in
// |kPreinstalledAppInstallFeatures| to be applicable.
//
// When specified, the app will only be installed when the feature is enabled.
// If the feature is disabled, existing installations will not be removed.
constexpr char kFeatureNameOrInstalled[] = "feature_name_or_installed";
// kDisableIfArcSupported is an optional bool which specifies whether to skip
// install of the app if the device supports Arc (Chrome OS only).
// Defaults to false.
constexpr char kDisableIfArcSupported[] = "disable_if_arc_supported";
// kDisableIfTabletFormFactor is an optional bool which specifies whether to
// skip install of the app if the device is a tablet form factor.
// This is only for Chrome OS tablets, Android does not use any of this code.
// Defaults to false.
constexpr char kDisableIfTabletFormFactor[] = "disable_if_tablet_form_factor";
// kLaunchContainer is a required string which can be "window" or "tab"
// and controls what sort of container the web app is launched in.
constexpr char kLaunchContainer[] = "launch_container";
constexpr char kLaunchContainerTab[] = "tab";
constexpr char kLaunchContainerWindow[] = "window";
// kLaunchQueryParams is an optional string which specifies query parameters to
// add to the start_url when launching the app. If the provided params are a
// substring of start_url's existing params then it will not be added a second
// time.
// Note that substring matches include "param=a" matching in "some_param=abc".
// Extend the implementation in WebAppRegistrar::GetAppLaunchUrl() if this edge
// case needs to be handled differently.
constexpr char kLaunchQueryParams[] = "launch_query_params";
// kLoadAndAwaitServiceWorkerRegistration is an optional bool that specifies
// whether to fetch the |kServiceWorkerRegistrationUrl| after installation to
// allow time for the app to register its service worker. This is done as a
// second pass after install in order to not block the installation of other
// background installed apps. No fetch is made if the service worker has already
// been registered by the |kAppUrl|.
// Defaults to true.
constexpr char kLoadAndAwaitServiceWorkerRegistration[] =
"load_and_await_service_worker_registration";
// kServiceWorkerRegistrationUrl is an optional string specifying the URL to use
// for the above |kLoadAndAwaitServiceWorkerRegistration|.
// Defaults to the |kAppUrl|.
constexpr char kServiceWorkerRegistrationUrl[] =
"service_worker_registration_url";
// kUninstallAndReplace is an optional array of strings which specifies App IDs
// which the app is replacing. This will transfer OS attributes (e.g the source
// app's shelf and app list positions on ChromeOS) and then uninstall the source
// app.
constexpr char kUninstallAndReplace[] = "uninstall_and_replace";
// kOnlyUseOfflineManifest is an optional bool.
// If set to true then no network install will be attempted and the app will be
// installed using |kOfflineManifest| data. |kOfflineManifest| must be specified
// in this case.
// If set to false and |kOfflineManifest| is set then it will be used as a
// fallback manifest if the network install fails.
// Defaults to false.
constexpr char kOnlyUseOfflineManifest[] = "only_use_offline_manifest";
// kOfflineManifest is a dictionary of manifest field values to use as an
// install to avoid the expense of fetching the install URL to download the
// app's true manifest. Next time the user visits the app it will undergo a
// manifest update check and correct any differences from the site (except for
// name and start_url).
//
// Why not use blink::ManifestParser?
// blink::ManifestParser depends on substantial sections of the CSS parser which
// is infeasible to run outside of the renderer process.
constexpr char kOfflineManifest[] = "offline_manifest";
// "name" manifest value to use for offline install. Cannot be updated.
// TODO(crbug.com/1119699): Allow updating of name.
constexpr char kOfflineManifestName[] = "name";
// "start_url" manifest value to use for offline install. Cannot be updated.
// TODO(crbug.com/1119699): Allow updating of start_url.
constexpr char kOfflineManifestStartUrl[] = "start_url";
// "scope" manifest value to use for offline install.
constexpr char kOfflineManifestScope[] = "scope";
// "display" manifest value to use for offline install.
constexpr char kOfflineManifestDisplay[] = "display";
// List of PNG files in the default web app config directory to use as the
// icons for offline install. Will be installed with purpose "any".
constexpr char kOfflineManifestIconAnyPngs[] = "icon_any_pngs";
// List of PNG files in the default web app config directory to use as the
// icons for offline install. Will be installed with purpose "maskable".
constexpr char kOfflineManifestIconMaskablePngs[] = "icon_maskable_pngs";
// Optional 8 value ARGB hex code to use as the "theme_color" manifest value.
// Example:
// "theme_color_argb_hex": "FFFF0000"
// is equivalent to
// "theme_color": "red"
constexpr char kOfflineManifestThemeColorArgbHex[] = "theme_color_argb_hex";
// Contains numeric milestone number M like 89 (the Chrome version). The app
// gets updated if browser's binary milestone number goes from <M to >=M.
constexpr char kForceReinstallForMilestone[] = "force_reinstall_for_milestone";
// Contains boolean indicating whether the app installation is requested by
// the device OEM.
constexpr char kOemInstalled[] = "oem_installed";
// Contains boolean indicating weather the app should only be install on devices
// with a built-in touchscreen with stylus support.
constexpr char kDisableIfTouchScreenWithStylusNotSupported[] =
"disable_if_touchscreen_with_stylus_not_supported";
void EnsureContains(base::Value::List& list, base::StringPiece value) {
for (const base::Value& item : list) {
if (item.is_string() && item.GetString() == value) {
return;
}
}
list.Append(value);
}
} // namespace
OptionsOrError ParseConfig(FileUtilsWrapper& file_utils,
const base::FilePath& dir,
const base::FilePath& file,
const base::Value& app_config) {
ExternalInstallOptions options(GURL(), mojom::UserDisplayMode::kStandalone,
ExternalInstallSource::kExternalDefault);
options.require_manifest = true;
options.force_reinstall = false;
if (app_config.type() != base::Value::Type::DICT) {
return base::StrCat(
{file.AsUTF8Unsafe(), " was not a dictionary as the top level"});
}
const base::Value::Dict& app_config_dict = app_config.GetDict();
// user_type
const base::Value::List* list = app_config_dict.FindList(kUserType);
if (!list) {
return base::StrCat({file.AsUTF8Unsafe(), " missing ", kUserType});
}
for (const auto& item : *list) {
if (!item.is_string()) {
return base::StrCat({file.AsUTF8Unsafe(), " has invalid ", kUserType,
item.DebugString()});
}
options.user_type_allowlist.push_back(item.GetString());
}
if (options.user_type_allowlist.empty()) {
return base::StrCat({file.AsUTF8Unsafe(), " has empty ", kUserType});
}
// feature_name
const std::string* feature_name = app_config_dict.FindString(kFeatureName);
if (feature_name) {
options.gate_on_feature = *feature_name;
}
// feature_name_or_installed
const std::string* feature_name_or_installed =
app_config_dict.FindString(kFeatureNameOrInstalled);
if (feature_name_or_installed) {
options.gate_on_feature_or_installed = *feature_name_or_installed;
}
// app_url
const std::string* string = app_config_dict.FindString(kAppUrl);
if (!string) {
return base::StrCat({file.AsUTF8Unsafe(), " had a missing ", kAppUrl});
}
options.install_url = GURL(*string);
if (!options.install_url.is_valid()) {
return base::StrCat({file.AsUTF8Unsafe(), " had an invalid ", kAppUrl});
}
// only_for_new_users
const base::Value* value = app_config_dict.Find(kOnlyForNewUsers);
if (value) {
if (!value->is_bool()) {
return base::StrCat(
{file.AsUTF8Unsafe(), " had an invalid ", kOnlyForNewUsers});
}
options.only_for_new_users = value->GetBool();
}
// only_if_previously_preinstalled
value = app_config_dict.Find(kOnlyIfPreviouslyPreinstalled);
if (value) {
if (!value->is_bool()) {
return base::StrCat({file.AsUTF8Unsafe(), " had an invalid ",
kOnlyIfPreviouslyPreinstalled});
}
options.only_if_previously_preinstalled = value->GetBool();
}
// hide_from_user
bool hide_from_user = false;
value = app_config_dict.Find(kHideFromUser);
if (value) {
if (!value->is_bool()) {
return base::StrCat(
{file.AsUTF8Unsafe(), " had an invalid ", kHideFromUser});
}
hide_from_user = value->GetBool();
}
options.add_to_applications_menu = !hide_from_user;
options.add_to_search = !hide_from_user;
options.add_to_management = !hide_from_user;
// create_shortcuts
bool create_shortcuts = false;
value = app_config_dict.Find(kCreateShortcuts);
if (value) {
if (!value->is_bool()) {
return base::StrCat(
{file.AsUTF8Unsafe(), " had an invalid ", kCreateShortcuts});
}
create_shortcuts = value->GetBool();
}
options.add_to_desktop = create_shortcuts;
options.add_to_quick_launch_bar = create_shortcuts;
// It doesn't make sense to hide the app and also create shortcuts for it.
DCHECK(!(hide_from_user && create_shortcuts));
// disable_if_arc_supported
value = app_config_dict.Find(kDisableIfArcSupported);
if (value) {
if (!value->is_bool()) {
return base::StrCat(
{file.AsUTF8Unsafe(), " had an invalid ", kDisableIfArcSupported});
}
options.disable_if_arc_supported = value->GetBool();
}
// disable_if_tablet_form_factor
value = app_config_dict.Find(kDisableIfTabletFormFactor);
if (value) {
if (!value->is_bool()) {
return base::StrCat({file.AsUTF8Unsafe(), " had an invalid ",
kDisableIfTabletFormFactor});
}
options.disable_if_tablet_form_factor = value->GetBool();
}
// launch_container
string = app_config_dict.FindString(kLaunchContainer);
if (!string) {
return base::StrCat(
{file.AsUTF8Unsafe(), " had an invalid ", kLaunchContainer});
}
std::string launch_container_str = *string;
if (launch_container_str == kLaunchContainerTab) {
options.user_display_mode = mojom::UserDisplayMode::kBrowser;
} else if (launch_container_str == kLaunchContainerWindow) {
options.user_display_mode = mojom::UserDisplayMode::kStandalone;
} else {
return base::StrCat({file.AsUTF8Unsafe(), " had an invalid ",
kLaunchContainer, ": ", launch_container_str});
}
// launch_query_params
value = app_config_dict.Find(kLaunchQueryParams);
if (value) {
if (!value->is_string()) {
return base::StrCat(
{file.AsUTF8Unsafe(), " had an invalid ", kLaunchQueryParams});
}
options.launch_query_params = value->GetString();
}
// load_and_await_service_worker_registration
value = app_config_dict.Find(kLoadAndAwaitServiceWorkerRegistration);
if (value) {
if (!value->is_bool()) {
return base::StrCat({file.AsUTF8Unsafe(), " had an invalid ",
kLoadAndAwaitServiceWorkerRegistration});
}
options.load_and_await_service_worker_registration = value->GetBool();
}
// service_worker_registration_url
value = app_config_dict.Find(kServiceWorkerRegistrationUrl);
if (value) {
if (!options.load_and_await_service_worker_registration) {
return base::StrCat({file.AsUTF8Unsafe(), " should not specify a ",
kServiceWorkerRegistrationUrl, " while ",
kLoadAndAwaitServiceWorkerRegistration,
" is disabled"});
}
if (!value->is_string()) {
return base::StrCat({file.AsUTF8Unsafe(), " had an invalid ",
kServiceWorkerRegistrationUrl});
}
options.service_worker_registration_url.emplace(value->GetString());
if (!options.service_worker_registration_url->is_valid()) {
return base::StrCat({file.AsUTF8Unsafe(), " had an invalid ",
kServiceWorkerRegistrationUrl});
}
}
// uninstall_and_replace
value = app_config_dict.Find(kUninstallAndReplace);
if (value) {
if (!value->is_list()) {
return base::StrCat(
{file.AsUTF8Unsafe(), " had an invalid ", kUninstallAndReplace});
}
const base::Value::List& uninstall_and_replace_values = value->GetList();
for (const auto& app_id_value : uninstall_and_replace_values) {
if (!app_id_value.is_string()) {
return base::StrCat({file.AsUTF8Unsafe(), " had an invalid ",
kUninstallAndReplace, " entry"});
}
options.uninstall_and_replace.push_back(app_id_value.GetString());
}
}
// only_use_offline_manifest
value = app_config_dict.Find(kOnlyUseOfflineManifest);
if (value) {
if (!value->is_bool()) {
return base::StrCat(
{file.AsUTF8Unsafe(), " had an invalid ", kOnlyUseOfflineManifest});
}
options.only_use_app_info_factory = value->GetBool();
}
// offline_manifest
value = app_config_dict.Find(kOfflineManifest);
if (value && value->is_dict()) {
WebAppInstallInfoFactoryOrError offline_manifest_result =
ParseOfflineManifest(file_utils, dir, file, *value);
if (std::string* error =
absl::get_if<std::string>(&offline_manifest_result)) {
return std::move(*error);
}
options.app_info_factory =
std::move(absl::get<WebAppInstallInfoFactory>(offline_manifest_result));
}
if (options.only_use_app_info_factory && !options.app_info_factory) {
return base::StrCat({file.AsUTF8Unsafe(), kOnlyUseOfflineManifest,
" set with no ", kOfflineManifest, " available"});
}
// force_reinstall_for_milestone
value = app_config_dict.Find(kForceReinstallForMilestone);
if (value) {
if (!value->is_int()) {
return base::StrCat({file.AsUTF8Unsafe(), " had an invalid ",
kForceReinstallForMilestone});
}
options.force_reinstall_for_milestone = value->GetInt();
}
// oem_installed
value = app_config_dict.Find(kOemInstalled);
if (value) {
if (!value->is_bool()) {
return base::StrCat(
{file.AsUTF8Unsafe(), " had an invalid ", kOemInstalled});
}
options.oem_installed = value->GetBool();
}
// disable_if_touchscreen_with_stylus_not_supported
value = app_config_dict.Find(kDisableIfTouchScreenWithStylusNotSupported);
if (value) {
if (!value->is_bool()) {
return base::StrCat({file.AsUTF8Unsafe(), " had an invalid ",
kDisableIfTouchScreenWithStylusNotSupported});
}
options.disable_if_touchscreen_with_stylus_not_supported = value->GetBool();
}
return options;
}
IconBitmapsOrError ParseOfflineManifestIconBitmaps(
FileUtilsWrapper& file_utils,
const base::FilePath& dir,
const base::FilePath& manifest_file,
const char* icon_key,
const base::Value::List& icon_files) {
std::map<SquareSizePx, SkBitmap> icon_bitmaps;
for (const base::Value& icon_file : icon_files) {
if (!icon_file.is_string()) {
return base::unexpected(base::StrCat(
{manifest_file.AsUTF8Unsafe(), " ", kOfflineManifest, " ", icon_key,
" ", icon_file.DebugString(), " invalid."}));
}
base::FilePath icon_path = dir.AppendASCII(icon_file.GetString());
std::string icon_data;
if (!file_utils.ReadFileToString(icon_path, &icon_data)) {
return base::unexpected(base::StrCat(
{manifest_file.AsUTF8Unsafe(), " ", kOfflineManifest, " ", icon_key,
" ", icon_file.DebugString(), " failed to read."}));
}
SkBitmap bitmap;
if (!gfx::PNGCodec::Decode(
reinterpret_cast<const unsigned char*>(icon_data.c_str()),
icon_data.size(), &bitmap)) {
return base::unexpected(base::StrCat(
{manifest_file.AsUTF8Unsafe(), " ", kOfflineManifest, " ", icon_key,
" ", icon_file.DebugString(), " failed to decode."}));
}
if (bitmap.width() != bitmap.height()) {
return base::unexpected(base::StrCat(
{manifest_file.AsUTF8Unsafe(), " ", kOfflineManifest, " ", icon_key,
" ", icon_file.DebugString(),
" must be square: ", base::NumberToString(bitmap.width()), "x",
base::NumberToString(bitmap.height())}));
}
icon_bitmaps[bitmap.width()] = std::move(bitmap);
}
return icon_bitmaps;
}
WebAppInstallInfoFactoryOrError ParseOfflineManifest(
FileUtilsWrapper& file_utils,
const base::FilePath& dir,
const base::FilePath& file,
const base::Value& offline_manifest) {
const base::Value::Dict& offline_manifest_dict = offline_manifest.GetDict();
WebAppInstallInfo app_info;
// name
const std::string* name_string =
offline_manifest_dict.FindString(kOfflineManifestName);
if (!name_string) {
return base::StrCat({file.AsUTF8Unsafe(), " ", kOfflineManifest, " ",
kOfflineManifestName, " missing or invalid."});
}
if (!base::UTF8ToUTF16(name_string->data(), name_string->size(),
&app_info.title) ||
app_info.title.empty()) {
return base::StrCat({file.AsUTF8Unsafe(), " ", kOfflineManifest, " ",
kOfflineManifestName, " invalid: ", *name_string});
}
// start_url
const std::string* start_url_string =
offline_manifest_dict.FindString(kOfflineManifestStartUrl);
if (!start_url_string) {
return base::StrCat({file.AsUTF8Unsafe(), " ", kOfflineManifest, " ",
kOfflineManifestStartUrl, " missing or invalid."});
}
app_info.start_url = GURL(*start_url_string);
if (!app_info.start_url.is_valid()) {
return base::StrCat({file.AsUTF8Unsafe(), " ", kOfflineManifest, " ",
kOfflineManifestStartUrl,
" invalid: ", *start_url_string});
}
// scope
const std::string* scope_string =
offline_manifest_dict.FindString(kOfflineManifestScope);
if (!scope_string) {
return base::StrCat({file.AsUTF8Unsafe(), " ", kOfflineManifest, " ",
kOfflineManifestScope, " missing or invalid."});
}
app_info.scope = GURL(*scope_string);
if (!app_info.scope.is_valid()) {
return base::StrCat({file.AsUTF8Unsafe(), " ", kOfflineManifest, " ",
kOfflineManifestScope, " invalid: ", *scope_string});
}
if (!base::StartsWith(app_info.start_url.path(), app_info.scope.path(),
base::CompareCase::SENSITIVE)) {
return base::StrCat({file.AsUTF8Unsafe(), " ", kOfflineManifest, " ",
kOfflineManifestScope, " (", app_info.start_url.spec(),
") not within ", kOfflineManifestScope, " (",
app_info.scope.spec(), ")."});
}
// display
const std::string* display_string =
offline_manifest_dict.FindString(kOfflineManifestDisplay);
if (!display_string) {
return base::StrCat({file.AsUTF8Unsafe(), " ", kOfflineManifest, " ",
kOfflineManifestDisplay, " missing or invalid."});
}
DisplayMode display = blink::DisplayModeFromString(*display_string);
if (display == DisplayMode::kUndefined) {
return base::StrCat({file.AsUTF8Unsafe(), " ", kOfflineManifest, " ",
kOfflineManifestDisplay,
" invalid: ", *display_string});
}
app_info.display_mode = display;
// icon_any_pngs || icon_maskable_pngs
const base::Value::List* icon_any_files =
offline_manifest_dict.FindList(kOfflineManifestIconAnyPngs);
const base::Value::List* icon_maskable_files =
offline_manifest_dict.FindList(kOfflineManifestIconMaskablePngs);
if (!icon_any_files && !icon_maskable_files) {
return base::StrCat({file.AsUTF8Unsafe(), " ", kOfflineManifest, " ",
kOfflineManifestIconAnyPngs, " and ",
kOfflineManifestIconMaskablePngs,
" missing or invalid."});
}
if (icon_any_files) {
if (icon_any_files->empty()) {
return base::StrCat({file.AsUTF8Unsafe(), " ", kOfflineManifest, " ",
kOfflineManifestIconAnyPngs, " empty."});
}
ASSIGN_OR_RETURN(app_info.icon_bitmaps.any,
ParseOfflineManifestIconBitmaps(
file_utils, dir, file, kOfflineManifestIconAnyPngs,
*icon_any_files));
}
if (icon_maskable_files) {
if (icon_maskable_files->empty()) {
return base::StrCat({file.AsUTF8Unsafe(), " ", kOfflineManifest, " ",
kOfflineManifestIconMaskablePngs, " empty."});
}
ASSIGN_OR_RETURN(
app_info.icon_bitmaps.maskable,
ParseOfflineManifestIconBitmaps(file_utils, dir, file,
kOfflineManifestIconMaskablePngs,
*icon_maskable_files));
}
// theme_color_argb_hex (optional)
const base::Value* theme_color_value =
offline_manifest_dict.Find(kOfflineManifestThemeColorArgbHex);
if (theme_color_value) {
const std::string* theme_color_argb_hex =
theme_color_value->is_string() ? &theme_color_value->GetString()
: nullptr;
SkColor theme_color;
if (!theme_color_argb_hex ||
!base::HexStringToUInt(*theme_color_argb_hex, &theme_color)) {
return base::StrCat({file.AsUTF8Unsafe(), " ", kOfflineManifest, " ",
kOfflineManifestThemeColorArgbHex,
" invalid: ", theme_color_value->DebugString()});
}
app_info.theme_color = SkColorSetA(theme_color, SK_AlphaOPAQUE);
}
return base::BindRepeating(
[](const WebAppInstallInfo& original) {
return std::make_unique<WebAppInstallInfo>(original.Clone());
},
std::move(app_info));
}
bool IsReinstallPastMilestoneNeeded(
base::StringPiece last_preinstall_synchronize_milestone_str,
base::StringPiece current_milestone_str,
int force_reinstall_for_milestone) {
int last_preinstall_synchronize_milestone = 0;
if (!base::StringToInt(last_preinstall_synchronize_milestone_str,
&last_preinstall_synchronize_milestone)) {
return false;
}
int current_milestone = 0;
if (!base::StringToInt(current_milestone_str, ¤t_milestone)) {
return false;
}
return last_preinstall_synchronize_milestone <
force_reinstall_for_milestone &&
current_milestone >= force_reinstall_for_milestone;
}
bool WasAppMigratedToWebApp(Profile* profile, const std::string& app_id) {
const base::Value::List& migrated_apps =
profile->GetPrefs()->GetList(webapps::kWebAppsMigratedPreinstalledApps);
for (const auto& val : migrated_apps) {
if (val.is_string() && val.GetString() == app_id) {
return true;
}
}
return false;
}
void MarkAppAsMigratedToWebApp(Profile* profile,
const std::string& app_id,
bool was_migrated) {
ScopedListPrefUpdate update(profile->GetPrefs(),
webapps::kWebAppsMigratedPreinstalledApps);
base::Value::List& update_list = update.Get();
if (was_migrated) {
EnsureContains(update_list, app_id);
} else {
update_list.EraseValue(base::Value(app_id));
}
}
bool WasMigrationRun(Profile* profile, base::StringPiece feature_name) {
const base::Value::List& migrated_features =
profile->GetPrefs()->GetList(prefs::kWebAppsDidMigrateDefaultChromeApps);
for (const auto& val : migrated_features) {
if (val.is_string() && val.GetString() == feature_name) {
return true;
}
}
return false;
}
void SetMigrationRun(Profile* profile,
base::StringPiece feature_name,
bool was_migrated) {
ScopedListPrefUpdate update(profile->GetPrefs(),
prefs::kWebAppsDidMigrateDefaultChromeApps);
base::Value::List& update_list = update.Get();
if (was_migrated) {
EnsureContains(update_list, feature_name);
} else {
update_list.EraseValue(base::Value(feature_name));
}
}
bool WasPreinstalledAppUninstalled(Profile* profile,
const std::string& app_id) {
const base::Value::List& uninstalled_apps =
profile->GetPrefs()->GetList(prefs::kWebAppsUninstalledDefaultChromeApps);
for (const auto& val : uninstalled_apps) {
if (val.is_string() && val.GetString() == app_id) {
return true;
}
}
return false;
}
void MarkPreinstalledAppAsUninstalled(Profile* profile,
const std::string& app_id) {
if (WasPreinstalledAppUninstalled(profile, app_id)) {
return;
}
ScopedListPrefUpdate update(profile->GetPrefs(),
prefs::kWebAppsUninstalledDefaultChromeApps);
EnsureContains(update.Get(), app_id);
}
absl::optional<bool> DeviceHasStylusEnabledTouchscreen() {
if (!ui::DeviceDataManager::HasInstance() ||
!ui::DeviceDataManager::GetInstance()->AreDeviceListsComplete()) {
return absl::nullopt;
}
for (const ui::TouchscreenDevice& device :
ui::DeviceDataManager::GetInstance()->GetTouchscreenDevices()) {
if (device.has_stylus &&
device.type == ui::InputDeviceType::INPUT_DEVICE_INTERNAL) {
return true;
}
}
return false;
}
} // namespace web_app
|
22d5a21fa1e91a7ea168c1c00fccdb816972ca5c | c9fac0b7dca58ec245f6dc46043b94d3ff17f073 | /MKGV001/Sorce/Scene.cpp | b85c05c2f8dd0a47dbd7a3064afedda312811970 | [
"MIT"
] | permissive | trashMaker/MKGV001 | d09a0ff4f465ea0a1b0f705957550e91c1047c7c | 872b769ec444c5a8e24a3bbd9358ae9cc44b2e53 | refs/heads/master | 2020-05-09T20:43:01.512233 | 2015-01-31T00:36:37 | 2015-01-31T00:36:37 | 29,885,989 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 165 | cpp | Scene.cpp | /**
* \file Flow
* \brief フローの抽象クラス
*/
#include "Scene.h"
/**
* \namespace MKGV001
*/
namespace MKGV001{
Scene::~Scene(){
}
} |
ad41b5a0ec07b5f875c056a7a617d56ecd39fa7c | 611adac564654739d42248485094f0883248d4cb | /ProcessTracer/Assert.cpp | d8c2f4cb320cb5b4b87d2b25e96dab1976129794 | [] | no_license | KrAnicom/ProcessTracer | f3514cbd0530f5c1bcac74aba8559bf04527cb53 | bee979906fad0bd4308a4dd2e28ede2f287c79a6 | refs/heads/master | 2020-03-13T07:04:07.856088 | 2013-09-12T04:53:17 | 2013-09-12T04:53:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 719 | cpp | Assert.cpp |
// Assert.cpp
// Contains functions that provides the ASSERT() service
// Shishir K Prasad (http://www.shishirprasad.net)
// History
// 06/23/13 Initial version
//
#include "Includes\Assert.h"
void vAssert(const char* psFile, unsigned int uLine)
{
fflush(NULL); // ensure that all buffers are written out first
fprintf(stderr, "Assertion failed in %s at Line %u\n", psFile, uLine);
fflush(stderr);
if(fIsLoggerInitialized())
{
WCHAR wsErrorMessage[1024];
swprintf_s(wsErrorMessage, _countof(wsErrorMessage),
L"vAssert(): Assertion failed in %S at Line %u", psFile, uLine);
logerror(wsErrorMessage);
fLoCloseLogger();
}
exit(0x666);
}// _Assert()
|
1f48c2df8a56116abeedd7e56d3e6755650503ae | 9c0c785a565d71fbc00341cbf5de02870cf4184b | /codes - ac/HDU/1286/12370684_AC_0ms_1680kB.cpp | f5649ee937f8a87ba5713eb1ddadb22f22d54397 | [] | no_license | NUC-NCE/algorithm-codes | bd833b4c7b8299704163feffc31dc37e832a6e00 | cbe9f78a0b921f5bf433f27587e7eeb944f7eb37 | refs/heads/master | 2020-06-28T05:14:48.180851 | 2019-08-02T02:40:51 | 2019-08-02T02:40:51 | 200,150,460 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | cpp | 12370684_AC_0ms_1680kB.cpp | #include<bits/stdc++.h>
#define rep(a,b,i) for(int i=a;i<=b;i++)
#define reps(a,b,i) for(int i=a;i>=b;i--)
#define sd(x) scanf("%d",&x)
#define ss(x) scanf("%s",x)
#define sc(x) scanf("%c",&x)
#define sf(x) scanf("%f",&x)
#define slf(x) scanf("%lf",&x)
#define slld(x) scanf("%lld",&x)
#define me(x,b) memset(x,b,sizeof(x))
#define pd(d) printf("%d\n",d);
using namespace std;
typedef long long ll;
int eular(int n)
{
int ret=1,i;
for(i=2;i*i<=n;i++){
if(n%i==0){
n/=i,ret*=i-1;
while(n%i==0)
n/=i,ret*=i;
}
}
if(n>1)
ret*=n-1;
return ret;
}
int main()
{
int t;
sd(t);
while(t--){
int n;
sd(n);
pd(eular(n));
}
return 0;
} |
ab1f97372de5533de2c59dccd9ef1878efc82177 | 4a83406f95a4ba8f15bb4bfff0bb34f5f36ddcde | /Practice/Segment Trees/basic_query.cpp | 5ebae80b895d3cebf72b8e0346a36894370d1b66 | [] | no_license | 2001adarsh/Contests | 5d3523ca6a5eb3eab0505733dc9144890eecb45e | a162b2a11b00d70e2b49292854b2ba826ca01311 | refs/heads/master | 2021-12-15T02:11:30.852367 | 2021-12-12T11:22:55 | 2021-12-12T11:22:55 | 252,377,884 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,730 | cpp | basic_query.cpp | /*
Segment Trees are used generally in a Range-Based Queries.
uses divide and conquer method
The root node contains info for (0-n) and then subsequently
divides itself in two parts for the left(0-mid) and right(mid+1, n)
and recursively fills up the tree.
Max Size of tree would be -> 4*N +1
else -> smallest power of 2 just greater than N.
*/
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void buildTree(int *arr, int s, int e, int *tree, int ind){
//base case
if(s == e)
{
tree[ind] = arr[s];
return;
}
//recursive case
int mid = (s+e)/2;
buildTree(arr, s, mid, tree, 2*ind );
buildTree(arr, mid+1, e, tree, 2*ind+1);
tree[ind] = min(tree[2*ind], tree[2*ind+1]);
return;
}
int minFind(int *tree, int ind, int s, int e, int qs, int qe){
//base case
//if(complete overlapping)
if( s>=qs && e<=qe ){
return tree[ind];
}
//if(no overlapping)
if(e<qs || qe<s){
return INT_MAX;
}
//recursive case
//if partial overlaping
int mid = (s+e)/2;
int a = minFind(tree, 2*ind, s, mid, qs, qe); //left
int b = minFind(tree, 2*ind+1, mid+1, e, qs, qe); //right
return min(a,b);
}
int main() {
int arr[] = { 1, 3, 2, -5, 6, 4};
int n = sizeof(arr)/sizeof(int);
int *tree = new int[4*n+1];
buildTree(arr, 0, n-1, tree, 1);
for(int i=1; i<14; i++){
cout<<tree[i]<<" ";
}
cout<<endl<<"The Min value in "<<endl;
//find min value in range 0..5
cout<<"0..5: "<<minFind(tree, 1, 0, n-1, 0, 5)<<endl;
cout<<"2..4: "<<minFind(tree, 1, 0, n-1, 2, 4)<<endl;
cout<<"4..4: "<<minFind(tree, 1, 0, n-1, 4, 4)<<endl;
}
|
da9ca1f74731a1f3eda2f656fcb272a577ec9709 | 4217ad2034022e63967f936f0bc2c375df62d110 | /ABC25x/ABC251/d.cpp | d4fe246d0db1f3fb6d240e208970aac41515b760 | [] | no_license | sealddr/MyAtCoder | 53b734124d08e479885274f4fd576d99683b50c8 | 3b9914115fd93503c04477233c5404a5f44f1378 | refs/heads/master | 2022-07-04T01:02:19.690485 | 2022-05-28T13:55:47 | 2022-05-28T13:55:47 | 239,226,855 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | cpp | d.cpp | #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
int main() {
int w;
cin >> w;
vector<int> a;
for(int i = 1; i<100; i++){
a.push_back(i);
a.push_back(100*i);
a.push_back(10000*i);
}
a.push_back(1000000);
int n = a.size();
cout << n << endl;
rep(i,n){
cout << a[i] << " ";
}
cout << endl;
} |
257053e0cc4d290578c20919be1ec68316bd6d72 | f699576e623d90d2e07d6c43659a805d12b92733 | /WTLOnline-SDK/SDK/WTLOnline_BTT_SetStateMonster_classes.hpp | d4781c382762d5a917aca284081aa72248876343 | [] | no_license | ue4sdk/WTLOnline-SDK | 2309620c809efeb45ba9ebd2fc528fa2461b9ca0 | ff244cd4118c54ab2048ba0632b59ced111c405c | refs/heads/master | 2022-07-12T13:02:09.999748 | 2019-04-22T08:22:35 | 2019-04-22T08:22:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,905 | hpp | WTLOnline_BTT_SetStateMonster_classes.hpp | #pragma once
// Will To Live Online (0.57) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "WTLOnline_BTT_SetStateMonster_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BTT_SetStateMonster.BTT_SetStateMonster_C
// 0x000C (0x00AC - 0x00A0)
class UBTT_SetStateMonster_C : public UBTTask_BlueprintBase
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x00A0(0x0008) (CPF_ZeroConstructor, CPF_Transient, CPF_DuplicateTransient)
TEnumAsByte<EStateMonster> SetStateMonster; // 0x00A8(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData)
bool SetOldState; // 0x00A9(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData)
unsigned char TempState; // 0x00AA(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
bool RestartLogic; // 0x00AB(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BTT_SetStateMonster.BTT_SetStateMonster_C"));
return ptr;
}
void ReceiveExecuteAI(class AAIController* OwnerController, class APawn* ControlledPawn);
void ExecuteUbergraph_BTT_SetStateMonster(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
2255fcd24954f44bb081743c037126a0a12e3d90 | 85cc18d2f5e5b4a62374943a0920dfd748c10417 | /C++/Data-Structures/Array/arrayEvenOdd.cpp | 7de462b7cee92a24c34a2f54f749f113af1ff5fc | [
"MIT"
] | permissive | Anima246/Data-Structures-and-Algorithms | 75889389ad8f21fd091e61d5592413c9e1e09d9f | abf0c2ce25c3bceac68dbdfd2f93ae55c5b32ec8 | refs/heads/main | 2022-12-30T14:27:50.870557 | 2020-10-20T17:22:43 | 2020-10-20T17:22:43 | 305,781,927 | 0 | 0 | MIT | 2020-10-20T17:19:35 | 2020-10-20T17:19:34 | null | UTF-8 | C++ | false | false | 619 | cpp | arrayEvenOdd.cpp | #include<iostream>
int main(){
int arr[]={2,4,5,5,8,2,3,4,7}; //you can take array elements as a user input also.
int i;
int length= sizeof(arr)/sizeof(arr[0]); //sizeof gives the size of the array in bytes (integer is of 4 bytes) divided by size of single element of array
std::cout<<"even index elements: ";
for(i=0;i<length;i++){
if (i%2==0){ //modulo(%) gives the remainder
std::cout<<arr[i]<<" ";
}
}
std::cout<<"\nodd index elements: ";
for(i=0;i<length;i++){
if(i%2!=0){
std::cout<<arr[i]<<" ";
}
}
}
|
4793f89544ea9acdfaf5d7005d973ce9eb74600a | 1925e169a11b21b1784eb06c839cb1cfc889d745 | /filter.cpp | 5c788533260f26c6706d4eb78ce79191bd8bf1e6 | [] | no_license | gcccpp/print_pcap | 3caaaa39f827da31a7587d5d40d55132aaa0ecb1 | d1133f6c55af38fc0dc8860f485860bce16fb259 | refs/heads/master | 2021-12-29T14:18:12.429553 | 2017-03-22T19:27:19 | 2017-03-22T19:27:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | cpp | filter.cpp | #include "filter.h"
Filter::Filter() :
_ip( QString() ),
_port( 0 )
{
}
Filter::~Filter()
{
}
bool Filter::pass( QString ip, u_int port )
{
return passIp( ip ) && passPort( port );
}
bool Filter::passIp( QString ip )
{
return ( !getIp().isEmpty() ) ? ip == getIp() : true;
}
bool Filter::passPort( u_int port )
{
return ( getPort() != 0 ) ? port == getPort() : true;
}
|
f7a414f61c5a85f1ccf6fd2437415aa842de5bef | 26c0577bc06512a6beeabb9104a949edf07bcf82 | /anagram.cpp | eb0442578f49e3da4b6bc23644281a84a87d00d6 | [] | no_license | knakul853/myprogram | 895e9f4b2fc6a779d2b97dccd06a81d8bb15f61a | 58d56beddde19eb839957226ad6f6b80918e5385 | refs/heads/master | 2020-03-27T01:09:11.310475 | 2018-08-23T01:30:52 | 2018-08-23T01:30:52 | 145,686,746 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 246 | cpp | anagram.cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
char s1[10],s2[10]; //strcmp return 0 if character array are same :
cin>>s1;
sort(s1,s1+strlen(s1)); //
cin>>s2;
sort(s2,s2+strlen(s2));
if(strcmp(s1,s2)==0)
cout<<s1<<" "<<s2<<endl;
}
|
0163a559883d37b40fb46dad8a97adc693ced951 | 1408c9b234d8d94f182c11c53f92dd0c8f80c16d | /Viewer/ecflowUI/src/NodeQueryEngine.cpp | dd66e09848010dcacfc941d32f129d5e2f8b058f | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSL-1.0"
] | permissive | XiaoLinhong/ecflow | 8f324250d0a5308b3e39f3dd5bd7a297a2e49c90 | 57ba5b09a35b064026a10638a10b31d660587a75 | refs/heads/master | 2023-06-19T04:07:54.150363 | 2021-05-19T14:58:16 | 2021-05-19T14:58:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,002 | cpp | NodeQueryEngine.cpp | //============================================================================
// Copyright 2009-2020 ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
//============================================================================
#include "NodeQueryEngine.hpp"
#include <QtAlgorithms>
#include <QStandardItemModel>
#include "NodeExpression.hpp"
#include "NodeQuery.hpp"
#include "ServerDefsAccess.hpp"
#include "ServerHandler.hpp"
#include "UiLog.hpp"
#include "UserMessage.hpp"
#include "VAttributeType.hpp"
#include "VFilter.hpp"
#include "VNode.hpp"
static bool metaRegistered=false;
NodeQueryEngine::NodeQueryEngine(QObject* parent) :
QThread(parent),
query_(new NodeQuery("tmp"))
{
//We will need to pass various non-Qt types via signals and slots
//So we need to register these types.
if(!metaRegistered)
{
qRegisterMetaType<NodeQueryResultTmp_ptr>("NodeQueryResultTmp_ptr");
qRegisterMetaType<QList<NodeQueryResultTmp_ptr> >("QList<NodeQueryResultTmp_ptr>");
metaRegistered=true;
}
connect(this,SIGNAL(finished()),
this,SLOT(slotFinished()));
}
NodeQueryEngine::~NodeQueryEngine()
{
delete query_;
if(parser_)
delete parser_;
}
bool NodeQueryEngine::runQuery(NodeQuery* query,QStringList allServers)
{
UiLog().dbg() << "NodeQueryEngine::runQuery -->";
if(isRunning())
wait();
stopIt_=false;
maxReached_=false;
res_.clear();
cnt_=0;
scanCnt_=0;
rootNode_=nullptr;
query_->swap(query);
maxNum_=query_->maxNum();
servers_.clear();
//Init the parsers
if(parser_)
{
delete parser_;
parser_=nullptr;
}
qDeleteAll(attrParser_);
attrParser_.clear();
//The nodequery parser
UiLog().dbg() << " node part: " << query_->nodeQueryPart().toStdString();
parser_=NodeExpressionParser::instance()->parseWholeExpression(query_->nodeQueryPart().toStdString(), query->caseSensitive());
if(parser_ == nullptr)
{
UiLog().err() << " unable to parse node query: " << query_->nodeQueryPart().toStdString();
UserMessage::message(UserMessage::ERROR,true,"Error, unable to parse node query: " + query_->nodeQueryPart().toStdString());
return false;
}
QStringList serverNames=query_->servers();
if(query_->servers().isEmpty())
serverNames=allServers;
Q_FOREACH(QString s,serverNames)
{
if(ServerHandler* server=ServerHandler::find(s.toStdString()))
{
servers_.push_back(server);
}
}
if(!query_->rootNode().empty())
{
if(servers_.size() != 1)
return false;
rootNode_=servers_.at(0)->vRoot()->find(query_->rootNode());
if(!rootNode_)
{
UiLog().err() << " the specified root node does not exist: " << query_->rootNode();
UserMessage::message(UserMessage::ERROR,true,
"Error, the specified root node <u>does not</u> exist: " + query_->rootNode());
return false;
}
}
//The attribute parser
UiLog().dbg() << " full attr part: " << query_->attrQueryPart().toStdString();
for(auto it : VAttributeType::types())
{
if(query_->hasAttribute(it))
{
QString attrPart=(query_->attrQueryPart(it));
UiLog().dbg() << " " << it->strName() << ": " << attrPart.toStdString();
BaseNodeCondition* ac=NodeExpressionParser::instance()->parseWholeExpression(attrPart.toStdString(), query->caseSensitive());
if(!ac)
{
UiLog().err() << " unable to parse attribute query: " << attrPart.toStdString();
UserMessage::message(UserMessage::ERROR,true, "Error, unable to parse attribute query: " + attrPart.toStdString());
return false;
}
attrParser_[it]=ac;
}
}
//Notify the servers that the search began
Q_FOREACH(ServerHandler* s,servers_)
{
s->searchBegan();
}
//Start thread execution
start();
UiLog().dbg() << "<-- runQuery";
return true;
}
void NodeQueryEngine::stopQuery()
{
stopIt_=true;
wait();
}
void NodeQueryEngine::run()
{
if(rootNode_)
{
run(servers_.at(0),rootNode_);
}
else
{
for(std::vector<ServerHandler*>::const_iterator it=servers_.begin(); it != servers_.end(); ++it)
{
ServerHandler *server=*it;
run(server,server->vRoot());
if(stopIt_)
{
broadcastChunk(true);
return;
}
}
}
broadcastChunk(true);
}
void NodeQueryEngine::run(ServerHandler *server,VNode* root)
{
runRecursively(root);
}
void NodeQueryEngine::runRecursively(VNode *node)
{
if(stopIt_)
return;
//Execute the node part
if(parser_->execute(node))
{
//Then execute the attribute part
if(!attrParser_.isEmpty())
{
QMap<VAttributeType*,BaseNodeCondition*>::const_iterator it = attrParser_.constBegin();
while (it != attrParser_.constEnd())
{
//Process a given attribute type
const std::vector<VAttribute*>& av=node->attrForSearch();
bool hasType=false;
for(auto i : av)
{
if(i->type() == it.key())
{
hasType=true;
if(it.value()->execute(i))
{
broadcastFind(node,i->data(true));
scanCnt_++;
}
}
//The the attribute vector elements are grouped by type.
//So we leave the loop when we reach the next type group
else if(hasType)
{
break;
}
}
++it;
}
}
else
{
broadcastFind(node);
scanCnt_++;
}
}
for(int i=0; i < node->numOfChildren(); i++)
{
runRecursively(node->childAt(i));
if(stopIt_)
return;
}
}
void NodeQueryEngine::broadcastFind(VNode* node,QStringList attr)
{
Q_ASSERT(node);
if(!attr.isEmpty())
{
NodeQueryResultTmp_ptr d(new NodeQueryResultTmp(node,attr));
res_ << d;
}
else
{
NodeQueryResultTmp_ptr d(new NodeQueryResultTmp(node));
res_ << d;
}
broadcastChunk(false);
cnt_++;
if(cnt_ >= maxNum_)
{
broadcastChunk(true);
stopIt_=true;
maxReached_=true;
}
}
void NodeQueryEngine::broadcastFind(VNode* node)
{
Q_ASSERT(node);
NodeQueryResultTmp_ptr d(new NodeQueryResultTmp(node));
res_ << d;
broadcastChunk(false);
cnt_++;
if(cnt_ >= maxNum_)
{
broadcastChunk(true);
stopIt_=true;
maxReached_=true;
}
}
void NodeQueryEngine::broadcastChunk(bool force)
{
bool doIt=false;
if(!force)
{
if(res_.count() >= chunkSize_)
{
doIt=true;
}
}
else if(!res_.isEmpty())
{
doIt=true;
}
if(doIt)
{
Q_EMIT found(res_);
res_.clear();
}
}
void NodeQueryEngine::slotFinished()
{
//Notify the servers that the search finished
Q_FOREACH(ServerHandler* s,servers_)
{
s->searchFinished();
}
}
void NodeQueryEngine::slotFailed()
{
}
NodeFilterEngine::NodeFilterEngine(NodeFilter* owner) :
query_(new NodeQuery("tmp")),
parser_(nullptr),
server_(nullptr),
owner_(owner),
rootNode_(nullptr)
{
}
NodeFilterEngine::~NodeFilterEngine()
{
delete query_;
if(parser_)
delete parser_;
}
void NodeFilterEngine::setQuery(NodeQuery* query)
{
query_->swap(query);
if(parser_)
delete parser_;
parser_=NodeExpressionParser::instance()->parseWholeExpression(query_->query().toStdString());
if(parser_ == nullptr)
{
UiLog().err() << "Error, unable to parse enabled condition: " << query_->query().toStdString();
UserMessage::message(UserMessage::ERROR, true,"Error, unable to parse enabled condition: " + query_->query().toStdString());
}
}
bool NodeFilterEngine::runQuery(ServerHandler* server)
{
rootNode_=nullptr;
if(!query_)
return false;
server_=server;
if(!server_)
return false;
if(!parser_)
return false;
if(!query_->rootNode().empty() &&
(query_->servers().count() == 1 && !query_->servers()[0].simplified().isEmpty()))
{
rootNode_=server_->vRoot()->find(query_->rootNode());
if(!rootNode_)
{
UiLog().err() << " the specified root node does not exist: " << query_->rootNode();
#if 0
UserMessage::message(UserMessage::ERROR,true,
"Node filter failed! The specified root node <u>does not</u> exist: <b>" + query_->rootNode() +
"</b><br> Please redefine your filter!");
#endif
return false;
}
}
if(rootNode_)
runRecursively(rootNode_);
else
runRecursively(server_->vRoot());
return true;
}
void NodeFilterEngine::runRecursively(VNode *node)
{
if(!node->isServer() &&
(node == owner_->forceShowNode() || parser_->execute(node)))
{
owner_->match_.push_back(node);
}
for(int i=0; i < node->numOfChildren(); i++)
{
runRecursively(node->childAt(i));
}
}
|
54621a34f8a14d28a7381e32926184ed43861c3d | 3624e9f0a026b57ebdafa4e842b93f56e5a8504d | /CodeChef/WF/Medium Hard/CARDSHUF/another.cc | 22286a6d48faf8a1ba037e24e0e70a70abd8815d | [
"MIT"
] | permissive | ailyanlu1/Competitive-Programming-2 | 54109c8644d3ac02715dc4570916b212412c25c0 | 6c990656178fb0cd33354cbe5508164207012f24 | refs/heads/master | 2020-03-23T07:48:20.560283 | 2018-02-15T06:49:49 | 2018-02-15T06:49:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,339 | cc | another.cc |
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <algorithm>
#include <tuple>
using namespace std;
// From indy256
struct TreapNode {
int val; // value stored at this node; there is no key
int priority; // large priority => closer to root
int size; // size of subtree rooted at this node
bool rev; // lazy reverse flag
TreapNode *left, *right;
TreapNode(int _val) : val(_val), priority(rand()), size(1), rev(false),
left(NULL), right(NULL) {
}
static int get_subtree_size(TreapNode *x) {
return x ? x->size : 0;
}
void update() {
size = 1 + get_subtree_size(left) + get_subtree_size(right);
}
void push() {
if (rev) {
rev = false;
if (left) left->rev ^= 1;
if (right) right->rev ^= 1;
swap(left, right);
}
}
};
typedef pair< TreapNode*, TreapNode* > LR;
LR split(TreapNode* cur, int k) {
if (!cur) return LR(NULL, NULL);
// assert(cur != NULL);
cur->push();
LR ret;
int left_subtree_size = TreapNode::get_subtree_size(cur->left);
if (k < left_subtree_size+1) {
LR sub = split(cur->left, k);
cur->left = sub.second;
ret = LR( sub.first, cur );
}
else if (k > left_subtree_size+1) {
LR sub = split(cur->right, k-left_subtree_size-1);
cur->right = sub.first;
ret = LR( cur, sub.second );
}
else {
ret.second = cur->right;
cur->right = NULL;
ret.first = cur;
}
cur->update();
return ret;
}
TreapNode* merge(TreapNode* left, TreapNode* right) {
if (!left || !right) return left ? left : right;
if (left->priority > right->priority) {
left->push();
left->right = merge(left->right, right);
left->update();
return left;
}
else {
right->push();
right->left = merge(left, right->left);
right->update();
return right;
}
}
class Treap {
TreapNode* root;
void print(TreapNode* cur) {
if (!cur) return;
cur->push();
print(cur->left);
printf("%d ", cur->val);
print(cur->right);
}
public:
Treap() : root(NULL) {}
int size() const {
return TreapNode::get_subtree_size(root);
}
TreapNode* insert(int x) {
// if (size() == 0) return root = new TreapNode(x);
LR t = split( root, x );
return root = merge(merge(t.first, new TreapNode(x)), t.second);
}
void print() {
print(root);
}
void shuffle(int a, int b, int c) {
TreapNode *A, *B, *C;
tie(A, root) = split(root, a); // take top a cards
tie(B, root) = split(root, b); // take top b cards
root = merge(A, root); // put a cards back into stack
tie(C, root) = split(root, c); // take top c cards
B->rev = true; // reverse the b cards
root = merge(B, root); // put the b cards back into stack
root = merge(C, root); // put the c cards back into stack
}
};
int main(int argc, char* argv[]) {
int N, M;
scanf("%d %d", &N, &M);
Treap t;
for (int i = 1; i <= N; ++i)
t.insert(i);
for (int m = 0; m < M; ++m) {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
t.shuffle(a, b, c);
}
t.print();
printf("\n");
return 0;
}
|
b5b447d42dc8c675b29fe99838d1f5491fa600b0 | f20263e46c5b79ecd27a68f57c888e73a6093585 | /UI/NewGameHUD/HUD_Game.cpp | 710eb1070751a5048e86380cb531de4a80be5060 | [
"MIT"
] | permissive | Bornsoul/Revenger_JoyContinue | 63cd4365a725ce50b5c9e0d41c00e3b1eb0ff6da | 599716970ca87a493bf3a959b36de0b330b318f1 | refs/heads/master | 2020-06-13T09:50:47.245820 | 2019-09-16T05:01:50 | 2019-09-16T05:01:50 | 194,618,283 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,082 | cpp | HUD_Game.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "HUD_Game.h"
#include "Widget_GHUD.h"
#include "Components/VerticalBox.h"
#include "UI/GameHUD/Widget/OffScreenIndicator/Cpt_OSIMng.h"
AHUD_Game::AHUD_Game()
{
static ConstructorHelpers::FObjectFinder<UClass> Widget_MainHUD(TEXT("/Game/1_Project_Main/1_Blueprints/UI/NEW/BP_Widget_GHUD.BP_Widget_GHUD_C"));
if (Widget_MainHUD.Succeeded())
{
m_pInst_MainHUD = Widget_MainHUD.Object;
}
m_pOSIMng = CreateDefaultSubobject<UCpt_OSIMng>(TEXT("OSI"));
}
void AHUD_Game::Init()
{
m_pController = Cast<APlayerController>(UGameplayStatics::GetPlayerController(GetWorld(), 0));
if (m_pController == nullptr)
{
ULOG(TEXT("Controller is nullptr"));
return;
}
m_pMainHUD = CreateWidget<UWidget_GHUD>(m_pController, m_pInst_MainHUD);
if (m_pMainHUD != nullptr)
{
m_pMainHUD->AddToViewport();
m_pMainHUD->GetSlowGageHUD()->SetSlowEnter(m_fGageSpeed);
m_pMainHUD->GetSkillHUD()->SetSkillEnter();
m_bActive = true;
SetHudActive(false);
}
}
void AHUD_Game::SetHudActive(bool bActive)
{
if (m_pMainHUD == nullptr) return;
if (m_bActive == bActive) return;
if ( bActive )
m_pMainHUD->SetPlayAnimation("Start");
else
m_pMainHUD->SetPlayAnimation("End");
m_bActive = bActive;
}
void AHUD_Game::BeginPlay()
{
Super::BeginPlay();
m_bDestroyOSI = false;
}
void AHUD_Game::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
Super::EndPlay(EndPlayReason);
if (m_pMainHUD != nullptr)
{
if (m_pMainHUD->IsValidLowLevel())
{
m_pMainHUD->RemoveFromViewport();
m_pMainHUD = nullptr;
}
}
if (m_pOSIMng != nullptr)
{
if (m_pOSIMng->IsValidLowLevel())
{
m_pOSIMng->DestroyComponent();
m_pOSIMng = nullptr;
}
}
}
void AHUD_Game::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if (m_pMainHUD->GetSlowGageHUD() != nullptr)
{
m_pMainHUD->GetSlowGageHUD()->Tick_SlowGage(DeltaTime);// UGameplayStatics::GetRealTimeSeconds(GetWorld()));
}
if (m_pMainHUD->GetSkillHUD() != nullptr)
{
m_pMainHUD->GetSkillHUD()->Tick_SkillCoolTime(DeltaTime);
m_pMainHUD->GetSkillHUD()->Tick_SkillCoolTimeCount(DeltaTime);
m_pMainHUD->GetSkillHUD()->Tick_SkillShieldTime(DeltaTime);
}
}
class UWidget_GHUD* AHUD_Game::GetRootHUD()
{
if (m_pController == nullptr)
{
m_pController = Cast<APlayerController>(UGameplayStatics::GetPlayerController(GetWorld(), 0));
m_pMainHUD = CreateWidget<UWidget_GHUD>(m_pController, m_pInst_MainHUD);
if (m_pMainHUD != nullptr)
{
m_pMainHUD->AddToViewport();
m_pMainHUD->GetSlowGageHUD()->SetSlowEnter(m_fGageSpeed);
m_pMainHUD->GetSkillHUD()->SetSkillEnter();
m_bActive = true;
SetHudActive(false);
}
GetRootHUD();
return nullptr;
}
return m_pMainHUD;
}
void AHUD_Game::AddOSIEnemy(class AGameCharacter* pEnemy, int32 nIconState)
{
if (m_pOSIMng == nullptr) return;
m_pOSIMng->AddPin(pEnemy, nIconState);
}
void AHUD_Game::DestroyOSIEnemy()
{
if (m_pOSIMng == nullptr) return;
if (m_bDestroyOSI == true) return;
m_pOSIMng->DestroyPin();
m_bDestroyOSI = true;
} |
2bd54b9f7cc8ed0ba08594cc08d8538bde55ef5c | 0a85c3a4f82d08ec43a62fce679745cd6c8514b4 | /Algorithms/algorithms_binary_search.cpp | f13a91ed75f606578815978eb156895391104f65 | [] | no_license | jpiccoli/STL_2017 | 77e521e7ce029fc23d636b333bda3ac4596f5038 | 71d4ce621c63342b8b38d1d31b280b0f89d0b1d6 | refs/heads/master | 2021-07-09T02:03:56.905300 | 2020-07-04T22:38:07 | 2020-07-04T22:38:07 | 144,506,894 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,461 | cpp | algorithms_binary_search.cpp | #include "../prototypes.h"
void lower_bound()
{
std::vector<int> vec = { 11, 13, 15, 17, 21, 23, 25, 27, 29, 31 };
auto iter = std::lower_bound(vec.begin(), vec.end(), 22);
if (*iter == 23)
{
std::cout << "lower_bound() passed" << std::endl;
}
else
{
std::cout << "lower_bound() failed" << std::endl;
}
}
void upper_bound()
{
std::vector<int> vec = { 11, 13, 15, 17, 21, 23, 25, 27, 29, 31 };
auto iter = std::upper_bound(vec.begin(), vec.end(), 23);
if (*iter == 25)
{
std::cout << "upper_bound() passed" << std::endl;
}
else
{
std::cout << "upper_bound() failed" << std::endl;
}
}
void equal_range()
{
std::vector<int> vec = { 11, 13, 15, 17, 21, 23, 25, 27, 29, 31 };
auto pair = std::equal_range(vec.begin(), vec.end(), 23);
if (*pair.first == 23 && *pair.second == 25)
{
std::cout << "equal_range() passed" << std::endl;
}
else
{
std::cout << "equal_range() failed" << std::endl;
}
}
void binary_search()
{
std::vector<int> vec = { 11, 13, 15, 17, 21, 23, 25, 27, 29, 31 };
auto status1 = std::binary_search(vec.begin(), vec.end(), 23);
auto status2 = std::binary_search(vec.begin(), vec.end(), 24);
if (status1 && !status2)
{
std::cout << "binary_search() passed" << std::endl;
}
else
{
std::cout << "binary_search() failed" << std::endl;
}
}
void algorithms_binary_search()
{
lower_bound();
upper_bound();
equal_range();
binary_search();
} |
6164bc495643088e137e4e16eb67f04feef0849e | 51f747c2cd270b909f421db31a04f17ee4824b23 | /Cpp_Single/chapter6/6_19.cpp | 0314e8fed8eb1851738b6205bafe67ba42b26bcc | [] | no_license | RIOterN/Code_cpp | 9b51a559d4af0d38f94337986bca0fb83e707aa9 | 77519879e9f9b5b7718ea6a2bdfba3c05fb8f0e3 | refs/heads/main | 2023-08-20T19:07:26.120839 | 2021-10-01T01:27:41 | 2021-10-01T01:27:41 | 400,073,114 | 0 | 0 | null | 2021-09-01T11:49:33 | 2021-08-26T07:02:52 | C++ | UTF-8 | C++ | false | false | 616 | cpp | 6_19.cpp | //6-19动态创建多维数组
#include <iostream>
using namespace std;
int main(){
float (*cp)[9][8]=new float[8][9][8];
for(int i=0;i<8;i++)
for(int j=0;j<9;j++)
for(int k=0;k<8;k++)
//以指针形式访问数组元素
*(*(*(cp+i)+j)+k)=static_cast<float>(i*100+j*10+k);
for(int i=0;i<8;i++)
{
for(int j=0;j<9;j++)
{
for(int k=0;k<8;k++)
//将cp做数组名使用,通过数组名和下标访问
cout<<cp[i][j][k]<<" ";
cout<<endl;
}
cout<<endl;
}
}
|
a06506ea3aa5dd703ba413e250b6f964d9617686 | d6cdcd762a73aeef4695d530b045fb1f1a4366aa | /Desert_World2/DObject.cpp | 5488bd7ad2cc1d645cb61e63e55307614adb83f4 | [] | no_license | Interceptor1337/Desert_worlD2 | 055da37a4cc7ce2107b856bc22eb19b20d2dd0b2 | e34e41049256b700ffbbd435b136606c67016209 | refs/heads/master | 2021-01-01T19:17:01.165769 | 2018-04-29T10:04:57 | 2018-04-29T10:04:57 | 98,554,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 674 | cpp | DObject.cpp | #include "stdafx.h"
#include "DObject.h"
#include "iostream"
#include <stdio.h>
#include <conio.h>
#include <fstream>
#include<windows.h>
DObject::DObject(int _x, int _y, char _texture, int _id, int _flag)
{
if (_x >= 0)
{
x = _x;
}
if (_y >= 0)
{
y = _y;
}
texture = _texture;
id = _id;
flag = _flag;
name = "DObject";
}
DObject::~DObject()
{
}
int DObject::getX()
{
return x;
}
int DObject::getY()
{
return y;
}
int DObject::getFlag()
{
return flag;
}
char DObject::getTexture()
{
return texture;
}
int DObject::getId()
{
return id;
}
std::string DObject::getName()
{
return name;
}
|
13149e3bb491dc0980ed4f89716ad3e69156c7b1 | c9eca1a1c21dafd6513167872243d2168d408c77 | /include/rnetlib/ofi/ofi_client.h | 8090bc32206736e2b5c8e4b006bd3fc94bbc30e8 | [] | no_license | hdaikoku/rnetlib | 2c5e296e27d6994900585d8f56d7e725d2aff896 | 8d90a0360c93fc86693aab69ce4a8b18603b0228 | refs/heads/master | 2022-11-29T18:22:19.122191 | 2018-03-30T02:36:52 | 2018-03-30T02:36:52 | 287,691,994 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,518 | h | ofi_client.h | #ifndef RNETLIB_OFI_OFI_CLIENT_H_
#define RNETLIB_OFI_OFI_CLIENT_H_
#include <cassert>
#include "rnetlib/client.h"
#include "rnetlib/ofi/ofi_channel.h"
#include "rnetlib/ofi/ofi_endpoint.h"
namespace rnetlib {
namespace ofi {
class OFIClient : public Client {
public:
explicit OFIClient(uint64_t self_desc) : ep_(OFIEndpoint::GetInstance(nullptr, nullptr)), self_desc_(self_desc) {
std::memset(&tx_req_, 0, sizeof(tx_req_));
}
~OFIClient() override = default;
Channel::ptr Connect(const std::string &peer_addr, uint16_t peer_port, uint64_t peer_desc) override {
fi_addr_t fi_addr = FI_ADDR_UNSPEC;
ep_.InsertAddr(peer_addr.c_str(), peer_port, &fi_addr);
auto &self_addrinfo = ep_.GetBindAddrInfo();
self_addrinfo.desc = self_desc_;
self_addrinfo.src_tag = ep_.GetNewSrcTag();
auto lmr = ep_.RegisterMemoryRegion(&self_addrinfo, sizeof(self_addrinfo), MR_LOCAL_READ);
std::unique_ptr<OFIChannel> ch(new OFIChannel(ep_, fi_addr, peer_desc, self_addrinfo.src_tag));
ep_.PostSend(lmr->GetAddr(), lmr->GetLength(), lmr->GetLKey(), fi_addr,
(TAG_PROTO_CTR << OFI_TAG_SOURCE_BITS), &tx_req_);
ep_.PollTxCQ(tx_req_.req, &tx_req_);
assert(tx_req_.req == 0);
uint64_t dst_tag = 0;
ch->Recv(&dst_tag, sizeof(dst_tag));
ch->SetDestTag(dst_tag);
return std::move(ch);
}
private:
OFIEndpoint &ep_;
uint64_t self_desc_;
struct ofi_req tx_req_;
};
} // namespace ofi
} // namespace rnetlib
#endif // RNETLIB_OFI_OFI_CLIENT_H_
|
e63c618ca3137288ebcec37db692d473701d00f6 | d67ecf51a645b226b2fc10334f3856a2106bfaa7 | /Chapter09/MultiInheri2.cpp | 82e17dcd688d0888c564e8183c4ed9e7fed00700 | [] | no_license | kusakina0608/Basic-Cpp | 802bac9763881fa2f778f6c3adc05872e8374c76 | 4ace606302f24450f2165c279dff07578e7ef5f4 | refs/heads/master | 2022-04-07T02:33:41.414052 | 2020-02-07T07:18:40 | 2020-02-07T07:18:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 476 | cpp | MultiInheri2.cpp | //
// Created by Kina on 2020/02/04.
//
/*
#include <iostream>
using namespace std;
class BaseOne{
public:
void SimpleFunc() { cout<<"BaseOne"<<endl; }
};
class BaseTwo{
public:
void SimpleFunc() { cout<<"BaseTwo"<<endl; }
};
class MultiDerived : public BaseOne, protected BaseTwo{
public:
void ComplexFunc(){
BaseOne::SimpleFunc();
BaseTwo::SimpleFunc();
}
};
int main(void){
MultiDerived mdr;
mdr.ComplexFunc();
return 0;
}*/
|
a1398f1d6b60b33489c59ddbdd6a898d3cdf0ff1 | 939ea84629e282a2193936f39d3f6b961b3989a8 | /ABC/SymbolsEncryption.cpp | 851bd89d3134d37355d3316f982e1523abfca7f8 | [] | no_license | PinkDoors/CSAHomework2 | 4a734e5b5c5d6dbe11a88a0e0a5c7fcb3d89d6c5 | d68fbb71bfd517ea9bf468c0487869485163cf2f | refs/heads/main | 2023-08-24T13:16:27.606288 | 2021-10-24T07:38:05 | 2021-10-24T07:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,362 | cpp | SymbolsEncryption.cpp | #include <iostream>
//------------------------------------------------------------------------------
// SymbolsEncryption.cpp - содержит реализацию строки, зашифрованной заменой символов на другие символы.
//------------------------------------------------------------------------------
#include "SymbolsEncryption.h"
SymbolsEncryption::SymbolsEncryption() {
Init();
RandomEncrypt();
}
SymbolsEncryption::SymbolsEncryption(std::ifstream &ifst) {
ifst >> size;
if (size > 256 || size < 0) {
std::cout << "Incorrect size of the input string, the size is set to 0" << "\n";
size = 0;
}
if (size > 0) {
ifst >> sourceString;
}
Init();
Encrypt(ifst);
}
void SymbolsEncryption::RandomEncrypt() {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
size = rand() % 255;
for (int i = 0; i < size; ++i) {
int symbol = rand() % 62;
sourceString[i] = alphanum[symbol];
}
for (int i = 0; i < 62; ++i) {
int symbol = rand() % 62;
symbols[i].second = alphanum[symbol];
}
for (int i = 0; i < size; ++i) {
for (int j = 0; j < 62; ++j) {
if (sourceString[i] == symbols[j].first) {
encryptedString[i] = symbols[j].second;
}
}
}
}
void SymbolsEncryption::Encrypt(std::ifstream &ifst) {
int numberOfSymbols = 0;
ifst >> numberOfSymbols;
for (int i = 0; i < numberOfSymbols; ++i) {
char oldSymbol;
char newSymbol;
ifst >> oldSymbol >> newSymbol;
for (int j = 0; j < 62; ++j) {
if (symbols[j].first == oldSymbol) {
symbols[j].second = newSymbol;
}
}
}
for (int i = 0; i < size; ++i) {
for (int j = 0; j < 62; ++j) {
if (sourceString[i] == symbols[j].first) {
encryptedString[i] = symbols[j].second;
}
}
}
}
void SymbolsEncryption::Init() {
symbols = new SymbolsEncryption::PairOfCharChar[62];
int numberOfSymbol = 0;
for (int i = 0; i < 10; ++i) {
symbols[numberOfSymbol].first = i + 48;
symbols[numberOfSymbol].second = i + 48;
++numberOfSymbol;
}
for (int i = 17; i < 43; ++i) {
symbols[numberOfSymbol].first = i + 48;
symbols[numberOfSymbol].second = i + 48;
++numberOfSymbol;
}
for (int i = 49; i < 75; ++i) {
symbols[numberOfSymbol].first = i + 48;
symbols[numberOfSymbol].second = i + 48;
++numberOfSymbol;
}
}
void SymbolsEncryption::Out(std::ofstream &ofst) {
ofst << "Input string = ";
for (int i = 0; i < size; ++i) {
ofst << sourceString[i];
}
ofst << ".\n" << "\n";
ofst << "The quotient of dividing the sum of "
"the codes of an unencrypted "
"string by the number of characters in "
"this string = " << QuotientOfDivision();
ofst << ".\n" << "\n";
ofst << "Result of the encryption: ";
for (int i = 0; i < size; ++i) {
ofst << encryptedString[i];
}
ofst << ".\n";
} |
f69f419bf914074c5891fc709a4e84eb850c5be8 | e3b67db8b0ea9af2ba890dc4e119ff22876a2232 | /libminifi/include/core/CachedValueValidator.h | b6f261fa0a2c26eebde981ea8afadc75da9a2455 | [
"MPL-2.0",
"Apache-2.0",
"BSD-3-Clause",
"curl",
"OpenSSL",
"libtiff",
"bzip2-1.0.6",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"MIT-0",
"Beerware",
"Zlib",
"NCSA",
"ISC",
"CC0-1.0",
"LicenseRef-scancode-object-form-exception-to-mit",
"BSL-1.0",
"LicenseRef-scancode-pu... | permissive | apache/nifi-minifi-cpp | 90919e880bf7ac1ce51b8ad0f173cc4e3aded7fe | 9b55dc0c0f17a190f3e9ade87070a28faf542c25 | refs/heads/main | 2023-08-29T22:29:02.420503 | 2023-08-25T17:21:53 | 2023-08-25T17:21:53 | 56,750,161 | 131 | 114 | Apache-2.0 | 2023-09-14T05:53:30 | 2016-04-21T07:00:06 | C++ | UTF-8 | C++ | false | false | 2,170 | h | CachedValueValidator.h | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#pragma once
#include <utility>
#include <memory>
#include <string>
#include "state/Value.h"
#include "ValidationResult.h"
namespace org::apache::nifi::minifi::core {
class PropertyValue;
class PropertyValidator;
namespace internal {
class CachedValueValidator {
friend class core::PropertyValue;
public:
enum class Result {
FAILURE,
SUCCESS,
RECOMPUTE
};
CachedValueValidator();
CachedValueValidator(const CachedValueValidator& other) : validator_(other.validator_) {}
CachedValueValidator& operator=(const CachedValueValidator& other) {
if (this == &other) {
return *this;
}
setValidator(*other.validator_);
return *this;
}
CachedValueValidator& operator=(const PropertyValidator& new_validator) {
setValidator(new_validator);
return *this;
}
private:
void setValidator(const PropertyValidator& new_validator) {
invalidateCachedResult();
validator_ = gsl::make_not_null(&new_validator);
}
ValidationResult validate(const std::string& subject, const std::shared_ptr<state::response::Value>& value) const;
void invalidateCachedResult() {
validation_result_ = Result::RECOMPUTE;
}
gsl::not_null<const PropertyValidator*> validator_;
mutable Result validation_result_{Result::RECOMPUTE};
};
} // namespace internal
} // namespace org::apache::nifi::minifi::core
|
4b06449b1dd823de83f0c1843db8b46cc9b2a41a | bafb23b4b6ff5076d182b1744e11fc19f89a3809 | /Quicksort/Quicksort/renderarea.cpp | 62a37e9e60799f544d7ea34261150959aeec24aa | [] | no_license | Siwady/QuickSort-GuiAnimations | 88756939795d600ef549bb81a8ff1807526cd741 | ec33040b404de4c9de0b194c6b5bcbe2cb4e0a5b | refs/heads/master | 2016-09-10T11:01:30.633497 | 2015-06-27T04:02:10 | 2015-06-27T04:02:10 | 36,894,556 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 542 | cpp | renderarea.cpp | #include "renderarea.h"
RenderArea::RenderArea(QuickSortArray *Q, QWidget *parent) :
QWidget(parent)
{
this->QArray=Q;// <----
}
void RenderArea::setArray(QuickSortArray *qArray)
{
this->QArray = qArray;
}
void RenderArea::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setPen(Qt::black);
painter.setBrush(Qt::white);
painter.drawRect(0,0,this->width()-1,this->height()-1);
this->QArray->RenderArray(&painter);
}
void RenderArea::enterEvent ( QEvent * event )
{
this->setFocus();
}
|
1389a88a7050c14186862322187d197902c53c30 | 726cf7daa77d92f1a6d2a46e8bf1115b7b3b6637 | /Player.h | bab50941ef330a39378dba29bfeec0b2a5e21c6c | [] | no_license | JoyMace/Escape-to-the-Stars | 7216f878c359ea0ec40b0b007ed13648b43d613d | cf42cd15194bf214f27dfaebbc56476b1c382f5f | refs/heads/master | 2020-03-30T16:19:45.518919 | 2019-05-30T21:42:38 | 2019-05-30T21:42:38 | 151,403,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 699 | h | Player.h | #ifndef PLAYER_H
#define PLAYER_H
#include <string>
#include "Item.h"
#include <vector>
using namespace std;
class Player
{
public:
Player();
~Player();
int HP;
int maxHP = 100;
int x;
int y;
bool isAlive;
int gold;
vector<Item> inventory;
void setName(string);
string getName();
void setHP(int HP);
int getHP();
void setX(int x);
void setY(int y);
int getX();
int getY();
void setGold(int g);
int getGold();
void AddItem(Item item);
protected:
private:
string name;
};
#endif // PLAYER_H
|
56c01603aa2247c0dde30df6269a0fba20d5d0c3 | 34b6e001c6bed62386250609a708790a5ec19d85 | /String/67.add-binary.cpp | 33768af088af14f1682f902769526a0c8f5b9f25 | [] | no_license | alkamaazmi/Data-Structures-and-Algorithms | 339b3420ee947cd1ed62147210a9d810f4fb23ee | 059cbda5f39b59ac7bab07f156e0ea4fe1a6a703 | refs/heads/main | 2023-04-28T04:32:27.598565 | 2023-04-20T16:35:05 | 2023-04-20T16:35:05 | 329,375,922 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,095 | cpp | 67.add-binary.cpp | /*
* Leetcode [67] Add Binary
* Given two binary strings a and b, return their sum as a binary string
* a and b consist only of '0' or '1' characters
* Each string does not contain leading zeros except for the zero itself
*/
class Solution
{
public:
string addBinary(string a, string b)
{
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
string s = "";
while (i >= 0 || j >= 0)
{
int sum = carry;
if (i >= 0)
{
sum += (a[i] - '0');
i--;
}
if (j >= 0)
{
sum += (b[j] - '0');
j--;
}
int temp = sum % 2;
s += to_string(temp);
carry = sum / 2;
}
if (carry > 0)
{
s += to_string(carry);
}
reverse(s.begin(), s.end());
return s;
}
};
// Time Complexity : O(max(M, N)), M & N is the length of string a, b;
// Space Complexity : O(max(M, N)), which is the size of "res" object
|
b2d29c67ed3a731832a75ede15d29dcf0b96067d | 8fa093401cd749085e4f4a12645cc9cd42e1e881 | /kssh.h | 1e91a67e4e67822c53f0d7195b1af9c1c952a353 | [
"BSD-3-Clause"
] | permissive | leblanc-simon/qlaunchoverssh | c3536819e773178208d338ca2c13ffd57da1357e | 013afe435657a165efca211bc0f5344959298626 | refs/heads/master | 2016-08-06T05:42:19.805337 | 2014-04-08T11:41:42 | 2014-04-08T11:41:42 | 16,562,227 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,563 | h | kssh.h | /*
Copyright (c) 2010, Simon Leblanc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification
, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice
, this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Simon Leblanc 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 KSSH_H
#define KSSH_H
#include <QString>
#include "libssh/libssh.h"
class Kssh
{
private:
/* The variable with the SSH session */
ssh_session m_session;
protected:
QString m_command;
QString m_return;
void init();
/* Connection method */
bool launch_connect(QString server, QString login, int port = 22);
bool check_known_host();
bool authenticate(QString private_key = "", QString password = "");
bool authenticateKey(QString private_key, QString password = "");
bool authenticatePassword(QString password);
bool authenticatePasswordInteractive(QString password);
public:
/* Constructor and destructor */
Kssh();
~Kssh();
/* Connection method */
bool connect(QString server, QString login, QString private_key = "", QString password = "", int port = 22);
bool disconnect();
/* Action method */
bool launch(QString command);
QString getLastCommand();
QString getReturn();
};
#endif // KSSH_H
|
5e0a6226eb35118cf41b480a902c09f696cb6b4b | 8d8810a014e03522f922a360489f26826e4f10e5 | /src/extended/response.hpp | 79232fd6f4a7fbc20aa65a9aeed459fbb5850f7d | [] | no_license | xforge-at/argo | 8976ffbad65b17d7f455be7b1f4590d3d609269c | 6a4735e3c7901e97bb39850b2ed5008c2030f8ae | refs/heads/master | 2021-05-03T19:11:33.105815 | 2016-10-12T22:23:53 | 2016-10-12T22:23:53 | 62,939,571 | 0 | 0 | null | 2016-10-12T22:23:53 | 2016-07-09T08:11:15 | C++ | UTF-8 | C++ | false | false | 930 | hpp | response.hpp | #import "component_container.hpp"
#import "extended/request.hpp"
#import "generated/response_base.hpp"
#import "http_component.hpp"
#import "util.hpp"
#import <cstdint>
#import <experimental/optional>
#import <string>
#import <unordered_map>
#import <utility>
#import <vector>
namespace Argo {
struct Response : public ResponseBase, public ComponentContainer {
Response(Request request_, int32_t status_code_, std::unordered_map<std::string, std::string> header_, std::experimental::optional<std::vector<uint8_t>> body_)
: ResponseBase(request_, status_code_, header_, body_) {}
virtual ~Response() = default;
Response(const Response &) = default;
Response(Response &&) = default;
Response &operator=(const Response &) = default;
Response &operator=(Response &&) = default;
// Extended methods:
using ComponentContainer::get_component;
};
}
|
dd7faceacd5aa87dd579ce75ef2191ea29293b84 | 15a43d68fd5b87d0e7834da35f451672bddfa9ca | /include/GUI/HidePage.h | 56078e1d34ca2779fa0084f2e075b6ca71de86ec | [] | no_license | Vaphen/Stegano | d05e03b880d32c0fd976fe82b5766dfeae7309d1 | 7ec85a4b59e43cdfc71cb1e52a5d957c1231409b | refs/heads/master | 2021-01-10T15:25:09.548968 | 2016-05-04T07:56:08 | 2016-05-04T07:56:08 | 49,865,198 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,612 | h | HidePage.h | #ifndef HIDEPAGE_H
#define HIDEPAGE_H
#include <wx/wx.h>
#include <wx/notebook.h>
#include <wx/gbsizer.h>
#include <wx/event.h>
#include <thread>
#include <cassert>
#include <utility>
#include "ActionNotebookPage.h"
#include "SteganoHide.h"
#include "Dialogs.h"
class HidePage : public ActionNotebookPage
{
public:
HidePage() = delete;
HidePage(wxWindow *, int);
virtual ~HidePage();
protected:
private:
// widgets
wxGridBagSizer *form;
wxBitmap *openDialogButtonIcon;
wxTextCtrl *outputFileInput;
wxTextCtrl *containerFileInput;
wxRadioButton *hideFileRadio;
wxTextCtrl *hideFileInput;
wxBitmapButton *openContainerDialogButton;
wxBitmapButton *openHideFileDialogButton;
wxRadioButton *hideTextRadio;
wxTextCtrl *textToHideCtrl;
wxButton *startHidingButton;
wxGauge *progressBar;
// events
void OnSelectOutputFileClicked(wxCommandEvent &event);
void OnOpenHideFileClicked(wxCommandEvent& event);
void OnOpenContainerFileClicked(wxCommandEvent& event);
void HideRadioChanged(wxCommandEvent& event);
void OnStart(wxCommandEvent &event);
// initialization functions
void addOutputFileArea();
void addContainerFileArea();
void addFileToHideArea();
void addPhraseToHideArea();
//void sendThreadMsg(const MessageData &);
void disableInputElements();
void reenableElements();
void startProgressbarThread();
void hideFileSelected(const std::string &);
void hideTextSelected(const std::string &);
// declare event table
wxDECLARE_EVENT_TABLE();
};
#endif // HIDEPAGE_H
|
cfdc14c065b29dedf35df5294743259087ed7631 | d8341d37a1275318bd469641d61360e6f0b35b39 | /yandex/white_belt/sort_lowercase/main.cpp | f7af61835496d18ce7c290810506ebf726689124 | [] | no_license | hapass/cpp_courses | 676fc67184c784455f166434ebd416d34ec76538 | 00f109cc48af8a8b3e3126a61e500b5da3ea7b36 | refs/heads/master | 2021-06-26T13:44:48.837730 | 2020-11-02T20:29:24 | 2020-11-02T20:29:24 | 166,034,643 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 613 | cpp | main.cpp | #include <iostream>
#include <algorithm>
#include <locale>
#include <vector>
using namespace std;
int main() {
int vectorSize = 0;
cin >> vectorSize;
vector<string> vec(vectorSize);
for (auto& value : vec) {
cin >> value;
}
sort(begin(vec), end(vec), [](string first, string second) {
for (auto& ch : first) {
ch = tolower(ch);
}
for (auto& ch : second) {
ch = tolower(ch);
}
return first < second;
});
for (const auto& value : vec) {
cout << value << ' ';
}
cout << endl;
return 0;
} |
631a5d36e709700072634ab857abe2a412dd1e98 | 10383a98e5e86bde76d6001ff51d68d428a3c2c2 | /cpp/opengl/3d_test1/test0_point.cpp | 9b7c59246a88eeb3ee88f0220c679c510b10f4c3 | [] | no_license | inksmallfrog/backup | 2e61d5d21be7aae16d86d73a34bcdb64d82048ef | 114af6ac12b79412672edd9721e9232efc946368 | refs/heads/master | 2021-01-10T09:45:54.964123 | 2016-04-16T02:23:10 | 2016-04-16T02:23:10 | 47,020,708 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 688 | cpp | test0_point.cpp | #include "test0_point.h"
#include "ui_trianglewindow.h"
#include <QScreen>
Test0_Point::Test0_Point() :
VBO(0)
{
}
Test0_Point::~Test0_Point()
{
}
void Test0_Point::initialize(){
}
void Test0_Point::render(){
GLfloat vertices[] = {
0.0f, 2.0f, 0.0f,
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f
};
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
}
|
a373ae2f51e7d4ef0bd19ff007e5f4e61d06292e | d496a181d54598f3fe43c354c1909ceb99befe0a | /includes/cuckoo/cuckoo_test.cpp | d87a46972d696e757ffded6ca5d46124e4575a3b | [] | no_license | ReichertL/MPFSS_Cuckoo | 10e06e57f5a7d818cb41f99af2a74ed34e816578 | d2f1c874cb686ecd86ca819a6bceb9d3ddf2a76b | refs/heads/master | 2021-08-08T06:50:18.974462 | 2021-01-07T21:21:11 | 2021-01-07T21:21:11 | 237,607,335 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,193 | cpp | cuckoo_test.cpp | #include <string>
#include <cmath>
#include <stdlib.h> /* srand, rand */
#include <time.h>
#include "gtest/gtest.h"
#include "absl/hash/hash_testing.h"
#include "cuckoo.h"
TEST(fast_mod, Works){
//TODO input zufällig generieren
int input=21;
int ceil=20;
int target=input%ceil;
EXPECT_EQ(
target,
fast_mod(input,ceil)
);
input++;
EXPECT_NE(
target,
fast_mod(input,ceil)
);
input++;
ceil++;
EXPECT_NE(
target,
fast_mod(input,ceil)
);
}
TEST(hashfunc_absl, Works){
for (int j = 0; j< 20; ++j){
srand (time(NULL));
int key = rand();
int i=rand();
int offset=rand()%10+1;
EXPECT_NE(
hashfunc_absl(i+offset,key),
hashfunc_absl(i,key)
);
EXPECT_NE(
hashfunc_absl(i,key+offset),
hashfunc_absl(i,key)
);
}
}
TEST(hash_this, Works){
for (int j = 0; j< 20; ++j){
srand (time(NULL));
int key = rand();
int i=rand();
int ceil=rand();
EXPECT_EQ(
abs(hashfunc_absl(i,key)%ceil),
hash_this(hashfunc_absl,key,i,ceil)
);
EXPECT_EQ(
abs(hashfunc_simple(i,key)%ceil),
hash_this(hashfunc_simple,key,i,ceil)
);
EXPECT_LE(
0,
hash_this(hashfunc_simple,key,-i,ceil)
);
EXPECT_LE(
0,
hash_this(hashfunc_simple,-key,i,ceil)
);
}
}
/*TEST(initialize, rands_array_predefined){
srand (time(NULL));
int w = rand()%100000;
int no_hash_tables=rand()%1000;
int *size_hash_tables=(int *)calloc(no_hash_tables,sizeof(int));
for (int i = 0; i < no_hash_tables; ++i)
{
size_hash_tables[i]=rand()%100000;
}
int *i_array=(int *)calloc(w,sizeof(int));
for (int i = 0; i < w; ++i)
{
i_array[i]=rand();
}
int max_loop=rand();
cuckoo_hashing *c=initialize(w, no_hash_tables, size_hash_tables, i_array, max_loop, hashfunc_absl );
EXPECT_EQ(w,c->no_hash_functions);
EXPECT_EQ(no_hash_tables,c->no_hash_tables);
EXPECT_EQ(size_hash_tables,c->size_hash_tables);
EXPECT_EQ(max_loop,c->max_loop);
//casting does not work
ASSERT_EQ(no_hash_tables*2,static_cast<int>(c->tables.size()));
for (int i = 0; i < no_hash_tables; ++i)
{
EXPECT_EQ(0,c->tables.at(i).size());
EXPECT_EQ(0,c->table_usage.at(i).size());
}
EXPECT_EQ(hashfunc_absl,c->hash_function);
for (int i = 0; i < w; ++i)
{
EXPECT_EQ(i_array[i],c->rands.at(i));
}
}
TEST(initialize, no_rands_array){
srand (time(NULL));
int w = rand()%100000;
int no_hash_tables=rand()%1000;
int *size_hash_tables=(int *)calloc(no_hash_tables,sizeof(int));
for (int i = 0; i < no_hash_tables; ++i)
{
size_hash_tables[i]=rand()%100000;
}
int max_loop=rand();
cuckoo_hashing *c=initialize(w, no_hash_tables, size_hash_tables, NULL, max_loop, hashfunc_absl );
EXPECT_EQ(w,c->no_hash_functions);
EXPECT_EQ(no_hash_tables,c->no_hash_tables);
EXPECT_EQ(size_hash_tables,c->size_hash_tables);
EXPECT_EQ(max_loop,c->max_loop);
//casting does not work
ASSERT_EQ(no_hash_tables*2,static_cast<int>(c->tables.size()));
for (int i = 0; i < no_hash_tables; ++i)
{
EXPECT_EQ(0,c->tables.at(i).size());
EXPECT_EQ(0,c->table_usage.at(i).size());
}
EXPECT_EQ(hashfunc_absl,c->hash_function);
for (int i = 0; i < w; ++i)
{
EXPECT_EQ(i,c->rands.at(i));
}
}*/
TEST(cuckoo, Works){
srand (time(NULL));
int w = rand()%100000;
int no_hash_tables=3;//rand()%1000;
int *size_hash_tables=(int *)calloc(no_hash_tables,sizeof(int));
int ceil=0;
for (int i = 0; i < no_hash_tables; ++i)
{
size_hash_tables[i]=rand()%100000;
ceil=ceil+size_hash_tables[i];
}
int max_loop=rand();
cuckoo_hashing *c=initialize(w, no_hash_tables, size_hash_tables, NULL, max_loop, hashfunc_absl );
ceil=0.01*ceil;
int no_keys=rand()%ceil;
int *keys= (int *) calloc(no_keys, sizeof(int));
for (int i = 0; i < no_keys; ++i)
{
keys[i]=rand();
}
cuckoo(keys, no_keys, c);
for (int i = 0; i < no_hash_tables; ++i)
{
for (int j = 0; j <size_hash_tables[i] ; ++j)
{
bool used =c->table_usage.at(i).at(j);
int set=c->tables.at(i).at(j);
if(set>0){
EXPECT_TRUE(used);
}
if(!used){
EXPECT_TRUE(set==0);
}else{
bool found=false;
for (int k = 0; k < no_keys; ++k)
{
if(keys[k]==set){
found=true;
}
}
EXPECT_TRUE(found);
}
}
}
} |
0d80dcb1e13c68e4d937f61dd6f000291c127684 | 7118b25865c8722f1882b19d3ac2661a7314bda9 | /runtime_lib_builder/build_lib_wrapper.cpp | 2a077323f5dbb98ba05b1d75fdedd4f09bd4e26d | [
"LLVM-exception",
"Apache-2.0"
] | permissive | sillycross/PochiVM | 8e6fb2130502a4be38d87ccccf926ae8b3a8e04c | 2e99da4cbd9b072726ab186f4171866aeef41b88 | refs/heads/master | 2023-07-23T12:41:05.110850 | 2021-09-09T02:35:23 | 2021-09-09T02:54:46 | 262,000,073 | 71 | 7 | null | 2021-07-13T07:47:31 | 2020-05-07T08:57:00 | C++ | UTF-8 | C++ | false | false | 8,479 | cpp | build_lib_wrapper.cpp | #include "check_file_md5.h"
// ****WARNING****
// If you changed this file, make sure you rebuild the whole project from scratch
// (delete 'build' folder and rebuild)
//
int main(int argc, char** argv)
{
using namespace PochiVMHelper;
// Params (in order):
// [dump_symbols]
// [update_symbol_matches]
// [build_runtime_lib]
// [generated_file_dir]
// [tmp_file_dir]
// [llc optimization level]
// [runtime_lib_output]
// [bc_files]
// [pochivm_register_runtime bc file]
//
ReleaseAssert(argc == 10);
std::string dump_symbols = argv[1];
std::string update_symbol_matches = argv[2];
std::string build_runtime_lib = argv[3];
std::string generated_file_dir = argv[4];
std::string tmp_file_dir = argv[5];
std::string llc_opt_level = argv[6];
std::string runtime_lib_output = argv[7];
std::string bcfilesArg = argv[8];
std::string pochivmBcFile = argv[9];
ReleaseAssert(llc_opt_level.length() == 1);
ReleaseAssert('0' <= llc_opt_level[0] && llc_opt_level[0] <= '3');
// the obj files are actually .bc file despite CMake named them .o
//
std::vector<std::string> allBitcodefiles;
{
size_t curPos = 0;
while (true)
{
size_t nextPos = bcfilesArg.find(";", curPos);
if (nextPos == std::string::npos)
{
ReleaseAssert(curPos < bcfilesArg.length());
allBitcodefiles.push_back(bcfilesArg.substr(curPos));
break;
}
ReleaseAssert(curPos < nextPos);
allBitcodefiles.push_back(bcfilesArg.substr(curPos, nextPos - curPos));
curPos = nextPos + 1;
}
}
ReleaseAssert(pochivmBcFile.find(";") == std::string::npos);
allBitcodefiles.push_back(pochivmBcFile);
for (const std::string& bcfile : allBitcodefiles)
{
ReleaseAssert(bcfile.find(" ") == std::string::npos);
ReleaseAssert(bcfile.find("'") == std::string::npos);
ReleaseAssert(bcfile.find("\"") == std::string::npos);
ReleaseAssert(bcfile.find(";") == std::string::npos);
}
std::vector<std::string> allSymfiles;
for (const std::string& bcfile: allBitcodefiles)
{
allSymfiles.push_back(bcfile + ".syms");
}
std::vector<std::string> allRealObjFiles;
for (const std::string& bcfile: allBitcodefiles)
{
allRealObjFiles.push_back(bcfile + ".obj.o");
}
std::string all_needed_symbol_filepath = tmp_file_dir + "/__pochivm_all_needed_symbols__.txt";
// if 'update_symbol_matches' changed, we need to clear all .sym.matches
// For simplicity we just call dump_symbol to do this (it empties the .syms.matches
// file corresponding to the input)
//
bool isUpdateSymbolMatchesChanged = !CheckMd5Match(update_symbol_matches);
bool isDumpSymbolChanged = !CheckMd5Match(dump_symbols);
// for each modified object file, call dump_symbols to update '.sym' and '.sym.matches'
// The order is a bit tricky:
// For dump_symbols, there is a dependency on pochivm_register_runtime.cpp for every other bitcode,
// (to canonicalize the other bitcodes' type names), so we need to process pochivm_register_runtime.cpp first.
// But for update_symbol_matches, pochivm_register_runtime.cpp depends on every other bitcode
// (to get the wrapped functions' implementation), so we need to process pochivm_register_runtime.cpp last.
//
// We pushed pochivmBcFile at the end of allBitcodefiles vector. Here we special-case to process pochivmBcFile first.
//
std::vector<size_t> processOrder;
processOrder.push_back(allBitcodefiles.size() - 1);
for (size_t i = 0; i < allBitcodefiles.size() - 1; i++)
{
processOrder.push_back(i);
}
bool shouldRebuildLibrary = false;
for (size_t i : processOrder)
{
std::string bcfile = allBitcodefiles[i];
std::string symfile = allSymfiles[i];
// important to call CheckMd5Match even if isUpdateSymbolMatchesChanged is true
// since it computes the md5 checksum file
//
bool isUnchanged = CheckMd5Match(bcfile);
// Always clear the .syms.matches file for pochivm_register_runtime.cpp
// The file contains the wrappers for the impl, and if the impl changed,
// the header files need to be regenerated. Of course there are better
// ways so we only re-generate headers for the modified wrappers, but for now go simple
//
bool isPochiVMObj = (i == allBitcodefiles.size() - 1);
if (!isUnchanged || isPochiVMObj || isUpdateSymbolMatchesChanged || isDumpSymbolChanged)
{
std::string cmd;
if (!isPochiVMObj)
{
cmd = dump_symbols + " --dump " + bcfile + " " + symfile + " " + pochivmBcFile;
}
else
{
cmd = dump_symbols + " --dump-list " + bcfile + " " + symfile
+ " " + all_needed_symbol_filepath + " " + generated_file_dir;
}
int r = system(cmd.c_str());
if (r != 0)
{
fprintf(stderr, "Command '%s' failed with return value %d\n", cmd.c_str(), r);
abort();
}
}
// Invoke llc to create the real object file
//
if (!isUnchanged)
{
shouldRebuildLibrary = true;
std::string realObjectFile = allRealObjFiles[i];
std::string cmd;
cmd = "llc -O=" + llc_opt_level + " -filetype=obj " + bcfile + " -o " + realObjectFile;
int r = system(cmd.c_str());
if (r != 0)
{
fprintf(stderr, "Command '%s' failed with return value %d\n", cmd.c_str(), r);
abort();
}
}
if (!isUnchanged)
{
UpdateMd5Checksum(bcfile);
}
}
if (isDumpSymbolChanged)
{
UpdateMd5Checksum(dump_symbols);
}
// call build_runtime_lib to generate the header files
//
{
std::string cmd = build_runtime_lib + " " + update_symbol_matches + " "
+ all_needed_symbol_filepath + " " + generated_file_dir;
for (const std::string& symfile : allSymfiles)
{
cmd += std::string(" ") + symfile;
}
int r = system(cmd.c_str());
if (r != 0)
{
fprintf(stderr, "Command '%s' failed with return value %d\n", cmd.c_str(), r);
abort();
}
}
if (isUpdateSymbolMatchesChanged)
{
UpdateMd5Checksum(update_symbol_matches);
}
if (shouldRebuildLibrary)
{
std::string tmp_file = runtime_lib_output + ".tmp.a";
int r = unlink(tmp_file.c_str());
int err = errno;
ReleaseAssert(r == 0 || r == -1);
if (r == -1)
{
if (err != ENOENT)
{
fprintf(stderr, "Failed to delete file %s, errno = %d (%s)\n",
tmp_file.c_str(), err, strerror(err));
abort();
}
}
{
struct stat st;
ReleaseAssert(stat(tmp_file.c_str(), &st) == -1);
ReleaseAssert(errno == ENOENT);
}
std::string cmd = "ar qc " + tmp_file;
for (const std::string& realObjFile : allRealObjFiles)
{
// make sure file exists
//
{
struct stat st;
if (stat(realObjFile.c_str(), &st) != 0)
{
fprintf(stderr, "Failed to access file '%s', errno = %d (%s)\n",
realObjFile.c_str(), errno, strerror(errno));
abort();
}
}
cmd += std::string(" ") + realObjFile;
}
r = system(cmd.c_str());
if (r != 0)
{
fprintf(stderr, "Command '%s' failed with return value %d\n", cmd.c_str(), r);
abort();
}
r = rename(tmp_file.c_str(), runtime_lib_output.c_str());
ReleaseAssert(r == 0 || r == -1);
if (r == -1)
{
fprintf(stderr, "Failed to rename file '%s' into '%s', errno = %d (%s)\n",
tmp_file.c_str(), runtime_lib_output.c_str(), errno, strerror(errno));
abort();
}
}
return 0;
}
|
0f38cdf0b374fe3ff7fa4accc2f4d788df1b09f5 | e90d34392f44b57922b8cf7cb5d931939118b8a6 | /StudentTest/adminctrl.cpp | f0d44df6355a553b5f30a9c274006ab7c81e8f3c | [] | no_license | YingkitTse/qualityAssessment | 2376b8c1c609276b9467eae6c35bfd4bb1a2d684 | ea241d99c9edc9952fb9fdd4cf8095aee1a10243 | refs/heads/master | 2021-01-01T18:55:55.266579 | 2015-01-12T13:28:44 | 2015-01-12T13:28:44 | 27,583,152 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,987 | cpp | adminctrl.cpp | #include "adminctrl.h"
#include "ui_adminctrl.h"
#include "changpwdialog.h"
#include "modassesdialog.h"
#include "syssetdialog.h"
#include "infomoddialog.h"
#include "logindialog.h"
#include "database.h"
static QString xauth;
static QString xid;
static QString xname;
/* 新建全局变量xauth,xid,xname记录由登录窗口传递的用户权限,登录名,姓名的值 */
adminCtrl::adminCtrl(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::adminCtrl)
{
ui->setupUi(this);
connect(ui->action_Exit,SIGNAL(triggered()),this,SLOT(on_exitBtn_clicked()));
connect(ui->action_Log_out,SIGNAL(triggered()),this,SLOT(logout()));
connect(ui->action_About_2,SIGNAL(triggered()),this,SLOT(about()));
}
/* 管理员主窗口的构造函数。
* 此函数在窗口产生时调用。
* 输入参数:QWidget类指针对象”父窗体“
* 继承自:QMainWindow类父窗体,命名空间ui。
* 在构造函数中手动连接:窗口控件的SIGNAL(信号)和目标的SLOT(槽,即相应动作)
*/
void adminCtrl::Authorize(QString id, QString name, QString auth){
xauth = auth;
xid = id;
xname = name;
ui->nameLabel->setText(name);
ui->idLabel->setText(id);
}
/* Authorize函数
* 输入参数:用户名id,姓名name,权限auth
* 把输入参数赋值到全局变量
* 调用此函数时,把窗体中的空间Label调用setText函数设定为指定文字
*/
adminCtrl::~adminCtrl()//析构函数
{
delete ui;
}
void adminCtrl::on_exitBtn_clicked() //退出按钮按下的动作
{
dbase db;//新建dbase类对象db
db.CloseDatabase();//调用db对象的CloseDatabase函数关闭数据库连接
qApp->quit();//告知主程序退出,终止进程。
}
void adminCtrl::on_modpw_clicked()//修改密码按钮的按下的动作
{
changPwDialog *dlg = new changPwDialog(this);//新建changePwDialog类窗口指针对象dlg,父窗体是本窗口(this)
dlg->show();//显示窗口
}
void adminCtrl::on_testBtn_clicked()
{
modAssesDialog *dlg = new modAssesDialog(this);
dlg->show();
}
void adminCtrl::on_infoBtn_clicked()
{
infoModDialog *dlg = new infoModDialog(this);
dlg->show();
}
void adminCtrl::on_sysBtn_clicked()
{
sysSetDialog *dlg = new sysSetDialog(this);
dlg->show();
}
void adminCtrl::logout(){
LoginDialog *dlg = new LoginDialog(0);
dlg->show();
this->~adminCtrl();
}
void adminCtrl::about(){
QMessageBox::about(this,QString::fromUtf8("关于"),
QString::fromUtf8("<h2>大学生综合素质测评系统 V1.0</h2>"
"<p>Copyright © 2014 TSE Studio."
"<p>程序设计人员:(按姓氏拼音排序)"
"<p>毕国康、陈贤权、谢景聪、谢英杰、杨炯建"));
}
/* 使用QMessageBox类弹出about关于对话框
* 父窗体:this,本窗口
* 标题:关于
*/
|
25c1b35ef09cee70254cc5885dd434ffa1590598 | 850b76b1a01107dca380fe27037475092c21050b | /src/parser/lexer.cc | 8a877103e0fa94cc43324cd19884193335f7f2ac | [
"MIT"
] | permissive | thomcc/ivcalc | 405f71d7d43e57f6d241ea43addb0a77f3f828b1 | 7d5b0caa7e1fa6ab0a5dbf4d1e99823f71cf2d29 | refs/heads/master | 2016-09-10T09:08:08.009726 | 2013-05-21T02:18:46 | 2013-05-21T02:18:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,888 | cc | lexer.cc | #include "parser/lexer.hh"
#include "utilities.hh"
namespace calc {
static inline bool starts_ident(char c) {
if (('a' <= c) && (c <= 'z')) return true;
if (('A' <= c) && (c <= 'Z')) return true;
if ((c == '_') || (c == '$')) return true;
return false;
}
static inline bool is_number(char c) { return ('0' <= c) && (c <= '9'); }
static inline bool is_ident(char c) { return starts_ident(c) || is_number(c); }
static inline bool is_wspace(char c) { return (c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'); }
bool Lexer::finished() const { return _index >= _text.size(); }
Token Lexer::next() {
for (;;) {
if (finished()) return make_token(T_EOF, "");
_start = _index;
char c = forward();
switch (c) {
case ' ': case '\t': case '\r': case '\n':
while (is_wspace(peek())) forward();
break;
case '(': return make_token(T_LPAREN);
case ')': return make_token(T_RPAREN);
case '[': return make_token(T_LBRACKET);
case ']': return make_token(T_RBRACKET);
case '=': return make_token(T_ASSIGN);
case ',': return make_token(T_COMMA);
case '+': return make_token(T_PLUS);
case '-': return make_token(T_MINUS);
// breaks subtraction e.g. 1-2 becomes {lit(1), lit(-2)}
// if (is_number(peek())) return scan_number();
// else return make_token(T_MINUS);
case '*': return make_token(T_ASTERISK);
case '/': return make_token(T_SLASH);
case '^': return make_token(T_CARET);
case '.':
if (is_number(peek())) return scan_number();
return error("Expected digit after decimal.");
default:
if (starts_ident(c)) return scan_ident();
if (is_number(c)) return scan_number();
return error(std::string("Unknown character '")+c+"'");
}
}
}
Token Lexer::scan_ident() {
while (is_ident(peek())) forward();
return make_token(T_NAME);
}
Token Lexer::scan_number() {
while (is_number(peek())) forward();
if (peek() == '.') // read decimal
do forward(); while (is_number(peek()));
if ((peek() == 'e') || (peek() == 'E')) {
// read exponent
forward();
if ((peek() == '+') || (peek() == '-')) // read optional sign
forward();
if (!is_number(peek())) return error("Bad exponent");
while (is_number(peek())) forward();
}
// check that there isn't a suffix on the number
if (is_ident(peek())) return error("Bad number");
return make_token(T_NUMBER);
}
Token Lexer::error(std::string const &message) { return make_token(T_ERROR, message); }
char Lexer::forward() {
char c = peek();
if (!finished()) ++_index;
return c;
}
void Lexer::forward(size_t ahead) { while (ahead--) forward(); }
Token Lexer::make_token(TokenType type) { return make_token(type, _text.substr(_start, _index-_start)); }
Token Lexer::make_token(TokenType t, std::string const &txt) { return Token(t, txt, _start, _index); }
char Lexer::peek(int ahead) {
if (ahead + _index >= _text.size()) return '\0';
return _text[_index + ahead];
}
}
|
c75102d52b025b03f8e82ff5b26266ec2813b648 | 1c731129aabaf6b04fb40a3d3387e7a3f2de1fa4 | /src/objects/quad.cpp | 1ab38c6574e2b230267603d369baf4e950ce6f63 | [] | no_license | grz0zrg/Mammoth3D | 1c757fac253fa402d9f57d4d488ffaacfa1daa88 | 3a5d952c866c09b4c5dc42b41f240ce0186f6d31 | refs/heads/master | 2021-01-10T20:00:48.396852 | 2015-08-22T21:55:37 | 2015-08-22T21:55:37 | 5,990,394 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21 | cpp | quad.cpp | #include "quad.hpp"
|
faac1982f39416dc50269a656b79eab95c82b3d2 | f0749232d54f17e3c321b0b90daaeb23b9faec82 | /Online Judge Code/codeforces/Codeforces Round #397/E.cpp | b6be03b1858e138dcf1f3d7c0f7152a5c9040a3b | [] | no_license | tmuttaqueen/MyCodes | c9024a5b901e68e7c7466885eddbfcd31a5c9780 | 80ec40b26649029ad546ce8ce5bfec0b314b1f61 | refs/heads/master | 2020-04-18T22:20:51.845309 | 2019-05-16T18:11:02 | 2019-05-16T18:11:02 | 167,791,029 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,615 | cpp | E.cpp | #include <bits/stdc++.h>
using namespace std;
const double pi = 3.141592653589793;
#define xx first
#define yy second
#define mp make_pair
#define intl long long
#define filein freopen("input.txt", "r", stdin)
#define fileout freopen("output.txt", "w", stdout)
#define debug printf("yes\n")
#define val_of(x) cout << #x << " is " << x << " "
#define what_is(x) cout << #x << " is " << x << endl
#define pb push_back
#define eb emplace_back
#define pii pair<int, int>
#define piii pair<pii, int>
#define double long double
int n;
vector<int>edge[200005];
int val[200005];
int vis[200005];
int one[200005];
vector<int>ver;
int len[200005];
void dfs( int u )
{
vis[u] = 1;
if( edge[u].size() == 1 && u != 1 )
{
len[u] = 0;
val[u] = 1;
return;
}
int x;
for( int i = 0; i < edge[u].size(); i++ )
{
int v = edge[u][i];
if( vis[v] == 0 )
{
dfs(v);
if( val[v] == 1 )
{
if( val[u] == 0 )
x = v;
val[u]++;
}
if( i == edge[u].size() - 1 && val[u] == 1 )
{
len[u] = len[x] + 1;
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
filein;
cin >> n;
for( int i = 1; i< n; i++ )
{
int a, b;
cin >> a >> b;
edge[a].pb(b);
edge[b].pb(a);
}
dfs(1);
int ans = 1e9;
//debug;
for( int i = 1; i<= n; i++ )
{
map<int, int>mm;
for( int j = 0; j < edge[i].size(); j++ )
{
if( val[edge[i][j]] == 1 )
{
one[i]++;
mm[len[ edge[i][j] ]]++;
}
}
if( one[i] == edge[i].size() && mm.size() == 2 )
{
cout << i << endl;
pii a = *(mm.begin());
mm.erase( mm.begin() );
pii b = *(mm.begin());
int x = -1;
if( a.yy == 1 && b.yy == 1)
x = a.xx + b.xx + 2;
else if( a.yy == edge[i].size() - 1 )
{
x = a.xx + b.xx + 2;
}
else if( b.yy == edge[i].size() - 1 )
{
x = a.xx + b.xx + 2;
}
if( x != -1 )
{
ans = min(ans, x);
}
}
mm.clear();
}
if( ans == (1e9) )
{
cout << -1 << endl;
}
else
cout << ans << endl;
return 0;
}
|
380ee175fcfd27b8ccab9d79d8d49a0faa54773d | b083751c6f8edd18ca8349c328be1d5b75cd7fe2 | /common_widgets/common_widgets.cpp | a6a80bb8c8c834f1ca09d2f1e03ebc6344e7b628 | [
"Apache-2.0"
] | permissive | sxlfhmsl/background_management_system | 5d2bf88d2527477f2c07ac1353c4c798f484516f | 5936dabb47b59a893df2923950c659c2242f22c2 | refs/heads/master | 2022-07-15T11:54:34.409365 | 2020-05-12T16:01:38 | 2020-05-12T16:01:38 | 263,263,295 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 66 | cpp | common_widgets.cpp | #include "common_widgets.h"
Common_widgets::Common_widgets()
{
}
|
a8a819284a424c7477e0c9ab0a615c4c0a1490b5 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/printscan/print/drivers/usermode/tools/uni/minidev.new/gtt.h | e05447505dd17061e5130f62d5852094fdf9be19 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 13,349 | h | gtt.h | /******************************************************************************
Header File: Glyph Translation.H
These classes define the mapping used from a Unicode or ANSI character to a
character sequence to render said character on a printer. They are content
equivalent to the CTT, RLE and GTT formats used in the various flavors of the
mini-driver architecture.
Copyright (c) 1997 by Microsoft Corporation. All Rights Reserved.
A Pretty Penny Enterprises Production
Change History:
02-13-97 Bob_Kjelgaard@Prodigy.Net Created it
******************************************************************************/
#if !defined(GLYPH_TRANSLATION)
#define GLYPH_TRANSLATION
#if defined(LONG_NAMES)
#include "Project Node.H"
#else
#include "ProjNode.H"
#endif
// Win16 CTT formats- since these can't change, I've recoded them to suit.
// Good thing, too- the mapping of direct was bogus- the union implies a word
// aligned structure, but the fact is that direct data is byte-aligned.
class CInvocation : public CObject {
CByteArray m_cbaEncoding;
DWORD m_dwOffset;
DECLARE_SERIAL(CInvocation)
void Encode(BYTE c, CString& cs) const;
public:
CInvocation() {}
void Init(PBYTE pb, unsigned ucb);
unsigned Length() const { return (int)m_cbaEncoding.GetSize(); }
const unsigned Size() const { return 2 * sizeof m_dwOffset; }
void GetInvocation(CString& csReturn) const;
BYTE operator[](unsigned u) const {
return u < Length() ? m_cbaEncoding[u] : 0;
}
CInvocation& operator =(CInvocation& ciRef) {
m_cbaEncoding.Copy(ciRef.m_cbaEncoding);
return *this;
}
void SetInvocation(LPCTSTR lpstrNew);
void NoteOffset(DWORD& dwOffset);
void WriteSelf(CFile& cfTarget) const;
void WriteEncoding(CFile& cfTarget, BOOL bWriteLength = FALSE) const;
virtual void Serialize(CArchive& car);
};
// The following class handles glyph handles and all associated details
class CGlyphHandle : public CObject {
CInvocation m_ciEncoding;
DWORD m_dwCodePage, m_dwidCodePage, m_dwOffset;
WORD m_wIndex;
WORD m_wCodePoint; // Unicode Representation of the glyph
WORD m_wPredefined;
public:
CGlyphHandle() ;
// Atributes
const unsigned RLESize() const { return sizeof m_dwCodePage; }
unsigned CodePage() const { return m_dwidCodePage; } // Only ID matters
WORD CodePoint() const { return m_wCodePoint; }
unsigned CompactSize() const;
unsigned MaximumSize() const {
return CompactSize() ?
sizeof m_wIndex + ((CompactSize() + 1) & ~1) : 0;
}
void GetEncoding(CString& csWhere) {
m_ciEncoding.GetInvocation(csWhere);
}
enum {Modified, Added, Removed};
WORD Predefined() const { return m_wPredefined; }
BOOL operator ==(CGlyphHandle& cghRef);
BOOL PairedRelevant() const { return m_ciEncoding.Length() == 2; }
// Operations
void Init(BYTE b, WORD wIndex, WORD wCode);
void Init(BYTE ab[2], WORD wIndex, WORD wCode);
void Init(PBYTE pb, unsigned ucb, WORD wIndex, WORD wCode);
CGlyphHandle& operator =(CGlyphHandle& cghTemplate);
void RLEOffset(DWORD& dwOffset, const BOOL bCompact);
void GTTOffset(DWORD& dwOffset, BOOL bPaired);
void SetCodePage(DWORD dwidPage, DWORD dwNewPage) {
m_dwCodePage = dwNewPage;
m_dwidCodePage = dwidPage;
}
void NewEncoding(LPCTSTR lpstrNew) {
m_ciEncoding.SetInvocation(lpstrNew);
}
void SetPredefined(WORD wNew) { m_wPredefined = wNew; }
// These write our contents for mini-driver files- they will throw
// exceptions on failure, so use an exception handler to handle errors
void WriteRLE(CFile& cfTarget, WORD wFormat) const;
void WriteGTT(CFile& cfTarget, BOOL bPredefined) const;
enum {GTT, RLEBig, RLESmall}; // Desired encoding format
void WriteEncoding(CFile& cfTarget, WORD wfHow) const;
};
// The next class maintains a record of the runs in the glyph set. It
// generates and merges instances of itself as glyphs are added to the map.
class CRunRecord {
WORD m_wFirst, m_wcGlyphs;
DWORD m_dwOffset; // These are the image...
CRunRecord *m_pcrrNext, *m_pcrrPrevious;
CPtrArray m_cpaGlyphs;
CRunRecord(CGlyphHandle *pcgh, CRunRecord* pcrrPrevious);
CRunRecord(CRunRecord* crrPrevious, WORD wWhere);
CRunRecord(CRunRecord* pcrrPrevious);
CGlyphHandle& Glyph(unsigned u) {
return *(CGlyphHandle *) m_cpaGlyphs[u];
}
const CGlyphHandle& GlyphData(unsigned u) const {
return *(CGlyphHandle *) m_cpaGlyphs[u];
}
public:
CRunRecord();
~CRunRecord();
unsigned Glyphs() const { return m_wcGlyphs; }
unsigned TotalGlyphs() const;
BOOL MustCompose() const;
unsigned RunCount() const {
return 1 + (m_pcrrNext ? m_pcrrNext -> RunCount() : 0);
}
WORD First() const { return m_wFirst; }
WORD Last() const {
return m_pcrrNext ? m_pcrrNext ->Last() : -1 + m_wFirst + m_wcGlyphs;
}
unsigned ExtraNeeded(BOOL bCompact = TRUE);
const unsigned Size(BOOL bRLE = TRUE) const {
return sizeof m_dwOffset << (unsigned) (!!bRLE);
}
void Collect(CPtrArray& cpaGlyphs) const {
cpaGlyphs.Append(m_cpaGlyphs);
if (m_pcrrNext) m_pcrrNext -> Collect(cpaGlyphs);
}
CGlyphHandle* GetGlyph(unsigned u ) const;
#if defined(_DEBUG) // While the linkage code seems to check out, keep this
// around in case of later problems
BOOL ChainIntact() {
_ASSERTE(m_wcGlyphs == m_cpaGlyphs.GetSize());
for (unsigned u = 0; u < Glyphs(); u++) {
_ASSERTE(Glyph(u).CodePoint() == m_wFirst + u);
}
return !m_pcrrNext || m_pcrrNext -> m_pcrrPrevious == this &&
m_pcrrNext -> ChainIntact();
}
#endif
// Operations
void Add(CGlyphHandle *pcgh);
void Delete(WORD wCodePoint);
void Empty();
void NoteOffset(DWORD& dwOffset, BOOL bRLE, BOOL bPaired);
void NoteExtraOffset(DWORD& dwOffset, const BOOL bCompact);
// File output operations
void WriteSelf(CFile& cfTarget, BOOL bRLE = TRUE) const;
void WriteHandles(CFile& cfTarget, WORD wFormat) const;
void WriteMapTable(CFile& cfTarget, BOOL bPredefined) const;
void WriteEncodings(CFile& cfTarget, WORD wfHow) const;
};
class CCodePageData : public CObject {
DWORD m_dwid;
CInvocation m_ciSelect, m_ciDeselect;
public:
CCodePageData() { m_dwid = 0; }
CCodePageData(DWORD dwid) { m_dwid = dwid; }
// Attributes
DWORD Page() const { return m_dwid; }
void Invocation(CString& csReturn, BOOL bSelect) const;
const unsigned Size() const {
return sizeof m_dwid + 2 * m_ciSelect.Size();
}
BOOL NoInvocation() const {
return !m_ciSelect.Length() && !m_ciDeselect.Length();
}
// Operations
void SetPage(DWORD dwNewPage) { m_dwid = dwNewPage; }
void SetInvocation(LPCTSTR lpstrInvoke, BOOL bSelect);
void SetInvocation(PBYTE pb, unsigned ucb, BOOL bSelect);
void NoteOffsets(DWORD& dwOffset);
void WriteSelf(CFile& cfTarget);
void WriteInvocation(CFile& cfTarget);
};
// This class is the generic class encompassing all glyph translation
// information. We can use it to output any of the other forms.
class CGlyphMap : public CProjectNode {
CSafeMapWordToOb m_csmw2oEncodings; // All of the defined encodings
CRunRecord m_crr;
long m_lidPredefined;
BOOL m_bPaired; // Use paired encoding...
CSafeObArray m_csoaCodePage; // Code page(s) in this map
// Framework support (workspace)
CString m_csSource; // Source CTT File name
// Predefined GTT support- must be in this DLL
static CSafeMapWordToOb m_csmw2oPredefined; // Cache loaded PDTs here
void MergePredefined(); // Use definitions to build "true" GTT
void UnmergePredefined(BOOL bTrackRemovals);
void GenerateRuns();
CCodePageData& CodePage(unsigned u) const {
return *(CCodePageData *) m_csoaCodePage[u];
}
DECLARE_SERIAL(CGlyphMap)
public:
bool ChngedCodePt() { return m_bChngCodePt ; } ;
void SetCodePt( bool b) { m_bChngCodePt = b ; }
// These variables hold parameters for PGetDefaultGlyphset().
WORD m_wFirstChar, m_wLastChar ;
// True iff GTT data should be loaded from resources or built.
bool m_bResBldGTT ;
CTime m_ctSaveTimeStamp ; // The last time this GTT was saved
// Predefined IDs, and a static function for retrieving predefined maps
enum {Wansung = -18, ShiftJIS, GB2312, Big5ToTCA, Big5ToNSA86, JISNoANK,
JIS, KoreanISC, Big5, CodePage863 = -3, CodePage850, CodePage437,
DefaultPage, NoPredefined = 0xFFFF};
static CGlyphMap* Public(WORD wID, WORD wCP = 0, DWORD dwDefCP = 0,
WORD wFirst = 0, WORD wLast = 255) ;
CGlyphMap();
// Attributes
unsigned CodePages() const { return m_csoaCodePage.GetSize(); }
DWORD DefaultCodePage() const { return CodePage(0).Page(); }
unsigned Glyphs() const {
return m_csmw2oEncodings.GetCount();
}
void CodePages(CDWordArray& cdaReturn) const;
unsigned PageID(unsigned u) const { return CodePage(u).Page(); }
long PredefinedID() const { return m_lidPredefined; }
CString PageName(unsigned u) const;
void Invocation(unsigned u, CString& csReturn, BOOL bSelect) const;
void UndefinedPoints(CMapWordToDWord& cmw2dCollector) const;
BOOL OverStrike() const { return m_bPaired; }
const CString& SourceName() { return m_csSource; }
// Operations- Framework support
void SetSourceName(LPCTSTR lpstrNew);
void Load(CByteArray& cbaMap) ; // Load GTT image
//void Load(CByteArray& cbaMap) const; // Load GTT image
// Operations- editor support
void AddPoints(CMapWordToDWord& cmw2dNew); // Add points and pages
void DeleteGlyph(WORD wGlyph);
BOOL RemovePage(unsigned uPage, unsigned uMapTo, bool bDelete = FALSE); // 118880
void SetDefaultCodePage(unsigned u) { CodePage(0).SetPage(u); }
void ChangeCodePage(CPtrArray& cpaGlyphs, DWORD dwidNewPage);
void AddCodePage(DWORD dwidNewPage);
void UsePredefined(long lidPredefined);
void SetInvocation(unsigned u, LPCTSTR lpstrInvoke, BOOL bSelect);
void ChangeEncoding(WORD wCodePoint, LPCTSTR lpstrInvoke);
void OverStrike(BOOL bOn) { m_bPaired = bOn; Changed();}
int ConvertCTT();
BOOL Load(LPCTSTR lpstrName = NULL);
BOOL RLE(CFile& cfTarget);
CGlyphHandle* Glyph(unsigned u);
// Font editor support operations
void Collect(CPtrArray& cpaGlyphs) { // Collect all glyph handles
cpaGlyphs.RemoveAll();
m_crr.Collect(cpaGlyphs);
}
virtual CMDIChildWnd* CreateEditor();
virtual BOOL Generate(CFile& cfGTT);
BOOL SetFileName(LPCTSTR lpstrNew) ;
virtual void Serialize(CArchive& car);
private:
bool m_bChngCodePt;
};
/////////////////////////////////////////////////////////////////////////////
// CGlyphMapContainer document
class CGlyphMapContainer : public CDocument {
CGlyphMap *m_pcgm;
BOOL m_bEmbedded; // From driver, or not?
BOOL m_bSaveSuccessful; // TRUE iff a successful save was performed
protected:
CGlyphMapContainer(); // protected constructor used by dynamic creation
DECLARE_DYNCREATE(CGlyphMapContainer)
// Attributes
public:
CGlyphMap* GlyphMap() { return m_pcgm; }
// Operations
public:
// Constructor- used to create from driver info editor
CGlyphMapContainer(CGlyphMap *pcgm, CString csPath);
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CGlyphMapContainer)
public:
virtual void Serialize(CArchive& ar); // overridden for document i/o
virtual BOOL OnSaveDocument(LPCTSTR lpszPathName);
virtual BOOL OnOpenDocument(LPCTSTR lpszPathName);
protected:
virtual BOOL OnNewDocument();
virtual BOOL SaveModified();
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CGlyphMapContainer();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
protected:
//{{AFX_MSG(CGlyphMapContainer)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#endif
|
ded049c47d02dc0e5dbdec911b4792f657f9e192 | 4f7c53c128328f294e9b67a4eb00b72c459692e6 | /app/Main/MainTabSaleItemController.cpp | 7a52028361e1f15b15bf5625f1aee9079d2e8af5 | [] | no_license | milczarekIT/agila | a94d59c1acfe171eb361be67acda1c5babc69df6 | ec0ddf53dfa54aaa21d48b5e7f334aabcba5227e | refs/heads/master | 2021-01-10T06:39:56.117202 | 2013-08-24T20:15:22 | 2013-08-24T20:15:22 | 46,000,158 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,073 | cpp | MainTabSaleItemController.cpp | #include "MainTabSaleItemController.h"
MainTabSaleItemController::MainTabSaleItemController()
{
view = new MainTabSaleItem(this);
invoiceService = new InvoiceService();
fkService = new DocumentFKService();
zalService = new DocumentZALService();
initModel();
initFilters();
initSelectingColumnVisibility();
restoreTableState();
}
MainTabSaleItemController::~MainTabSaleItemController()
{
saveTableState();
delete invoiceService;
delete fkService;
}
void MainTabSaleItemController::addDocument(const int index)
{
switch(index)
{
case 0:{
dialogInvoiceAdd();break;
}
case 1:{
dialogDocumentFKAdd();break;
}
case 2:{
dialogDocumentFMPAdd();break;
}
case 3:{
dialogDocumentPROAdd();break;
}
case 4:{
dialogDocumentFMAdd();break;
}
case 5:{
dialogDocumentPIAdd();break;
}
case 6:{
dialogDocumentPAAdd();break;
}
case 7:{
dialogDocumentZALAdd();break;
}
case 8:{
dialogDocumentRZLAdd();break;
}
}
}
MainTabItem *MainTabSaleItemController::getView()
{
return view;
}
void MainTabSaleItemController::dialogInvoiceAdd()
{
InvoiceController dialog(this,"FV",0);
dialog.exec();
documentTVModel->getDocuments();
}
void MainTabSaleItemController::dialogDocumentFMPAdd()
{
InvoiceController dialog(this,"FMP",0);
dialog.exec();
documentTVModel->getDocuments();
}
void MainTabSaleItemController::dialogDocumentPROAdd()
{
InvoiceController dialog(this, "PRO",0);
dialog.exec();
documentTVModel->getDocuments();
}
void MainTabSaleItemController::dialogDocumentPIAdd()
{
InvoiceController dialog(this, "PI",0);
dialog.exec();
documentTVModel->getDocuments();
}
void MainTabSaleItemController::dialogDocumentZALAdd()
{
DocumentZALController dialog(this, "ZAL",0);
dialog.exec();
documentTVModel->getDocuments();
}
void MainTabSaleItemController::dialogDocumentRZLAdd()
{
DocumentZALController dialog(this,"RZL",0);
dialog.exec();
documentTVModel->getDocuments();
}
void MainTabSaleItemController::dialogDocumentPAAdd()
{
DocumentPAController dialog(this,0);
dialog.exec();
documentTVModel->getDocuments();
}
void MainTabSaleItemController::dialogDocumentFKAdd()
{
DocumentFKController dialog(this,0);
dialog.exec();
documentTVModel->getDocuments();
}
void MainTabSaleItemController::dialogDocumentFMAdd()
{
DocumentFMController dialog(this,"FM",0);
dialog.exec();
documentTVModel->getDocuments();
}
void MainTabSaleItemController::issuedFK()
{
DocumentFKController dialog(this,0);
dialog.setFirst(true);
dialog.insertInvoiceData(invoiceService->getInvoice(view->getTableView()->getSymbol()));
dialog.exec();
documentTVModel->getDocuments();
}
void MainTabSaleItemController::issuedKP()
{
CashDocumentController dialog("KP",false,this);
dialog.insertInvoiceData(invoiceService->getInvoice(view->getTableView()->getSymbol()));
dialog.exec();
emit issuedCashDoc();
}
void MainTabSaleItemController::issuedKW()
{
CashDocumentController dialog("KW",false,this);
dialog.insertInvoiceData(invoiceService->getInvoice(view->getTableView()->getSymbol()));
dialog.exec();
emit issuedCashDoc();
}
void MainTabSaleItemController::printDocument()
{
PrintSaleDocumentController *pc = new PrintSaleDocumentController(view->getTableView()->getSymbol());
if(view->getTableView()->getSymbol() == "")
{
MessageBox *messageBox = new MessageBox();
messageBox->createInfoBox("Zaznacz dokument do druku");
delete messageBox;
}
else if(view->getTableView()->getSymbol().contains("FK"))
{
DocumentFK doc = fkService->getDocumentFK(view->getTableView()->getSymbol());
pc->print(&doc);
}
else
{
DocumentZAL docZal;
docZal= zalService->getDocumentZAL(view->getTableView()->getSymbol());
if(docZal.getDocumentType().contains("RZL")||docZal.getDocumentType().contains("ZAL"))
{
pc->print(&docZal);
}
else
{
Invoice doc = invoiceService->getInvoice(view->getTableView()->getSymbol());
pc->print(&doc);
}
}
delete pc;
}
void MainTabSaleItemController::changeDisabledMenuActions()
{
if(!(view->getTableView()->getSymbol().contains("FV")||view->getTableView()->getSymbol().contains("FMP")||view->getTableView()->getSymbol().contains("PRO")))
view->getTableView()->getExtendedMenu()->getMenuSale()->getActionIssuedFK()->setDisabled(true);
else
view->getTableView()->getExtendedMenu()->getMenuSale()->getActionIssuedFK()->setDisabled(false);
if(ApplicationManager::getInstance()->containsModule(ModuleManager::Cash))
{
if(checkAmount()>0 ||view->getTableView()->getSymbol().contains("FV"))
{
view->getTableView()->getExtendedMenu()->getMenuSale()->getActionIssuedCashDocKW()->setDisabled(true);
view->getTableView()->getExtendedMenu()->getMenuSale()->getActionIssuedCashDocKP()->setDisabled(false);
}
else if(checkAmount()<0)
{
view->getTableView()->getExtendedMenu()->getMenuSale()->getActionIssuedCashDocKW()->setDisabled(false);
view->getTableView()->getExtendedMenu()->getMenuSale()->getActionIssuedCashDocKP()->setDisabled(true);
}
else if(checkAmount()==0)
{
view->getTableView()->getExtendedMenu()->getMenuSale()->getActionIssuedCashDocKW()->setDisabled(true);
view->getTableView()->getExtendedMenu()->getMenuSale()->getActionIssuedCashDocKP()->setDisabled(true);
}
}
}
float MainTabSaleItemController::checkAmount()
{
float amount = fkService->getDocumentFK(view->getTableView()->getSymbol()).getTotal()-
fkService->getDocumentFK(view->getTableView()->getSymbol()).getInvoice().getTotal();
return amount;
}
void MainTabSaleItemController::dialogDocumentEdit()
{
if(view->getTableView()->getSymbol() == "")
{
MessageBox *messageBox = new MessageBox();
messageBox->createInfoBox("Zaznacz dokument do edycji");
delete messageBox;
}
else if (view->getTableView()->getSymbol().contains("PA"))
{
DocumentPAController dialog(this,1);
dialog.exec(view->getTableView()->getSymbol());
documentTVModel->getDocuments();
}
else if (view->getTableView()->getSymbol().contains("FK"))
{
DocumentFKController dialog(this,1);
dialog.exec(view->getTableView()->getSymbol());
documentTVModel->getDocuments();
}
else if (view->getTableView()->getSymbol().section("/",0,0)=="FM")
{
DocumentFMController dialog(this,"FM",1);
dialog.exec(view->getTableView()->getSymbol());
documentTVModel->getDocuments();
}
else if (view->getTableView()->getSymbol().contains("FV")||view->getTableView()->getSymbol().contains("FMP")
||view->getTableView()->getSymbol().contains("PRO")||view->getTableView()->getSymbol().contains("PI"))
{
DocumentZAL doc;
doc= zalService->getDocumentZAL(view->getTableView()->getSymbol());
if(doc.getDocumentType().contains("RZL")||doc.getDocumentType().contains("ZAL"))
{ DocumentZALController*dialog;
if(doc.getDocumentType().contains("RZL"))
dialog = new DocumentZALController(this,"RZL",1);
else
dialog = new DocumentZALController(this,"ZAL",1);
dialog->exec(view->getTableView()->getSymbol());
documentTVModel->getDocuments();
delete dialog;
}
else
{
InvoiceController dialog(this,view->getTableView()->getSymbol().section("/",0,0),1);
dialog.exec(view->getTableView()->getSymbol());
documentTVModel->getDocuments();
}
}
}
void MainTabSaleItemController::removeDocument()
{
MessageBox *msgBox = new MessageBox();
bool storeUpdate = false;
if(view->getTableView()->getId()==-1)
{
msgBox->createInfoBox("Zaznacz dokument do usunięcia");
}
if(view->getTableView()->getSymbol().contains("FV")||view->getTableView()->getSymbol().contains("FMP")||view->getTableView()->getSymbol().contains("PRO")
||view->getTableView()->getSymbol().contains("PI")||view->getTableView()->getSymbol().contains("PA")||view->getTableView()->getSymbol().section("/",0,0)=="FM")
{
if(msgBox->createQuestionBox("Usuwanie dokumentu " +view->getTableView()->getSymbol())== MessageBox::YES)
{
if(invoiceService->getInvoice(view->getTableView()->getSymbol()).getStoreResult())
{
if(msgBox->createQuestionBox("Usunięto dokument "+view->getTableView()->getSymbol(),"Cofnąć skutek magazynowy?")==MessageBox::YES)
storeUpdate=true;
}
invoiceService->removeInvoice(view->getTableView()->getSymbol(),storeUpdate);
}
}
if(view->getTableView()->getSymbol().contains("FK"))
{
if( msgBox->createQuestionBox("Usuwanie dokumentu " +view->getTableView()->getSymbol())== MessageBox::YES)
{
if(fkService->getDocumentFK(view->getTableView()->getSymbol()).getStoreResult())
{
if(msgBox->createQuestionBox("Usunięto dokument "+view->getTableView()->getSymbol(),"Cofnąć skutek magazynowy?")==MessageBox::YES)
storeUpdate=true;
}
fkService->removeDocumentFK(view->getTableView()->getSymbol(),storeUpdate);
}
}
delete msgBox;
documentTVModel->getDocuments();
}
void MainTabSaleItemController::initModel()
{
documentTVModel = new SaleDocumentTVModel();
documentTVModel->getDocuments();
view->getTableView()->setSaleDocumentModel(documentTVModel);
}
void MainTabSaleItemController::initFilters()
{
documentTVModel->setFromDateFilter(view->getFilterWidget()->getFromDate());
documentTVModel->setToDateFilter(view->getFilterWidget()->getToDate());
documentTVModel->getDocuments();
}
void MainTabSaleItemController::restoreTableState() {
QByteArray state = tableStateManager->getState("MAIN_TAB_SALE");
view->getTableView()->horizontalHeader()->restoreState(state);
view->getTableView()->hideIdColumn(); // ukrywa id
view->getTableView()->horizontalHeader()->setSortIndicatorShown(true); // pokazuje sortindicator
int columnAtTable = view->getTableView()->horizontalHeader()->sortIndicatorSection();
documentTVModel->sortByColumn(columnAtTable, view->getTableView()->horizontalHeader()->sortIndicatorOrder());
documentTVModel->getDocuments();
}
void MainTabSaleItemController::saveTableState() {
QByteArray state = view->getTableView()->horizontalHeader()->saveState();
QByteArray oldState = tableStateManager->getState("MAIN_TAB_SALE");
if(state != oldState)
tableStateManager->saveState("MAIN_TAB_SALE", state);
}
void MainTabSaleItemController::changeColumnVisiblity(QList<int> visibleColumns)
{
for(int column = 0; column < view->getTableView()->model()->columnCount(); column++) {
if(visibleColumns.contains(column))
view->getTableView()->setColumnHidden(column, false);
else
view->getTableView()->setColumnHidden(column, true);
}
}
void MainTabSaleItemController::initSelectingColumnVisibility()
{
selectColumnsDialog = new SelectVisibleColumns(view->getTableView(), this);
connect(selectColumnsDialog, SIGNAL(selectedColumnsChanged(QList<int>)), this, SLOT(changeColumnVisiblity(QList<int>)));
}
void MainTabSaleItemController::sortByColumn(int column)
{
documentTVModel->sortByColumn(column, view->getTableView()->horizontalHeader()->sortIndicatorOrder());
}
ModuleManager::Module MainTabSaleItemController::module()
{
return ModuleManager::Sale;
}
|
d7d84ea53f403050d72b1cccdd22294aaa50d723 | f7a34c7cc3534cd49d4505198c294b607949a26c | /src/AppInstallerRepositoryCore/SQLiteWrapper.h | 3a5913ce95ca8fed57122ca1dc107bf98cfcd411 | [
"LicenseRef-scancode-generic-cla",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LGPL-2.1-or-later",
"MIT",
"BSD-3-Clause"
] | permissive | microsoft/winget-cli | 4176b886b257ec562cf6d8a74a9b4410693f9627 | f7c1a4499af38608f378a30f0a3e2417ec595529 | refs/heads/master | 2023-09-06T10:45:08.034474 | 2023-09-05T23:26:37 | 2023-09-05T23:26:37 | 197,275,130 | 22,630 | 1,570 | MIT | 2023-09-14T21:29:31 | 2019-07-16T22:16:49 | C++ | UTF-8 | C++ | false | false | 11,782 | h | SQLiteWrapper.h | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include <wil/result_macros.h>
#include <wil/resource.h>
#include <winsqlite/winsqlite3.h>
#include <AppInstallerLogging.h>
#include <AppInstallerLanguageUtilities.h>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#define SQLITE_MEMORY_DB_CONNECTION_TARGET ":memory:"
using namespace std::string_view_literals;
namespace AppInstaller::Repository::SQLite
{
// The name of the rowid column in SQLite.
extern std::string_view RowIDName;
// The type of a rowid column in code.
using rowid_t = int64_t;
// The type to use for blob data.
using blob_t = std::vector<uint8_t>;
namespace details
{
template<typename>
constexpr bool dependent_false = false;
template <typename T, typename = void>
struct ParameterSpecificsImpl
{
static T& ToLog(T&&)
{
static_assert(dependent_false<T>, "No type specific override has been supplied");
}
static void Bind(sqlite3_stmt*, int, T&&)
{
static_assert(dependent_false<T>, "No type specific override has been supplied");
}
static T GetColumn(sqlite3_stmt*, int)
{
static_assert(dependent_false<T>, "No type specific override has been supplied");
}
};
template <>
struct ParameterSpecificsImpl<nullptr_t>
{
inline static std::string_view ToLog(nullptr_t) { return "null"sv; }
static void Bind(sqlite3_stmt* stmt, int index, nullptr_t);
};
template <>
struct ParameterSpecificsImpl<std::string>
{
inline static const std::string& ToLog(const std::string& v) { return v; }
static void Bind(sqlite3_stmt* stmt, int index, const std::string& v);
static std::string GetColumn(sqlite3_stmt* stmt, int column);
};
template <>
struct ParameterSpecificsImpl<std::string_view>
{
inline static const std::string_view& ToLog(const std::string_view& v) { return v; }
static void Bind(sqlite3_stmt* stmt, int index, std::string_view v);
};
template <>
struct ParameterSpecificsImpl<int>
{
inline static int ToLog(int v) { return v; }
static void Bind(sqlite3_stmt* stmt, int index, int v);
static int GetColumn(sqlite3_stmt* stmt, int column);
};
template <>
struct ParameterSpecificsImpl<int64_t>
{
inline static int64_t ToLog(int64_t v) { return v; }
static void Bind(sqlite3_stmt* stmt, int index, int64_t v);
static int64_t GetColumn(sqlite3_stmt* stmt, int column);
};
template <>
struct ParameterSpecificsImpl<bool>
{
inline static bool ToLog(bool v) { return v; }
static void Bind(sqlite3_stmt* stmt, int index, bool v);
static bool GetColumn(sqlite3_stmt* stmt, int column);
};
template <>
struct ParameterSpecificsImpl<blob_t>
{
static std::string ToLog(const blob_t& v);
static void Bind(sqlite3_stmt* stmt, int index, const blob_t& v);
static blob_t GetColumn(sqlite3_stmt* stmt, int column);
};
template <typename E>
struct ParameterSpecificsImpl<E, typename std::enable_if_t<std::is_enum_v<E>>>
{
static auto ToLog(E v)
{
return ToIntegral(v);
}
static void Bind(sqlite3_stmt* stmt, int index, E v)
{
ParameterSpecificsImpl<std::underlying_type_t<E>>::Bind(stmt, index, ToIntegral(v));
}
static E GetColumn(sqlite3_stmt* stmt, int column)
{
return ToEnum<E>(ParameterSpecificsImpl<std::underlying_type_t<E>>::GetColumn(stmt, column));
}
};
template <typename T>
using ParameterSpecifics = ParameterSpecificsImpl<std::decay_t<T>>;
}
// A SQLite exception.
struct SQLiteException : public wil::ResultException
{
SQLiteException(int error) : wil::ResultException(MAKE_HRESULT(SEVERITY_ERROR, FACILITY_SQLITE, error)) {}
};
// The connection to a database.
struct Connection
{
// The disposition for opening a database connection.
enum class OpenDisposition : int
{
// Open existing database for reading.
ReadOnly = SQLITE_OPEN_READONLY,
// Open existing database for reading and writing.
ReadWrite = SQLITE_OPEN_READWRITE,
// Create new database for reading and writing.
Create = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
};
// Flags for opening a database connection.
enum class OpenFlags : int
{
// No flags specified.
None = 0,
// Indicate that the target can be a URI.
Uri = SQLITE_OPEN_URI,
};
static Connection Create(const std::string& target, OpenDisposition disposition, OpenFlags flags = OpenFlags::None);
Connection() = default;
Connection(const Connection&) = delete;
Connection& operator=(const Connection&) = delete;
Connection(Connection&& other) = default;
Connection& operator=(Connection&& other) = default;
~Connection() = default;
// Enables the ICU integrations on this connection.
void EnableICU();
// Gets the last inserted rowid to the database.
rowid_t GetLastInsertRowID();
// Gets the count of changed rows for the last executed statement.
int GetChanges() const;
//. Gets the (fixed but arbitrary) identifier for this connection.
size_t GetID() const;
operator sqlite3* () const { return m_dbconn.get(); }
private:
Connection(const std::string& target, OpenDisposition disposition, OpenFlags flags);
size_t m_id = 0;
wil::unique_any<sqlite3*, decltype(sqlite3_close_v2), sqlite3_close_v2> m_dbconn;
};
// A SQL statement.
struct Statement
{
static Statement Create(const Connection& connection, const std::string& sql);
static Statement Create(const Connection& connection, std::string_view sql);
static Statement Create(const Connection& connection, char const* const sql);
Statement() = default;
Statement(const Statement&) = delete;
Statement& operator=(const Statement&) = delete;
Statement(Statement&& other) = default;
Statement& operator=(Statement&& other) = default;
operator sqlite3_stmt* () const { return m_stmt.get(); }
// The state of the statement.
enum class State
{
// The statement has been prepared, but not evaluated.
Prepared = 0,
// The statement has a row available for reading.
HasRow = 1,
// The statement has been completed.
Completed = 2,
// The statement has resulted in an error.
Error = 3,
};
// Gets the current state of the statement.
State GetState() const { return m_state; }
// Bind parameters to the statement.
// The index is 1 based.
template <typename Value>
void Bind(int index, Value&& v)
{
AICLI_LOG(SQL, Verbose, << "Binding statement #" << m_connectionId << '-' << m_id << ": " << index << " => " << details::ParameterSpecifics<Value>::ToLog(std::forward<Value>(v)));
details::ParameterSpecifics<Value>::Bind(m_stmt.get(), index, std::forward<Value>(v));
}
// Evaluate the statement; either retrieving the next row or executing some action.
// Returns true if there is a row of data, or false if there is none.
// This return value is the equivalent of 'GetState() == State::HasRow' after calling Step.
bool Step(bool failFastOnError = false);
// Equivalent to Step, but does not ever expect a result, throwing if one is retrieved.
void Execute(bool failFastOnError = false);
// Gets a boolean value that indicates whether the specified column value is null in the current row.
// The index is 0 based.
bool GetColumnIsNull(int column);
// Gets the value of the specified column from the current row.
// The index is 0 based.
template <typename Value>
Value GetColumn(int column)
{
THROW_HR_IF(E_BOUNDS, m_state != State::HasRow);
return details::ParameterSpecifics<Value>::GetColumn(m_stmt.get(), column);
}
// Gets the entire row of values from the current row.
// The values requested *must* be those available starting from the first column, but trailing columns can be omitted.
template <typename... Values>
std::tuple<Values...> GetRow()
{
return GetRowImpl<Values...>(std::make_integer_sequence<int, sizeof...(Values)>{});
}
// Resets the statement state, allowing it to be evaluated again.
// Note that this does not clear data bindings.
void Reset();
// Determines if the statement owns an underlying object.
operator bool() const { return static_cast<bool>(m_stmt); }
private:
Statement(const Connection& connection, std::string_view sql);
// Helper to receive the integer sequence from the public function.
// This is equivalent to calling:
// for (i = 0 .. count of Values types)
// GetColumn<current Value type>(i)
// Then putting them all into a tuple.
template <typename... Values, int... I>
std::tuple<Values...> GetRowImpl(std::integer_sequence<int, I...>)
{
THROW_HR_IF(E_BOUNDS, m_state != State::HasRow);
return std::make_tuple(details::ParameterSpecifics<Values>::GetColumn(m_stmt.get(), I)...);
}
size_t m_connectionId = 0;
size_t m_id = 0;
wil::unique_any<sqlite3_stmt*, decltype(sqlite3_finalize), sqlite3_finalize> m_stmt;
State m_state = State::Prepared;
};
// A SQLite savepoint.
struct Savepoint
{
// Creates a savepoint, beginning it.
static Savepoint Create(Connection& connection, std::string name);
Savepoint(const Savepoint&) = delete;
Savepoint& operator=(const Savepoint&) = delete;
Savepoint(Savepoint&&) = default;
Savepoint& operator=(Savepoint&&) = default;
~Savepoint();
// Rolls back the Savepoint.
void Rollback();
// Commits the Savepoint.
void Commit();
private:
Savepoint(Connection& connection, std::string&& name);
std::string m_name;
DestructionToken m_inProgress = true;
Statement m_rollbackTo;
Statement m_release;
};
// The escape character used in the EscapeStringForLike function.
extern std::string_view EscapeCharForLike;
// Escapes the given input string for passing to a like operation.
std::string EscapeStringForLike(std::string_view value);
}
|
12913534ee4ce6003f124d4ba4d4367842de46db | eda7f1e5c79682bf55cfa09582a82ce071ee6cee | /aspects/electrical/Batt/test/UtGunnsElectBattery.hh | bf5141bf5ecebf993922de971439dbc65c8c8b5b | [
"LicenseRef-scancode-us-govt-public-domain",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | nasa/gunns | 923f4f7218e2ecd0a18213fe5494c2d79a566bb3 | d5455e3eaa8b50599bdb16e4867a880705298f62 | refs/heads/master | 2023-08-30T06:39:08.984844 | 2023-07-27T12:18:42 | 2023-07-27T12:18:42 | 235,422,976 | 34 | 11 | NOASSERTION | 2023-08-30T15:11:41 | 2020-01-21T19:21:16 | C++ | UTF-8 | C++ | false | false | 5,958 | hh | UtGunnsElectBattery.hh | #ifndef UtGunnsElectBattery_EXISTS
#define UtGunnsElectBattery_EXISTS
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @defgroup UT_GUNNS_ELECTRICAL_BATTERY_LINK GUNNS Electrical Battery Unit Test
/// @ingroup UT_GUNNS_ELECTRICAL_BATTERY
///
/// @copyright Copyright 2021 United States Government as represented by the Administrator of the
/// National Aeronautics and Space Administration. All Rights Reserved.
///
/// @details Unit Tests for the GUNNS Electrical Battery model.
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestFixture.h>
#include <iostream>
#include "aspects/electrical/Batt/GunnsElectBattery.hh"
#include <string>
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Inherit from GunnsElectBattery and befriend UtGunnsElectBattery.
///
/// @details Class derived from the unit under test. It just has a constructor with the same
/// arguments as the parent and a default destructor, but it befriends the unit test case
/// driver class to allow it access to protected data members.
////////////////////////////////////////////////////////////////////////////////////////////////////
class FriendlyGunnsElectBattery : public GunnsElectBattery
{
public:
FriendlyGunnsElectBattery();
virtual ~FriendlyGunnsElectBattery();
friend class UtGunnsElectBattery;
};
inline FriendlyGunnsElectBattery::FriendlyGunnsElectBattery() : GunnsElectBattery() {};
inline FriendlyGunnsElectBattery::~FriendlyGunnsElectBattery() {}
// Forward class declarations.
class TsLinearInterpolator;
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Battery model unit tests.
////
/// @details This class provides the unit tests for the model within the CPPUnit framework.
////////////////////////////////////////////////////////////////////////////////////////////////////
class UtGunnsElectBattery: public CppUnit::TestFixture
{
public:
UtGunnsElectBattery();
virtual ~UtGunnsElectBattery();
void tearDown();
void setUp();
void testConfig();
void testInput();
void testDefaultConstruction();
void testNominalInitialization();
void testInitializationExceptions();
void testRestart();
void testUpdateStateParallel();
void testUpdateStateSeries();
void testUpdateFlux();
void testThermalRunaway();
void testAccessors();
private:
CPPUNIT_TEST_SUITE(UtGunnsElectBattery);
CPPUNIT_TEST(testConfig);
CPPUNIT_TEST(testInput);
CPPUNIT_TEST(testDefaultConstruction);
CPPUNIT_TEST(testNominalInitialization);
CPPUNIT_TEST(testInitializationExceptions);
CPPUNIT_TEST(testRestart);
CPPUNIT_TEST(testUpdateStateParallel);
CPPUNIT_TEST(testUpdateStateSeries);
CPPUNIT_TEST(testUpdateFlux);
CPPUNIT_TEST(testThermalRunaway);
CPPUNIT_TEST(testAccessors);
CPPUNIT_TEST_SUITE_END();
enum {N_NODES = 2};
GunnsElectBatteryConfigData* tConfigData; /**< (--) Pointer to nominal config data. */
GunnsElectBatteryInputData* tInputData; /**< (--) Pointer to nominal input data. */
FriendlyGunnsElectBattery* tArticle; /**< (--) Pointer to test article. */
std::vector<GunnsBasicLink*> tLinks; /**< (--) Links vector. */
std::string tName; /**< (--) Nominal name. */
GunnsBasicNode tNodes[N_NODES]; /**< (--) Nominal connected nodes. */
GunnsNodeList tNodeList; /**< (--) Network node structure. */
int tPort0; /**< (--) Nominal inlet port index. */
int tPort1; /**< (--) Nominal outlet port index. */
int tNumCells; /**< (--) Nominal config data. */
bool tCellsInParallel; /**< (--) Nominal config data. */
double tCellResistance; /**< (ohm) Nominal config data. */
double tInterconnectResistance; /**< (ohm) Nominal config data. */
double tMaxCapacity; /**< (amp*hr) Nominal config data. */
TsLinearInterpolator* tSocVocTable; /**< (--) Nominal config data. */
bool tMalfBlockageFlag; /**< (--) Nominal input data. */
double tMalfBlockageValue; /**< (--) Nominal input data. */
bool tMalfThermalRunawayFlag; /**< (--) Nominal input data. */
double tMalfThermalRunawayDuration; /**< (s) Nominal input data. */
double tMalfThermalRunawayInterval; /**< (s) Nominal input data. */
double tSoc; /**< (--) Nominal input data. */
static int TEST_ID; /**< (--) Test identification number. */
/// @brief Copy constructor unavailable since declared private and not implemented.
UtGunnsElectBattery(const UtGunnsElectBattery& that);
/// @brief Assignment operator unavailable since declared private and not implemented.
UtGunnsElectBattery& operator =(const UtGunnsElectBattery& that);
};
///@}
#endif
|
db9fe651f55400e190bf40213f32b764f83f29f6 | 22ba04fdf637a2daa7b12ba420996819467270a8 | /Engine/TBSGFramework/src/rendering/dx/DX12Material.cpp | f55f6c45cadc949cf7c9e209c7e1d6638479d8e3 | [] | no_license | jornveen/Reptoads | 6c592b72337153c53b27bc101c150ca37574f13f | a1c04d316a0745140fc74981d0488d6088f17911 | refs/heads/master | 2020-12-28T17:46:32.340045 | 2020-02-05T11:04:23 | 2020-02-05T11:04:23 | 238,426,513 | 0 | 0 | null | 2020-02-05T11:08:51 | 2020-02-05T10:43:42 | JavaScript | UTF-8 | C++ | false | false | 565 | cpp | DX12Material.cpp | #include <rendering/dx/DX12Material.h>
namespace gfx
{
DX12Material::DX12Material(const glm::vec3& /*a_ambient*/, const glm::vec3& /*a_diffuse*/, const glm::vec3& /*a_specular*/,
float /*a_specularPower*/, const char* /*a_id*/)
: m_data(nullptr),
m_hasTexture(false), m_texId{}
{
}
DX12Material::DX12Material(const glm::vec3& /*a_ambient*/, const glm::vec3& /*a_diffuse*/,
const glm::vec3& /*a_specular*/, float /*a_specularPower*/, const char* a_textureId, const char* /*a_id*/)
: m_data(nullptr),
m_hasTexture(true), m_texId(a_textureId)
{
}
} |
cb527f6b929e2996e7b6cd93328ed4eafdd7dd80 | d1ac9e5a19a0e720e2f79d24eb4808a3075e3607 | /include/merge_sort.h | 8a45aece0c17e83770c7003378e246e8c9c555fe | [
"MIT"
] | permissive | Samana/algorithms | db804acdf32e2e9bff2e526792cbbd68b1719dc4 | d81d1a693c6fa1d5fb1ce903b05faf9d7267158d | refs/heads/master | 2021-01-17T11:24:16.190232 | 2014-11-27T03:33:21 | 2014-11-27T03:33:21 | 10,540,035 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,640 | h | merge_sort.h | /*******************************************************************************
* DANIEL'S ALGORITHM IMPLEMENTAIONS
*
* /\ | _ _ ._ o _|_ |_ ._ _ _
* /--\ | (_| (_) | | |_ | | | | | _>
* _|
*
* MERGE SORT
*
* Features:
* This is divide and conquer algorithm. This works as follows.
* (1) Divide the input which we have to sort into two parts in the middle. Call it the left part
* and right part.
* Example: Say the input is -10 32 45 -78 91 1 0 -16 then the left part will be
* -10 32 45 -78 and the right part will be 91 1 0 6.
* (2) Sort Each of them seperately. Note that here sort does not mean to sort it using some other
* method. We already wrote fucntion to sort it. Use the same.
* (3) Then merge the two sorted parts.
*
* ------------
* Worst case performance O(n log n)
* Best case performance
* O(n log n) typical,
* O(n) natural variant
* Average case performance O(n log n)
* Worst case space complexity O(n) auxiliary
* ------------
*
* Merge sort can easily be optmized for parallized computing.
*
* http://en.wikipedia.org/wiki/Merge_sort
*
******************************************************************************/
#ifndef __MERGE_SORT_H__
#define __MERGE_SORT_H__
namespace alg {
/**
* Merge functions merges the two sorted parts. Sorted parts will be from [left, mid] and [mid+1, right].
*/
template<typename T>
static void __merge(T *array, int left, int mid, int right) {
/*We need a Temporary array to store the new sorted part*/
T tempArray[right-left+1];
int pos=0,lpos = left,rpos = mid + 1;
while(lpos <= mid && rpos <= right) {
if(array[lpos] < array[rpos]) {
tempArray[pos++] = array[lpos++];
}
else {
tempArray[pos++] = array[rpos++];
}
}
while(lpos <= mid) tempArray[pos++] = array[lpos++];
while(rpos <= right)tempArray[pos++] = array[rpos++];
int iter;
/* Copy back the sorted array to the original array */
for(iter = 0;iter < pos; iter++) {
array[iter+left] = tempArray[iter];
}
return;
}
/**
* sort an array from left->right
*/
template<typename T>
static void merge_sort(T *array, int left, int right) {
int mid = (left+right)/2;
/* We have to sort only when left<right because when left=right it is anyhow sorted*/
if(left<right) {
/* Sort the left part */
merge_sort(array,left,mid);
/* Sort the right part */
merge_sort(array,mid+1,right);
/* Merge the two sorted parts */
__merge(array,left,mid,right);
}
}
}
#endif //
|
aa5f532a642cbb9bcd6bfab1a12589ca2f1bee4e | 21054a50b92e214b1e3b3547102c3a3cb5ba6aa1 | /TestCpp/OldFiles/TwoSumOld.cpp | 360c4a516b266430c8945953f862ec9f00bacc35 | [] | no_license | AugustineChang/LearningDoc | 028ee228f872e744f8883301ac49c13c985b1211 | d379c5a68def0a1f2ea9fd0400e6c0bbfe5e1f1e | refs/heads/master | 2022-10-03T05:18:16.603894 | 2022-09-14T13:43:05 | 2022-09-14T13:43:05 | 69,629,443 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,761 | cpp | TwoSumOld.cpp | /*Given an array of integers , find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target , where index1 must be less than index2.Please note that your returned answers( both index1 and index2 ) are not zero - based.
You may assume that each input would have exactly one solution.
Input: numbers = { 2 , 7 , 11 , 15 } , target = 9
Output : index1 = 1 , index2 = 2*/
#include<vector>
using namespace std;
class Solution
{
public:
struct MyStruct
{
int originIndex;
int value;
};
vector<int> twoSum( vector<int> &numbers , int target )
{
vector<int> result;
vector<MyStruct> temp;
size_t length = numbers.size();
for( size_t i = 0; i < length; i++ )
{
MyStruct one;
one.originIndex = i;
one.value = target - numbers[i];
int ret = halfFind( temp , one );
if( ret == -1 )
{
one.value = numbers[i];
halfInsert( temp , one );
}
else
{
result.push_back( ret + 1 );
result.push_back( i + 1 );
}
}
return result;
}
void halfInsert( vector<MyStruct>& findCol , MyStruct newNum )
{
if( findCol.size() == 0 )
{
findCol.push_back( newNum );
}
else if( findCol.size() == 1 )
{
if( findCol[0].value <= newNum.value )
{
findCol.insert( findCol.begin() + 1 , newNum );
}
else
{
findCol.insert( findCol.begin() , newNum );
}
}
else
{
int startIndex = -1;
int endIndex = findCol.size();
while( true )
{
int middle = ( startIndex + endIndex ) / 2;
if( findCol[middle].value <= newNum.value )
{
startIndex = middle;
}
else
{
endIndex = middle;
}
if( endIndex - startIndex == 1 )
{
findCol.insert( findCol.begin() + endIndex , newNum );
break;
}
}
}
}
int halfFind( vector<MyStruct>& findCol , MyStruct findNum )
{
if( findCol.size() == 0 )
{
return -1;
}
else if( findCol.size() == 1 )
{
if( findCol[0].value == findNum.value )
{
return findCol[0].originIndex;
}
else
{
return -1;
}
}
else
{
int startIndex = -1;
int endIndex = findCol.size();
while( true )
{
int middle = ( startIndex + endIndex ) / 2;
if( findCol[middle].value < findNum.value )
{
startIndex = middle;
}
else if( findCol[middle].value > findNum.value )
{
endIndex = middle;
}
else
{
return findCol[middle].originIndex;
}
if( endIndex - startIndex == 1 )
{
return -1;
}
}
}
}
};
/*int main()
{
Solution test;
vector<int> input = { 2 , 15 , -5 , 7 , 4 , 90 , 32 , 6 , -3 , -58 , 5 };
const vector<int>& output = test.twoSum( input , 4 );
return 0;
}*/ |
7b45de060ee6a3735e21542d560c32b5e37cf212 | 7ada282d3a5481452363f2475a6be794f408b10b | /队列/链式队列.cpp | db1da0bba600eff6b26015076172dcf0eccb344d | [] | no_license | wintershii/Data-Structure | cec45d453bd89e2dc5f347503d6aa00f4be606e0 | 3bbde89c5c22558a42b65be7e5efbacb0f25b244 | refs/heads/master | 2020-03-19T00:05:22.842133 | 2018-12-27T09:47:53 | 2018-12-27T09:47:53 | 135,452,164 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,685 | cpp | 链式队列.cpp | #include<stdio.h>
#include<stdlib.h>
typedef struct Qnode{
int date;
struct Qnode *next;
}Qnode,*ptr;
typedef struct{
ptr front;
ptr rear;
int count;
}linkqueue;
linkqueue *Initqueue(linkqueue *queue){
queue = (linkqueue *)malloc(sizeof(linkqueue));
ptr pHead = (ptr)malloc(sizeof(Qnode));
pHead->next = NULL;
queue->front = pHead;
queue->rear = pHead;
queue->count = 0;
return queue;
}
void Enqueue(linkqueue *queue){
ptr pnew = (ptr)malloc(sizeof(Qnode));
printf("请输入入队数据:");
scanf("%d",&pnew->date);
pnew->next = NULL;
queue->rear->next = pnew;
queue->rear = pnew;
queue->count++;
printf("入队成功!\n");
}
void Dequeue(linkqueue *queue){
if(queue->front == queue->rear){
printf("队列目前为空!\n");
return;
}
ptr temp = queue->front->next;
printf("你要删除的数据为:%d",temp->date);
queue->front->next = temp->next;
if(queue->rear == temp)
queue->rear = queue->front;
free(temp);
queue->count--;
printf("出队成功!\n");
}
void print_queue(linkqueue *queue){
if(queue->front == queue->rear){
printf("目前为空队列!\n");
return;
}
printf("目前队列中共有%d个数据\n",queue->count);
int index = 1;
ptr temp = queue->front->next;
while(temp != NULL){
printf("第%d个数据:",index++);
printf("%d\n",temp->date);
temp = temp->next;
}
}
int main(){
linkqueue *queue;
queue = Initqueue(queue);
int choice;
while(1){
printf("1.入队\n");
printf("2.出队\n");
printf("3.输出\n");
scanf("%d",&choice);
switch(choice){
case 1:Enqueue(queue);
break;
case 2:Dequeue(queue);
break;
case 3:print_queue(queue);
break;
}
}
return 0;
}
|
64d1a3f01fbd9555aa71180a872913051fba626d | 428772b35b690d21abf9e2eec5fac25581e4d2cc | /src/entity.cpp | 3c9e2af85ff1827384f917646aae2b47390a1fc7 | [] | no_license | lyr316/MiniEmployeeRecordDatabase | 738b09f3060fd5ebe4d3bcd522d7da326c9ecfee | 78eeb12fa336082b9146c8a6c336d8883500c1b7 | refs/heads/master | 2020-05-20T00:42:07.811950 | 2015-01-19T03:15:05 | 2015-01-19T03:15:05 | 25,338,592 | 0 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 316 | cpp | entity.cpp | /*
* entity.cpp
*
* Created on: 2015Äê1ÔÂ18ÈÕ
* Author: Yanren
*/
#include "entity.h"
void Entity::addEmployee(Employee e)
{
fout.open("database.txt");
fout << e.id << '/n'
<< e.name << '/n'
<< e.department << '/n'
<< e.position << '/n'
<< e.salary << std::endl;
}
|
741b81fd7f82636cf5ddc23da9df1a4bac40561d | e0974be566f6d75c8cd1c0eec0ffaf931a0fe714 | /a1/penguin/scenegraph.cpp | da46082ea3c6fd9f5fcb3bf994a62d79af5e79e1 | [] | no_license | Adjective-Object/418 | 2ca84f00b7938d152356366a02648803da166169 | 8cd87da3cbaf22777ea1519014c97fe84f9b8363 | refs/heads/master | 2021-01-24T19:50:19.838397 | 2016-01-21T15:34:47 | 2016-01-21T15:34:47 | 44,570,098 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,242 | cpp | scenegraph.cpp | #include <tgmath.h>
#include "scenegraph.hpp"
#include <functional>
#include <vector>
SceneNode::SceneNode(
float internalTimeMax,
std::function<float (float)> easingfn,
std::function<void (float)> applyParameter,
std::function<void ()> draw,
Transform baseTransform,
std::vector<SceneNode *> children)
: generateParameter(easingfn),
applyParameter(applyParameter),
draw(draw),
internalTime(0.0f),
internalTimeMax(internalTimeMax),
baseTransform(baseTransform),
children(children) {
}
SceneNode::~SceneNode() {
}
void SceneNode::update(float tDelta) {
// update the internal animation timer by incrementing it by tDelta,
// and do the same to all children of this scene node
for(std::vector<SceneNode *>::size_type i = 0;
i < this->children.size(); i++) {
this->children[i]->update(tDelta);
}
this->internalTime = (float) fmod(this->internalTime + tDelta,
this->internalTimeMax);
}
void SceneNode::render() {
// generate the animation parameter based on the internal time counter
// and the timing function of the SceneNode
this->param = this->generateParameter(
this->internalTime / this->internalTimeMax);
glPushMatrix();
// apply the specified base transformation
glTranslatef(this->baseTransform.translateX,
this->baseTransform.translateY,
this->baseTransform.translateZ);
glRotatef(this->baseTransform.rotation, 0, 0, 1);
glScalef(this->baseTransform.scaleX, this->baseTransform.scaleY, 1);
// apply the animation parameter before drawing and draw the element
this->applyParameter(this->param);
this->draw();
for(std::vector<SceneNode *>::size_type i = 0;
i < this->children.size(); i++) {
this->children[i]->render();
}
glPopMatrix();
}
//////////////////////
// Easing Functions //
//////////////////////
// normalized sinusoid (period of 1)
const float PI = 3.14159f;
float _normSin(float t) {return sin(t * 2 * PI);}
std::function<float (float)> normSin = std::function<float (float)>(_normSin);
// holding a flat value
std::function<float (float)> flatValue(float value){
return [=] (float time) {return value;};
}
// triangle wave (UNTESTED)
float triangleWave (float t) {
if (t<0.25f) {
return 0.5 + t*2;
} else if (t<0.75f) {
return 1.0f - (t - 0.25f) *2;
} else {
return -1 - (1.0f - t) * 2;
}
}
/////////////////////////////////////
// Paramater Application Functions //
/////////////////////////////////////
// rotate about an x,y point in the local coordinate space of the object
// in range (-thetaScale, thetaScale)
std::function<void (float)> rotateAbout(
float xOff, float yOff, float thetaScale) {
return [=] (float param) {
glTranslatef(-xOff, -yOff, 0);
glRotatef(param * thetaScale, 0.0f, 0.0f, 1.0f);
glTranslatef(xOff,yOff, 0);
};
}
// translate between (-xOff, -yOff) -> (xOff, yOff)
std::function<void (float)> scaledTranslate(
float xOff, float yOff) {
return [=] (float param) {
glTranslatef(xOff * param, yOff * param, 0);
};
}
// do no animation
std::function<void (float)> doNothing = [] (float time) {};
///////////////////////
// Drawing functions //
///////////////////////
// draw a rectange
std::function<void ()> drawRect(
Color c, float x1, float y1, float x2, float y2) {
return [=] () { _drawRect(c, x1, y1, x2, y2); };
}
void _drawRect(Color color, float x1, float y1, float x2, float y2) {
glColor3f(color.red, color.green, color.blue);
glBegin(GL_POLYGON);
glVertex2d(x1,y1);
glVertex2d(x2,y1);
glVertex2d(x2,y2);
glVertex2d(x1,y2);
glEnd();
}
// draw an arbitrary polygon
std::function<void ()> drawPolygon(
Color color, std::vector<std::pair<float, float>> points) {
return [=] () {_drawPolygon(color, points);};
}
void _drawPolygon(Color color, std::vector<std::pair<float, float>> points) {
glColor3f(color. red, color.green, color.blue);
glBegin(GL_POLYGON);
for (int i=0; i<points.size(); i++) {
glVertex3d(points[i].first, points[i].second, 0);
}
glEnd();
}
// draw an nGon
std::function<void ()> drawNgon(Color color, int n, float radius) {
return [=] () {_drawNgon(color, n, radius);};
}
void _drawNgon(Color color, int n, float radius) {
glColor3f(color. red, color.green, color.blue);
glPushMatrix();
float rStep = 2 * PI / n;
float angle = 0;
glBegin(GL_POLYGON);
for (int i=0; i<n; i++) {
glVertex3d(cos(angle) * radius, sin(angle) * radius, 0);
angle += rStep;
}
glEnd();
glPopMatrix();
}
// control the use of anothe rendering function based on a boolean switch
// (actually an int switch because of the types required by glui)
std::function<void ()> conditionalRender(
std::function<void ()> renderFn, int * control) {
return [=] () {
if (* control) {
renderFn();
}
};
}
|
3cfd0d10d8cd8f7ff647983a7ce77ddefbd6b674 | 39eac74fa6a244d15a01873623d05f480f45e079 | /SalesDlg.cpp | f36112019038d86b04d709b550fe2a97c192ed15 | [] | no_license | 15831944/Practice | a8ac8416b32df82395bb1a4b000b35a0326c0897 | ae2cde9c8f2fb6ab63bd7d8cd58701bd3513ec94 | refs/heads/master | 2021-06-15T12:10:18.730367 | 2016-11-30T15:13:53 | 2016-11-30T15:13:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,717 | cpp | SalesDlg.cpp | // SalesDlg.cpp : implementation file
//
#include "stdafx.h"
#include "PatientsRc.h"
#include "SalesDlg.h"
#include "GlobalDataUtils.h"
#include "TaskEditDlg.h"
#include "MultiSelectDlg.h" // (j.armen 2011-06-28 11:54) - PLID 44342
#include "SpecialtyConfigDlg.h" // (j.luckoski 04/10/12) - PLID 49491 - Specialty Dialog to edit specialties for proposals.
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
using namespace ADODB;
using namespace NXDATALISTLib;
/////////////////////////////////////////////////////////////////////////////
// SalesDlg dialog
CSalesDlg::CSalesDlg(CWnd* pParent)
: CPatientDialog(CSalesDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(SalesDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void CSalesDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(SalesDlg)
DDX_Control(pDX, IDC_CREATE_TODO, m_btnCreateTodo);
DDX_Control(pDX, IDC_SEL_REFERRAL, m_btnSelReferral);
DDX_Control(pDX, IDC_COMPANY, m_nxeditCompany);
DDX_Control(pDX, IDC_TITLE_BOX, m_nxeditTitleBox);
DDX_Control(pDX, IDC_FIRST_NAME_BOX, m_nxeditFirstNameBox);
DDX_Control(pDX, IDC_MIDDLE_NAME_BOX, m_nxeditMiddleNameBox);
DDX_Control(pDX, IDC_LAST_NAME_BOX, m_nxeditLastNameBox);
DDX_Control(pDX, IDC_ADDRESS1_BOX, m_nxeditAddress1Box);
DDX_Control(pDX, IDC_ADDRESS2_BOX, m_nxeditAddress2Box);
DDX_Control(pDX, IDC_ZIP_BOX, m_nxeditZipBox);
DDX_Control(pDX, IDC_CITY_BOX, m_nxeditCityBox);
DDX_Control(pDX, IDC_STATE_BOX, m_nxeditStateBox);
DDX_Control(pDX, IDC_CALLER_BOX, m_nxeditCallerBox);
DDX_Control(pDX, IDC_WORK_PHONE_BOX, m_nxeditWorkPhoneBox);
DDX_Control(pDX, IDC_EXT_PHONE_BOX, m_nxeditExtPhoneBox);
DDX_Control(pDX, IDC_FAX_PHONE_BOX, m_nxeditFaxPhoneBox);
DDX_Control(pDX, IDC_BACKLINE_BOX, m_nxeditBacklineBox);
DDX_Control(pDX, IDC_CELL_PHONE_BOX, m_nxeditCellPhoneBox);
DDX_Control(pDX, IDC_PAGER_PHONE_BOX, m_nxeditPagerPhoneBox);
DDX_Control(pDX, IDC_WEBSITE_BOX, m_nxeditWebsiteBox);
DDX_Control(pDX, IDC_DOC_EMAIL_BOX, m_nxeditDocEmailBox);
DDX_Control(pDX, IDC_PRAC_EMAIL_BOX, m_nxeditPracEmailBox);
DDX_Control(pDX, IDC_REF_DATE, m_nxeditRefDate);
DDX_Control(pDX, IDC_SOURCE_BOX, m_nxeditSourceBox);
DDX_Control(pDX, IDC_REFERRAL, m_nxeditReferral);
DDX_Control(pDX, IDC_NOTES, m_nxeditNotes);
DDX_Control(pDX, IDC_CUSTOM1_LABEL, m_nxstaticCustom1Label);
DDX_Control(pDX, IDC_CUSTOM3_LABEL, m_nxstaticCustom3Label);
DDX_Control(pDX, IDC_CUSTOM1_LABEL3, m_nxstaticCustom1Label3);
//(a.wilson 2011-4-28) PLID 43355 - controls to handle the information in the boxes
DDX_Control(pDX, IDC_DISCOUNT_PERCENT_BOX, m_neditDiscountPercent);
DDX_Control(pDX, IDC_ADDON_DISCOUNT_PERCENT_BOX, m_neditAddOnDiscountPercent);
DDX_Control(pDX, IDC_SOCIETY_LABEL, m_nxlSocietyLabel); // (j.armen 2011-06-28 11:54) - PLID 44342 - added binding for society label
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CSalesDlg, CPatientDialog)
//{{AFX_MSG_MAP(SalesDlg)
ON_BN_CLICKED(IDC_EMAIL, OnEmail)
ON_BN_CLICKED(IDC_EMAIL2, OnEmail2)
ON_BN_CLICKED(IDC_VIEW_TODO, OnViewTodo)
ON_BN_CLICKED(IDC_CREATE_TODO, OnCreateTodo)
ON_BN_CLICKED(IDC_VIEW_OPPORTUNITIES, OnViewOpportunities)
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_VISIT_WEBSITE, &CSalesDlg::OnBnClickedVisitWebsite) //(a.wilson 2011-5-6) PLID 9702
// (j.armen 2011-06-28 11:54) - PLID 44342 - event handling for clicking/mouse over labels
ON_MESSAGE(NXM_NXLABEL_LBUTTONDOWN, OnLabelClick)
ON_WM_SETCURSOR()
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// SalesDlg message handlers
void CSalesDlg::SetColor(OLE_COLOR nNewColor)
{
((CNxColor*)GetDlgItem(IDC_DEMOGRAPHICS_BKG))->SetColor(nNewColor);
((CNxColor*)GetDlgItem(IDC_PHONE_BKG))->SetColor(nNewColor);
((CNxColor*)GetDlgItem(IDC_OTHER_BKG))->SetColor(nNewColor);
((CNxColor*)GetDlgItem(IDC_REFERENCE_BKG))->SetColor(nNewColor);
//(a.wilson 2011-4-28) PLID 43355 - to handle what color the background box should be for the current patient
((CNxColor*)GetDlgItem(IDC_DISCOUNT_BKG))->SetColor(nNewColor);
CPatientDialog::SetColor(nNewColor);
}
void CSalesDlg::Save(int nID)
{
CString field, value;
double temp; //(a.wilson 2011-6-8) PLID 43355
if(!m_changed)
return;
if(!nID) {
m_changed = false;
return;
}
try{
GetDlgItemText(nID, value);
switch(nID)
{
case IDC_COMPANY:
field = "Company";
break;
case IDC_FIRST_NAME_BOX:
field = "First";
break;
case IDC_MIDDLE_NAME_BOX:
field = "Middle";
break;
case IDC_LAST_NAME_BOX:
field = "Last";
break;
case IDC_ADDRESS1_BOX:
field = "Address1";
break;
case IDC_ADDRESS2_BOX:
field = "Address2";
break;
case IDC_CITY_BOX:
field = "City";
break;
case IDC_STATE_BOX:
field = "State";
break;
case IDC_ZIP_BOX:
field = "Zip";
break;
case IDC_CALLER_BOX: //custom 1
{
_RecordsetPtr rs;
rs = CreateRecordset("SELECT TextParam FROM CustomFieldDataT WHERE PersonID = %li AND FieldID = 1", m_id);
if(rs->eof) { //no record here
//check CustomFieldsT
if(IsRecordsetEmpty("SELECT ID FROM CustomFieldsT WHERE ID = 1"))
ExecuteSql("INSERT INTO CustomFieldsT (ID, Name, Type) VALUES (1, 'Custom 1', 1)");
ExecuteSql("INSERT INTO CustomFieldDataT (PersonID, FieldID, TextParam) (SELECT %li, 1, '%s')", m_id, _Q(value));
}
else
ExecuteSql("UPDATE CustomFieldDataT SET TextParam = '%s' WHERE PersonID = %li AND FieldID = 1", _Q(value), m_id);
rs->Close();
return;
}
break;
case IDC_WORK_PHONE_BOX:
field = "WorkPhone";
break;
case IDC_EXT_PHONE_BOX:
field = "Extension";
break;
case IDC_FAX_PHONE_BOX:
field = "Fax";
break;
case IDC_BACKLINE_BOX:
field = "EmergWPhone";
break;
case IDC_CELL_PHONE_BOX:
field = "CellPhone";
break;
case IDC_PAGER_PHONE_BOX:
field = "Pager";
break;
case IDC_WEBSITE_BOX: //custom 3
{
_RecordsetPtr rs;
rs = CreateRecordset("SELECT TextParam FROM CustomFieldDataT WHERE PersonID = %li AND FieldID = 3", m_id);
if(rs->eof) { //no record here
//check CustomFieldsT
if(IsRecordsetEmpty("SELECT ID FROM CustomFieldsT WHERE ID = 3"))
ExecuteSql("INSERT INTO CustomFieldsT (ID, Name, Type) VALUES (3, 'Custom 3', 1)");
ExecuteSql("INSERT INTO CustomFieldDataT (PersonID, FieldID, TextParam) (SELECT %li, 3, '%s')", m_id, _Q(value));
}
else
ExecuteSql("UPDATE CustomFieldDataT SET TextParam = '%s' WHERE PersonID = %li AND FieldID = 3", _Q(value), m_id);
rs->Close();
return;
}
break;
case IDC_DOC_EMAIL_BOX:
field = "Email";
break;
case IDC_PRAC_EMAIL_BOX:
{
ExecuteSql("UPDATE NxClientsT SET PracEmail = '%s' WHERE PersonID = %li", _Q(value), m_id);
return;
}
break;
case IDC_SOURCE_BOX: //custom 2
{
_RecordsetPtr rs;
rs = CreateRecordset("SELECT TextParam FROM CustomFieldDataT WHERE PersonID = %li AND FieldID = 2", m_id);
if(rs->eof) { //no record here
//check CustomFieldsT
if(IsRecordsetEmpty("SELECT ID FROM CustomFieldsT WHERE ID = 2"))
ExecuteSql("INSERT INTO CustomFieldsT (ID, Name, Type) VALUES (2, 'Custom 2', 1)");
ExecuteSql("INSERT INTO CustomFieldDataT (PersonID, FieldID, TextParam) (SELECT %li, 2, '%s')", m_id, _Q(value));
}
else
ExecuteSql("UPDATE CustomFieldDataT SET TextParam = '%s' WHERE PersonID = %li AND FieldID = 2", _Q(value), m_id);
rs->Close();
return;
}
break;
case IDC_NOTES:
field = "Note";
break;
case IDC_TITLE_BOX:
field = "Title";
break;
case IDC_REF_DATE:
if(value == "")
ExecuteSql("UPDATE NxClientsT SET RefDate = NULL WHERE PersonID = %li", m_id);
else
ExecuteSql("UPDATE NxClientsT SET RefDate = '%s' WHERE PersonID = %li", _Q(value), m_id);
return;
break;
//(a.wilson 2011-4-29) PLID 43355 - store the changed percents
case IDC_DISCOUNT_PERCENT_BOX: //save the discount percent box
temp = atof(value);
if (temp >= 0.00 && temp <= 100.00) {
ExecuteParamSql("UPDATE SupportDiscountsT SET DiscountPercent = {DOUBLE} WHERE PersonID = {INT}", temp, m_id);
SetDlgItemText(IDC_DISCOUNT_PERCENT_BOX, FormatString("%.02f", temp));
} else {
SetDlgItemText(IDC_DISCOUNT_PERCENT_BOX, "0.00");
}
break;
case IDC_ADDON_DISCOUNT_PERCENT_BOX: //save the add on discount percent box
temp = atof(value);
if (temp >= 0.00 && temp <= 100.00) {
ExecuteParamSql("UPDATE SupportDiscountsT SET AddOnDiscountPercent = {DOUBLE} WHERE PersonID = {INT}", temp, m_id);
SetDlgItemText(IDC_ADDON_DISCOUNT_PERCENT_BOX, FormatString("%.02f", temp));
} else {
SetDlgItemText(IDC_ADDON_DISCOUNT_PERCENT_BOX, "0.00");
}
break;
default:
break;
}
if(field == "") {
m_changed = false;
return;
}
ExecuteSql("UPDATE PersonT SET %s = '%s' WHERE ID = %li", field, _Q(value), m_id);
} NxCatchAll("Error in CSalesDlg::Save()");
m_changed = false;
}
void CSalesDlg::Load()
{
try{
_RecordsetPtr rs; //(a.wilson 2011-4-28) PLID 43355 - updated query with discount information and parameterized
rs = CreateParamRecordset("SELECT PersonT.Company, PersonT.First, PersonT.Middle, PersonT.Last, PersonT.Address1, "
"PersonT.Address2, PersonT.City, PersonT.State, PersonT.Zip, PersonT.WorkPhone, PersonT.Extension, PersonT.Fax, "
"PersonT.EmergWPhone, PersonT.CellPhone, PersonT.Pager, PersonT.Email, PersonT.Note, PersonT.Title, "
"NxClientsT.RefRating, NxClientsT.RefDate, NxClientsT.RefStatus, "
"SupportDiscountsT.TypeID, SupportDiscountsT.AddOnDiscountPercent, SupportDiscountsT.DiscountPercent "
"FROM PersonT "
"INNER JOIN NxClientsT ON PersonT.ID = NxClientsT.PersonID "
"LEFT JOIN SupportDiscountsT ON PersonT.ID = SupportDiscountsT.PersonID "
"WHERE PersonT.ID = {INT}", m_id);
if(!rs->eof){
SetDlgItemText(IDC_COMPANY, CString(rs->Fields->Item["Company"]->Value.bstrVal));
SetDlgItemText(IDC_FIRST_NAME_BOX, CString(rs->Fields->Item["First"]->Value.bstrVal));
SetDlgItemText(IDC_MIDDLE_NAME_BOX, CString(rs->Fields->Item["Middle"]->Value.bstrVal));
SetDlgItemText(IDC_LAST_NAME_BOX, CString(rs->Fields->Item["Last"]->Value.bstrVal));
SetDlgItemText(IDC_ADDRESS1_BOX, CString(rs->Fields->Item["Address1"]->Value.bstrVal));
SetDlgItemText(IDC_ADDRESS2_BOX, CString(rs->Fields->Item["Address2"]->Value.bstrVal));
SetDlgItemText(IDC_CITY_BOX, CString(rs->Fields->Item["City"]->Value.bstrVal));
SetDlgItemText(IDC_STATE_BOX, CString(rs->Fields->Item["State"]->Value.bstrVal));
SetDlgItemText(IDC_ZIP_BOX, CString(rs->Fields->Item["Zip"]->Value.bstrVal));
SetDlgItemText(IDC_WORK_PHONE_BOX, CString(rs->Fields->Item["WorkPhone"]->Value.bstrVal));
SetDlgItemText(IDC_EXT_PHONE_BOX, CString(rs->Fields->Item["Extension"]->Value.bstrVal));
SetDlgItemText(IDC_FAX_PHONE_BOX, CString(rs->Fields->Item["Fax"]->Value.bstrVal));
SetDlgItemText(IDC_BACKLINE_BOX, CString(rs->Fields->Item["EmergWPhone"]->Value.bstrVal));
SetDlgItemText(IDC_CELL_PHONE_BOX, CString(rs->Fields->Item["CellPhone"]->Value.bstrVal));
SetDlgItemText(IDC_PAGER_PHONE_BOX, CString(rs->Fields->Item["Pager"]->Value.bstrVal));
SetDlgItemText(IDC_DOC_EMAIL_BOX, CString(rs->Fields->Item["Email"]->Value.bstrVal));
SetDlgItemText(IDC_NOTES, CString(rs->Fields->Item["Note"]->Value.bstrVal));
SetDlgItemText(IDC_TITLE_BOX, CString(rs->Fields->Item["Title"]->Value.bstrVal));
SetDlgItemVar(IDC_REF_DATE, rs->Fields->Item["RefDate"]->Value);
//(a.wilson 2011-4-28) PLID 43355 //discount - when selecting a different patient these queries will be
//triggered and get the new patients data.
CString str;
_variant_t tempVariant = rs->Fields->Item["TypeID"]->Value;
if (tempVariant.vt == VT_NULL) {
m_pDiscountType->CurSel = 0;
SetDlgItemText(IDC_DISCOUNT_PERCENT_BOX, "0.00");
SetDlgItemText(IDC_ADDON_DISCOUNT_PERCENT_BOX, "0.00");
} else {
m_pDiscountType->SetSelByColumn(0, rs->Fields->Item["TypeID"]->Value);
str.Format("%.2f", VarDouble(rs->Fields->Item["DiscountPercent"]->Value));
SetDlgItemText(IDC_DISCOUNT_PERCENT_BOX, str);
str.Format("%.2f", VarDouble(rs->Fields->Item["AddOnDiscountPercent"]->Value));
SetDlgItemText(IDC_ADDON_DISCOUNT_PERCENT_BOX, str);
}
}
//set reference rating and reference status combos
if(rs->Fields->Item["RefStatus"]->Value.vt == VT_BSTR)
m_pRefStatus->SetSelByColumn(0, rs->Fields->Item["RefStatus"]->Value);
else
m_pRefStatus->CurSel = -1;
if(rs->Fields->Item["RefRating"]->Value.vt == VT_BSTR)
m_pRefRating->SetSelByColumn(0, rs->Fields->Item["RefRating"]->Value);
else
m_pRefRating->CurSel = -1;
//
rs->Close();
rs = CreateRecordset("SELECT PracEmail FROM NxClientsT WHERE PersonID = %li", m_id);
if(!rs->eof)
SetDlgItemText(IDC_PRAC_EMAIL_BOX, CString(rs->Fields->Item["PracEmail"]->Value.bstrVal));
else
SetDlgItemText(IDC_PRAC_EMAIL_BOX, "");
//custom fields
rs = CreateRecordset("SELECT TextParam FROM CustomFieldDataT WHERE PersonID = %li AND FieldID = 2", m_id); //source
if(!rs->eof)
SetDlgItemText(IDC_SOURCE_BOX, CString(rs->Fields->Item["TextParam"]->Value.bstrVal));
else
SetDlgItemText(IDC_SOURCE_BOX, "");
rs = CreateRecordset("SELECT Textparam FROM CustomFieldDataT WHERE PersonID = %li AND FieldID = 1", m_id); //caller
if(!rs->eof)
SetDlgItemText(IDC_CALLER_BOX, CString(rs->Fields->Item["TextParam"]->Value.bstrVal));
else
SetDlgItemText(IDC_CALLER_BOX, "");
rs = CreateRecordset("SELECT Textparam FROM CustomFieldDataT WHERE PersonID = %li AND FieldID = 3", m_id); //website
if(!rs->eof)
SetDlgItemText(IDC_WEBSITE_BOX, CString(rs->Fields->Item["TextParam"]->Value.bstrVal));
else
SetDlgItemText(IDC_WEBSITE_BOX, "");
//fill in the datalists
//alt contact
rs = CreateRecordset("SELECT IntParam FROM CustomFieldDataT WHERE PersonID = %li AND FieldID = 31",m_id);
if(!rs->eof)
m_altContact->SetSelByColumn(0, rs->Fields->Item["IntParam"]->Value);
else
m_altContact->CurSel = 0;
//status
rs = CreateRecordset("SELECT TypeOfPatient FROM PatientsT WHERE PersonID = %li", m_id);
if(!rs->eof)
m_status->SetSelByColumn(0, rs->Fields->Item["TypeOfPatient"]->Value);
else
m_status->CurSel = 0;
//society
// (j.armen 2011-06-28 11:55) - PLID 44342 - moved into a seperate function
RefreshSociety();
} NxCatchAll("Error in CSalesDlg::Load()");
}
// (j.armen 2011-06-28 11:56) - PLID 44342 - Function for refreshing the Society box/label
void CSalesDlg::RefreshSociety()
{
try {
_RecordsetPtr rs(__uuidof(Recordset));
// (j.armen 2011-06-28 11:57) - PLID 44342 - reset the box/label before filling it
m_society->PutCurSel(-1);
m_nxlSocietyLabel.SetText("");
m_nxlSocietyLabel.ShowWindow(SW_HIDE);
ShowDlgItem(IDC_SOCIETY_BOX, SW_SHOWNA);
// (j.armen 2011-06-28 11:57) - PLID 44342 - Get data from the custom field
rs = CreateParamRecordset(
"SELECT CustomListDataT.PersonID, CustomListDataT.FieldID, CustomListDataT.CustomListItemsID, CustomListItemsT.Text, ItemCount \r\n"
"FROM CustomListDataT \r\n"
"INNER JOIN (SELECT PersonID, FieldID, COUNT(*) AS ItemCount FROM CustomListDataT GROUP BY PersonID, FieldID) CountQ \r\n"
" ON CustomListDataT.PersonID = CountQ.PersonID AND CustomListDataT.FieldID = CountQ.FieldID \r\n"
"INNER JOIN CustomListItemsT ON CustomListDataT.CustomListItemsID = CustomListItemsT.ID \r\n"
"WHERE CustomListDataT.PersonID = {INT} AND CustomListDataT.FieldID = 22 ORDER BY CustomListItemsT.Text;", m_id);
while(!rs->eof)
{
// (j.armen 2011-06-28 11:57) - PLID 44342 - If we have more than 1 item selected, show the label
if(AdoFldLong(rs, "ItemCount", 0) > 1)
{
ShowDlgItem(IDC_SOCIETY_BOX, SW_HIDE);
if(m_nxlSocietyLabel.GetText().IsEmpty())
{
m_nxlSocietyLabel.SetText(AdoFldString(rs, "Text"));
m_nxlSocietyLabel.SetToolTip(AdoFldString(rs, "Text"));
}
else
{
m_nxlSocietyLabel.SetText(m_nxlSocietyLabel.GetText() + ", " + AdoFldString(rs, "Text"));
m_nxlSocietyLabel.SetToolTip(m_nxlSocietyLabel.GetToolTip() + ", " + AdoFldString(rs, "Text"));
}
m_nxlSocietyLabel.SetSingleLine();
m_nxlSocietyLabel.SetType(dtsHyperlink);
m_nxlSocietyLabel.ShowWindow(SW_SHOWNA);
}
// (j.armen 2011-06-28 11:58) - PLID 44342 - If we have only one item selected, show the box
else
{
m_nxlSocietyLabel.ShowWindow(SW_HIDE);
m_society->SetSelByColumn(0, rs->Fields->Item["CustomListItemsID"]->Value);
ShowDlgItem(IDC_SOCIETY_BOX, SW_SHOWNA);
}
rs->MoveNext();
}
m_changed = false;
m_ForceRefresh = false;
}
NxCatchAll(__FUNCTION__);
}
// (j.armen 2011-06-28 11:59) - PLID 44342 - Store the society data
void CSalesDlg::StoreSociety(NXDATALISTLib::_DNxDataListPtr customList, UINT customListIDC)
{
CParamSqlBatch sqlBatch;
_RecordsetPtr rs;
CArray<long, long> arynSelection;
// (j.armen 2012-06-20 15:23) - PLID 49607 - Provide MultiSelect Sizing ConfigRT Entry
CMultiSelectDlg dlg(this, "CustomListDataT.FieldID = 22");
int nVal;
switch(customListIDC)
{
// (j.armen 2011-06-28 11:59) - PLID 44342 - if we are coming from the box, then get the current selection from that box
case IDC_SOCIETY_BOX:
if(customList->GetCurSel() == -1)
{
nVal = -1;
}
else
{
nVal = VarLong(customList->GetValue(customList->GetCurSel(), 0));
}
break;
case IDC_SOCIETY_LABEL:
// (j.armen 2011-06-28 12:00) - PLID 44342 - if we are coming from the label, then we must show the multi select dlg
nVal = -2;
break;
default:
ASSERT(FALSE);
break;
}
sqlBatch.Add("DELETE FROM CustomListDataT WHERE FieldID = 22 AND PersonID = {INT}; ", m_id);
switch(nVal)
{
// (j.armen 2011-06-28 12:00) - PLID 44342 - Show the multiselect dlg
case -2:
rs = CreateParamRecordset(
"SELECT CustomListItemsID FROM CustomListDataT "
"WHERE FieldID = 22 AND PersonID = {INT}", m_id);
while(!rs->eof)
{
arynSelection.Add(AdoFldLong(rs, "CustomListItemsID"));
rs->MoveNext();
}
dlg.PreSelect(arynSelection);
if(IDOK == dlg.Open("CustomListItemsT", "CustomFieldID = 22", "ID", "Text", "Select Custom List Items", 0))
{
dlg.FillArrayWithIDs(arynSelection);
for(int i = 0; i < arynSelection.GetCount(); i++)
{
sqlBatch.Add("INSERT INTO CustomListDataT (PersonID, FieldID, CustomListItemsID) VALUES({INT}, 22, {INT})", m_id, arynSelection.GetAt(i));
}
sqlBatch.Execute(GetRemoteData());
}
break;
// (j.armen 2011-06-28 12:00) - PLID 44342 - no selection, remove all data
case -1:
sqlBatch.Execute(GetRemoteData());
break;
// (j.armen 2011-06-28 12:01) - PLID 44342 - insert the single selected item
default:
sqlBatch.Add("INSERT INTO CustomListDataT (PersonID, FieldID, CustomListItemsID) VALUES({INT}, 22, {INT}); ", m_id, VarLong(customList->GetValue(customList->GetCurSel(), 0)));
sqlBatch.Execute(GetRemoteData());
break;
}
RefreshSociety();
}
BOOL CSalesDlg::OnInitDialog()
{
CNxDialog::OnInitDialog();
IRowSettingsPtr pRow;
_variant_t var;
m_btnCreateTodo.AutoSet(NXB_NEW);
m_btnSelReferral.AutoSet(NXB_MODIFY);
m_changed = FALSE;
m_altContact = BindNxDataListCtrl(IDC_ALT_CONTACT_LIST);
m_society = BindNxDataListCtrl(IDC_SOCIETY_BOX);
m_status = BindNxDataListCtrl(IDC_STATUS);
//(a.wilson 2011-4-28) PLID 43355 - pointer setup to control the datalist
m_pDiscountType = BindNxDataListCtrl(IDC_DISCOUNT_TYPE);
pRow = m_altContact->GetRow(-1);
var = (long)0;
pRow->PutValue(0,var);
pRow->PutValue(1,"<No Contact>");
m_altContact->InsertRow(pRow,0);
pRow = m_society->GetRow(-1);
pRow->PutValue(0,(long)-1);
pRow->PutValue(1,"<No Society>");
m_society->InsertRow(pRow,0);
// (j.armen 2011-06-28 12:01) - PLID 44342 - added entry for multiple societies
pRow = m_society->GetRow(-1);
pRow->PutValue(0,(long)-2);
pRow->PutValue(1, "<Multiple Societies>");
m_society->InsertRow(pRow, 0);
pRow = m_status->GetRow(-1);
var = (long)0;
pRow->PutValue(0,var);
pRow->PutValue(1,"<No Status>");
m_status->InsertRow(pRow,0);
//fill in the ratings combo
m_pRefRating = BindNxDataListCtrl(IDC_REF_RATING, false);
pRow = m_pRefRating->GetRow(-1);
pRow->PutValue(0,"<No Rating>");
m_pRefRating->InsertRow(pRow,0);
pRow = m_pRefRating->GetRow(-1);
pRow->PutValue(0,"F");
m_pRefRating->InsertRow(pRow,0);
pRow = m_pRefRating->GetRow(-1);
pRow->PutValue(0,"D");
m_pRefRating->InsertRow(pRow,0);
pRow = m_pRefRating->GetRow(-1);
pRow->PutValue(0,"C");
m_pRefRating->InsertRow(pRow,0);
pRow = m_pRefRating->GetRow(-1);
pRow->PutValue(0,"B");
m_pRefRating->InsertRow(pRow,0);
pRow = m_pRefRating->GetRow(-1);
pRow->PutValue(0,"A");
m_pRefRating->InsertRow(pRow,0);
//
//fill in the ratings combo
m_pRefStatus = BindNxDataListCtrl(IDC_REF_STATUS, false);
//TODO: What should these be?
pRow = m_pRefStatus->GetRow(-1);
pRow->PutValue(0,"<No Status>");
m_pRefStatus->InsertRow(pRow,0);
pRow = m_pRefStatus->GetRow(-1);
pRow->PutValue(0,"Power User");
m_pRefStatus->InsertRow(pRow,0);
pRow = m_pRefStatus->GetRow(-1);
pRow->PutValue(0,"Normal User");
m_pRefStatus->InsertRow(pRow,0);
//
//a.wilson 2011-4-29 PLID 43355 - add the no discount option to the discount type control and the add on discount type control
pRow = m_pDiscountType->GetRow(-1);
pRow->PutValue(0, 0);
pRow->PutValue(1,"<No Discount>");
m_pDiscountType->InsertRow(pRow,0);
//(a.wilson 2011-5-2) PLID 43355
//check permissions to decide whether the user is allowed to edit these controls
if(!GetCurrentUserPermissions(bioInternalDiscount)) {
m_neditDiscountPercent.SetReadOnly(TRUE);
m_neditAddOnDiscountPercent.SetReadOnly(TRUE);
m_pDiscountType->ReadOnly = TRUE;
} else {
m_neditDiscountPercent.SetReadOnly(FALSE);
m_neditAddOnDiscountPercent.SetReadOnly(FALSE);
m_pDiscountType->ReadOnly = FALSE;
}
m_bFormatPhoneNums = GetRemotePropertyInt("FormatPhoneNums", 1, 0, "<None>", true);
m_strPhoneFormat = GetRemotePropertyText("PhoneFormatString", "(###) ###-####", 0, "<None>", true);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
BEGIN_EVENTSINK_MAP(CSalesDlg, CNxDialog)
//{{AFX_EVENTSINK_MAP(SalesDlg)
ON_EVENT(CSalesDlg, IDC_ALT_CONTACT_LIST, 2 /* SelChanged */, OnSelChangedAltContactList, VTS_I4)
ON_EVENT(CSalesDlg, IDC_STATUS, 2 /* SelChanged */, OnSelChangedStatus, VTS_I4)
ON_EVENT(CSalesDlg, IDC_SOCIETY_BOX, 2 /* SelChanged */, OnSelChangedSocietyBox, VTS_I4)
ON_EVENT(CSalesDlg, IDC_REF_RATING, 16 /* SelChosen */, OnSelChosenRefRating, VTS_I4)
ON_EVENT(CSalesDlg, IDC_REF_STATUS, 16 /* SelChosen */, OnSelChosenRefStatus, VTS_I4)
//(a.wilson 2011-4-28) PLID 43355 - Messages to handle the combo boxes for discount types.
ON_EVENT(CSalesDlg, IDC_DISCOUNT_TYPE, 16 /* SelChosen */, OnSelChosenDiscountType, VTS_I4)
ON_EVENT(CSalesDlg, IDC_DISCOUNT_TYPE, 1 /* SelChanging */, OnSelChangingDiscountType, VTS_PI4)
//}}AFX_EVENTSINK_MAP
END_EVENTSINK_MAP()
void CSalesDlg::OnSelChangedAltContactList(long nNewSel)
{
try{
_RecordsetPtr rs;
rs = CreateRecordset("SELECT IntParam FROM CustomFieldDataT WHERE PersonID = %li AND FieldID = 31", m_id);
if(rs->eof) { //no record
//check CustomFieldsT
if(IsRecordsetEmpty("SELECT ID FROM CustomFieldsT WHERE ID = 31"))
ExecuteSql("INSERT INTO CustomFieldsT (ID, Name, Type) VALUES (31, 'Custom Contact', 12)");
ExecuteSql("INSERT INTO CustomFieldDataT (PersonID, FieldID, IntParam) (SELECT %li, 31, %li)", m_id, VarLong(m_altContact->GetValue(nNewSel, 0)));
}
else //update existing record
ExecuteSql("UPDATE CustomFieldDataT SET IntParam = %li WHERE PersonID = %li AND FieldID = 31", VarLong(m_altContact->GetValue(nNewSel, 0)), m_id);
} NxCatchAll("Error in OnSelChangedAltContactList()");
}
void CSalesDlg::OnSelChangedStatus(long nNewSel)
{
try{
ExecuteSql("UPDATE PatientsT SET TypeOfPatient = %li WHERE PersonID = %li", VarLong(m_status->GetValue(nNewSel, 0)), m_id);
} NxCatchAll("Error in OnSelChangedStatus()");
}
void CSalesDlg::OnSelChangedSocietyBox(long nNewSel)
{
try{
// (j.armen 2011-06-28 12:02) - PLID 44342 - now call the store society function
StoreSociety(m_society, IDC_SOCIETY_BOX);
} NxCatchAll(__FUNCTION__);
}
void CSalesDlg::UpdateView(bool bForceRefresh) // (a.walling 2010-10-12 15:27) - PLID 40906 - UpdateView with option to force a refresh
{
StoreDetails();
m_id = GetActivePatientID();
//DRT - 12/03/02 - Copied this code from the support dialog (including the below comments), because at some point we started
// reading things out of NxClientsT on this tab as well.
//just for this tab we're going to do things a little differently
//when this tab is loaded it checks to see if an entry exists in NxClientsT (which contains a PersonID to
//link with PersonT). If nothing exists, this function will add an entry with the default values to it
//This saves us changing a bunch of code elsewhere in the program and conflicts with actual Clients who
//don't have a Support tab.
//If an entry does exist, nothing will happen and the dialog will act as it normally would
_RecordsetPtr rs(__uuidof(Recordset));
CString sql;
sql.Format("SELECT PersonID FROM NxClientsT WHERE PersonID = %li", m_id);
try{
rs = CreateRecordsetStd(sql);
if(rs->eof)
{
ExecuteSql("INSERT INTO NxClientsT (PersonID, LicenseKey) (SELECT %li,%li)", m_id, NewNumber("NxClientsT","LicenseKey"));
}
rs->Close();
} NxCatchAll("Error in CSupportDlg::UpdateView()");
Load();
}
void CSalesDlg::StoreDetails()
{
try
{
if (m_changed)
{ Save (GetFocus()->GetDlgCtrlID());
m_changed = false;
}
}NxCatchAll("Error in StoreDetails");
}
BOOL CSalesDlg::OnCommand(WPARAM wParam, LPARAM lParam)
{
int nID;
CString str;
switch (HIWORD(wParam))
{
case EN_CHANGE:
switch(nID = LOWORD(wParam))
{
case IDC_WORK_PHONE_BOX:
case IDC_FAX_PHONE_BOX:
case IDC_BACKLINE_BOX:
case IDC_CELL_PHONE_BOX:
case IDC_PAGER_PHONE_BOX:
GetDlgItemText(nID, str);
str.TrimRight();
if (str != "") {
if(m_bFormatPhoneNums) {
FormatItem (nID, m_strPhoneFormat);
}
}
break;
break;
case IDC_EXT_PHONE_BOX:
GetDlgItemText(nID, str);
str.TrimRight();
if (str != "")
FormatItem (nID, "nnnnnnn");
break;
case IDC_ZIP_BOX:
// (d.moore 2007-04-23 12:11) - PLID 23118 -
// Capitalize letters in the zip code as they are typed in. Canadian postal
// codes need to be formatted this way.
CapitalizeAll(IDC_ZIP_BOX);
break;
}
m_changed = true;
break;
case EN_KILLFOCUS:
Save(LOWORD(wParam));
break;
default:
break;
}
return CPatientDialog::OnCommand(wParam, lParam);
}
void CSalesDlg::OnSelChosenRefRating(long nNewSel) {
//save the ref rating
long nCurSel = m_pRefRating->GetCurSel();
if(nCurSel == -1)
return;
try {
CString strRefRating = CString(m_pRefRating->GetValue(nNewSel, 0).bstrVal);
//we don't want to save "<No Rating>", so we'll just toss in an empty string
if(strRefRating == "<No Rating>")
strRefRating = "";
ExecuteSql("UPDATE NxClientsT SET RefRating = '%s' WHERE PersonID = %li", strRefRating, m_id);
} NxCatchAll("Error saving reference rating.");
}
void CSalesDlg::OnSelChosenRefStatus(long nNewSel) {
//save the rating
long nCurSel = m_pRefStatus->GetCurSel();
if(nCurSel == -1)
return;
try {
CString strStatus = CString(m_pRefStatus->GetValue(nNewSel, 0).bstrVal);
//we don't want to save "<No Rating>", so we'll just toss in an empty string
if(strStatus == "<No Status>")
strStatus = "";
ExecuteSql("UPDATE NxClientsT SET RefStatus = '%s' WHERE PersonID = %li", strStatus, m_id);
} NxCatchAll("Error saving reference status.");
}
void CSalesDlg::OnEmail() {
CString str;
GetDlgItemText(IDC_DOC_EMAIL_BOX, str);
str.TrimRight();
str.TrimLeft();
if (str != "") {
// (a.walling 2009-08-10 16:17) - PLID 35153 - Use NULL instead of "open" when calling ShellExecute(Ex). Usually equivalent; see PL notes.
if ((int)ShellExecute(GetSafeHwnd(), NULL, "mailto:" + str,
NULL, "", SW_MAXIMIZE) < 32)
AfxMessageBox("Could not e-mail patient");
}
else
AfxMessageBox("Please enter an e-mail address.");
}
void CSalesDlg::OnEmail2() {
CString str;
GetDlgItemText(IDC_PRAC_EMAIL_BOX, str);
str.TrimRight();
str.TrimLeft();
if (str != "") {
// (a.walling 2009-08-10 16:17) - PLID 35153 - Use NULL instead of "open" when calling ShellExecute(Ex). Usually equivalent; see PL notes.
if ((int)ShellExecute(GetSafeHwnd(), NULL, "mailto:" + str,
NULL, "", SW_MAXIMIZE) < 32)
AfxMessageBox("Could not e-mail patient");
}
else
AfxMessageBox("Please enter an e-mail address.");
}
void CSalesDlg::OnViewTodo() {
CMainFrame *pMainFrame = GetMainFrame();
if (pMainFrame->GetSafeHwnd()) {
pMainFrame->ShowTodoList();
}
}
void CSalesDlg::OnCreateTodo() {
//DRT 3/4/03 - copied this from followupdlg.cpp, removed the code that adds a row
/* Create a new todo from the task edit dialog */
// (j.jones 2008-11-14 10:38) - PLID 31208 - we decided you should not be required to have patient permissions
//to create a todo alarm
/*
if (!CheckCurrentUserPermissions(bioPatient, sptWrite))
return;
*/
try {
CTaskEditDlg dlg(this);
dlg.m_nPersonID = GetActivePatientID(); // (a.walling 2008-07-07 17:54) - PLID 29900 - Do not use GetActive[Patient,Contact][ID,Name]
//(c.copits 2010-12-06) PLID 40794 - Permissions for individual todo alarm fields
dlg.m_bIsNew = TRUE;
long nResult = dlg.DoModal();
if (nResult != IDOK) return;
// Added by CH 1/17: Force the next remind
// time to be 5 minutes if a new task is
// added so the "Don't remind me again"
// option will not cause the new task to
// be forgotten.
{
COleDateTime dt = COleDateTime::GetCurrentTime();
dt += COleDateTimeSpan(0,0,5,0);
SetPropertyDateTime("TodoTimer", dt);
// (j.dinatale 2012-10-22 17:59) - PLID 52393 - set our user preference
SetRemotePropertyInt("LastTimeOption_User", 5, 0, GetCurrentUserName());
SetTimer(IDT_TODO_TIMER, 5*60*1000, NULL);
}
}NxCatchAll("Error in CSalesDlg::OnCreateTodo() ");
}
//DRT 5/24/2007 - PLID 25892 - Open the opportunities window. This is managed by the mainfrm.
void CSalesDlg::OnViewOpportunities()
{
try {
GetMainFrame()->ShowOpportunityList();
} NxCatchAll("Error in OnViewOpportunities");
}
//(a.wilson 2011-4-28) PLID 43355 - when the user selects a new discount type from the control we need
//to update the database tables
void CSalesDlg::OnSelChosenDiscountType(long nNewSel)
{
try {
long nSelection = VarLong(m_pDiscountType->GetValue(nNewSel, 0));
if (nSelection == 0) { //if they set the type to no discount then we want to remove them from the table.
SetDlgItemText(IDC_DISCOUNT_PERCENT_BOX, "0.00");
SetDlgItemText(IDC_ADDON_DISCOUNT_PERCENT_BOX, "0.00");
ExecuteParamSql("DELETE FROM SupportDiscountsT WHERE SupportDiscountsT.PersonID = {INT}", m_id);
} else { //update their table information
CString str;
double temp, tempAddOn;
GetDlgItemText(IDC_DISCOUNT_PERCENT_BOX, str);
temp = atof(str);
GetDlgItemText(IDC_ADDON_DISCOUNT_PERCENT_BOX, str);
tempAddOn = atof(str);
ExecuteParamSql("UPDATE SupportDiscountsT SET SupportDiscountsT.TypeID = {INT}, SupportDiscountsT.DiscountPercent = {DOUBLE}, "
"SupportDiscountsT.AddOnDiscountPercent = {DOUBLE} WHERE SupportDiscountsT.PersonID = {INT} \r\n " //update
"IF @@ROWCOUNT = 0 \r\n " //if they aren't in the list
"INSERT INTO SupportDiscountsT (TypeID, PersonID, DiscountPercent, Note, Inactive, AddOnDiscountPercent) "
"VALUES ({INT}, {INT}, {DOUBLE}, '', 0, {DOUBLE})", nSelection, temp, tempAddOn, m_id, nSelection, m_id, temp, tempAddOn);
}
} NxCatchAll("Error saving discount type.");
}
// (a.wilson 2011-4-6) PLID 43355 - to prevent you from selecting the small space in the drop down which could cause errors.
void CSalesDlg::OnSelChangingDiscountType(long FAR* nRow)
{
try {
if (*nRow==-1)
{
*nRow=m_pDiscountType->CurSel;
}
} NxCatchAll(__FUNCTION__);
}
//(a.wilson 2011-5-6) PLID 9702 - when you click the visit button you will be sent to the clients website.
void CSalesDlg::OnBnClickedVisitWebsite()
{
try {
CString strTemp;
GetDlgItemText(IDC_WEBSITE_BOX, strTemp); //get the url for the site.
if (strTemp != "") {
//executes the url and opens the website in internet explorer.
::ShellExecute(m_hWnd, _T("open"), strTemp, NULL, NULL, SW_SHOWNORMAL);
}
} NxCatchAll(__FUNCTION__);
}
// (j.armen 2011-06-28 12:02) - PLID 44342 - event handling for when label is clicked
LRESULT CSalesDlg::OnLabelClick(WPARAM wParam, LPARAM lParam)
{
try
{
UINT nIdc = (UINT)wParam;
switch(nIdc)
{
case IDC_SOCIETY_LABEL:
StoreSociety(m_society, IDC_SOCIETY_LABEL);
break;
default:
ASSERT(FALSE);
break;
}
}
NxCatchAll(__FUNCTION__);
return 0;
}
// (j.armen 2011-06-28 12:02) - PLID 44342- event handling for when mouse over label
BOOL CSalesDlg::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
{
try {
CPoint pt;
CRect rc;
GetCursorPos(&pt);
ScreenToClient(&pt);
if(m_nxlSocietyLabel.IsWindowVisible() && m_nxlSocietyLabel.IsWindowEnabled())
{
m_nxlSocietyLabel.GetWindowRect(rc);
ScreenToClient(&rc);
if(rc.PtInRect(pt))
{
SetCursor(GetLinkCursor());
return TRUE;
}
}
}NxCatchAll(__FUNCTION__);
return CNxDialog::OnSetCursor(pWnd, nHitTest, message);
}
|
7b254d9e5f970f534eba2c21240e422eabe53e5e | 017aa927dcdae9de383757cf61696dd7e1a61cce | /src/IniFile_ff.h | 0c35cd9a5e035cc377718d53de99755630a04811 | [
"MIT"
] | permissive | winginitau/FodderFactory | f12bb299f14dd1ea945411d79ab07af4e8373c2a | 78958c5f7eda92d521ce0c936ccf97d1b7f245a7 | refs/heads/master | 2021-06-18T13:00:25.046326 | 2019-08-11T00:42:10 | 2019-08-11T00:42:10 | 103,604,580 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,993 | h | IniFile_ff.h | #ifndef _INIFILE_H
#define _INIFILE_H
#define INIFILE_VERSION "1.0.1 BM"
#include <build_config.h>
#include <HAL.h>
#include <stdint.h>
#include <stddef.h>
#ifdef PLATFORM_ARDUINO
//#include <SdFat.h>
#include "SD.h"
//#include "Ethernet.h"
#endif //PLATFORM_ARDUINO
#ifdef PLATFORM_LINUX
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#endif
class IniFileState;
class IniFile {
public:
enum error_t {
//enum {
errorNoError = 0,
errorFileNotFound,
errorFileNotOpen,
errorBufferTooSmall,
errorSeekError,
errorSectionNotFound,
errorKeyNotFound,
errorEndOfFile,
errorUnknownError,
};
static const uint8_t maxFilenameLen;
// Create an IniFile object. It isn't opened until open() is called on it.
#ifdef PLATFORM_ARDUINO
IniFile(const char* filename, uint8_t mode = FILE_READ, bool caseSensitive = false);
~IniFile();
#endif //PLATFORM_ARDUINO
#ifdef PLATFORM_LINUX
IniFile(const char* filename, char* mode, bool caseSensitive = false);
~IniFile();
#endif
inline bool open(void); // Returns true if open succeeded
inline void close(void);
inline bool isOpen(void) const;
inline error_t getError(void) const;
inline void clearError(void) const;
// Get the file mode (FILE_READ/FILE_WRITE)
#ifdef PLATFORM_ARDUINO
inline uint8_t getMode(void);
#endif //PLATFORM_ARDUINO
#ifdef PLATFORM_LINUX
inline char* getMode(void);
#endif
// Get the filename asscoiated with the ini file object
inline const char* getFilename(void) const;
bool validate(char* buffer, size_t len) const;
// Get value from the file, but split into many short tasks. Return
// value: false means continue, true means stop. Call getError() to
// find out if any error
bool getValue(const char* section, const char* key,
char* buffer, size_t len, IniFileState &state) const;
// Get value, as one big task. Return = true means value is present
// in buffer
bool getValue(const char* section, const char* key,
char* buffer, size_t len) const;
// Get the value as a string, storing the result in a new buffer
// (not the working buffer)
bool getValue(const char* section, const char* key,
char* buffer, size_t len, char *value, size_t vlen) const;
// Get a boolean value
bool getValue(const char* section, const char* key,
char* buffer, size_t len, bool& b) const;
// Get an integer value
bool getValue(const char* section, const char* key,
char* buffer, size_t len, int& val) const;
// Get a uint16_t value
bool getValue(const char* section, const char* key,
char* buffer, size_t len, uint16_t& val) const;
// Get a long value
bool getValue(const char* section, const char* key,
char* buffer, size_t len, long& val) const;
bool getValue(const char* section, const char* key,
char* buffer, size_t len, unsigned long& val) const;
// Get a float value
bool getValue(const char* section, const char* key,
char* buffer, size_t len, float& val) const;
/*
bool getIPAddress(const char* section, const char* key,
char* buffer, size_t len, uint8_t* ip) const;
#if defined(ARDUINO) && ARDUINO >= 100
bool getIPAddress(const char* section, const char* key,
char* buffer, size_t len, IPAddress& ip) const;
#endif
bool getMACAddress(const char* section, const char* key,
char* buffer, size_t len, uint8_t mac[6]) const;
*/
// Utility function to read a line from a file, make available to all
//static int8_t readLine(File &file, char *buffer, size_t len, uint32_t &pos);
#ifdef PLATFORM_ARDUINO
static error_t readLine(File &file, char *buffer, size_t len, uint32_t &pos);
#endif //PLATFORM_ARDUINO
#ifdef PLATFORM_LINUX
static error_t readLine(FILE* file, char *buffer, size_t len, uint32_t &pos);
#endif
static bool isCommentChar(char c);
static char* skipWhiteSpace(char* str);
static void removeTrailingWhiteSpace(char* str);
bool getCaseSensitive(void) const;
void setCaseSensitive(bool cs);
protected:
// True means stop looking, false means not yet found
bool findSection(const char* section, char* buffer, size_t len,
IniFileState &state) const;
bool findKey(const char* section, const char* key, char* buffer,
size_t len, char** keyptr, IniFileState &state) const;
private:
char _filename[INI_FILE_MAX_FILENAME_LEN];
#ifdef PLATFORM_ARDUINO
uint8_t _mode;
#endif //PLATFORM_ARDUINO
#ifdef PLATFORM_LINUX
char _mode[3];
#endif
mutable error_t _error;
#ifdef PLATFORM_ARDUINO
mutable File _file;
#endif //PLATFORM_ARDUINO
#ifdef PLATFORM_LINUX
mutable FILE* _file;
#endif
bool _caseSensitive;
};
bool IniFile::open(void)
{
if (_file)
#ifdef PLATFORM_ARDUINO
_file.close();
#endif //PLATFORM_ARDUINO
#ifdef PLATFORM_LINUX
fclose(_file); //used to be a problem here - now seems fixed
#endif
#ifdef PLATFORM_ARDUINO
_file = SD.open(_filename, _mode);
#endif //PLATFORM_ARDUINO
#ifdef PLATFORM_LINUX
_file = fopen(_filename, _mode);
#endif
if (isOpen()) {
_error = errorNoError;
return true;
}
else {
_error = errorFileNotFound;
return false;
}
}
void IniFile::close(void) {
#ifdef PLATFORM_ARDUINO
if (_file) {
_file.close();
SD.end();
}
#endif //PLATFORM_ARDUINO
#ifdef PLATFORM_LINUX
if (_file) {
fclose(_file);
_file = NULL;
}
#endif
}
bool IniFile::isOpen(void) const
{
return _file;
}
IniFile::error_t IniFile::getError(void) const
{
return _error;
}
void IniFile::clearError(void) const
{
_error = errorNoError;
}
#ifdef PLATFORM_ARDUINO
uint8_t IniFile::getMode(void)
{
return _mode;
}
#endif //PLATFORM_ARDUINO
#ifdef PLATFORM_LINUX
char* IniFile::getMode(void)
{
return _mode;
}
#endif
const char* IniFile::getFilename(void) const
{
return _filename;
}
class IniFileState {
public:
IniFileState();
private:
enum {funcUnset = 0,
funcFindSection,
funcFindKey,
};
uint32_t readLinePosition;
uint8_t getValueState;
friend class IniFile;
};
#endif
|
f43870ff4bcb0879756d0a40bd860304395dda73 | 7d7a3d894a863d4e022f2cbcb29a463d059b4692 | /main.cpp | 28a5e6d05f088bdfaebe89f307aba9efe359b5c5 | [] | no_license | panduhbyte/8Queens | 20845051829b8130cd778287b0a0a01ba8b998a3 | f3f1895f8d19a5adee08b2c3f0c3127e43fa9bd8 | refs/heads/master | 2021-06-28T22:17:37.804895 | 2017-09-21T05:43:26 | 2017-09-21T05:43:26 | 104,282,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 922 | cpp | main.cpp | #include <iostream>
using namespace std;
void trace(int, int); // Backtracks to find all possible solutions.
bool safe(int, int); // Returns true if no other Qs can attack
int row[10];
int main(){
trace(1,8);
return 0;
}
void trace(int xTwo,int board){
for(int xOne = 1 ; xOne <= board ;xOne++){
if(safe(xTwo, xOne)){
// Safely moving on to next row.
row[xTwo] = xOne;
if (xTwo==board){
cout<<row[1]<<row[2]<<row[3]<<row[4];
cout<<row[5]<<row[6]<<row[7]<<row[8]<<endl;
}else{
trace(xTwo+1,board);
}
}
}
}
bool safe(int xTwo , int xOne){
for(int yOne = 1; yOne<=(xTwo-1); yOne++){
// Checks if columns and diagonals are safe.
if((row[yOne] == xOne) || (abs(row[yOne] - xOne) == abs(yOne - xTwo))){
return false;
}
}
return true;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.