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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
702ce7167ba93e59df12d59328dc73fa89f0e370 | 749e6814d6488aea461676385780d847e07fd380 | /Core/GDCore/Project/MeasurementUnitElement.cpp | 98f4a258adfe045b14b10e0ecbfe44fdc364c1a4 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | 4ian/GDevelop | 258a007a2aa74bfd97c75a6c1753bc3fd48e634f | 134886eedcfaeaa04139463aaf826b71c11819c5 | refs/heads/master | 2023-08-18T23:14:56.149709 | 2023-08-18T20:39:40 | 2023-08-18T20:39:40 | 21,331,090 | 4,722 | 748 | NOASSERTION | 2023-09-14T21:40:54 | 2014-06-29T19:58:38 | JavaScript | UTF-8 | C++ | false | false | 385 | cpp | MeasurementUnitElement.cpp | /*
* GDevelop Core
* Copyright 2008-present Florian Rival (Florian.Rival@gmail.com). All rights
* reserved. This project is released under the MIT License.
*/
#include "MeasurementUnitElement.h"
#include "GDCore/Serialization/SerializerElement.h"
#include "GDCore/String.h"
#include <vector>
namespace gd {
MeasurementUnitElement::~MeasurementUnitElement() {}
} // namespace gd
|
c39c41baec47d4f243a907e73926dcd098e9c320 | ffc0a33915a144af3aca54afe14685a2f9dbba85 | /Err.hpp | 991eedb059a315c9aaa628c3be25db8a201137a1 | [] | no_license | 3dik/MPong | b3b6d3ac8a1940c9fc903b313d10532a22ecce56 | 053603b288d7f29bde41fccb9f08834c3e8569a9 | refs/heads/master | 2021-01-23T07:59:59.212433 | 2013-06-14T13:43:33 | 2013-06-14T13:43:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,061 | hpp | Err.hpp | //Error class
#pragma once
#include <string>
#include <vector>
#include "Functions.hpp"
using std::wstring;
class Err
{
public:
Err ();
~Err ();
//Sets the type to function error object and the function name
Err (Err &ClassErr, wstring sName);
//Sets the type to class error object and the class name
bool SetClass (Err *pMainErr, wstring sName);
//Get the address of the main error object
Err *GetMain ();
//Is this object a class error object? Otherwise: Its function error object
bool IsClass ();
//Is an error occurred?
bool IsError ();
//Sets an error
bool Set (wstring sErr);
//Adds a function to the list of the class error object
void AddFunction (wstring sName);
//Erases the last function from the list of the class error object
void KickFunction ();
private:
std::vector<wstring> m_lsFunctions;
wstring m_sClassName;
Err * m_pMainErr; //Pointer to the main or class error object
bool m_bError;
};//Err
|
69316edb128ffbe5f9169dcf3b99e132522b65bc | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /live/src/model/StartPlaylistResult.cc | 40bddb21c05e43151908224e528a3d077285d9ac | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 2,593 | cc | StartPlaylistResult.cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/live/model/StartPlaylistResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Live;
using namespace AlibabaCloud::Live::Model;
StartPlaylistResult::StartPlaylistResult() :
ServiceResult()
{}
StartPlaylistResult::StartPlaylistResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
StartPlaylistResult::~StartPlaylistResult()
{}
void StartPlaylistResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto streamInfoNode = value["StreamInfo"];
if(!streamInfoNode["AppName"].isNull())
streamInfo_.appName = streamInfoNode["AppName"].asString();
if(!streamInfoNode["DomainName"].isNull())
streamInfo_.domainName = streamInfoNode["DomainName"].asString();
if(!streamInfoNode["StreamName"].isNull())
streamInfo_.streamName = streamInfoNode["StreamName"].asString();
auto allStreamsNode = streamInfoNode["Streams"]["Stream"];
for (auto streamInfoNodeStreamsStream : allStreamsNode)
{
StreamInfo::Stream streamObject;
if(!streamInfoNodeStreamsStream["Quality"].isNull())
streamObject.quality = streamInfoNodeStreamsStream["Quality"].asString();
if(!streamInfoNodeStreamsStream["PullFlvUrl"].isNull())
streamObject.pullFlvUrl = streamInfoNodeStreamsStream["PullFlvUrl"].asString();
if(!streamInfoNodeStreamsStream["PullM3U8Url"].isNull())
streamObject.pullM3U8Url = streamInfoNodeStreamsStream["PullM3U8Url"].asString();
if(!streamInfoNodeStreamsStream["PullRtmpUrl"].isNull())
streamObject.pullRtmpUrl = streamInfoNodeStreamsStream["PullRtmpUrl"].asString();
streamInfo_.streams.push_back(streamObject);
}
if(!value["ProgramId"].isNull())
programId_ = value["ProgramId"].asString();
}
StartPlaylistResult::StreamInfo StartPlaylistResult::getStreamInfo()const
{
return streamInfo_;
}
std::string StartPlaylistResult::getProgramId()const
{
return programId_;
}
|
6c76f300364a659dafb3ae32f41d61274d6fe634 | d66b6b20cd16f317f3a3581b2091e4800c63b6f9 | /src/mbgl/map/sprite.hpp | 32fa16de12befddbd834c3b7b821bea849134eab | [
"ISC",
"BSD-2-Clause"
] | permissive | mgdesign-fr/mapbox-gl-native | 229a3adbfc890a9c6f29c8faa6dee8cfcc8d037b | 244fe93f0e6610cd7d66e1f9fd08ca84cb0dd7b2 | refs/heads/master | 2021-01-16T23:02:54.919101 | 2015-09-01T13:48:46 | 2015-09-01T13:49:35 | 41,555,336 | 6 | 0 | null | 2015-08-28T15:39:54 | 2015-08-28T15:39:54 | null | UTF-8 | C++ | false | false | 1,185 | hpp | sprite.hpp | #ifndef MBGL_STYLE_SPRITE
#define MBGL_STYLE_SPRITE
#include <mbgl/annotation/sprite_parser.hpp>
#include <mbgl/util/image.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <mbgl/util/ptr.hpp>
#include <mbgl/storage/request.hpp>
#include <cstdint>
#include <atomic>
#include <iosfwd>
#include <string>
#include <unordered_map>
namespace mbgl {
class Request;
class Sprite : private util::noncopyable {
public:
struct Data {
std::string image;
std::string json;
};
class Observer {
public:
virtual ~Observer() = default;
virtual void onSpriteLoaded(const Sprites& sprites) = 0;
virtual void onSpriteLoadingFailed(std::exception_ptr error) = 0;
};
Sprite(const std::string& baseUrl, float pixelRatio);
~Sprite();
inline bool isLoaded() const {
return loaded;
}
const float pixelRatio;
void setObserver(Observer* observer);
private:
void emitSpriteLoadedIfComplete();
void emitSpriteLoadingFailed(const std::string& message);
struct Loader;
std::unique_ptr<Loader> loader;
bool loaded = false;
Observer* observer = nullptr;
};
} // namespace mbgl
#endif
|
b33d393e5eb077cbc8abca5de5797e5abaf5f715 | e84e19c5d52f511ae280bb02d2febb8e0650a116 | /code1288.cpp | 0f16ad2ffa73eab566f73c28d79bd2ec56a614cb | [] | no_license | AlJamilSuvo/LeetCode | 2e3afe0c588d003aa15ea3eb08a8d2ca381c35dd | 9ad26f2974ad4a41a9654a5564fe1ad27ae2463c | refs/heads/master | 2022-03-15T15:43:21.826485 | 2022-03-04T20:40:50 | 2022-03-04T20:40:50 | 174,458,244 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,103 | cpp | code1288.cpp | #include <bits/stdc++.h>
using namespace std;
class IntervalCmp
{
public:
bool operator()(const vector<int> &i1, const vector<int> &i2)
{
if (i1[0] == i2[0])
return i1[1] >= i2[1];
else
return i1[0] < i2[0];
}
};
class Solution
{
public:
int removeCoveredIntervals(vector<vector<int>> &intervals)
{
sort(intervals.begin(), intervals.end(), IntervalCmp());
vector<bool> isRemoved(intervals.size(), false);
int removedCnt = 0;
for (int i = 0; i < intervals.size() - 1; i++)
{
if (isRemoved[i])
continue;
for (int j = i + 1; j < intervals.size(); j++)
{
if (isRemoved[j])
continue;
if (intervals[j][0] >= intervals[i][1])
break;
if (intervals[j][1] <= intervals[i][1])
{
isRemoved[j] = true;
removedCnt += 1;
}
}
}
return intervals.size() - removedCnt;
}
}; |
d6e3aeac3d7f256a1a6deb8a60132edbff9dc16e | 320b3f12a4fe55a6b41d8154782c104bce7d967f | /protos/srm/2.2/n/n_srmMv.cpp | 6b8e7ef2ee44e08a1fabdbb4fcdcbb60bdd2d355 | [] | permissive | dCache/s2 | c513d4375951e5c488e75c1cd9489938f66dc757 | b84ce6a17b9fe36f0f7edf4615c5fc2dd925dd53 | refs/heads/master | 2021-05-24T03:44:25.497865 | 2020-08-27T09:57:11 | 2020-08-27T09:57:11 | 10,648,935 | 0 | 1 | BSD-3-Clause | 2018-02-18T09:52:46 | 2013-06-12T18:20:00 | C++ | UTF-8 | C++ | false | false | 2,704 | cpp | n_srmMv.cpp | #ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/types.h>
#ifdef DG_DIAGNOSE
#include "diagnose/dg.h"
#endif
#include "n_srm.h"
#include "srm2api.h"
#include "srm_soap27.h"
#include "constants.h"
#include "i18.h"
#include "sysdep.h" /* BOOL, STD_BUF, ... */
#include "free.h" /* FREE(), DELETE() */
#include "str.h" /* dq_param() */
#include <iostream> /* std::string, cout, endl, ... */
#include <sstream> /* ostringstream */
using namespace std;
/*
* srmMv request constuctor
*/
srmMv::srmMv()
{
init();
}
/*
* Initialise srmMv request
*/
void
srmMv::init()
{
/* request (parser/API) */
fromSURL = NULL;
toSURL = NULL;
/* response (parser) */
}
/*
* srmMv request copy constuctor
*/
srmMv::srmMv(Node &node)
{
init();
Node::init(node);
}
/*
* srmMv request destructor
*/
srmMv::~srmMv()
{
DM_DBG_I;
/* request (parser/API) */
DELETE(fromSURL);
DELETE(toSURL);
DELETE_VEC(storageSystemInfo.key);
DELETE_VEC(storageSystemInfo.value);
/* response (parser) */
DM_DBG_O;
}
/*
* Free process-related structures.
*/
void
srmMv::finish(Process *proc)
{
DM_DBG_I;
FREE_SRM_RET(Mv);
}
int
srmMv::exec(Process *proc)
{
#define EVAL_VEC_STR_MV(vec) vec = proc->eval_vec_str(srmMv::vec)
DM_DBG_I;
tStorageSystemInfo storageSystemInfo;
EVAL_VEC_STR_MV(storageSystemInfo.key);
EVAL_VEC_STR_MV(storageSystemInfo.value);
#ifdef SRM2_CALL
NEW_SRM_RET(Mv);
Mv(
soap,
EVAL2CSTR(srm_endpoint),
EVAL2CSTR(authorizationID),
EVAL2CSTR(fromSURL),
EVAL2CSTR(toSURL),
storageSystemInfo,
resp
);
#endif
DELETE_VEC(storageSystemInfo.key);
DELETE_VEC(storageSystemInfo.value);
/* matching */
if(!resp || !resp->srmMvResponse) {
DM_LOG(DM_N(1), "no SRM response\n");
RETURN(ERR_ERR);
}
RETURN(matchReturnStatus(resp->srmMvResponse->returnStatus, proc));
#undef EVAL_VEC_STR_MV
}
std::string
srmMv::toString(Process *proc)
{
#define EVAL_VEC_STR_MV(vec) EVAL_VEC_STR(srmMv,vec)
DM_DBG_I;
GET_SRM_RESP(Mv);
BOOL quote = TRUE;
std::stringstream ss;
tStorageSystemInfo_ storageSystemInfo;
EVAL_VEC_STR_MV(storageSystemInfo.key);
EVAL_VEC_STR_MV(storageSystemInfo.value);
/* request */
SS_SRM("srmMv");
SS_P_DQ(authorizationID);
SS_P_DQ(fromSURL);
SS_P_DQ(toSURL);
SS_VEC_DEL(storageSystemInfo.key);
SS_VEC_DEL(storageSystemInfo.value);
/* response (parser) */
SS_P_DQ(returnStatus.explanation);
SS_P_DQ(returnStatus.statusCode);
/* response (API) */
if(!resp || !resp->srmMvResponse) RETURN(ss.str());
SS_P_SRM_RETSTAT(resp->srmMvResponse);
RETURN(ss.str());
#undef EVAL_VEC_STR_MV
}
|
05ee6562fc5dfa3b2cfb46680116e3ce4a4bc3da | aedec0779dca9bf78daeeb7b30b0fe02dee139dc | /Modules/Image/include/mirtk/VoxelDomain.h | fae591e3b67160a2defd805955b84205d7db0679 | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | BioMedIA/MIRTK | ca92f52b60f7db98c16940cd427a898a461f856c | 973ce2fe3f9508dec68892dbf97cca39067aa3d6 | refs/heads/master | 2022-08-08T01:05:11.841458 | 2022-07-28T00:03:25 | 2022-07-28T10:18:00 | 48,962,880 | 171 | 78 | Apache-2.0 | 2022-07-28T10:18:01 | 2016-01-03T22:25:55 | C++ | UTF-8 | C++ | false | false | 9,195 | h | VoxelDomain.h | /*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2013-2015 Imperial College London
* Copyright 2013-2015 Andreas Schuh
*
* 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.
*/
#ifndef MIRTK_VoxelDomain_H
#define MIRTK_VoxelDomain_H
namespace mirtk {
/**
* Types which implement inside/outside image domain checks
*
* This namespace defines auxiliary types which implement inside/outside image
* domain checks for voxels as static methods. These types can be used as
* Domain template argument as used by the ForEachVoxelIf and ParallelForEachVoxelIf
* template functions to restrict the evaluation of the voxel function to a specific
* subdomain of the image(s). Moreover, if it is known how the subdomain is
* defined, e.g., by a binary mask, a background value, a lower foreground threshold,
* or an interpolation domain, a specialized inside/outside domain check is more
* efficient as it only needs to test one particular condition. The more generic
* default domain check has to evaluate multiple conditions to first decide
* how the domain is being defined and then evaluate the actual inside/outside
* condition for this domain. This requires multiple if-statements and can be
* expensive when all these if-statements have to be evaluated for each voxel.
* Therefore, whenever possible use a specialized domain check to focus on the
* condition that matters.
*
* Example:
* \code
* #include "mirtk/GenericImage.h"
* #include "mirtk/VoxelFunction.h"
* #include "mirtk/VoxelDomain.h"
*
* namespace mirtk {
*
*
* void ProcessImageVoxelByVoxel(GreyImage &image)
* {
* using namespace ForEachVoxelDomain;
* ForEachVoxelIf<AboveBackgroundLevel>(image, func);
* }
*
*
* } // namespace mirtk
* \endcode
*
* \note The last image passed to ForEachVoxelIf/ParallelForEachVoxelIf is
* the one which defines the image domain over which to iterate as it
* is often an output image. Therefore, this last image is passed on
* to the domain checks defined within the ImageDomain namespace.
*
*/
namespace ForEachVoxelDomain {
// -----------------------------------------------------------------------------
/**
* Checks if voxel is in foreground using BaseImage::IsForeground
*/
struct Foreground
{
static inline bool IsInside(const BaseImage &image, int idx, const void *)
{
return image.IsForeground(idx);
}
static inline bool IsInside(const BaseImage &image, int i, int j, int k, int l, const void *)
{
return image.IsForeground(i, j, k, l);
}
};
// -----------------------------------------------------------------------------
/**
* Checks if voxel is in foreground using background value of image
*/
struct NotBackgroundValue
{
template <class T>
static inline bool IsInside(const BaseImage &image, int, const T *p)
{
const double bg = image.GetBackgroundValueAsDouble();
return (*p != bg) && (bg == bg || *p == *p /*, i.e., not both NaN */);
}
template <class T>
static inline bool IsInside(const BaseImage &image, int, int, int, int, const T *p)
{
const double bg = image.GetBackgroundValueAsDouble();
return (*p != bg) && (bg == bg || *p == *p /*, i.e., not both NaN */);
}
};
// -----------------------------------------------------------------------------
/**
* Checks if voxel is in foreground using background value of image as threshold
*/
struct AboveBackgroundLevel
{
template <class T>
static inline bool IsInside(const BaseImage &image, int, const T *p)
{
const double bg = image.GetBackgroundValueAsDouble();
return (*p > bg) && (bg == bg || *p == *p /*, i.e., not both NaN */);
}
template <class T>
static inline bool IsInside(const BaseImage &image, int, int, int, int, const T *p)
{
const double bg = image.GetBackgroundValueAsDouble();
return (*p > bg) && (bg == bg || *p == *p /*, i.e., not both NaN */);
}
};
// -----------------------------------------------------------------------------
/**
* Checks if voxel is in background using BaseImage::IsBackground
*/
struct Background
{
static inline bool IsInside(const BaseImage &image, int idx, const void *)
{
return image.IsBackground(idx);
}
static inline bool IsInside(const BaseImage &image, int i, int j, int k, int l, const void *)
{
return image.IsBackground(i, j, k, l);
}
};
// -----------------------------------------------------------------------------
/**
* Checks if voxel is in background using background value of image
*/
struct BackgroundValue
{
template <class T>
static inline bool IsInside(const BaseImage &image, int, const T *p)
{
const double bg = image.GetBackgroundValueAsDouble();
return (*p == bg) || (bg != bg && *p != *p /*, i.e., both NaN */);
}
template <class T>
static inline bool IsInside(const BaseImage &image, int, int, int, int, const T *p)
{
const double bg = image.GetBackgroundValueAsDouble();
return (*p == bg) || (bg != bg && *p != *p /*, i.e., both NaN */);
}
};
// -----------------------------------------------------------------------------
/**
* Checks if voxel is in image domain using mask of image
*/
struct InMask
{
static inline bool IsInside(const BaseImage &image, int idx, const void *)
{
const BinaryImage * const mask = image.GetMask();
if (mask->GetT() > 1) {
return (mask->Get(idx) != BinaryPixel(0));
} else {
return (mask->Get(idx % (image.GetX() * image.GetY() * image.GetZ())) != BinaryPixel(0));
}
}
static inline bool IsInside(const BaseImage &image, int i, int j, int k, int l, const void *)
{
const BinaryImage * const mask = image.GetMask();
return (mask->Get(i, j, k, mask->GetT() > 1 ? l : 0) != BinaryPixel(0));
}
};
// -----------------------------------------------------------------------------
/**
* Checks if voxel is in image domain using mask of image (BaseImage::GetMask)
*
* Use this domain check if the foreground mask is never four-dimensional even
* when the image itself has multiple frames, channels, or vector components.
*/
struct InSpatialMask
{
static inline bool IsInside(const BaseImage &image, int idx, const void *)
{
return (image.GetMask()->Get(idx % (image.GetX() * image.GetY() * image.GetZ())) != BinaryPixel(0));
}
static inline bool IsInside(const BaseImage &image, int i, int j, int k, int, const void *)
{
return (image.GetMask()->Get(i, j, k) != BinaryPixel(0));
}
};
} // namespace ForEachVoxelDomain
/**
* Types which implement inside/outside image interpolation domain checks
*
* This namespace defines auxiliary types which implement inside/outside
* interpolation domain checks for (transformed) voxel coordinates as
* static methods. These types can be used, in particular, as InputDomain
* template argument of the voxel transformation functions derived from
* MultipleVoxelTransformation::BaseTransform.
*/
namespace InterpolationDomain {
// -----------------------------------------------------------------------------
/**
* Wraps call to InterpolateImageFunction::IsForeground
*
* Checks if voxel coordinates are inside the domain for which the interpolation
* is defined and also if all values required for interpolation are part of the
* foreground region of the image.
*/
struct Foreground
{
template <class InterpolateImageFunction>
static inline bool IsInside(InterpolateImageFunction *interpolator, const double &x, const double &y, const double &z)
{
return interpolator->IsForeground(x, y, z);
}
};
// -----------------------------------------------------------------------------
/**
* Wraps call to InterpolateImageFunction::IsInside
*
* Use as argument for the InputDomain template parameter of the voxel
* transformation functors to interpolate the input at a given transformed
* voxel when its coordinates are inside the domain for which the interpolation
* is well defined.
*
* More efficient then the default Foreground domain check, but only ensures that
* the transformed coordinates are within the interpolation domain of the input
* image(s). Can be used when background value of input images is very dominant,
* e.g., minimum negative value supported by scalar type, and thus interpolated
* values are below a certain threshold, or if influence of background values
* is considered negligible.
*/
struct Inside
{
template <class InterpolateImageFunction>
static inline bool IsInside(InterpolateImageFunction *interpolator, const double &x, const double &y, const double &z)
{
return interpolator->IsInside(x, y, z);
}
};
} // namespace InterpolationDomain
} // namespace mirtk
#endif // MIRTK_VoxelDomain_H
|
dab145932570254120aca4f66514f3b7e89e6402 | dee9c35a1279bf9087f0eaaed3d49a37e4ff8bac | /UDPBroadcastQTDemo-csdn/QTDemoUDPBroadcast-csdn/UDPTestClient/mainwindow.cpp | d900ee998f702bba6258eaf361c9c6e0389b8e82 | [] | no_license | jdb333333/qt-project | c6adf17f40bb617aeb65dfb1a9ca947a1c375298 | 89b9df82806ba07837b57669bf2d417cbb46c61d | refs/heads/master | 2020-04-08T06:52:45.613088 | 2018-11-26T05:40:20 | 2018-11-26T05:40:20 | 159,116,508 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,154 | cpp | mainwindow.cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QtNetwork>
#include<QLabel>
#include <QListWidget>
#include <QVBoxLayout>
#include <QListWidgetItem>
//#define GET_HOST_COMMAND "GetCYHost"
#define GET_HOST_COMMAND "GetIPAddr"
#define LOCAL_PORT 6000
#define DEST_PORT 6000
#define TRY_TIMES 1
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setWindowTitle("Client");
initList();
////////////////////////////////
initBroadcast();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::initBroadcast()
{
receiver = new QUdpSocket(this);
/////绑定,第一个参数为端口号,第二儿表示允许其它地址链接该广播
receiver->bind(LOCAL_PORT,QUdpSocket::ShareAddress);
//readyRead:每当有数据报来时发送这个信号
connect(receiver,SIGNAL(readyRead()),this,SLOT(processPengingDatagram()));
BroadcastGetIpCommand();
}
void MainWindow::BroadcastGetIpCommand()
{
//QByteArray datagram = "Hello World!";
QByteArray datagram = GET_HOST_COMMAND;
int times = TRY_TIMES;
while(times--)
{
//sender->writeDatagram(datagram.data(),datagram.size(),QHostAddress::Broadcast,1066);
receiver->writeDatagram(datagram.data(),datagram.size(),QHostAddress::Broadcast,DEST_PORT);
}
}
void MainWindow::initList()
{
label = new QLabel;
label->setFixedWidth(70);
label->setText("搜索到IP地址:");
mlistWidget = new QListWidget;
QVBoxLayout* layout = new QVBoxLayout;
QListWidgetItem* lst1 = new QListWidgetItem("searched ip list:", mlistWidget);
// QListWidgetItem* lst2 = new QListWidgetItem("decision", mlistWidget);
// QListWidgetItem* lst3 = new QListWidgetItem("document", mlistWidget);
// QListWidgetItem* lst4 = new QListWidgetItem("process", mlistWidget);
// QListWidgetItem* lst5 = new QListWidgetItem("printer", mlistWidget);
mlistWidget->insertItem(1, lst1);
// mlistWidget->insertItem(2, lst2);
// mlistWidget->insertItem(3, lst3);
// mlistWidget->insertItem(4, lst4);
// mlistWidget->insertItem(5, lst5);
//mlistWidget->show();
layout->addWidget(label);
layout->addWidget(mlistWidget);
QWidget *mainWidget = new QWidget;
mainWidget->setLayout(layout);
setCentralWidget(mainWidget);
}
void MainWindow::processPengingDatagram()
{
QString s;
//数据报不为空
while( receiver->hasPendingDatagrams() )
{
QByteArray datagram;
//datagram大小为等待处理数据报的大小才能就收数据;
datagram.resize( receiver->pendingDatagramSize() );
//接收数据报
receiver->readDatagram(datagram.data(),datagram.size());
//label->setText(datagram);
s = datagram;
qDebug() << "datagram = " << s;
addIpItem(datagram);
}
}
void MainWindow::addIpItem(QByteArray data)
{
QListWidgetItem* lst1 = new QListWidgetItem(data, mlistWidget);
mlistWidget->insertItem(1, lst1);
}
|
63ee8aab199c3e3345bd1caab521627bd28f6fb8 | 9ce12679092dfd823f7c62b0e2ea89c93e7fd765 | /AMproj.cpp | 7bd38370423f1e116a64fc4c5e7778f90d943839 | [] | no_license | ksynnott/Lyapunov_Exponent_Calculation_with_Kicks | 0b9a5d0a0cbdfa7c32c526f65374b885d7636b50 | 6f89d58a474bbe6a9dd16f567ccc3c0d8f68e149 | refs/heads/master | 2021-01-21T16:00:37.291908 | 2016-10-25T18:34:57 | 2016-10-25T18:34:57 | 68,705,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,604 | cpp | AMproj.cpp | #include "Attach.h"
// Helper Functions
void OutMat(vector <vector <double> > Mat);
void OutVec(vector <double> Vec);
void Matoutfile(vector <vector <double> > Mat ,std::string filename);
void Vecoutfile(vector <double> vec ,std::string filename);
void MatToVecOutFiles(vector <vector <double> > Mat ,std::string filename);
static inline void loadbarMain(unsigned int x, unsigned int n, unsigned int w);
static inline void loadbarMain(unsigned int x, unsigned int n, unsigned int w, clock_t start);
vector <double> normalize(vector<double> v);
// Set the parameters - important
void SetParameters(string filename);
void ExecuteScaling();
// Here are the updated systems with forcing included in the Jacobian
// when doing the linearization.
vector<double> ClassCPlanerWithJacobian(vector<double> ENvec);
vector<double> ClassCPlanerWithJacobian_Kicking_Instance(vector<double> ENvec, double Kick_Size);
vector<double> ClassBPlanerWithJacobian(vector<double> ENvec);
vector<double> ClassBPlanerWithJacobian_Kicking_Instance(vector<double> ENvec, double Kick_Size);
vector<long double> ClassBPlanerWithJacobian(vector<long double> ENvec);
vector<long double> ClassBPlanerWithJacobian_Kicking_Instance(vector<long double> ENvec, double Kick_Size);
// Need a get phi function as this can be tricky as atan function wont deal with the full circle
double GetPhi(vector<double> ENvec);
long double GetPhi(vector<long double> ENvec);
int main(){
cout << "Start the clock !!!\n";
clock_t t = clock();
SetParameters("Parameters.txt");
ExecuteScaling();
//****************************************************************************************
{
double TimeEvlo = ((double)NumOfNorm*NormStep*dt);
cout << "Total Number of steps: " << NumOfNorm*NormStep << endl;
// We are excuting on lig Scale
double kickitlg = log10(InKick);
double kickfnlg = log10(FinKick);
double dklg = (kickfnlg - kickitlg)/NKick;
//Now for the values we deal with
double runkit = log10(IrunK);
double runkfn = log10(FrunK);
int numRuns = (int)((runkfn - runkit)/dklg);
int vecsize = 3;
/*vector <double> p0(vecsize); vector <double> y0(vecsize);
p0[0] = 0.001; y0[0] = 1.0;
p0[1] = -0.001; y0[1] = -2.0;
p0[2] = 0.001; y0[2] = 3.0;
p0[3] = 0.001; y0[3] = 2.0;
p0[4] = 0.001; y0[4] = 5.1;*/
vector <double> p0(vecsize); vector <double> y0(vecsize);
p0[0] = -0.00001; y0[0] = -2.1;
p0[1] = -0.00001; y0[1] = 1.5;
p0[2] = -0.00001; y0[2] = 5.1;
vector<double> h;
vector<double> k;
clock_t st = clock();
for(int i = 0; i < numRuns; i++){
Lyapunov LyapLase(NormStep, dt, TransientTime, TimeEvlo, y0, p0);
double t_kick = pow(10, (runkit + i*dklg) );
//cout << t_kick << endl;
h.push_back(LyapLase.CalcBigLypunov_Kick_new(ClassBPlanerWithJacobian, ClassBPlanerWithJacobian_Kicking_Instance, t_kick, Perturb ));
k.push_back(runkit + i*dklg);
//break;
loadbarMain(i, NKick, 50, st);
}
string st0 = "LyapunovSlice_C_3_";
string st1 = "Kvals_C_3_";
string num = to_string(FlNum);
string ext = ".txt";
st0.append(num);
st0.append(ext);
st1.append(num);
st1.append(ext);
cout << st0 << endl;
Vecoutfile(h , st0);
Vecoutfile(k , st1);
}
//****************************************************************************************
cout << "Stop the clock !!!" << endl;
t = clock() - t;
cout << " It took me " << t << " clicks ( " << ((float)t)/CLOCKS_PER_SEC << " seconds). " << endl;
cout << "You are the weakest link—goodbye!" << endl;
cout << "Enter 0 to exit . . . ";
double kjkjkj = 0;
cin >> kjkjkj;
return 0;
}
//****************************************************************************************
vector<double> ClassCPlanerWithJacobian(vector<double> ENvec){
vector<double> f(10);
// Here, the dx/dt = f(x)
f[0] = - ENvec[0] - Dp*ENvec[1] - ENvec[3];
f[1] = - ENvec[1] + Dp*ENvec[0] + ENvec[2];
f[2] = Gpc*( -1*ENvec[2] + Dp*ENvec[3] + ENvec[1]*ENvec[4] );
f[3] = Gpc*( -1*ENvec[3] - Dp*ENvec[2] - ENvec[0]*ENvec[4] );
f[4] = Gnc*( Lambda - ENvec[4] + ENvec[3]*ENvec[0] - ENvec[2]*ENvec[1] );
// Jacobian
f[5] = (-1.0)*ENvec[5] + (-1.0*Dp)*ENvec[6] - ENvec[8];
f[6] = (Dp)*ENvec[5] + (-1.0)*ENvec[6] + ENvec[7];
f[7] = Gpc*( ENvec[4]*ENvec[6] - ENvec[7] + Dp*ENvec[8] + ENvec[1]*ENvec[9] );
f[8] = Gpc*( - ENvec[4]*ENvec[5] - Dp*ENvec[7] - ENvec[8] - ENvec[0]*ENvec[9] );
f[9] = Gnc*( ENvec[3]*ENvec[5] - ENvec[2]*ENvec[6] - ENvec[1]*ENvec[7] +
ENvec[0]*ENvec[8] - ENvec[9] );
f[0] = EquScal*f[0];
f[1] = EquScal*f[1];
f[2] = EquScal*f[2];
f[3] = EquScal*f[3];
f[4] = EquScal*f[4];
f[5] = EquScal*f[5];
f[6] = EquScal*f[6];
f[7] = EquScal*f[7];
f[8] = EquScal*f[8];
f[9] = EquScal*f[9];
return f;
}
vector<double> ClassCPlanerWithJacobian_Kicking_Instance(vector<double> ENvec, double Kick_Size){
vector<double> f(10);
// From Documentation "Linearization/Linearization.pdf" I am including the functions f_x(T) and f_y(T)
double phi = GetPhi(ENvec);
double f_x = Kick_Size*cos(phi)*sin(phi*NumPet);
double f_y = Kick_Size*sin(phi)*sin(phi*NumPet);
// Here, the dx/dt = f(x)
f[0] = ENvec[0] + f_x;
f[1] = ENvec[1] + f_y;
f[2] = ENvec[2];
f[3] = ENvec[3];
f[4] = ENvec[4];
// Again from Documentation "Linearization/Linearization.pdf" I am including the necessary differentials of f_x(T) and f_y(T)
double Dphi_Ex = (-ENvec[1])/( ENvec[0]*ENvec[0] + ENvec[1]*ENvec[1] );
double Dphi_Ey = ( ENvec[0])/( ENvec[0]*ENvec[0] + ENvec[1]*ENvec[1] );
double Df_xx = Dphi_Ex*Kick_Size*( NumPet*cos(phi)*cos(phi*NumPet) - sin(phi)*sin(phi*NumPet) );
double Df_xy = Dphi_Ey*Kick_Size*( NumPet*cos(phi)*cos(phi*NumPet) - sin(phi)*sin(phi*NumPet) );
double Df_yx = Dphi_Ex*Kick_Size*( NumPet*sin(phi)*cos(phi*NumPet) + cos(phi)*sin(phi*NumPet) );
double Df_yy = Dphi_Ey*Kick_Size*( NumPet*sin(phi)*cos(phi*NumPet) + cos(phi)*sin(phi*NumPet) );
// Jacobian
f[5] = ENvec[5] + Df_xx*ENvec[5] + Df_xy*ENvec[6];
f[6] = ENvec[6] + Df_yx*ENvec[5] + Df_yy*ENvec[6];
f[7] = ENvec[7];
f[8] = ENvec[8];
f[9] = ENvec[9];
return f;
}
//****************************************************************************************
vector<double> ClassBPlanerWithJacobian(vector<double> ENvec){
vector<double> f(6);
// Here, the dx/dt = f(x)
f[0] = ( (ENvec[2]/(1.0 + Dp*Dp)) - 1.0)*(ENvec[0] + Dp*ENvec[1]);
f[1] = ( (ENvec[2]/(1.0 + Dp*Dp)) - 1.0)*(ENvec[1] - Dp*ENvec[0]);
f[2] = Gnc*( Lambda - ENvec[2] - ((ENvec[0]*ENvec[0] + ENvec[1]*ENvec[1])*ENvec[2])/(1.0 + Dp*Dp));
// Jacobian
double alf = (ENvec[2]/(1 + Dp*Dp)) - 1.0;
double Lor = (1.0/(1.0 + Dp*Dp));
double EEE = ENvec[0]*ENvec[0] + ENvec[1]*ENvec[1];
f[3] = (alf)*ENvec[3] + (Dp*alf)*ENvec[4] + (ENvec[0] + Dp*ENvec[1])*Lor*ENvec[5];
f[4] = (-Dp*alf)*ENvec[3] + (alf)*ENvec[4] + (ENvec[1] - Dp*ENvec[0])*Lor*ENvec[5];
f[5] = -Gnc*( 2.0*ENvec[0]*ENvec[2]*Lor*ENvec[3] + 2.0*ENvec[1]*ENvec[2]*Lor*ENvec[4] + ENvec[5] + EEE*Lor*ENvec[5] );
f[0] = EquScal*f[0];
f[1] = EquScal*f[1];
f[2] = EquScal*f[2];
f[3] = EquScal*f[3];
f[4] = EquScal*f[4];
f[5] = EquScal*f[5];
return f;
}
vector<double> ClassBPlanerWithJacobian_Kicking_Instance(vector<double> ENvec, double Kick_Size){
// From Documentation "Linearization/Linearization.pdf" I am including the functions f_x(T) and f_y(T)
double phi = GetPhi(ENvec);
double f_x = Kick_Size*cos(phi)*sin(phi*NumPet);
double f_y = Kick_Size*sin(phi)*sin(phi*NumPet);
// Again from Documentation "Linearization/Linearization.pdf" I am including the necessary differentials of f_x(T) and f_y(T)
double Dphi_Ex = (-ENvec[1])/( ENvec[0]*ENvec[0] + ENvec[1]*ENvec[1] );
double Dphi_Ey = ( ENvec[0])/( ENvec[0]*ENvec[0] + ENvec[1]*ENvec[1] );
double Df_xx = Dphi_Ex*Kick_Size*( NumPet*cos(phi)*cos(phi*NumPet) - sin(phi)*sin(phi*NumPet) );
double Df_xy = Dphi_Ey*Kick_Size*( NumPet*cos(phi)*cos(phi*NumPet) - sin(phi)*sin(phi*NumPet) ); // d/d(Ey) fx(T)
double Df_yx = Dphi_Ex*Kick_Size*( NumPet*sin(phi)*cos(phi*NumPet) + cos(phi)*sin(phi*NumPet) ); // d/d(Ex) fy(T)
double Df_yy = Dphi_Ey*Kick_Size*( NumPet*sin(phi)*cos(phi*NumPet) + cos(phi)*sin(phi*NumPet) );
vector<double> f(6);
f[0] = ENvec[0] + f_x;
f[1] = ENvec[1] + f_y;
f[2] = ENvec[2];
f[3] = ENvec[3] + ENvec[3]*Df_xx + ENvec[4]*Df_xy;
f[4] = ENvec[4] + ENvec[3]*Df_yx + ENvec[4]*Df_yy;
f[5] = ENvec[5];
return f;
}
//****************************************************************************************
vector<long double> ClassBPlanerWithJacobian(vector<long double> ENvec){
vector<long double> f(6);
// Here, the dx/dt = f(x)
f[0] = ( (ENvec[2]/(1.0 + Dp*Dp)) - 1.0)*(ENvec[0] + Dp*ENvec[1]);
f[1] = ( (ENvec[2]/(1.0 + Dp*Dp)) - 1.0)*(ENvec[1] - Dp*ENvec[0]);
f[2] = Gnc*( Lambda - ENvec[2] - ((ENvec[0]*ENvec[0] + ENvec[1]*ENvec[1])*ENvec[2])/(1.0 + Dp*Dp));
// Jacobian
long double alf = (ENvec[2]/(1 + Dp*Dp)) - 1.0;
long double Lor = (1.0/(1.0 + Dp*Dp));
long double EEE = ENvec[0]*ENvec[0] + ENvec[1]*ENvec[1];
f[3] = (alf)*ENvec[3] + (Dp*alf)*ENvec[4] + (ENvec[0] + Dp*ENvec[1])*Lor*ENvec[5];
f[4] = (-Dp*alf)*ENvec[3] + (alf)*ENvec[4] + (ENvec[1] - Dp*ENvec[0])*Lor*ENvec[5];
f[5] = -Gnc*( 2.0*ENvec[0]*ENvec[2]*Lor*ENvec[3] + 2.0*ENvec[1]*ENvec[2]*Lor*ENvec[4] + ENvec[5] + EEE*Lor*ENvec[5] );
f[0] = EquScal*f[0];
f[1] = EquScal*f[1];
f[2] = EquScal*f[2];
f[3] = EquScal*f[3];
f[4] = EquScal*f[4];
f[5] = EquScal*f[5];
return f;
}
vector<long double> ClassBPlanerWithJacobian_Kicking_Instance(vector<long double> ENvec, double Kick_Size){
// From Documentation "Linearization/Linearization.pdf" I am including the functions f_x(T) and f_y(T)
long double phi = GetPhi(ENvec);
long double f_x = Kick_Size*cos(phi)*sin(phi*NumPet);
long double f_y = Kick_Size*sin(phi)*sin(phi*NumPet);
// Again from Documentation "Linearization/Linearization.pdf" I am including the necessary differentials of f_x(T) and f_y(T)
long double Dphi_Ex = (-ENvec[1])/( ENvec[0]*ENvec[0] + ENvec[1]*ENvec[1] );
long double Dphi_Ey = ( ENvec[0])/( ENvec[0]*ENvec[0] + ENvec[1]*ENvec[1] );
long double Df_xx = Dphi_Ex*Kick_Size*( NumPet*cos(phi)*cos(phi*NumPet) - sin(phi)*sin(phi*NumPet) );
long double Df_xy = Dphi_Ey*Kick_Size*( NumPet*cos(phi)*cos(phi*NumPet) - sin(phi)*sin(phi*NumPet) ); // d/d(Ey) fx(T)
long double Df_yx = Dphi_Ex*Kick_Size*( NumPet*sin(phi)*cos(phi*NumPet) + cos(phi)*sin(phi*NumPet) ); // d/d(Ex) fy(T)
long double Df_yy = Dphi_Ey*Kick_Size*( NumPet*sin(phi)*cos(phi*NumPet) + cos(phi)*sin(phi*NumPet) );
vector<long double> f(6);
f[0] = ENvec[0] + f_x;
f[1] = ENvec[1] + f_y;
f[2] = ENvec[2];
f[3] = ENvec[3] + ENvec[3]*Df_xx + ENvec[4]*Df_xy;
f[4] = ENvec[4] + ENvec[3]*Df_yx + ENvec[4]*Df_yy;
f[5] = ENvec[5];
return f;
}
//****************************************************************************************
void SetParameters(string filename){
fstream myfile(filename.c_str(), std::ios_base::in);
myfile >> Lambda >> Dp >> Gnc >> Gpc >> TransientTime >> dt >> InKick >> FinKick
>> NKick >> IrunK >> FrunK >> FlNum >> Perturb >> NumPet >> NormStep >> NumOfNorm >> EquScal;
myfile.close();
cout << " **** Parameters **** " << endl;
cout << "Lambda = " << Lambda << endl;
cout << "Dp = " << Dp << endl;
cout << "Gnc = " << Gnc << endl;
cout << "Gpc = " << Gpc << endl;
cout << "--------------------------------" << endl;
cout << "Transient Time = " << TransientTime << endl;
cout << "dt = " << dt << endl;
cout << "--------------------------------" << endl;
cout << "Now doing log scale:" << endl;
cout << "Initial Kick nonlog yet = " << InKick << endl;
cout << "Final Kick nonlog yet = " << FinKick << endl;
cout << "Num of diff intvls = " << NKick << endl;
cout << "Inital Kick for this run = " << IrunK << endl;
cout << "Final Kick for this run = " << FrunK << endl;
cout << "File Number = " << FlNum << endl;
cout << "Kick Size = " << Perturb << endl;
cout << "Number of petals = " << NumPet << endl;
cout << "--------------------------------" << endl;
cout << "Steps Till Normalize = " << NormStep << endl;
cout << "Num of Normalize = " << NumOfNorm << endl;
cout << "--------------------------------" << endl;
cout << "Equation Scaling = " << EquScal << endl;
cout << "*********************************" << endl;
}
void ExecuteScaling(){
// Scale all the time
dt = dt / EquScal;
TransientTime = TransientTime / EquScal;
InKick = InKick / EquScal;
FinKick = FinKick / EquScal;
dKick = dKick / EquScal;
IrunK = IrunK / EquScal;
FrunK = FrunK / EquScal;
}
//****************************************************************************************
double GetPhi(vector<double> ENvec){
double phi = fabs(atan(ENvec[1]/ENvec[0]));
if(ENvec[0] == 0){
if(ENvec[1] > 0 )
return PI/2.0;
else
return 3*PI/2.0;
}
else if( ENvec[0] > 0 && ENvec[1] >= 0 )
return phi;
else if( ENvec[0] < 0 && ENvec[1] >= 0 )
return PI - phi;
else if( ENvec[0] < 0 && ENvec[1] <= 0 )
return PI + phi;
else
return 2*PI - phi;
}
long double GetPhi(vector<long double> ENvec){
double phi = fabs(atan(ENvec[1]/ENvec[0]));
if(ENvec[0] == 0){
if(ENvec[1] > 0 )
return PI/2.0;
else
return 3*PI/2.0;
}
else if( ENvec[0] > 0 && ENvec[1] >= 0 )
return phi;
else if( ENvec[0] < 0 && ENvec[1] >= 0 )
return PI - phi;
else if( ENvec[0] < 0 && ENvec[1] <= 0 )
return PI + phi;
else
return 2*PI - phi;
}
//****************************************************************************************
void OutMat(vector <vector <double> > Mat){
for(int i = 0; i < (int)Mat[0].size(); i++){
for(int j = 0; j < (int)Mat.size(); j++){
cout << " " << Mat[j][i];
}
cout << "\n" << endl;
}
}
void OutVec(vector <double> Vec){
for(int j = 0; j < Vec.size(); j++){
cout << Vec[j] << endl;;
}
}
void Matoutfile(vector <vector <double> > Mat ,std::string filename){
std::ofstream ofile(filename.c_str(), std::ios::out);
ofile.precision(15);
for(int i = 0; i < (int)Mat.size(); i++)
{
for(int j = 0; j < (int)Mat[0].size(); j++)
{ofile << Mat[i][j] << " ";}
ofile << "\n";
}
ofile.close();
}
void Vecoutfile(vector <double> vec ,std::string filename){
std::ofstream ofile(filename.c_str(), std::ios::out);
ofile.precision(15);
for(int i = 0; i < (int)vec.size(); i++)
{
ofile << vec[i] << "\n";
}
ofile.close();
}
/*void MatToVecOutFiles(vector <vector <double> > Mat ,std::string filename){
ofstream sizefile("NumOfFiles.txt", std::ios::out);
sizefile << Mat.size() << "\n";
sizefile.close();
for(int j = 0; j < Mat.size(); j++){
vector<string> thisname;
thisname.push_back(filename);
string num = to_string(j);
thisname.push_back(num);
thisname.push_back(".txt");
string thefilename = thisname[0] + thisname[1] + thisname[2];
ofstream ofile(thefilename, std::ios::out);
ofile.precision(15);
for(int i = 0; i < (int)Mat[j].size(); i++)
{
ofile << Mat[j][i] << "\n";
}
ofile.close();
}
}
*/
static inline void loadbarMain(unsigned int x, unsigned int n, unsigned int w){
if ( (x != n) && (x % (n/100+1) != 0) ) return;
float ratio = x/(float)n;
int c = ratio * w;
cout << setw(3) << (int)(ratio*100) << "% [";
for (int x=0; x<c; x++) cout << "=";
for (int x=c; x<w; x++) cout << " ";
cout << "]\r" << flush;
}
static inline void loadbarMain(unsigned int x, unsigned int n, unsigned int w, clock_t start){
if ( (x != n) && (x % (n/100+1) != 0) ) return;
float ratio = x/(float)n;
int c = ratio * w;
clock_t current = clock();
double tinsec = ((float)current - start)/CLOCKS_PER_SEC;
double tinmin = tinsec/60.0;
double tin1per = tinmin/(ratio*100.0);
int trmper = ceil(int((100.0 - (ratio*100.0))*tin1per));
if(trmper < 0){
trmper = 0;
}
cout << setw(3) << (int)(ratio*100) << "% [";
for (int x=0; x<c; x++) cout << "=";
for (int x=c; x<w; x++) cout << " ";
cout << "] Estimated Time Remaining: " << trmper << "mins \r" << flush;
}
vector <double> normalize(vector<double> v){
double norm = 0.0;
for(int i = 0; i < (int)v.size(); i++){
norm = norm + v[i]*v[i];
}
norm = sqrt(norm);
vector<double> unitv;
for(int i = 0; i < (int)v.size(); i++){
unitv.push_back(v[i]/(double)norm);
}
return unitv;
}
|
fe80170625964962920fd7991f5f9e8c6fd2d188 | e99c20155e9b08c7e7598a3f85ccaedbd127f632 | / sjtu-project-pipe/thirdparties/VTK.Net/src/Imaging/vtkImageWrapPadDotNet.h | 0753927f9cbf8cfdba09f140587a8653d76e72f7 | [
"BSD-3-Clause"
] | permissive | unidevop/sjtu-project-pipe | 38f00462d501d9b1134ce736bdfbfe4f9d075e4a | 5a09f098db834d5276a2921d861ef549961decbe | refs/heads/master | 2020-05-16T21:32:47.772410 | 2012-03-19T01:24:14 | 2012-03-19T01:24:14 | 38,281,086 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,959 | h | vtkImageWrapPadDotNet.h | #pragma once
// managed includes
#include "vtkImagePadFilterDotNet.h"
// native includes
using namespace System;
namespace vtk {
public ref class vtkImageWrapPad : public vtkImagePadFilter
{
public:
// Did not wrap: static vtkImageWrapPad *New ();
// const char *GetClassName ();
System::String^ GetClassName();
// int IsA (const char *name);
int IsA(System::String^ name);
// vtkImageWrapPad *NewInstance ();
vtkImageWrapPad^ NewInstance();
// vtkImageWrapPad *SafeDownCast (vtkObject* o);
static vtkImageWrapPad^ SafeDownCast(vtkObject^ o);
// Did not wrap: vtkImageWrapPad ();
// Did not wrap: ~vtkImageWrapPad ();
// Did not wrap: void ComputeInputUpdateExtent (int inExt[6], int outExt[6], int wExt[6]);
// Did not wrap: void ThreadedRequestData (vtkInformation *request, vtkInformationVector *inputVector, vtkInformationVector *outputVector, vtkImageData *inData, vtkImageData *outData, int ext[6], int id);
// Did not wrap: vtkImageWrapPad (const vtkImageWrapPad &);
// Did not wrap: void vtkImageWrapPad
/// <summary>
/// This constructor is used to convert native pointers into managed wrapper classes.
/// </summary>
vtkImageWrapPad(System::IntPtr native, bool bConst);
/// <summary>
/// This constructor is called only by derived classes. It asks base classes not allocate a native instance.
/// </summary>
vtkImageWrapPad(bool donothing);
/// <summary>
/// This constructor creates a wrapper class. It is the one to call. /// </summary>
vtkImageWrapPad();
/// <summary>
/// This method calls Delete() on the native instance.
/// Use it to release resources in a timely fashion.
/// </summary>
/// <remarks>
/// If this method is not called, then the finalizer will
/// call Delete on this instance.
/// </remarks>
virtual ~vtkImageWrapPad();
};
} // end vtkImaging
|
a54417836f62d15ff510181633502180f6802f4f | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /chrome/browser/extensions/activity_log/activity_action_constants.h | 5f9c2a78bf3faeb8e90d42eb7f60fa71c64e20e6 | [
"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 | 1,220 | h | activity_action_constants.h | // Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// String constants used when logging data in the extension activity log.
#ifndef CHROME_BROWSER_EXTENSIONS_ACTIVITY_LOG_ACTIVITY_ACTION_CONSTANTS_H_
#define CHROME_BROWSER_EXTENSIONS_ACTIVITY_LOG_ACTIVITY_ACTION_CONSTANTS_H_
namespace activity_log_constants {
// Keys that may be used in the "other" attribute of an Action.
extern const char kActionDomVerb[];
extern const char kActionExtra[];
extern const char kActionPrerender[];
extern const char kActionWebRequest[];
// A string used in place of the real URL when the URL is hidden because it is
// in an incognito window. Extension activity logs mentioning kIncognitoUrl
// let the user know that an extension is manipulating incognito tabs without
// recording specific data about the pages.
extern const char kIncognitoUrl[];
// A string used as a placeholder for URLs which have been removed from the
// argument list and stored to the arg_url field.
extern const char kArgUrlPlaceholder[];
} // namespace activity_log_constants
#endif // CHROME_BROWSER_EXTENSIONS_ACTIVITY_LOG_ACTIVITY_ACTION_CONSTANTS_H_
|
7ca52f1c65a71b75d84a7ebba4f1afd1c96df2b9 | 7ff3ff25deee18dd7aa521ace6681e7f257a2133 | /Exceptions/absencemultigraphexception.h | 21c177b940d15f8fa83a31aa3787bda3d811e4aa | [] | no_license | LepilkinaElena/EasyRouting | 8d5c2c843fb496969830e2cd004e59a94c7192fc | 795a5ecec74bef3f00ecbeb25c46a4bcd6acd1de | refs/heads/master | 2021-01-10T16:54:40.647195 | 2016-05-16T11:38:21 | 2016-05-16T11:38:21 | 51,464,876 | 2 | 0 | null | 2016-05-15T21:48:45 | 2016-02-10T19:10:41 | C++ | UTF-8 | C++ | false | false | 373 | h | absencemultigraphexception.h | #ifndef ABSENCEMULTIGRAPHEXCEPTION_H
#define ABSENCEMULTIGRAPHEXCEPTION_H
#include <exception>
#include <string>
class AbsenceMultigraphException : public std::exception
{
protected:
std::string message;
public:
explicit AbsenceMultigraphException(const std::string& message = "");
const char* what() const throw();
};
#endif // ABSENCEMULTIGRAPHEXCEPTION_H
|
409db420947491aa7e39b8f014625fffe33cb7d7 | 5fa8ea197fb870ed933919670c32d20afb7c8189 | /binary_tree_least_common_ancestor.cpp | 44e5d8d45c4e594e5210af1225dffc953d1ad8b6 | [] | no_license | Attull/C_plus_plus_with_coding_block | ec4cf559e8c9631ff5a73b34b8e7e2c060366e94 | 6e31aa379b2595c879ceb9eb12489917f2221dea | refs/heads/master | 2020-11-24T04:23:52.086337 | 2020-09-27T03:19:17 | 2020-09-27T03:19:17 | 227,963,089 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,299 | cpp | binary_tree_least_common_ancestor.cpp | #include<iostream>
using namespace std;
class node
{
public:
int val;
node *left;
node *right;
node(int data)
{
val=data;
left=NULL;
right=NULL;
}
};
node* build_tree()
{
int data;
cin>>data;
if(data==-1)
{
return NULL;
}
node *root=new node(data);
root->left=build_tree();
root->right=build_tree();
return root;
}
node *lca(node *root,int a,int b)
{
if(root==NULL)
return NULL;
if(root->val==a || root->val==b)
return root;
//search in left and right subtree
node *left_ans=lca(root->left,a,b);
node *right_ans=lca(root->right,a,b);
if(left_ans!=NULL && right_ans!=NULL) //it means both a and is present on either side of root
return root;
if(left_ans!=NULL) //it means we get one a or b in left side so if return that node
{
return left_ans;
}
return right_ans;
}
int main()
{
node *root=build_tree();
int a,b;
cin>>a>>b;
cout<<"lca of "<<a<<" & "<<b<<" is :";
node *ans=lca(root,a,b);
cout<<ans->val;
return 0;
}
|
dde358b35881f1718eb90ad717849a56cf1d90f3 | 2d096ad8906696812feb9c7e536865421e91a900 | /plugins/HardInteractionInfo.h | 8194e3e2022efdd55230d5688526736c743d7d4e | [] | no_license | jpata/single-top | a4483acc52736575b6b7e1709f21bd727e29a1ef | 34794d155de25533baef1921f1bee69c31326296 | refs/heads/master | 2020-12-11T01:46:35.384249 | 2014-08-14T10:46:50 | 2014-08-14T12:09:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,952 | h | HardInteractionInfo.h | #pragma once
#include <UserCode/SingleTop/interface/GenParticle.h>
#include <FWCore/Framework/interface/EDAnalyzer.h>
#include <FWCore/Framework/interface/Event.h>
#include <FWCore/ParameterSet/interface/ParameterSet.h>
#include <FWCore/ParameterSet/interface/ConfigurationDescriptions.h>
#include <FWCore/ParameterSet/interface/ParameterSetDescription.h>
#include <FWCore/Utilities/interface/InputTag.h>
#include <FWCore/ServiceRegistry/interface/Service.h>
#include <CommonTools/UtilAlgos/interface/TFileService.h>
#include <TTree.h>
#include <vector>
/**
* \class HardInteractionInfo
* \author Andrey Popov
* \brief Stores particles from the hard interaction in a ROOT file
*
* Particles from the hard interaction are identified with their status, which is hard-coded to the
* value used in Pythia 6.
*/
class HardInteractionInfo: public edm::EDAnalyzer
{
public:
/// Constructor
HardInteractionInfo(edm::ParameterSet const &cfg);
public:
/// A method to verify plugin's configuration
static void fillDescriptions(edm::ConfigurationDescriptions &descriptions);
/// Creates the output tree
virtual void beginJob();
/// Reads the event and stores the relevant information in the output tree
virtual void analyze(edm::Event const &event, edm::EventSetup const &setup);
private:
/// A tag to access generator-level particles
edm::InputTag const genParticlesTag;
/// An object to handle the output ROOT file
edm::Service<TFileService> fileService;
/// Tree to be written in the output ROOT file
TTree *outTree;
/// Trimmed generator-level particles to be stored in the output file
std::vector<pec::GenParticle> storeParticles;
/**
* \brief An auxiliary pointer
*
* ROOT needs a variable with a pointer to an object to store the object in a tree.
*/
std::vector<pec::GenParticle> *storeParticlesPointer;
};
|
2f4ae0b3a41c5f18d343c121defc4a2ba17da61a | d612eb675e3197820f15bd749d5161773ab5c319 | /Sem. 11/PriorityQueue.h | 7e64d15fbb43aea97568bd2d2867565873d824ff | [] | no_license | ivanahristova/Data_structures_and_algorithms_FMI | 54ebfd87202bb92428a4fdacdd964043d22e1f1b | 58c70a26064bde536dc82064c1aee205e8a42dad | refs/heads/main | 2023-09-06T06:54:59.021135 | 2021-10-27T16:44:56 | 2021-10-27T16:44:56 | 423,717,480 | 1 | 0 | null | 2021-11-02T05:27:39 | 2021-11-02T05:27:38 | null | UTF-8 | C++ | false | false | 405 | h | PriorityQueue.h | #include <iostream>
#include <vector>
class PriorityQueue
{
int leftChild(int i);
int rightChild(int i);
int parent(int i);
void heapify(int ind);
std::vector<int> data;
void print_rec(int elIndex, int spaces);
public:
PriorityQueue() = default;
PriorityQueue(const std::vector<int>& v);
int get(); //Връща най-големият елемент.
void insert(int el);
void print();
};
|
1fe7e1123bcc8d5cb4a28bee324b1bc083debdba | 85edd16a14ed5c2aeb658c1763b30a7dc08b3095 | /Whisper/Source/BackEnd/Core/Source/Unit Tests/XIOUTest.cpp | 3130480785403cd0dc15ec5d854008cb8d75d162 | [
"MIT"
] | permissive | jesse99/whisper | 14a17f94de8fccad2ddc6e9abf9cfa5f40922d50 | c71c2da3d71463a59411b36730713f517934ffc4 | refs/heads/master | 2020-04-21T00:16:20.627290 | 2019-02-05T05:21:44 | 2019-02-05T05:21:44 | 169,191,357 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,113 | cpp | XIOUTest.cpp | /*
* File: XIOUTest.h
* Summary: XIOU and XThread unit test.
* Written by: Jesse Jones
*
* Copyright © 1999 Jesse Jones.
* This code is distributed under the zlib/libpng license (see License.txt for details).
*
* Change History (most recent first):
*
* $Log: XIOUTest.cpp,v $
* Revision 1.3 2000/11/12 07:55:34 jesjones
* Renamed the callback adaptor functions Bind. Removed the Procedure callback adaptors.
*
* Revision 1.2 2000/11/09 12:40:29 jesjones
* 1) Removed double CRs introduced during the initial checkin. 2) Changed the header comments to make it clearer that Whisper is using the zlib license agreement. 3) Added the Log keyword.
*
* <1> 5/31/99 JDJ Created
*/
#include <XWhisperHeader.h>
#include <XIOUTest.h>
#include <XBind.h>
#include <XThread.h>
#if MAC
#include <MSystemInfo.h>
#endif
namespace Whisper {
#if DEBUG
// ===================================================================================
// class XIOUTest
// ===================================================================================
//---------------------------------------------------------------
//
// XIOUTest::~XIOUTest
//
//---------------------------------------------------------------
XIOUTest::~XIOUTest()
{
}
//---------------------------------------------------------------
//
// XIOUTest::XIOUTest
//
//---------------------------------------------------------------
XIOUTest::XIOUTest() : XUnitTest(L"Backend", L"XIOU")
{
}
//---------------------------------------------------------------
//
// XIOUTest::OnTest
//
//---------------------------------------------------------------
void XIOUTest::OnTest()
{
#if MAC
if (!MSystemInfo::HasThreadMgr()) {
TRACE("Couldn't run the XIOU test (the Thread Manager isn't installed).\n\n");
return;
}
#endif
const double kEpsilon = 0.000001;
XIOU<double> result;
XCallback2<void, XIOU<double>&, double> temp(this, &XIOUTest::DoComputePi);
XCallback0<void> function = Bind2(temp, result, kEpsilon);
XThread::ErrorHandler errors(&result, &XIOU<double>::Abort);
XThread* thread = XThread::Create(function, errors);
thread->Start();
thread->RemoveReference(); // XIOU's are ref counted so we don't need to hang onto the thread
result.Wait();
if (result.Redeemable())
TRACE("Completed XIOU test, pi = ", result.Redeem(), "\n\n");
else
TRACE(L"Couldn't compute pi. ", result.GetAbortText(), "\n");
}
//---------------------------------------------------------------
//
// XIOUTest::DoComputePi
//
// Uses the identity pi/4 = Sum[(-1)^k/(2*k + 1)] for k = 0 to infinity.
//
//---------------------------------------------------------------
void XIOUTest::DoComputePi(XIOU<double>& result, double epsilon)
{
double value = 0.0;
double delta;
uint32 i = 0;
do {
delta = 1.0/(2*i + 1);
value += delta;
++i;
delta = 1.0/(2*i + 1);
value -= delta;
++i;
// throw std::bad_alloc();
XThread::Yield();
} while (delta > epsilon*value && i < ULONG_MAX-2);
result.Fulfill(4.0*value);
}
#endif // DEBUG
} // namespace Whisper
|
d742908635bf8ef5ffa4b381296a4ceba0cd185b | a756eed9030c5afa645436412d777a1774357c70 | /CP/loc.cpp | 321777c87ab8f36c6db54e9031b694f45e857e11 | [] | no_license | jainsourav43/DSA | fc92faa7f8e95151c8f0af4c69228d4db7e1e5ce | deb46f70a1968b44bb28389d01b35cb571a8c293 | refs/heads/master | 2021-05-25T09:13:42.418930 | 2020-06-30T07:36:56 | 2020-06-30T07:36:56 | 126,943,860 | 0 | 1 | null | 2020-06-30T07:36:57 | 2018-03-27T07:07:51 | C++ | UTF-8 | C++ | false | false | 603 | cpp | loc.cpp | #include<iostream>
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
while(1)
{
ll w,b,n;
cin>>w>>b;
if(w==-1&&b==-1)
{
break;
}
cin>>n;
ll i,x[n],y[n],r[n],y1[n],y2[n];
for(i=0;i<n;i++)
{
cin>>x[i]>>y[i]>>r[i];
y1[i]=y[i]+r[i];
y2[i]=y[i]-r[i];
}
ll max=0,p=0,count=0,j;
for(i=0;i<n;i++)
{
count=0;
for(j=0;j<n;j++)
{
if(y2[j]<=y1[i]&&)
{
count1++;
}
else
{
count++;
}
}
if(count>max)
{
max=count;
}
}
cout<<max<<endl;
}
}
|
1cd548b32ce6e250e75ca6f4af7a5d1dcc4feece | aaad41597a60fbd3f39f5736189bd85385ef8aa3 | /src/Triangle.cpp | 4011db8f42fe11e429f843ca86dcefa8810563e2 | [] | no_license | DaanMiddelkoop/RayTraceEngine | 68a000d465449e652540a89d8e38ac92db8c56ce | 3339c3277b79ae3b1578578cfa3950a095c5c12c | refs/heads/master | 2020-08-07T12:10:47.684068 | 2019-11-12T15:37:50 | 2019-11-12T15:37:50 | 213,444,842 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 600 | cpp | Triangle.cpp | #include "Triangle.h"
#include <algorithm>
using namespace std;
Triangle::Triangle()
{
u1 = 0.0;
u2 = 1.0;
u3 = 2.0;
v1 = 0.0;
v2 = 2.0;
v3 = 0.0;
w1 = 0;
w2 = 0;
w3 = 0;
material = -1;
}
float Triangle::minx() {
return min(x1, min(x2, x3));
}
float Triangle::miny() {
return min(y1, min(y2, y3));
}
float Triangle::minz() {
return min(z1, min(z2, z3));
}
float Triangle::maxx() {
return max(x1, max(x2, x3));
}
float Triangle::maxy() {
return max(y1, max(y2, y3));
}
float Triangle::maxz() {
return max(z1, max(z2, z3));
}
|
aaa679344d86f0efcaaacc32ee74950a69689b28 | 033ada39d5a6212a9c4d0d5282c53c551d0e9c20 | /tests/test_comm-manager.cpp | facd20b969c0b1b5c4df69f2ce288c8402f7b571 | [
"BSL-1.0",
"Apache-2.0"
] | permissive | angelmaster6/ckm | 50db8765755837aa173bfd4e58ee7cce85429152 | a61e9ce01fa45323b381e6456d07117516d2e55d | refs/heads/master | 2020-07-19T09:12:32.128657 | 2016-01-08T12:32:28 | 2016-01-14T08:38:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,474 | cpp | test_comm-manager.cpp | /*
* Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
/*
* @file test_comm-manager.cpp
* @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
* @version 1.0
*/
#include <boost/test/unit_test.hpp>
#include <boost/test/results_reporter.hpp>
#include <communication-manager.h>
#include <string>
#include <random>
#include <chrono>
namespace {
struct MessageA {
MessageA(int ai) : i(ai) {}
int i;
};
struct MessageB {
MessageB(char ac) : c(ac) {}
char c;
};
struct MessageC {
MessageC(const std::string& astr) : str(astr) {}
std::string str;
};
struct Listener {
Listener() : i(0) {}
void Handle(const MessageA& msg) {
i = msg.i;
}
void Handle(const MessageC& msg) {
str = msg.str;
}
int i;
std::string str;
};
} // namespace anonymous
BOOST_AUTO_TEST_SUITE(MESSAGE_MANAGER_TEST)
BOOST_AUTO_TEST_CASE(TMM_0010_NoListener) {
CKM::CommunicationManager<MessageA> mgr;
BOOST_REQUIRE_MESSAGE(0 == mgr.SendMessage(MessageA(22)), "There should be no listener.");
}
BOOST_AUTO_TEST_CASE(TMM_0020_Basic) {
CKM::CommunicationManager<MessageA> mgr;
int received = 0;
mgr.Register<MessageA>([&](const MessageA& msg){ received = msg.i; });
BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageA(4)), "No listener found");
BOOST_REQUIRE_MESSAGE(received != 0, "Message not received");
BOOST_REQUIRE_MESSAGE(received == 4, "Wrong message received i=" << received);
}
BOOST_AUTO_TEST_CASE(TMM_0030_MultipleMessages) {
CKM::CommunicationManager<MessageA, MessageB> mgr;
int reci = 0;
char recc = 0;
mgr.Register<MessageA>([&](const MessageA& msg){ reci = msg.i; });
mgr.Register<MessageB>([&](const MessageB& msg){ recc = msg.c; });
BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageB('c')), "No listener found");
BOOST_REQUIRE_MESSAGE(reci == 0, "Unexpected message received");
BOOST_REQUIRE_MESSAGE(recc != 0, "Message not received");
BOOST_REQUIRE_MESSAGE(recc == 'c', "Wrong message received c=" << recc);
BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageA(42)), "No listener found");
BOOST_REQUIRE_MESSAGE(reci!= 0, "Message not received");
BOOST_REQUIRE_MESSAGE(reci == 42, "Wrong message received i=" << reci);
BOOST_REQUIRE_MESSAGE(recc == 'c', "Previous message overwritten c=" << recc);
}
BOOST_AUTO_TEST_CASE(TMM_0040_Listener) {
CKM::CommunicationManager<MessageA, MessageB, MessageC> mgr;
Listener l;
mgr.Register<MessageC>([&](const MessageC& msg){ l.Handle(msg); });
mgr.Register<MessageA>([&](const MessageA& msg){ l.Handle(msg); });
BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageC("lorem ipsum")), "No listener found");
BOOST_REQUIRE_MESSAGE(l.i == 0, "Unexpected message received");
BOOST_REQUIRE_MESSAGE(!l.str.empty(), "Message not received");
BOOST_REQUIRE_MESSAGE(l.str == "lorem ipsum", "Wrong message received c=" << l.str);
BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageA(3)), "No listener found");
BOOST_REQUIRE_MESSAGE(l.i!= 0, "Message not received");
BOOST_REQUIRE_MESSAGE(l.i == 3, "Wrong message received i=" << l.i);
BOOST_REQUIRE_MESSAGE(l.str == "lorem ipsum", "Previous message overwritten str=" << l.str);
}
BOOST_AUTO_TEST_CASE(TMM_0050_2Listeners) {
CKM::CommunicationManager<MessageA> mgr;
bool called[2];
called[0] = false;
called[1] = false;
mgr.Register<MessageA>([&](const MessageA& msg){
BOOST_REQUIRE_MESSAGE(msg.i == 5, "Unexpected message received i=" << msg.i);
called[0] = true;
});
mgr.Register<MessageA>([&](const MessageA& msg){
BOOST_REQUIRE_MESSAGE(msg.i == 5, "Unexpected message received i=" << msg.i);
called[1] = true;
});
BOOST_REQUIRE_MESSAGE(2 == mgr.SendMessage(MessageA(5)), "No listener found");
BOOST_REQUIRE_MESSAGE(called[0], "First listener not called");
BOOST_REQUIRE_MESSAGE(called[1], "Second listener not called");
}
BOOST_AUTO_TEST_CASE(TMM_0060_Stress) {
CKM::CommunicationManager<MessageA, MessageB, MessageC> mgr;
std::default_random_engine generator(std::chrono::system_clock::now().time_since_epoch().count());
std::uniform_int_distribution<size_t> message_dist(0,2);
std::uniform_int_distribution<size_t> count_dist(1,10);
size_t a = 0;
size_t b = 0;
size_t c = 0;
mgr.Register<MessageA>([&](const MessageA& msg) {
BOOST_REQUIRE_MESSAGE(msg.i == 42, "Wrong message: " << msg.i);
a++;
});
mgr.Register<MessageB>([&](const MessageB& msg) {
BOOST_REQUIRE_MESSAGE(msg.c == 'c', "Wrong message: " << msg.c);
b++;
});
mgr.Register<MessageC>([&](const MessageC& msg) {
BOOST_REQUIRE_MESSAGE(msg.str == "lorem ipsum", "Wrong message: " << msg.str);
c++;
});
for (size_t i=0; i < 1000; i++)
{
size_t cnt = count_dist(generator);
for (size_t s = 0; s < cnt; s++) {
switch(message_dist(generator))
{
case 0:
BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageA(42)), "No listener found");
a--;
break;
case 1:
BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageB('c')), "No listener found");
b--;
break;
case 2:
BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageC("lorem ipsum")), "No listener found");
c--;
break;
default:
BOOST_FAIL("Unexpected message type");
}
}
}
BOOST_REQUIRE_MESSAGE(a == 0, "Unexpected number of MessageA: " << a);
BOOST_REQUIRE_MESSAGE(b == 0, "Unexpected number of MessageB: " << b);
BOOST_REQUIRE_MESSAGE(c == 0, "Unexpected number of MessageC: " << c);
}
BOOST_AUTO_TEST_SUITE_END()
|
32ae296d57d6b5490bd925f69be49978752c70bc | e1cd579c8dcd952cc338ce3684397eddb0920760 | /archive/3/xor2.cpp | 2804fe4cfda1108fdc1d9a21be70a73610a05e65 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | Aleshkev/algoritmika | 0b5de063870cb8a87654613241a204b534037079 | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | refs/heads/master | 2021-06-05T10:46:59.313945 | 2020-02-02T12:39:47 | 2020-02-02T12:39:47 | 148,994,588 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 794 | cpp | xor2.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long unsigned int I;
I xor_up_to(I n) {
switch(n % 4) {
case 0: return n;
case 1: return 1;
case 2: return n + 1;
case 3: return 0;
}
}
I rec(I m, I n) {
if(n - m == 1) {
return m ^ n;
} else {
I pivot = (m + n) / 2;
if(pivot + 1 == n) {
return rec(m, pivot) ^ n;
} else {
return rec(m, pivot) ^ rec(pivot + 1, n);
}
}
}
int main()
{
cout.sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
I n;
cin >> n;
for(I i = 0; i < n; ++i) {
I a, b;
cin >> a >> b;
//cout << (xor_up_to(a - 1) ^ xor_up_to(b)) << '\n';
cout << rec(a, b) << '\n';
}
return 0;
}
|
f311d7af73b80acf315dc1a93ed6b2461bef48e8 | 3c47ddab3cd13b053fb3e107c263c59ebd06db8a | /Proj/Copy.ino | 94abce08a3a8ebc9e017f1036dddc84f06d8f831 | [
"MIT"
] | permissive | MaxShalom/arduino | 60c57cee427413f28bd4e1ffb6eb14b15787899a | 6b3bf2dab581e3fcdf3cce1439e2bed3a13e2c5a | refs/heads/master | 2021-04-15T12:24:16.125182 | 2018-05-08T15:59:06 | 2018-05-08T15:59:06 | 126,357,387 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 733 | ino | Copy.ino |
// Initialize
int rowZero = 13; // the number of the LED pin
int rowFive = 12;
int buttonOne = 1; // the number of the Button pin
int buttonStateOne = 0; // Buttons
int row;
void setup() {
// put your setup code here, to run once:
pinMode(rowZero, OUTPUT);
pinMode(rowFive, OUTPUT);
pinMode(buttonOne, INPUT);
}
void loop() {
row = random(12, 14);
buttonStateOne = digitalRead(buttonOne);
digitalWrite(row, HIGH);
delay(2000);
if (rowZero == HIGH) {
if (buttonStateOne == HIGH) {
// turn LED off:
digitalWrite(rowZero, LOW);
}
}
if (rowFive == HIGH) {
if (buttonStateTwo == HIGH) {
// turn LED off:
digitalWrite(rowFive, LOW);
}
}
}
|
7c9b959d56c965db4b432905c08ad96dbea28666 | 8d7e3aa92278f1e89b55a371dddfbf542fc40daa | /include/circle_queue.h | 009b82bf04837d489f1879c2303bcb2a65c1964a | [] | no_license | young-forever/AQ_002_CONSOLE_RL_20200703 | 241962726db6d6362133f583d16d7a58861c4018 | e7d2a8804473c9366b4ac81d04f7884a412bd99e | refs/heads/master | 2022-11-15T09:54:44.823650 | 2020-07-06T08:37:34 | 2020-07-06T08:37:34 | 277,486,121 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,863 | h | circle_queue.h | #ifndef CIRCLE_QUEUE_H
#define CIRCLE_QUEUE_H
#include <vector>
template <class T>
class Circle_Queue
{
public:
Circle_Queue(int queueCapacity);
virtual ~Circle_Queue();//销毁队列
void ClearQueue();//清空队列
bool QueueEmpty();//判空队列
bool QueueFull();//判满队列
int QueueLength() const;//队列长度
bool EnQueue(T element);//新元素入队
bool DeQueue(T &element);//首元素出队
int get_tail();
int GetQueneFullLength();
std::vector<T> QueueTraverse(int cnt);//遍历队列,遍历cnt个数据
private:
T *m_pQueue;//队列数组指针
int m_iQueueLen;//队列元素个数
int m_iQueueCapacity;//队列数组容量
int m_iHead;
int m_iTail;
std::vector<T> data;
};
template <class T>
Circle_Queue<T>::Circle_Queue(int queueCapacity)
{
m_iQueueCapacity = queueCapacity;
m_pQueue = new T[m_iQueueCapacity];
ClearQueue();
}
template <class T>
Circle_Queue<T>::~Circle_Queue()
{
delete[] m_pQueue;
m_pQueue = nullptr;
}
template <class T>
void Circle_Queue<T>::ClearQueue()
{
m_iHead = 0;
m_iTail = 0;
m_iQueueLen = 0;
}
template <class T>
bool Circle_Queue<T>::QueueEmpty()
{
return m_iQueueLen == 0 ? true : false;
}
template <class T>
bool Circle_Queue<T>::QueueFull()
{
return m_iQueueLen == m_iQueueCapacity ? true : false;
}
template <class T>
bool Circle_Queue<T>::EnQueue(T element)
{
if (QueueFull())
{
T mr;
DeQueue(mr);
m_pQueue[m_iTail] = element;
m_iTail++;
m_iTail = m_iTail % m_iQueueCapacity;
m_iQueueLen++;
return false;
}
else {
m_pQueue[m_iTail] = element;
m_iTail++;
m_iTail = m_iTail % m_iQueueCapacity;
m_iQueueLen++;
return true;
}
}
template <class T>
bool Circle_Queue<T>::DeQueue(T &element) //传入引用是为了可以直接修改实参的值,
{
if (QueueEmpty())
{
return false;
}
else {
element = m_pQueue[m_iHead] ;
m_iHead++;
m_iHead = m_iHead % m_iQueueCapacity;
m_iQueueLen--;
return true;
}
}
template <class T>
int Circle_Queue<T>::get_tail()
{
return m_iTail;
}
template <class T>
int Circle_Queue<T>::GetQueneFullLength()
{
return m_iQueueCapacity;
}
template <class T>
std::vector<T> Circle_Queue<T>::QueueTraverse(int cnt)
{
int head;
if(cnt>=m_iQueueLen)
{
head = m_iHead;
cnt = m_iQueueLen;
}
else
{
head = (m_iHead + m_iQueueLen - cnt)%m_iQueueCapacity;
}
data.clear();
for (int i = head; i < head + cnt; i++)
{
data.append(m_pQueue[i%m_iQueueCapacity]);
}
return data;
}
template <class T>
int Circle_Queue<T>::QueueLength() const
{
return m_iQueueLen;
}
#endif // CIRCLE_QUEUE_H
|
3f7b0d2f6c2b238982381f72121b1617c704e06c | fa0c642ba67143982d3381f66c029690b6d2bd17 | /Source/Module/Graphic/Template/TGraphicScene.h | 68fd69fd502d1de7fc5f7dfff72f2ad6973f8374 | [
"MIT"
] | permissive | blockspacer/EasyGameEngine | 3f605fb2d5747ab250ef8929b0b60e5a41cf6966 | da0b0667138573948cbd2e90e56ece5c42cb0392 | refs/heads/master | 2023-05-05T20:01:31.532452 | 2021-06-01T13:35:54 | 2021-06-01T13:35:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,630 | h | TGraphicScene.h | //! @file TGraphicScene.h
//! @author LiCode
//! @version 1.1
//! @date 2007.10
//! Copyright ...
#pragma once
namespace EGE
{
//----------------------------------------------------------------------------
// TGraphicScene
//----------------------------------------------------------------------------
template< typename Type >
class TGraphicScene : public INTERFACE_OBJECT_IMPL( Type )
{
protected:
//! The scissor rect info
template< typename DataType >
struct ScissorRectInfo
{
_ubool mEnable;
Rect< DataType > mRect;
ScissorRectInfo( )
{
mEnable = _false;
mRect = Rect< DataType >::cNull;
}
ScissorRectInfo( _ubool enable, const Rect< DataType >& rect )
{
mEnable = enable;
mRect = rect;
}
};
typedef ScissorRectInfo< _dword > ScissorRectUInfo;
typedef ScissorRectInfo< _float > ScissorRectFInfo;
typedef Stack< ScissorRectUInfo > ScissorRectUStack;
typedef Stack< ScissorRectFInfo > ScissorRectFStack;
//! The overlay transform info.
struct OverlayTransformInfo
{
Matrix3 mTransform;
Matrix3 mInversedTransform;
OverlayTransformInfo( )
{
mTransform = Matrix3::cIdentity;
mInversedTransform = Matrix3::cIdentity;
}
OverlayTransformInfo( const Matrix3& transform )
{
mTransform = transform;
mInversedTransform = transform;
mInversedTransform.Inverse( );
}
};
typedef Stack< OverlayTransformInfo > OverlayTransformInfoStack;
//! The render slot stack
typedef Stack< _GRAPHIC_RENDER_QUEUE > RenderSlotStack;
protected:
//! The client size
PointU mClientSize;
//! The viewport of ratio
Viewport mViewport;
//! The environment's texture cube
IGraphicTextureCubeRef mEnvTextureCube;
//! The render slot stack
RenderSlotStack mRenderSlotStack;
//! The scissor rect stack
ScissorRectUStack mScissorRectStack;
//! The overlay scissor rect stack
ScissorRectFStack mOverlayScissorRectStack;
//! The overlay transform
OverlayTransformInfoStack mOverlayTransformStack;
//! The overlay world transform
Matrix4Stack mUserOrthoTransformStack;
//! The offset transform
Matrix4Stack mOffsetTransformStack;
//! The scene view
IGraphicSceneViewRef mSceneView;
//! Clear buffers operations
GraphicClearBuffersInfo mClearBuffersInfo;
protected:
//! Reset clear buffers operations.
_void ResetClearBuffersOperations( );
protected:
//! When update scissor rect.
virtual _void OnUpdateScissorRect( _ubool enable, const RectU& rect ) { }
protected:
TGraphicScene( );
virtual ~TGraphicScene( );
// IGraphicSceneDrawer Interface
public:
virtual _void SetScissorRect( _ubool enable, const RectU& rect ) override;
virtual _void GetScissorRect( _ubool& enable, RectU& rect ) const override;
virtual _void PushScissorRect( _ubool enable, const RectU& rect ) override;
virtual _void PopScissorRect( ) override;
virtual _void PushOverlayScissorRect( const RectF& rect ) override;
virtual _void PopOverlayScissorRect( ) override;
virtual _void PushOverlayTransform( const Matrix3& transform ) override;
virtual _void PopOverlayTransform( ) override;
virtual _void SetOverlayTransform( const Matrix3& transform ) override;
virtual const Matrix3& GetOverlayTransform( ) const override;
virtual _void PushUserOrthoTransform( const Matrix4& transform ) override;
virtual _void PopUserOrthoTransform( ) override;
virtual _void SetUserOrthoTransform( const Matrix4& transform ) override;
virtual const Matrix4& GetUserOrthoTransform( ) const override;
virtual _void PushOffsetTransform( const Matrix4& transform ) override;
virtual _void PopOffsetTransform( ) override;
virtual _void SetOffsetTransform( const Matrix4& transform ) override;
virtual const Matrix4& GetOffsetTransform( ) const override;
// IGraphicScene Interface
public:
virtual _void SetViewport( const Viewport& viewport ) override;
virtual const Viewport& GetViewport( ) const override;
virtual _void SetClientSize( const PointU& size ) override;
virtual const PointU& GetClientSize( ) const override;
virtual _void ClearRenderBuffers( _ubool clearcolor, const Color& color, _ubool cleardepth, _float depth, _ubool clearstencil, _dword stencil ) override;
virtual _void PresentRenderBuffers( ) override;
virtual _void PresentRenderBuffers( IGraphicCanvas* canvas ) override;
virtual _void SetSceneView( IGraphicSceneView* view ) override;
virtual IGraphicSceneView* GetSceneView( ) const override;
virtual _void PushRenderSlot( _GRAPHIC_RENDER_QUEUE slot ) override;
virtual _void PopRenderSlot( ) override;
virtual _void SetRenderSlot( _GRAPHIC_RENDER_QUEUE slot ) override;
virtual _GRAPHIC_RENDER_QUEUE GetRenderSlot( ) const override;
};
//----------------------------------------------------------------------------
// TGraphicScene Implementation
//----------------------------------------------------------------------------
template< typename Type >
TGraphicScene< Type >::TGraphicScene( )
{
mClientSize = PointU::cZeroPoint;
mScale = Vector2::cIdentity;
mViewport = Viewport::cNull;
mSceneView = GetGraphicResourceManager( )->CreateSceneView( );
mRenderSlotStack.Push( _GRS_TRANSPARENT );
mScissorRectStack.Push( ScissorRectUInfo( _false, RectU::cNull ) );
mOverlayScissorRectStack.Push( ScissorRectFInfo( _false, RectF::cNull ) );
mOverlayTransformStack.Push( OverlayTransformInfo( ) );
mUserOrthoTransformStack.Push( Matrix4::cIdentity );
mOffsetTransformStack.Push( Matrix4::cIdentity );
ResetClearBuffersOperations( );
// Enable check mesh visibility feature in default
EnableOptions( _GSO_ENABLE_CHECK_MESH_VISIBILITY, _true );
}
template< typename Type >
TGraphicScene< Type >::~TGraphicScene( )
{
}
template< typename Type >
_void TGraphicScene< Type >::ResetClearBuffersOperations( )
{
mClearBuffersInfo.Reset( );
}
template< typename Type >
_void TGraphicScene< Type >::SetScissorRect( _ubool enable, const RectU& rect )
{
ScissorRectUInfo& scissor_info = mScissorRectStack.Top( );
scissor_info.mEnable = enable;
scissor_info.mRect = rect;
OnUpdateScissorRect( enable, rect );
}
template< typename Type >
_void TGraphicScene< Type >::GetScissorRect( _ubool& enable, RectU& rect ) const
{
const ScissorRectUInfo& scissor_info = mScissorRectStack.Top( );
enable = scissor_info.mEnable;
rect = scissor_info.mRect;
}
template< typename Type >
_void TGraphicScene< Type >::PushScissorRect( _ubool enable, const RectU& rect )
{
mScissorRectStack.Push( ScissorRectUInfo( enable, rect ) );
OnUpdateScissorRect( enable, rect );
}
template< typename Type >
_void TGraphicScene< Type >::PopScissorRect( )
{
// At least we have one scissor rect info
if ( mScissorRectStack.Number( ) == 1 )
return;
mScissorRectStack.Pop( );
const ScissorRectUInfo& scissor_info = mScissorRectStack.Top( );
OnUpdateScissorRect( scissor_info.mEnable, scissor_info.mRect );
}
template< typename Type >
_void TGraphicScene< Type >::PushOverlayScissorRect( const RectF& rect )
{
mOverlayScissorRectStack.Push( ScissorRectFInfo( _true, rect ) );
}
template< typename Type >
_void TGraphicScene< Type >::PopOverlayScissorRect( )
{
// At least we have one scissor rect info
EGE_ASSERT( mOverlayScissorRectStack.Number( ) != 1 );
mOverlayScissorRectStack.Pop( );
}
template< typename Type >
_void TGraphicScene< Type >::PushOverlayTransform( const Matrix3& transform )
{
mOverlayTransformStack.Push( OverlayTransformInfo( transform ) );
}
template< typename Type >
_void TGraphicScene< Type >::PopOverlayTransform( )
{
EGE_ASSERT( mOverlayTransformStack.Number( ) != 1 );
mOverlayTransformStack.Pop( );
}
template< typename Type >
_void TGraphicScene< Type >::SetOverlayTransform( const Matrix3& transform )
{
mOverlayTransformStack.Top( ) = OverlayTransformInfo( transform );
}
template< typename Type >
const Matrix3& TGraphicScene< Type >::GetOverlayTransform( ) const
{
return mOverlayTransformStack.Top( ).mTransform;
}
template< typename Type >
_void TGraphicScene< Type >::PushUserOrthoTransform( const Matrix4& transform )
{
mUserOrthoTransformStack.Push( transform );
}
template< typename Type >
_void TGraphicScene< Type >::PopUserOrthoTransform( )
{
EGE_ASSERT( mUserOrthoTransformStack.Number( ) != 1 );
mUserOrthoTransformStack.Pop( );
}
template< typename Type >
_void TGraphicScene< Type >::SetUserOrthoTransform( const Matrix4& transform )
{
mUserOrthoTransformStack.Top( ) = transform;
}
template< typename Type >
const Matrix4& TGraphicScene< Type >::GetUserOrthoTransform( ) const
{
return mUserOrthoTransformStack.Top( );
}
template< typename Type >
_void TGraphicScene< Type >::PushOffsetTransform( const Matrix4& transform )
{
mOffsetTransformStack.Push( transform );
}
template< typename Type >
_void TGraphicScene< Type >::PopOffsetTransform( )
{
EGE_ASSERT( mOffsetTransformStack.Number( ) != 1 );
mOffsetTransformStack.Pop( );
}
template< typename Type >
_void TGraphicScene< Type >::SetOffsetTransform( const Matrix4& transform )
{
mOffsetTransformStack.Top( ) = transform;
}
template< typename Type >
const Matrix4& TGraphicScene< Type >::GetOffsetTransform( ) const
{
return mOffsetTransformStack.Top( );
}
template< typename Type >
_void TGraphicScene< Type >::SetViewport( const Viewport& viewport )
{
mViewport = viewport;
}
template< typename Type >
const Viewport& TGraphicScene< Type >::GetViewport( ) const
{
return mViewport;
}
template< typename Type >
_void TGraphicScene< Type >::SetClientSize( const PointU& size )
{
// Update the viewport
mViewport = Viewport( 0.0f, 0.0f, (_float)size.x, (_float)size.y, 0.0f, 1.0f );
// Update client size
mClientSize = size;
}
template< typename Type >
const PointU& TGraphicScene< Type >::GetClientSize( ) const
{
return mClientSize;
}
template< typename Type >
_void TGraphicScene< Type >::ClearRenderBuffers( _ubool clearcolor, const Color& color, _ubool cleardepth, _float depth, _ubool clearstencil, _dword stencil )
{
mClearBuffersInfo.mIsClearColor = clearcolor;
mClearBuffersInfo.mIsClearDepth = cleardepth;
mClearBuffersInfo.mIsClearStencil = clearstencil;
mClearBuffersInfo.mClearColor = color;
mClearBuffersInfo.mClearDepth = depth;
mClearBuffersInfo.mClearStencil = stencil;
}
template< typename Type >
_void TGraphicScene< Type >::PresentRenderBuffers( )
{
}
template< typename Type >
_void TGraphicScene< Type >::PresentRenderBuffers( IGraphicCanvas* canvas )
{
}
template< typename Type >
_void TGraphicScene< Type >::SetSceneView( IGraphicSceneView* view )
{
mSceneView = view;
}
template< typename Type >
IGraphicSceneView* TGraphicScene< Type >::GetSceneView( ) const
{
return mSceneView.GetPtr( );
}
template< typename Type >
_void TGraphicScene< Type >::SetEnvTextureCube( IGraphicTextureCube* texture_cube )
{
mEnvTextureCube = texture_cube;
}
template< typename Type >
IGraphicTextureCube* TGraphicScene< Type >::GetEnvTextureCube( )
{
return mEnvTextureCube;
}
template< typename Type >
_void TGraphicScene< Type >::PushRenderSlot( _GRAPHIC_RENDER_QUEUE slot )
{
mRenderSlotStack.Push( slot );
}
template< typename Type >
_void TGraphicScene< Type >::PopRenderSlot( )
{
mRenderSlotStack.Pop( );
// The 'AUTO' render slot is our default setting
EGE_ASSERT( mRenderSlotStack.Number( ) != 0 );
}
template< typename Type >
_void TGraphicScene< Type >::SetRenderSlot( _GRAPHIC_RENDER_QUEUE slot )
{
mRenderSlotStack.Top( ) = slot;
}
template< typename Type >
_GRAPHIC_RENDER_QUEUE TGraphicScene< Type >::GetRenderSlot( ) const
{
return mRenderSlotStack.Top( );
}
} |
82a9e94286b2acc8ff5d04d46c5500237d585f24 | d6d6893f488941edfc5d244221583c63572d9d5f | /qtfred/src/ui/dialogs/TeamLoadoutDialog.cpp | bb3d0f236517d12b4c425320faaf1d7434d5141c | [
"Unlicense"
] | permissive | scp-fs2open/fs2open.github.com | 4170cc58b92577b41308a9e6343dd3fc3fb7a074 | 865f7e725c7a4d9c0b209a49ed0cbd8dc45e8ae7 | refs/heads/master | 2023-08-29T11:29:27.822804 | 2023-08-27T20:33:28 | 2023-08-27T20:33:28 | 7,700,081 | 382 | 311 | NOASSERTION | 2023-09-14T15:49:22 | 2013-01-19T06:10:53 | C++ | UTF-8 | C++ | false | false | 1,211 | cpp | TeamLoadoutDialog.cpp | #include "TeamLoadoutDialog.h"
#include "ui_TeamLoadoutDialog.h"
#include <QtWidgets/QMenuBar>
namespace fso {
namespace fred {
namespace dialogs {
TeamLoadoutDialog::TeamLoadoutDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::TeamLoadoutDialog)
{
ui->setupUi(this);
QMenuBar *menubar = new QMenuBar();
QMenu *teamMenu = new QMenu("Select Team");
teamMenu->addAction("Team 1");
teamMenu->addAction("Team 2");
QMenu *optionsMenu = new QMenu("Options");
optionsMenu->addAction("Balance Teams");
menubar->addMenu(teamMenu);
menubar->addMenu(optionsMenu);
ui->mainLayout->insertWidget(0,menubar);
/*
* Note: For the weapon and ship loadout listWidgest, will need to do something similar to the following during loading to
* add each ship and weapon option as a checkbox
QStringList itemLabels= getLabels();
QStringListIterator it(itemLabels);
while (it.hasNext())
{
QListWidgetItem *listItem = new QListWidgetItem(it.next(),listWidget);
listItem->setCheckState(Qt::Unchecked);
ui->listWidget->addItem(listItem);
}
*/
}
TeamLoadoutDialog::~TeamLoadoutDialog()
{
delete ui;
}
}
}
}
|
759144280ce62f0b8bb23d22c9a79f17c831a6fd | cbf187c628e9aef224c6cc432a3c63401567d6c7 | /interview/1.cpp | 1d16369bee438095776e0a0775f70b4b1ad3e521 | [] | no_license | WayKwin/WD_backup | 64bbddcd1fc8b64dd5d941766f9f66636aef5c5a | e2e0005b9f0e06bb20d4b9d0c86106e9e8842148 | refs/heads/master | 2020-03-10T03:56:44.044819 | 2018-08-30T15:30:54 | 2018-08-30T15:30:54 | 129,179,507 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 692 | cpp | 1.cpp | #include<stdio.h>
#include<iostream>
using namespace std;
#define Max(a,b) ((a) > (b) ? (a):(b))
union test
{
short a;
char buf[2];
};
class __TrueType
{
};
class __FalseType
{
};
template<class T>
struct _TypeTraits
{
typedef __FalseType IsPodType;
};
template< >
struct _TypeTraits<int>
{
typedef __TrueType IsPodType;
};
template<typename T>
void myadd(T&a, T&b,__TrueType f)
{
cout << "int called" << endl;
}
template<typename T>
void myadd( T&a, T&b, __FalseType f)
{
cout << "other called" << endl;
}
template<typename T>
T myadd(T& a, T&b)
{
return myadd(a,b,_TypeTraits<T>::IsPodType );
}
int main()
{
int a= 0;
int b = 0;
cout << myadd(a,b);
}
|
1c7ec5f14c17261279bb97e1f1d9451bf1064ed6 | 6ceecb13bbafc1657addef59953d68dab636590a | /app/models/distributed_accountancy/DistributedSubAccount.hpp | f542dda2461a8454f40c08b0bd6af5cc604b65cf | [] | no_license | Offirmo-graveyard/nomrpg | a2c243470843e86916939c75c6be2e12168c4a2b | dae552f4cccdc6341902a5ab7ddce3d494a4879e | refs/heads/master | 2020-12-14T18:54:41.619954 | 2015-02-14T18:18:17 | 2015-02-14T18:18:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,250 | hpp | DistributedSubAccount.hpp | /*
#include "DistributedSubAccount.hpp"
*/
#ifndef DISTRIBUTED_SUB_ACCOUNT_HPP_
#define DISTRIBUTED_SUB_ACCOUNT_HPP_
// ancestor classes
#include "NamedPersistableObject.hpp"
#include "TiedToDistributedAccount.hpp"
class DistributedSubAccount: public NamedPersistableObject, public TiedToDistributedAccount
{
public:
static const std::string cm_main_subaccount_name;
static const std::string cm_default_subaccount_name;
/* enum ToMainAccountRelation
{
IS_INTERNAL,
IS_EXTERNAL
};*/
DistributedSubAccount(const std::string& denomination = cm_default_subaccount_name);
DistributedSubAccount(const DistributedAccount& da, const std::string& denomination = cm_default_subaccount_name); //, enum ToMainAccountRelation ma_rel = DistributedSubAccount::IS_EXTERNAL);
virtual ~DistributedSubAccount();
//////////////////////////////////// DBO ////////////////////////////////////
// for STI (Single Type Inheritance). It MUST be equals to the class name.
virtual const std::string get_class_name() const { return "DistributedSubAccount"; }
//////////////////////////////////// DBO ////////////////////////////////////
protected:
//enum ToMainAccountRelation m_relation_to_main_account;
};
#endif /* DISTRIBUTED_SUB_ACCOUNT_HPP_ */
|
9d153d003933336ae0187efd9ffef356d9d89089 | 90c2869fe170f56e0ea0341832a63ca2a7f0d3f2 | /Day 8/Day8Learning.cpp | 6551621b4d5780ef888cb7df0e1b4c98982e6522 | [] | no_license | Majesty5/ET-575-C- | f0ff8c88ab45d33581118d2b3b55fcc09ac6bc13 | 4b6ec29662c7ec84cb20a943a8d3b761d81e5f2b | refs/heads/master | 2021-01-06T08:32:20.104164 | 2020-04-16T01:08:51 | 2020-04-16T01:08:51 | 241,262,227 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 593 | cpp | Day8Learning.cpp | #include <iostream>
#include <string>
using namespace std;
int main () {
cout << endl;
int n, x;
n= 5 + 4 * 3 -(2-1);
// 1
// 12
// 17
// 16
bool t = false; // 0 or false , !=0 or true
n = t = x =5 + 4;
cout << n << " " << t << " "<< x << endl;
cout << n << endl;
cout << endl << endl;
x=5;
n = -x + 5 * 4;
cout << n << endl;
cout << endl << endl;
int y = +5;
x = -y;
cout << x << endl;
cout << endl << endl;
//Generating Random Numbers
return 0;
}
|
5a93ec39710fbfac7d455940937dfb69ec8f71d8 | c51febc209233a9160f41913d895415704d2391f | /library/ATF/CLuaLootingMgrInfo.hpp | 8a72bcea44457c9e41737d66a54e83772a41a580 | [
"MIT"
] | permissive | roussukke/Yorozuya | 81f81e5e759ecae02c793e65d6c3acc504091bc3 | d9a44592b0714da1aebf492b64fdcb3fa072afe5 | refs/heads/master | 2023-07-08T03:23:00.584855 | 2023-06-29T08:20:25 | 2023-06-29T08:20:25 | 463,330,454 | 0 | 0 | MIT | 2022-02-24T23:15:01 | 2022-02-24T23:15:00 | null | UTF-8 | C++ | false | false | 1,935 | hpp | CLuaLootingMgrInfo.hpp | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <CLuaLootingMgr.hpp>
START_ATF_NAMESPACE
namespace Info
{
using CLuaLootingMgrAddNovusItem2_ptr = bool (WINAPIV*)(struct CLuaLootingMgr*, char*, struct CMapData*, uint16_t, float*, uint16_t, unsigned int, unsigned int, char);
using CLuaLootingMgrAddNovusItem2_clbk = bool (WINAPIV*)(struct CLuaLootingMgr*, char*, struct CMapData*, uint16_t, float*, uint16_t, unsigned int, unsigned int, char, CLuaLootingMgrAddNovusItem2_ptr);
using CLuaLootingMgrctor_CLuaLootingMgr4_ptr = void (WINAPIV*)(struct CLuaLootingMgr*);
using CLuaLootingMgrctor_CLuaLootingMgr4_clbk = void (WINAPIV*)(struct CLuaLootingMgr*, CLuaLootingMgrctor_CLuaLootingMgr4_ptr);
using CLuaLootingMgrDestroy6_ptr = void (WINAPIV*)();
using CLuaLootingMgrDestroy6_clbk = void (WINAPIV*)(CLuaLootingMgrDestroy6_ptr);
using CLuaLootingMgrInitSDM8_ptr = bool (WINAPIV*)(struct CLuaLootingMgr*, unsigned int, unsigned int);
using CLuaLootingMgrInitSDM8_clbk = bool (WINAPIV*)(struct CLuaLootingMgr*, unsigned int, unsigned int, CLuaLootingMgrInitSDM8_ptr);
using CLuaLootingMgrInstance10_ptr = struct CLuaLootingMgr* (WINAPIV*)();
using CLuaLootingMgrInstance10_clbk = struct CLuaLootingMgr* (WINAPIV*)(CLuaLootingMgrInstance10_ptr);
using CLuaLootingMgrLoop12_ptr = void (WINAPIV*)(struct CLuaLootingMgr*);
using CLuaLootingMgrLoop12_clbk = void (WINAPIV*)(struct CLuaLootingMgr*, CLuaLootingMgrLoop12_ptr);
using CLuaLootingMgrdtor_CLuaLootingMgr16_ptr = void (WINAPIV*)(struct CLuaLootingMgr*);
using CLuaLootingMgrdtor_CLuaLootingMgr16_clbk = void (WINAPIV*)(struct CLuaLootingMgr*, CLuaLootingMgrdtor_CLuaLootingMgr16_ptr);
}; // end namespace Info
END_ATF_NAMESPACE
|
387dcab7cb26f54cd6b909ddfa76e117f6358276 | 85490535042dabf6e25303adcd3e69e9fd425976 | /src/unit-tests/test-string-reader.cpp | 7f809cbdd5beb37a1296fdd7ee54e39ac0c4d104 | [
"Apache-2.0"
] | permissive | DalavanCloud/decompressor-prototype | 3185d03ee45ad81c111bae8c6c4d16a46c94ae99 | 44075ebeef75b950fdd9c0cd0b369928ef05a09c | refs/heads/master | 2020-04-24T12:39:12.132953 | 2017-05-29T17:07:42 | 2017-05-29T17:07:42 | 171,962,228 | 1 | 0 | null | 2019-02-21T23:39:19 | 2019-02-21T23:39:19 | null | UTF-8 | C++ | false | false | 1,815 | cpp | test-string-reader.cpp | // -*- C++ -*- */
//
// Copyright 2016 WebAssembly Community Group participants
//
// 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.
// Runs some basic tests on class StreamReader.
// Note: Requires gtest from https://github.com/google/googletest
#include "gtest/gtest.h"
#include "stream/StringReader.h"
namespace {
class StreamReaderTest : public ::testing::Test {
protected:
// You can remove any or all of the following functions if its body
// is empty.
};
using namespace wasm;
using namespace wasm::decode;
TEST(StreamReaderTest, ReadBlock) {
std::string Input("this is some text");
static constexpr size_t OverflowSize = 10;
for (size_t i = 0; i < Input.size() + OverflowSize; ++i) {
StringReader Reader(Input);
uint8_t Buffer[1024];
assert(size(Buffer) >= Input.size() + OverflowSize);
size_t Count = Reader.read(Buffer, i);
if (i <= Input.size()) {
EXPECT_EQ(i, Count) << "Did not fill reader as expected";
} else {
EXPECT_EQ(Count, Input.size())
<< "Did not read entire string as expected";
}
for (size_t j = 0; j < Count; j++) {
EXPECT_EQ(Buffer[j], uint8_t(Input[j])) << "Buffer filled incorrectly";
}
}
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
fce293000f860108ee85c6849557cfb315b4d9a0 | 44863355790a57f9935934ea467132fa09433d67 | /includes/garwor.h | 44ed2437d5bbda52e9e386646c9911b42a3cdfc5 | [] | no_license | Xiaoming94/WoW-TDA572 | b722f228b233bec92c648963577982f75bf4e305 | 3f7307122a6dd1e5a1a89c178d760300f4325942 | refs/heads/master | 2020-03-23T05:27:19.914442 | 2018-08-27T19:03:11 | 2018-08-27T19:03:11 | 141,144,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 203 | h | garwor.h | #ifndef GARWOR_H
#define GARWOR_H
class Garwor : public Monster
{
public:
std::string GetMonsterType()
{
return GARWOR;
}
Message GetCollideMessage()
{
return Message::GARWOR_HIT;
}
};
#endif |
4759b1f2a7d39c684cb389710ded7a024e80fcc1 | a7764174fb0351ea666faa9f3b5dfe304390a011 | /drv/StepBasic/StepBasic_PhysicallyModeledProductDefinition.ixx | ca91f2f96ddedd8ea1ac9bc16cce595ef7541bc9 | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 902 | ixx | StepBasic_PhysicallyModeledProductDefinition.ixx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#include <StepBasic_PhysicallyModeledProductDefinition.jxx>
#ifndef _Standard_Type_HeaderFile
#include <Standard_Type.hxx>
#endif
IMPLEMENT_STANDARD_TYPE(StepBasic_PhysicallyModeledProductDefinition)
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY()
STANDARD_TYPE(StepBasic_ProductDefinition),
STANDARD_TYPE(MMgt_TShared),
STANDARD_TYPE(Standard_Transient),
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY_END()
IMPLEMENT_STANDARD_TYPE_END(StepBasic_PhysicallyModeledProductDefinition)
IMPLEMENT_DOWNCAST(StepBasic_PhysicallyModeledProductDefinition,Standard_Transient)
IMPLEMENT_STANDARD_RTTI(StepBasic_PhysicallyModeledProductDefinition)
|
9a85876945c7820293af4476e4b3765da7c8b346 | 8da436fd0574a0808c24a6793f93e07b480ba81d | /test/jflags_declare_flags.cc | cd01b61d95c5417d52df4ffcbbac79c749c5e3f7 | [
"BSD-3-Clause"
] | permissive | jaydee-io/jflags | 5776c9d7833f2909d1b8f2f99fb24a0d00ae020b | 2c4e6387345faf502f8048f749d0c850276ec1a7 | refs/heads/master | 2021-01-17T21:23:03.808806 | 2016-10-30T18:10:54 | 2016-10-30T18:10:54 | 64,214,315 | 0 | 0 | NOASSERTION | 2018-09-28T13:53:41 | 2016-07-26T10:58:11 | C++ | UTF-8 | C++ | false | false | 234 | cc | jflags_declare_flags.cc | #define JFLAGS_DLL_DECLARE_FLAG
#include <iostream>
#include <jflags/jflags_declare.h>
DECLARE_string(message); // in jflags_delcare_test.cc
void print_message();
void print_message()
{
std::cout << FLAGS_message << std::endl;
}
|
fb00075bd0c9116f3e83584324de6a71f4046ed0 | 3a5eb86d4605bef00f69daeedc476b025847c90b | /TSHS/TSHS.cpp | d4f812ffa69f6e3f87a1b6f1a2b36ec860cacab0 | [] | no_license | TheColonelYoung/ALOHAL | 7e2732b0852a57a5ed3d3c90e3c3fe4dc52191ad | 4f857f7092bd8d7435f3e28125e62f72d19c65bb | refs/heads/master | 2023-04-05T05:14:49.615181 | 2021-06-16T17:00:50 | 2021-06-16T17:00:50 | 170,518,008 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 609 | cpp | TSHS.cpp | #include "TSHS.hpp"
TSHS::TSHS(ESP8266 *ESP)
: ESP(ESP){ }
int TSHS::Init(){
ESP->Init();
ESP->Set_rec_callback(&(this->Receive_callback));
Connect_to_network("wifi_is_coming", "ifyouplaythegameofthronesyouwinordie");
ESP->Estab_UDP("brodcast", 2008);
ESP->Send("TSHS");
return 0;
}
void TSHS::Receive_callback(){
Pin('C', 14).Toggle();
}
void TSHS::Connect_to_network(string SSID, string password){
ESP->Set_SSID(SSID);
ESP->Set_password(password);
ESP->Connect_to_AP();
}
int TSHS::Disconnect(){
// TODO Need to be done in ESP8266.hpp
return -95;
}
|
4a800ef75acf472053b04d13200387a1dd76af92 | ce29d99c84fc7a54d7eed578d9360dc266b01ff9 | /222/CF222C.cpp | 8d85d917d54972199f26db18f1f6031f6745c797 | [] | no_license | mruxim/codeforces | a3f8d28029a77ebc247d939adedc1d547bab0225 | 5a214b19a0d09c9152ca5b2ef9ff7e5dcc692c50 | refs/heads/master | 2021-10-26T04:33:42.553698 | 2019-04-10T12:58:21 | 2019-04-10T12:58:21 | 180,573,952 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,138 | cpp | CF222C.cpp | // .... .... .....!
// ...... ......!
// .... ....... ..... ..!
// ...... ... ... .... ... .... .....!
// ... .. ... .... ...?
#include<bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0, _n = (int)(n); i < _n; i++)
#define fer(i, x, n) for (int i = (int)(x), _n = (int)(n); i < _n; i++)
#define rof(i, n, x) for (int i = (int)(n), _x = (int)(x); i-- > _x; )
#define sz(x) (int((x).size()))
#define pb push_back
#define all(X) (X).begin(),(X).end()
#define X first
#define Y second
//#define endl '\n'
template<class P, class Q> inline void smin(P &a, Q b) { if (b < a) a = b; }
template<class P, class Q> inline void smax(P &a, Q b) { if (a < b) a = b; }
typedef long long ll;
typedef pair<int, int> pii;
////////////////////////////////////////////////////////////////////////////////
const int maxl = 10000000 + 100;
const int maxn = 100000 + 100;
int n, m;
int a[maxn], b[maxn];
bool ip[maxl];
vector<int> p;
vector<int> c;
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
cin >> n >> m;
rep(i, n) cin >> a[i];
rep(i, m) cin >> b[i];
fer(i, 2, 10000) if(!ip[i])
for(int j = i * i; j < maxl; j += i)
ip[j] = true;
fer(i, 2, maxl) if(!ip[i]) p.pb(i);
c.resize(sz(p));
rep(i, n) {
rep(j, sz(p)) {
if(p[j] * p[j] > a[i]) break;
while(a[i] % p[j] == 0) a[i] /= p[j], c[j]++;
}
if(a[i] > 1) c[lower_bound(all(p), a[i]) - p.begin()]++;
}
rep(i, n) {
rep(j, sz(p)) {
if(p[j] * p[j] > b[i]) break;
while(b[i] % p[j] == 0) b[i] /= p[j], c[j]--;
}
if(b[i] > 1) c[lower_bound(all(p), b[i]) - p.begin()]--;
}
vector<int> x, y;
int num = 1, den = 1;
rep(i, sz(p)) {
while(c[i] != 0) {
if(c[i] > 0) {
if(maxl / num >= p[i]) num *= p[i], c[i]--;
else x.pb(num), num = 1;
} else {
if(maxl / den >= p[i]) den *= p[i], c[i]++;
else y.pb(den), den = 1;
}
}
}
if(num > 1) x.pb(num);
if(den > 1) y.pb(den);
if(sz(x) == 0) x.pb(1);
if(sz(y) == 0) y.pb(1);
cout << sz(x) << ' ' << sz(y) << endl;
rep(i, sz(x)) cout << (i ? " " : "") << x[i]; cout << endl;
rep(i, sz(y)) cout << (i ? " " : "") << y[i]; cout << endl;
return 0;
}
|
ce8fa42f8bdfdb7852a84f84220622cf204c1e03 | bbb72525e14f41c56969d732c24f0d619a7923a0 | /tests/unit/functions/index.cpp | b2063a6d0dcbf980b5ba7d90c463472f7c1594bb | [] | no_license | Jori-Romans-Student/6502-CPU-Emulator | 2e7af2a1dc7272374bb0f955b1b10e6bbb18654d | 6c9ca57b8ddee36ff53e6abed04b0c5d97d1587f | refs/heads/main | 2023-06-03T23:18:18.591037 | 2021-06-16T01:05:17 | 2021-06-16T01:05:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 304 | cpp | index.cpp | // Byte Functions
#include "bytes/isAddedOverflow.cpp"
#include "bytes/isClear.cpp"
#include "bytes/isNegative.cpp"
#include "bytes/isOdd.cpp"
#include "bytes/isOverflow.cpp"
#include "bytes/isPositive.cpp"
#include "bytes/isSet.cpp"
#include "bytes/isSubtractedOverflow.cpp"
#include "bytes/isZero.cpp" |
ac732f5bcd9cb89bf1d9b7c93e357a35f59ecb91 | 69c3c068ceb0782ccb9569f7234cc44be4e4a798 | /lang/cpp/AltesCppZeug/AlterETHZCppKurs/U2/addtest.cpp | 283226329ff397967dce1359c97dde9400ecdb1d | [] | no_license | Irratzo/notes | cf0d99120855a333748e3320542aea0c7cc65b35 | aa7144591ae3dda9be8cf3107338318fcfa89eda | refs/heads/master | 2021-06-24T13:20:17.566262 | 2020-11-23T08:42:41 | 2020-11-23T08:42:41 | 171,057,556 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | addtest.cpp | using namespace std;
#include <iostream>
int main () {
int a=1;
double b=0.5;
cout << "Konsole + Konsole: " << 1 + 0.5 << endl;
cout << "Konsole + double: " << 1 + b << endl;
cout << "int + Konsole: " << a + 0.5 << endl;
cout << "int + double: " << a+ b << endl;
cout << endl;
cout << (15.0/6) << endl;
cout << (int) (15.0/6) << endl;
return 0;
}
|
57511c15ee66cd539467478203d69aa38b1bf80b | b6cfb2fd474d6d64743fe5f6387ef06673b68059 | /source/Acceleration/BVH.cpp | 5aa9793694f43e2c00fdfce91978e3c674058013 | [] | no_license | bareya/GeometryAcceleration | 9114ba9007102e9674f9dc36d8aeac34b5bbed7c | c99a433152ee473eab99cb83d56d7ad12de02d35 | refs/heads/master | 2020-07-04T13:08:23.857936 | 2019-08-14T07:14:26 | 2019-08-14T07:14:26 | 202,294,896 | 0 | 0 | null | 2019-08-14T20:13:35 | 2019-08-14T07:10:26 | C++ | UTF-8 | C++ | false | false | 6,217 | cpp | BVH.cpp | //
// MIT License
//
// Copyright (c) 2019 Piotr Barejko
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#include "BVH.h"
#include <Core/Math.h>
#include <Geometry/Face.h>
#include <algorithm>
#include <memory>
using Range = BVHNode::Range;
using SplitMethod = BVHAccelerator::SplitMethod;
namespace
{
///
/// TODO How long stack can go with imbalanced tree?
///
template <typename T, Index S = 256> class Stack
{
public:
Stack() = default;
void Push(const T& v) { s[size++] = v; }
void Push(T&& v) { s[size++] = std::move(v); }
T Pop() { return s[--size]; }
T Back() { return s[size-1]; }
Index Size() const { return size; }
bool Empty() const { return size == 0; }
void Clear() { size = 0; }
private:
T s[S]{};
Index size{};
};
struct PrimCache
{
PrimCache(const Prim& prim, Index i)
: index(i)
, centroid(prim.Centroid())
, bbox(prim.Bounds())
{
}
PrimCache(const PrimCache&) = default;
PrimCache(PrimCache&&) = default;
PrimCache& operator=(const PrimCache&) = default;
PrimCache& operator=(PrimCache&&) = default;
Index index;
Vector3 centroid;
AABBox bbox;
};
std::vector<PrimCache> create_prim_cache(const std::vector<const Prim*>& prims, AABBox& centroid_bbox)
{
std::vector<PrimCache> entries;
entries.reserve(prims.size());
// fill entries and compute box
for (auto it = prims.begin(); it != prims.end(); ++it)
{
const Prim* prim = *it;
entries.emplace_back(*prim, std::distance(prims.begin(), it));
centroid_bbox = ::Union(centroid_bbox, entries.back().bbox);
}
return entries;
}
// TODO move as a method of BVH node
void split_bbox(const AABBox& bbox, const Vector3 & p, Index axis, AABBox(&bboxes)[2])
{
Vector3 l_max = bbox.MaxPoint();
l_max[axis] = p[axis];
Vector3 r_min = bbox.MinPoint();
r_min[axis] = p[axis];
bboxes[0] = AABBox{ bbox.MinPoint(), l_max };
bboxes[1] = AABBox{ r_min, bbox.MaxPoint() };
}
} // namespace
BVHNode::BVHNode(Range r, AABBox b)
: range_(r)
, bbox_(b)
{
}
BVHAccelerator::BVHAccelerator(const std::vector<const Prim *>& prims, Index max_prims)
{
auto num_prims = static_cast<Index>(prims.size());
if (num_prims == 0)
{
return;
}
max_prims = max_prims == 0 ? 1 : max_prims;
// allocate space for all nodes
nodes_.reserve(2 * num_prims - 1);
// create root bvh node
AABBox centroid_bbox;
std::vector<PrimCache> entries = create_prim_cache(prims, centroid_bbox);
nodes_.emplace_back(Range{ 0, num_prims }, centroid_bbox);
Stack<BVHNode*, 256> stack;
stack.Push(&nodes_.back());
while (!stack.Empty())
{
// For DFS traversal we keep non leaf nodes on the stack
// Their bbox will be updated after drilling to the children is done
BVHNode* node = stack.Back();
// Sum bounding boxes for parent node
if (!node->IsLeaf())
{
AABBox children_bbox;
for (Index i{}; i < node->NumChildren(); ++i)
{
children_bbox = ::Union(children_bbox, node->GetChild(i)->GetBBox());
}
node->GetBBox() = children_bbox;
stack.Pop();
continue;
}
const Range& node_range = node->GetRange();
const Index num_node_entries = node->NumEntries();
// BVHNode leaf can group few entries, compute union for all of them from the range
if (num_node_entries <= max_prims)
{
AABBox leaf_bbox;
for (auto i = node_range.start; i < node_range.end; ++i)
{
leaf_bbox = ::Union(leaf_bbox, entries[i].bbox);
}
node->GetBBox() = leaf_bbox;
stack.Pop();
continue;
}
// Split Bounds into left and right
const AABBox& bbox = node->GetBBox();
const Index max_extent = bbox.MaxExtent();
auto centroid_cmp = [max_extent](const PrimCache& l, const PrimCache& r)
{
return l.centroid[max_extent] < r.centroid[max_extent];
};
// partial sort along longest extent
const Index median_index = node_range.start + static_cast<Index>(0.5 * num_node_entries);
std::nth_element(entries.begin() + node_range.start,
entries.begin() + median_index,
entries.begin() + node_range.end,
centroid_cmp);
// split to L - R
Range lr_range[2] = { { node_range.start, median_index }, { median_index, node_range.end } };
// median for box split
AABBox lr_bbox[2];
const PrimCache& median = entries[median_index];
split_bbox(bbox, median.centroid, max_extent, lr_bbox);
// append children
for (Index c{}; c < 2; ++c)
{
//auto new_size = lr_range[c].end - lr_range[c].start;
nodes_.emplace_back(lr_range[c], lr_bbox[c]);
BVHNode* child = &nodes_.back();
node->SetChild(c, child);
// put on top
stack.Push(child);
}
}
// move all nodes to
}
|
5f2ead1a982b273a49bf28b6e0ab35281672729d | 8ca3856744d74cd3c0f3eeabcecd24c5bac961e2 | /include/radio_player.h | 5dba1038a42f63a9d80a5c31094f0a28c8a009c3 | [] | no_license | dhxjb/HiLib | d99d93475d3db24351334c780f360a5127625d3c | 8b07c0f82f642baa04ac7f8c23d4e5bc22664c8f | refs/heads/master | 2022-11-07T10:02:00.661158 | 2020-06-23T07:37:48 | 2020-06-23T07:37:48 | 256,419,586 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,684 | h | radio_player.h | #ifndef __RADIO_PLAYER_H__
#define __RADIO_PLAYER_H__
#include "sdl_audio.h"
#include "audio_mixer.h"
namespace HiCreation
{
class TRadioPlayer
{
public:
TRadioPlayer(TSDLAudioRecord *radio_dev):
FRadioDev(radio_dev),
FAudioMixer(TAudioMixer::InstRef())
{}
~TRadioPlayer()
{
Close();
TAudioMixer::Release();
}
int Open(audio_params_t *audio_params)
{
int ret;
audio_params_t radio_params;
ret = FAudioMixer->Open(audio_params);
if (ret < 0)
return ret;
FAudioMixer->Params(&radio_params);
return FRadioDev->Open(&radio_params);
}
void Close()
{
if (! FRadioDev)
return;
FRadioDev->Close();
FAudioMixer->Remove(FRadioDev);
}
int Play()
{
if (! FRadioDev)
return -ENODEV;
FAudioMixer->Add(FRadioDev);
FRadioDev->Pause(0);
usleep(10 * 1000);
FAudioMixer->Pause(FRadioDev, 0);
return 0;
}
int Pause()
{
if (! FRadioDev)
return -ENODEV;
FRadioDev->Pause(1);
FAudioMixer->Pause(FRadioDev, 1);
return 0;
}
// to do...
int SetAudioParams(audio_params_t *params)
{ return 0; }
private:
TSDLAudioRecord *FRadioDev;
TAudioMixer *FAudioMixer;
};
};
#endif |
d50c226b9b4528b2e6266532a249b95ea52ed449 | 09f14385df362343d710570e9e851295118b9863 | /tempatureConverter/tempCon.cpp | db0516292a6ae7368db67e61f7220ee9fd1baeda | [] | no_license | enderweb/smallStuff | a7b74bf9c1c0c33ca072ba3b5abff456bbc326fb | f5d6380a6e3df5672c44fe3dbf5ac8b308f43df3 | refs/heads/main | 2023-03-17T14:21:41.740178 | 2021-03-13T15:37:04 | 2021-03-13T15:37:04 | 345,121,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 838 | cpp | tempCon.cpp |
#include <iostream>
using namespace std;
int main() {
int convert, intCel, intFah, finCel, finFah = 0;
cout << "Do you want to convert Celsius to Fahrenheit or Fahrenheit to Celsius? Type (1) to convert to Fahrenheit and (2) to convert to Celsius" << endl;
cin >> convert;
switch (convert)
case 1:
{
cout << "What tempature Celsius do you want to convert?" << endl;
cin >> intCel;
finFah = intCel * 9/5 + 32;
cout << "Your tempature is " << finFah << "°F" << endl;
break;
case 2:
cout << "What tempature Fahrenheit do you want to convert?" << endl;
cin >> intFah;
finCel = (intFah - 32) * 5/9;
cout << "Your tempature is " << finCel << "°C" << endl;
break;
default:
cout << "There has been an error. Please read the top bit before putting in a number because that is probably the thing that went wrong" << endl;
}
}
|
c1c01f5a02fcbc172cd413cc3cfc4c4f6cafdc32 | a5f5283abf4dec1584e0fa4465f212db8b72a82b | /GPU_SupportVectorMachine_Unmanaged/GPU_SupportVectorMachine_Unmanaged/SMOSet.h | 2e78dde57e132fc9ce0106aa25582092e2e24f14 | [] | no_license | nagyistoce/thesis-gpgpu-svm-computeshader | d4e636f32c0f5064c97cea08cc92d7f8ba8b47a3 | 4c1e115a57d55d118e1616f2d55f4860d8d39f97 | refs/heads/master | 2020-06-05T04:05:08.136384 | 2012-04-02T09:12:08 | 2012-04-02T09:12:08 | 32,892,551 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,287 | h | SMOSet.h | #pragma once
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
namespace SVM_Framework{
class SMOset{
public:
SMOset(unsigned int size){
m_indicators.assign(size,false);
m_next.assign(size,0);
m_previous.assign(size,0);
m_number = 0;
m_first = -1;
}
bool contains(unsigned int index){
return m_indicators[index];
}
void remove(int index) {
if (m_indicators[index]) {
if (m_first == index) {
m_first = m_next[index];
}
else {
m_next[m_previous[index]] = m_next[index];
}
if (m_next[index] != -1) {
m_previous[m_next[index]] = m_previous[index];
}
m_indicators[index] = false;
m_number--;
}
}
void insert(int index) {
if (!m_indicators[index]) {
if (m_number == 0) {
m_first = index;
m_next[index] = -1;
m_previous[index] = -1;
}
else{
m_previous[m_first] = index;
m_next[index] = m_first;
m_previous[index] = -1;
m_first = index;
}
m_indicators[index] = true;
m_number++;
}
}
int getNext(int index) {
if (index == -1) {
return m_first;
}
else {
return m_next[index];
}
}
int numElements() {
return m_number;
}
private:
/** The current number of elements in the set */
int m_number;
/** The first element in the set */
int m_first;
/** Indicators */
std::vector<bool> m_indicators;
/** The next element for each element */
std::vector<int> m_next;
/** The previous element for each element */
std::vector<int> m_previous;
};
}
typedef boost::shared_ptr<SVM_Framework::SMOset> SMOSetPtr; |
69174f044eab2104fc9c27afbb36508d391cd396 | 588b7a5a487ca2ed68966d45ef0533f2890720e0 | /terminal/commands.cpp | ab6dd849ca29149e937beb3edb3f604727d49829 | [] | no_license | furterc/avr_shweeetController | e962443a82b40960945bd723b25a308ca39cda75 | 609b5d4f50d9906abba7e2bc836e7ca4510f91cd | refs/heads/master | 2020-05-21T02:31:32.375963 | 2017-10-25T20:57:12 | 2017-10-25T20:57:12 | 84,560,367 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 452 | cpp | commands.cpp | #include "terminal.h"
extern const dbg_entry btResetEntry;
extern const dbg_entry rebootEntry;
extern const dbg_entry btSendEntry;
extern const dbg_entry btCommandSendEntry;
extern const dbg_entry timeEntry;
extern const dbg_entry lightEntry;
extern const dbg_entry powerEntry;
const dbg_entry* dbg_entries[] =
{
&helpEntry,
&btResetEntry,
&rebootEntry,
&btSendEntry,
&btCommandSendEntry,
&timeEntry,
&lightEntry,
&powerEntry,
0
};
|
3dfedb5e6f0f7e5d32ffffddc4a8854dc7ce8216 | 6bf096324c07931a82a3009750566da096a176f4 | /Task_02/File.cpp | cbb76958ada5d7df6b64f874dc0c857785a2b781 | [] | no_license | chenxiaoyu233/SoftwareDevelopmentLecture | aca5ae44c2c2091cacf6b5d6a0b6ecf786c26025 | 27aa31a857c6a7ed435dbfdbb0c9da6be43a227a | refs/heads/master | 2021-08-31T22:12:12.526226 | 2017-12-23T04:32:04 | 2017-12-23T04:32:04 | 109,772,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | cpp | File.cpp | #include "Automaton.h"
#include <cstdio>
using namespace std;
void saveGame(){
FILE *out = fopen("Maze", "w");
fprintf(out, "%d %d\n", N, M);
FOR(i, 1, N) {
FOR(j, 1, M){
fprintf(out, "%d ", w[i][j]);
} fprintf(out, "\n");
}
fprintf(out, "%f %f\n", Me.x, Me.y);
fclose(out);
}
void loadGame(){
FILE *in = fopen("Maze", "r");
fscanf(in, " %d%d", &N, &M);
FOR(i, 1, N) FOR(j, 1, M)
fscanf(in, " %d", &w[i][j]);
float x, y;
fscanf(in, " %f%f", &x, &y);
Me.setPosition(x, y);
fclose(in);
}
|
fda8ba31876b5eac5c680d8e5ab0d83b72e5f8f9 | b6d1df49c1ec621a02204b1100312ecbb3e76ad3 | /src/mains/JAV/draw_obj_bboxes.cc | 0d6b6ebcd6434933322a115bbff6dc649f937efb | [] | no_license | flylong0204/projects | 5271acde325cf3947fac7433077353b52fa07bc4 | b1e5c918d4aeb34c36576dababc5509dbb89afd1 | refs/heads/master | 2017-12-06T06:35:20.926786 | 2017-01-24T23:53:13 | 2017-01-24T23:53:13 | 79,988,197 | 1 | 2 | null | 2017-01-25T06:11:23 | 2017-01-25T06:11:23 | null | UTF-8 | C++ | false | false | 5,010 | cc | draw_obj_bboxes.cc | // ========================================================================
// Program DRAW_OBJ_BBOXES imports a bounding box parameters for a set
// of images. It draws purple rectangles on copies of the input
// images and exports the annotated results to a new subdirectory.
// ./draw_obj_bboxes
// ========================================================================
// Last updated on 11/27/13; 11/28/13; 11/29/13
// ========================================================================
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include "general/filefuncs.h"
#include "math/fourvector.h"
#include "general/stringfuncs.h"
#include "general/sysfuncs.h"
#include "video/texture_rectangle.h"
#include "time/timefuncs.h"
#include "video/videofuncs.h"
// ==========================================================================
int main( int argc, char** argv )
{
using std::cin;
using std::cout;
using std::endl;
using std::map;
using std::ofstream;
using std::string;
using std::vector;
std::set_new_handler(sysfunc::out_of_memory);
timefunc::initialize_timeofday_clock();
// string images_subdir="/data/ImageEngine/BostonBombing/clips_1_thru_133/";
// string JAV_subdir="/data/video/JAV/NewsWraps/early_Sep_2013/";
string JAV_subdir="/data/video/JAV/NewsWraps/w_transcripts/";
// string root_subdir=JAV_subdir;
// string images_subdir=root_subdir+"jpg_frames/";
// string root_subdir="./bundler/aleppo_1K/";
// string images_subdir=root_subdir+"images/";
// string root_subdir="./bundler/GrandCanyon/";
// string root_subdir="/home/cho/Desktop/profile_faces/";
// string images_subdir=root_subdir+"individuals/";
// string images_subdir=root_subdir+"difficult/resized_images/homogenized/";
string root_subdir="/home/cho/Downloads/people/standing/";
string images_subdir=root_subdir+"difficult/resized_images/";
// string objects_subdir=images_subdir+"FaceBboxes/";
string objects_subdir=images_subdir+"StandingPeopleBboxes/";
string obj_bboxes_filename=objects_subdir+"object_bboxes.dat";
string object_detections_subdir=objects_subdir+"object_detection_bboxes/";
filefunc::dircreate(object_detections_subdir);
typedef map<string,vector<fourvector> > OBJ_BBOXES_MAP;
// independent string = image filename
// dependent STL vector of fourvector contains (Ulo,Uhi,Vlo,Vhi) for
// detected object bounding boxes
OBJ_BBOXES_MAP obj_bboxes_map;
OBJ_BBOXES_MAP::iterator iter;
// Import object detection bboxes:
vector<vector<string> > substrings=filefunc::ReadInSubstrings(
obj_bboxes_filename);
for (unsigned int i=0; i<substrings.size(); i++)
{
vector<string> column_strings=substrings[i];
string image_filename=column_strings[0];
// int bbox_index=stringfunc::string_to_number(column_strings[1]);
double Ulo=stringfunc::string_to_number(column_strings[2]);
double Uhi=stringfunc::string_to_number(column_strings[3]);
double Vlo=stringfunc::string_to_number(column_strings[4]);
double Vhi=stringfunc::string_to_number(column_strings[5]);
fourvector bbox_params(Ulo,Uhi,Vlo,Vhi);
// cout << "image_index = " << image_index
// << " bbox_index = " << bbox_index << endl;
// cout << "Ulo = " << Ulo << " Uhi = " << Uhi
// << " Vlo = " << Vlo << " Vhi = " << Vhi << endl;
// outputfunc::enter_continue_char();
iter=obj_bboxes_map.find(image_filename);
if (iter==obj_bboxes_map.end())
{
vector<fourvector> V;
V.push_back(bbox_params);
obj_bboxes_map[image_filename]=V;
}
else
{
iter->second.push_back(bbox_params);
}
} // loop over index i labeling lines in obj_bboxes_filename
// Superpose purple bboxes on images containing detected objects.
// Export annotated images to object_detections_subdir.
int i=0;
for (iter=obj_bboxes_map.begin(); iter != obj_bboxes_map.end(); iter++)
{
outputfunc::update_progress_fraction(i++,100,obj_bboxes_map.size());
string image_filename=iter->first;
// cout << "image_filename = " << image_filename << endl;
texture_rectangle* texture_rectangle_ptr=new texture_rectangle(
image_filename,NULL);
vector<fourvector> bbox_params=iter->second;
int bbox_color_index=colorfunc::brightpurple;
int line_thickness=1;
videofunc::display_bboxes(
bbox_params,texture_rectangle_ptr,bbox_color_index,line_thickness);
string basename=filefunc::getbasename(image_filename);
string annotated_filename=object_detections_subdir+basename;
texture_rectangle_ptr->write_curr_frame(annotated_filename);
delete texture_rectangle_ptr;
string banner="Exported "+annotated_filename;
outputfunc::write_banner(banner);
} // loop over obj_bboxes_map iterator
cout << "At end of program DRAW_OBJ_BBOXES" << endl;
outputfunc::print_elapsed_time();
}
|
f862b2ad25d2a345d6374155b45950d684b8ea12 | f9c5341ffcde2bd3ea3ac85f5fb119f93e92935b | /CodeForce/C++/327A_Flipping Game.cpp | ac9bf8d236457d76c29ce9e1b30fba392e2cc81d | [] | no_license | leejaeseung/Algorithm | d9ab4f65b59c091cb65185c0d1f5f4772593eff9 | 644c69836cd0c578961d3b00741af4f4ff7c8339 | refs/heads/master | 2023-07-09T12:21:35.248238 | 2021-07-30T08:35:36 | 2021-07-30T08:35:36 | 247,437,095 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 818 | cpp | 327A_Flipping Game.cpp | #include<iostream>
#include<algorithm>
#include<math.h>
#include<string>
#include<string.h>
#include<vector>
using namespace std;
#define FIO ios_base::sync_with_stdio(false); cin.tie(NULL)
#define pii pair<int, int>
int N;
int arr[101];
int dp[101][101][2];
int main(void) {
FIO;
cin >> N;
for (int i = 1; i <= N; i++)
{
cin >> arr[i];
}
for (int i = 1; i <= N; i++)
{
for (int j = i; j <= N; j++)
{
for (int k = i; k <= j; k++)
{
dp[i][j][arr[k]]++;
}
}
}
int s = 0 , e = 0;
int max = 0;
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
{
if (max < dp[i][j][0] - dp[i][j][1]) {
max = dp[i][j][0] - dp[i][j][1];
s = i;
e = j;
}
}
}
if (dp[1][N][1] != N)
cout << dp[1][s - 1][1] + dp[s][e][0] + dp[e + 1][N][1];
else
cout << N - 1;
} |
143aaae1dee83c4bf8537b889fcb892a19f433c9 | 5766835d64e7b8695029e887188b3d2b684c5c9d | /water/Particle.h | 81b736e81ba6cb2e3fd78488e692e80fb38cd653 | [] | no_license | tinmanSimon/waterEffect | d06bc9898e4b553c738613d65129330871bd3e86 | c37fd80e1360a703e8624e6a762f631bb92ca17c | refs/heads/master | 2020-07-06T06:18:13.583669 | 2019-12-01T22:27:44 | 2019-12-01T22:27:44 | 202,920,253 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 779 | h | Particle.h | #ifndef PARTICLE_H
#define PARTICLE_H
#include "RenderObject.h"
#include "VAO.h"
#include "Camera.h"
#include "Shader.h"
class Particle : public RenderObject {
int ID;
VAO* vao;
Shader* shader;
const char* vertex = "particleVertex.txt";
const char* frag = "particleFrag.txt";
unsigned int quadVBO;
unsigned int quadVAO;
void useShader(int i);
glm::mat4 model, view, proj;
std::vector<glm::mat4> models;
void initShader();
Texture* albedoMap;
float t;
bool hitWater;
std::vector<bool> hitWaters;
float hit_time;
std::vector <float> hit_times;
glm::vec3 velocity;
std::vector <glm::vec3> velocities;
public:
Particle(int i);
~Particle();
void draw();
void reset_time();
void it_hits_water(glm::vec3 pos, glm::vec3 v, int i);
bool hits_water();
};
#endif |
61bc455c9310dbe9b67028e18705043a8754b64b | 008055bf40776fdf62f22efb131a8ce6a7095703 | /cpp/src/gis/dispatch/type_scanner.h | 78b40ee6ce01be185a5d01cbcf82bbb866bc8ad4 | [
"Apache-2.0"
] | permissive | xiaocai2333/arctern | aeca72b7318a0cba96bb1bb5a9e864b272638967 | 1043ce0c85de1bddc7d485bcccf9f1414324589e | refs/heads/master | 2022-11-28T16:32:14.968632 | 2020-06-04T13:00:34 | 2020-06-04T13:00:34 | 240,625,278 | 1 | 0 | Apache-2.0 | 2020-05-08T06:14:27 | 2020-02-15T01:07:41 | C++ | UTF-8 | C++ | false | false | 4,426 | h | type_scanner.h | /*
* Copyright (C) 2019-2020 Zilliz. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <arrow/api.h>
#include <cassert>
#include <map>
#include <memory>
#include <set>
#include <utility>
#include <vector>
#include "gis/wkb_types.h"
#include "utils/arrow_alias.h"
namespace arctern {
namespace gis {
namespace dispatch {
using GroupedWkbTypes = std::set<WkbTypes>;
struct GeometryTypeMasks {
public:
using EncodeUid = uint32_t;
struct Info {
public:
// TODO(dog): remove mask since encode_uids contains all the info
// TODO(dog): now make unittest happy
// This field contains mask[i] = is_matched(data[i]);
std::vector<bool> mask;
// TODO(dog): remove later since mask_count === indexes.size()
// TODO(dog): now make unittest happy
// This field contains counts of true in mask, or size of indexes
int64_t mask_count = 0;
};
const auto& get_info(const GroupedWkbTypes& grouped_types) const& {
auto iter = dict.find(grouped_types);
if (iter == dict.end()) {
throw std::runtime_error("check is_unique first");
}
return iter->second;
}
auto&& get_info(const GroupedWkbTypes& grouped_types) && {
auto iter = dict.find(grouped_types);
if (iter == dict.end()) {
throw std::runtime_error("check is_unique first");
}
return std::move(iter->second);
}
// helper function
const auto& get_mask(const GroupedWkbTypes& grouped_types) const& {
return get_info(grouped_types).mask;
}
auto&& get_mask(const GroupedWkbTypes& grouped_types) && {
return std::move(std::move(*this).get_info(grouped_types).mask);
}
auto get_count(const GroupedWkbTypes& grouped_types) const {
return get_info(grouped_types).mask_count;
}
public:
// If the given geometries share identical type, this field will be set true.
bool is_unique_type;
// This field is valid only if 'is_unique_type' equals true.
GroupedWkbTypes unique_type;
// extra fields for
public:
// This contains Info for each geometry type, enable only if !unique_type
std::map<GroupedWkbTypes, Info> dict;
};
class GeometryTypeScanner {
public:
virtual std::shared_ptr<GeometryTypeMasks> Scan() const = 0;
const std::vector<GroupedWkbTypes>& types() const { return types_; }
std::vector<GroupedWkbTypes>& mutable_types() { return types_; }
private:
std::vector<GroupedWkbTypes> types_;
};
class MaskResult {
public:
enum class Status {
kInvalid,
kOnlyFalse,
kMixed,
kOnlyTrue,
};
explicit MaskResult(Status status) : status_(status) {
assert(status != Status::kMixed);
}
explicit MaskResult(std::vector<bool>&& mask)
: status_(Status::kMixed), mask_(std::move(mask)) {}
MaskResult() = default;
MaskResult(const std::shared_ptr<arrow::StringArray>& geometries,
const GroupedWkbTypes& supported) {
this->AppendFilter(geometries, supported);
}
MaskResult(const std::shared_ptr<arrow::BinaryArray>& geometries,
const GroupedWkbTypes& supported) {
this->AppendFilter(geometries, supported);
}
void AppendFilter(const std::shared_ptr<arrow::StringArray>& geometries,
const GroupedWkbTypes& supported_type);
void AppendFilter(const std::shared_ptr<arrow::BinaryArray>& geometries,
const GroupedWkbTypes& supported_type);
Status get_status() const { return status_; }
const std::vector<bool>& get_mask() const { return mask_; }
private:
// bitwise append
void AppendFilter(const GeometryTypeScanner& scanner,
const GroupedWkbTypes& supported_type);
private:
Status status_ = Status::kOnlyTrue;
// valid only when status = kMixed
std::vector<bool> mask_;
};
MaskResult RelateSelector(const WkbArrayPtr& left_geo, const WkbArrayPtr& right_geo);
} // namespace dispatch
} // namespace gis
} // namespace arctern
|
954898f38254d4fd0b386b1b98c9706f55d4d787 | 07b82afdf7170322a48ac89b5b7c9daa01699472 | /ООП/Лекции/ООП/lect5/lect5/lect5_3.cpp | a46f592005c99728f1e0e0169f8d4816609832c0 | [] | no_license | plamenayovcheva/University | a727f2e1a47a9f962b393e0907f257d0d967b4a6 | a0682914d8b8e65eb603ae4a9b48e402575e0d88 | refs/heads/master | 2020-05-05T00:56:19.886582 | 2019-04-05T11:03:42 | 2019-04-05T11:03:42 | 179,588,162 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,518 | cpp | lect5_3.cpp | #include <iostream>
#include <string>
using namespace std;
template <typename T>
class Stack{
private:
enum {SIZE=4}; // razmer na steka
T list[SIZE];
int top; // vryh na steka, svobodna poziciya
public:
Stack(){
top=0; // zapochvame ot 0 element na masiva
}
bool isEmpty(){
return top==0;
}
bool isFull(){
return top==SIZE;
}
//vmykva element v steka
bool push(T element){
if(!isFull()){
list[top++]=element;
// cout<<element <<" e dobaven \n";
cout<<element.toString() <<" e dobaven \n";
return true;
}
else{
// cout<<element <<" NE e dobaven \n";
cout<<element.toString() <<"Ne e dobaven \n";
return false;
}
}
//izvlicha element ot steka
bool pop(T& element){
if(!isEmpty()){
element=list[--top];
return true;
}
else{
return false;
}
}
};
class Person{
string name;
int yb; //year Born
public:
Person():name("Ivan"), yb(1997){
}
Person(string n, int _yb):name(n), yb(_yb){
}
string toString(){
return "Ime:"+name+" godina na razdane:"
+ to_string(yb);
}
};
int main(){
// masiv ot lica
Person si[5]={Person(),
Person("Gabriela", 1998),
Person("Kamelia", 1999),
Person("Ekaterina", 2000),
Person("Alex", 1997)
};
Stack<Person> pSt;
for(int i{0}; i<5; i++){
pSt.push(si[i]);
}
}
|
ab046feea2434be53cee1bbde1d83fc6ed677cf8 | 55d725aa833d4992089aeac2b015aa655a607c8d | /PS2X_controller/PS2X_controller.ino | ea4dff0e7f45f7afb1789c63329f95fd7fe4ad91 | [] | no_license | polchky/micropython-ps2x-bridge | 5c813ce325c68f620260e55ba8b89e6dcf6022e1 | 67bb21e6de0977758e5c3e5842af7dab23e77cbb | refs/heads/master | 2021-01-21T22:21:50.766250 | 2017-09-01T22:34:58 | 2017-09-01T22:34:58 | 102,153,361 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,548 | ino | PS2X_controller.ino | #include <PS2X_lib.h> //for v1.6
/******************************************************************
* set pins connected to PS2 controller
******************************************************************/
#define PS2_DAT 7
#define PS2_CMD 5
#define PS2_SEL 4
#define PS2_CLK 6
#define DEBUG true
#define BAUD_RATE 115200
#define READ_DELAY_MS 0 // Delay between gamepad readings
bool request;
/******************************************************************
* select modes of PS2 controller:
* - pressures = analog reading of push-butttons
* - rumble = motor rumbling
******************************************************************/
#define pressures false
#define rumble false
PS2X ps2x; // create PS2 Controller Class
byte sticks[] = {PSS_LX, PSS_LY, PSS_RX, PSS_RY};
unsigned int l_buttons[] = {PSB_PAD_UP, PSB_PAD_RIGHT, PSB_PAD_DOWN, PSB_PAD_LEFT, PSB_L1, PSB_L2, PSB_L3};
unsigned int r_buttons[] = {PSB_TRIANGLE, PSB_CIRCLE, PSB_CROSS, PSB_SQUARE, PSB_R1, PSB_R2, PSB_R3};
unsigned int m_buttons[] = {PSB_SELECT, PSB_START};
byte s_data[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; // bytes to send
int error = 0;
byte type = 0;
byte vibrate = 0;
void ps2_connect(){
do{
delay(500);
error = ps2x.config_gamepad(PS2_CLK, PS2_CMD, PS2_SEL, PS2_DAT, pressures, rumble);
}while(error != 0 && error != 3);
}
void set_s_data(){
// joysticks
s_data[6] = 0x00;
for (int i=0; i<4; i++){
s_data[i] = ps2x.Analog(sticks[i]) >> 1;
s_data[6] |= ps2x.Analog(sticks[i]) >> 7 << 4 - i;
}
// left and right buttons
s_data[4] = s_data[5] = 0x00;
for (int i=0; i<7; i++){
s_data[4] |= ps2x.Button(l_buttons[i]) << 6 - i;
s_data[5] |= ps2x.Button(r_buttons[i]) << 6 - i;
}
// middle buttons
s_data[6] |= ps2x.Button(m_buttons[0]) << 6 | ps2x.Button(m_buttons[1]) << 5;
// set message starting bit
s_data[0] |= 1 << 7;
}
void send_s_data() {
if(DEBUG){digitalWrite(LED_BUILTIN, HIGH);}
for(int i=0; i < 7; i++) {
Serial.write(s_data[i]);
}
if(DEBUG){digitalWrite(LED_BUILTIN, LOW);}
}
void setup(){
Serial.begin(BAUD_RATE);
ps2_connect();
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
// read controller
if(!ps2x.read_gamepad(false, vibrate)){
ps2_connect();
return;
}
// set data
set_s_data();
request = false;
while(Serial.available()){
Serial.read();
request = true;
}
if(request) {
send_s_data();
}
delay(READ_DELAY_MS);
}
|
82dfb33df69e26662ed5330c1cfe2134d14bdf96 | 33f1b5f6afa115be45cade93479bb7fbc33e7da0 | /UVA/1585/8566110_AC_0ms_0kB.cpp | 88e4d645d3cfc984b08fb9db27988a9b51413373 | [] | no_license | showmic96/Online-Judge-Solution | 3960c37a646f4885210c09096c21dabd7f2154d2 | 94c34e9db2833fb84d0ac885b637dfebac30a5a2 | refs/heads/master | 2022-11-26T09:56:58.469560 | 2020-08-02T04:42:33 | 2020-08-02T04:42:33 | 230,185,618 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 459 | cpp | 8566110_AC_0ms_0kB.cpp | // In the name of Allah the Most Merciful.
#include<bits/stdc++.h>
using namespace std;
int main(void)
{
int t;
cin >> t;
while(t--){
string ar;
cin >> ar;
int si = ar.size();
int total = 0 , c = 1;
for(int i=0;i<si;i++){
if(ar[i]=='O'){
total+=c;
c++;
}
else c = 1;
}
cout << total << endl;
}
return 0;
}
|
19a3cf9c36ccd4aca94c1a2414dadaa315f6b342 | f97398fafde5ce92e6c80bba9bc3dd551c63c01e | /tower_of_hanoi.cpp | ffbdd51cd63d263592de8082680b433afc9bcafc | [] | no_license | kharepratyush/tower-of-hanoi | dd42aefbb97e7099f9f9066d86fd02cdc1c0f6bf | 88b9dc295f687717f33dc4bc6da622f61f7dc878 | refs/heads/master | 2021-01-19T13:25:42.119630 | 2018-12-17T09:28:14 | 2018-12-17T09:28:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,011 | cpp | tower_of_hanoi.cpp | /*Code to show solution of Tower_Of_Hanoi*/
#include <iostream>
int n;
void prin(int a[],int b[],int c[],char c1,char c2,char c3)
{ int j,f,g=0;
for(int i=0;i<n;i++)
{ f=-1;
if(a[i]==1)
{ f=1;g=1;
for(j=i+1;j>0;j--)
std::cout<<'-';
}
std::cout<<"\t\t";
if(b[i]==1)
{ f=1;g=1;
for(j=i+1;j>0;j--)
std::cout<<'-';
}
std::cout<<"\t\t";
if(c[i]==1)
{ f=1;g=1;
for(j=i+1;j>0;j--)
std::cout<<'-';
}
if(f==1)std::cout<<"\n";
}//if(g==1)std::cout<"\n\n\n";
std::cout<<c1<<"\t\t"<<c2<<"\t\t"<<c3<<"\t\t"<<"\n\n";
}
void tower(int a,char from,char aux,char to, int a1[],int b1[],int c1[]){
if(a==1){
//std::cout<<"\t\tMove disc 1 from "<<from<<" to "<<to<<"\n";
if(from=='A')
a1[0]=0;
else if(from=='B')
b1[0]=0;
else if(from=='C')
c1[0]=0;
if(to=='A')
a1[0]=1;
else if(to=='B')
b1[0]=1;
else if(to=='C')
c1[0]=1;
prin(a1,b1,c1,'A','B','C');
return;
}
else{
tower(a-1,from,to,aux,a1,b1,c1);
//std::cout<<"\t\tMove disc "<<a<<" from "<<from<<" to "<<to<<"\n";
if(from=='A')
a1[a-1]=0;
else if(from=='B')
b1[a-1]=0;
else if(from=='C')
c1[a-1]=0;
if(to=='A')
a1[a-1]=1;
else if(to=='B')
b1[a-1]=1;
else if(to=='C')
c1[a-1]=1;
prin(a1,b1,c1,'A','B','C');
tower(a-1,aux,from,to,a1,b1,c1);
}
}
int main(){
int i;
std::cout<<"\n\t\tTower of Hanoi\n";
std::cout<<"\t\tEnter number of discs : ";
std::cin>>n;
int a1[n],b1[n],c1[n];
for(i=0;i<n;i++)
{
a1[i]=1;
b1[i]=-1;
c1[i]=-1;
}
std::cout<<"\n\n";
prin(a1,b1,c1,'A','B','C');
tower(n,'A','B','C',a1,b1,c1);
return 1;
}
|
1ab2f0b2c08cd3f410d04a0051931c09452fd704 | dfb4db37ff8503f2b46c177c589b2355971279c6 | /cs221/project2/SquareMaze.h | dbf503e5def858daf99d97dab248465fc2165178 | [] | no_license | williamwii/ubc_proj | abc9c365551bc84b19ab3312b1b1ee8555a969a1 | 0d7e546a473e3a46a5a805d37768e128aa4576d7 | refs/heads/master | 2020-05-19T19:16:09.388655 | 2014-05-04T08:14:19 | 2014-05-04T08:14:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,000 | h | SquareMaze.h | #ifndef _SQUAREMAZE_H
#define _SQUAREMAZE_H
#include "Maze.h"
using namespace std;
/*
SquareMaze.h
The classes in Maze.h decribe abstract mazes. The classes in this
file declares concrete implementations of those abstract classes
in order to represent square mazes.
221 STUDENTS: You need only use this class as it is already used in
runmaze.cpp to load a maze file (and work with the visualization, if
you choose to).
Many of these classes are "friends" of each other. This is because
they are all part of the exact same implementation. But, they merely present
different views of the same information, for the convenience of other classes.
*/
class SquareMaze : public Maze {
public:
class SquareMazeNode; // forward declaration of our nested class
protected:
int width,height;
SquareMazeNode *nodes;
// define the Start
SquareMazeNode *startNode;
// define the Exit
SquareMazeNode *exitNode;
// convenience function to get a node*, given (x,y)
SquareMazeNode *getNode (int x,int y);
// sub-routines used to read in from file
void ParseSizeLine(istream& inData);
void ReadActualMaze(istream& inData);
public:
// construct a SquareMaze from a file, using the format described in the Project 1 handout
SquareMaze (istream& inData);
// dump maze in computer-oriented format, for debugging
void DebugDump (ostream& out);
~SquareMaze();
// methods from abstract base class
MazeNode *getStartMazeNode (void);
MazeNodeIterator *getAllMazeNodes (void);
int getNumNodes (void);
int getMaxNeighborsForNode (void);
// things for classes that want to know that this is a square maze (like the visualizer)
enum Directions { Left=0,Right=1,Up=2,Down=3 };
int getWidth (void);
int getHeight (void);
SquareMazeNode *getNodeAt (int x,int y);
protected: // our nested iterator classes are not public - you can only access them via the abstract classes defined in Maze.h
// AllNodesIterator nested class iterates through all nodes
class AllNodesIterator : public MazeNodeIterator {
friend class SquareMaze; // SquareMaze knows about this class, mainly so it can call the protected constructor
protected:
SquareMaze *maze;
int x,y; // current x,y position
AllNodesIterator (SquareMaze *_maze);
public:
~AllNodesIterator ();
// methods from abstract base class
bool hasNext (void);
MazeNode * next (void);
};
friend class AllNodesIterator; // AllNodesIterator knows about the internals of how the SquareMaze is implemented
public: // but some classes (e.g. visualizer) may want to see the SquareMazeNode
// here's our node class, which is also nested
class SquareMazeNode : public MazeNode {
friend class SquareMaze; // SquareMaze knows about this class, mainly so it can call the protected constructor
protected:
SquareMaze *maze;
int x,y; // x,y coordinates of this node, so we know what it's neighbors are
bool canGoDirs[4]; // array of whether or not we can go in each of the 4 directions
SquareMazeNode (); // must set members 'maze', 'x', 'y'
public:
~SquareMazeNode ();
// methods from abstract base class
bool isExitNode (void);
MazeNodeIterator *getNeighbors (void);
void setVisitationState (VisitationState newVisitationState);
void print (ostream& out);
// things for classes that want to know that this is a square maze (like the visualizer)
int getX (void) const;
int getY (void) const;
bool canGoLeft (void);
bool canGoRight (void);
bool canGoUp (void);
bool canGoDown (void);
// The following methods are for use by SquareMazeNodeCompare:
int getMazeWidth() const;
int getMazeHeight() const;
int getExitX() const;
int getExitY() const;
// read the x,y coordinates we outputted with our print method
// returns true iff the input had a legitimate print out (in particular, it'll return false if there was an end-of-line character
static bool /* got node */ readXY (istream& inData,int *x,int *y);
// the NeighborIterator class, nested
protected:
class NeighborIterator : public MazeNodeIterator {
friend class SquareMazeNode; // SquareMazeNode knows about this class, mainly so it can call the protected constructor
protected:
SquareMazeNode *node,*nextNode;
int currDir;
NeighborIterator (SquareMazeNode *_node);
// convenience function, set nextNode based on currDir and node
void ComputeNextNode(void);
public:
~NeighborIterator ();
// methods from abstract base class
bool hasNext (void);
MazeNode * next (void);
};
friend class NeighborIterator; // NeighborIterator knows about the internals of SquareMazeNode
};
friend class SquareMazeNode; // SquareMazeNode knows about the internals of how the SquareMaze is implemented
friend class SquareMazeNode::NeighborIterator; // NeighborIterator knows about the internals of SquareMaze
};
#endif
|
e8da0f18e91768d8175a2852142b901dad09e382 | ee67417fb76e88d2e7905efb5dadff527f981fe2 | /FVector/comm.cpp | 7e483547f9ae408b4f610fefcb7c6181700ac3d9 | [] | no_license | taylorlu/FVector | c8e1b7b96cb61bbf695f516b3b0fa3bceb4468ae | 474289a8ea49dbfe0518e3a98d9e178bc82971cd | refs/heads/master | 2020-04-11T03:03:01.396122 | 2019-04-15T06:47:05 | 2019-04-15T06:47:05 | 161,465,591 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,109 | cpp | comm.cpp | //
// comm.cpp
// FVector
//
// Created by LuDong on 2018/1/26.
// Copyright © 2018年 LuDong. All rights reserved.
//
#include "comm.hpp"
using namespace cv;
void readDirectory(const char *directoryName, std::vector<std::string>& filenames, int searchFolder) {
filenames.clear();
struct dirent *dirp;
DIR* dir = opendir(directoryName);
while ((dirp = readdir(dir)) != nullptr) {
if(dirp->d_name[0]!='.') {
if (dirp->d_type == DT_REG && !searchFolder) {
// 文件
std::string directoryStr(directoryName);
std::string nameStr(dirp->d_name);
filenames.push_back(directoryStr + "/" + nameStr);
//printf("file: %s\n", dirp->d_name);
} else if (dirp->d_type == DT_DIR && searchFolder) {
// 文件夹
std::string directoryStr(directoryName);
std::string nameStr(dirp->d_name);
filenames.push_back(directoryStr + "/" + nameStr);
//printf("folder: %s\n", dirp->d_name);
}
}
}
std::sort(filenames.begin(), filenames.end());
closedir(dir);
}
void saveMatrix(float *matrix, int rows, int cols, const char *fileName) {
//save fisher vectors(images, so a matrix) in each class folder, (label-00, label-01, ...)
hid_t fileId = H5Fcreate(fileName, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
hsize_t dims[] = {(hsize_t)rows, (hsize_t)cols};
hid_t dataSpaceId = H5Screate_simple(2, dims, NULL);
hid_t dataSetId = H5Dcreate1(fileId, "fileName", H5T_NATIVE_FLOAT, dataSpaceId, H5P_DEFAULT);
H5Dwrite(dataSetId, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, matrix);
H5Dclose(dataSetId);
H5Sclose(dataSpaceId);
H5Fclose(fileId);
}
void saveMatrix(void *matrix, int dataType, int rows, int cols, const char *fileName) {
//save fisher vectors(images, so a matrix) in each class folder, (label-00, label-01, ...)
hid_t fileId = H5Fcreate(fileName, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
hsize_t dims[] = {(hsize_t)rows, (hsize_t)cols};
hid_t dataSpaceId = H5Screate_simple(2, dims, NULL);
hid_t dataSetId = H5Dcreate1(fileId, "fileName", H5T_NATIVE_FLOAT, dataSpaceId, H5P_DEFAULT);
H5Dwrite(dataSetId, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, matrix);
H5Dclose(dataSetId);
H5Sclose(dataSpaceId);
H5Fclose(fileId);
}
Mat readMatrix(const char *fileName) {
//read fisher vectors(label-00, label-01, ...) to matrix.
hid_t fileId = H5Fopen(fileName, H5F_ACC_RDONLY, H5P_DEFAULT);
////get dataset 1
hid_t datasetId = H5Dopen1(fileId, "fileName");
hid_t spaceId = H5Dget_space(datasetId);
int ndims = H5Sget_simple_extent_ndims(spaceId);
hsize_t dims[ndims];
herr_t status = H5Sget_simple_extent_dims(spaceId, dims, NULL);
int cap = 1;
int rows = (int)dims[0];
int cols = (int)dims[1];
cap = rows*cols;
Mat dataMatrix;
dataMatrix.create(rows, cols, CV_32F);
hid_t memspace = H5Screate_simple(ndims, dims, NULL);
status = H5Dread(datasetId, H5T_NATIVE_FLOAT, memspace, spaceId, H5P_DEFAULT, dataMatrix.data);
H5Sclose(spaceId);
H5Dclose(datasetId);
H5Fclose(fileId);
return dataMatrix;
}
void *readMatrix(const char *fileName, int dataType) {
//read fisher vectors(label-00, label-01, ...) to matrix.
hid_t fileId = H5Fopen(fileName, H5F_ACC_RDONLY, H5P_DEFAULT);
////get dataset 1
hid_t datasetId = H5Dopen1(fileId, "fileName");
hid_t spaceId = H5Dget_space(datasetId);
int ndims = H5Sget_simple_extent_ndims(spaceId);
hsize_t dims[ndims];
herr_t status = H5Sget_simple_extent_dims(spaceId, dims, NULL);
int cap = 1;
int rows = (int)dims[0];
int cols = (int)dims[1];
cap = rows*cols;
void *data = malloc(rows*cols*4);
hid_t memspace = H5Screate_simple(ndims, dims, NULL);
status = H5Dread(datasetId, dataType, memspace, spaceId, H5P_DEFAULT, data);
H5Sclose(spaceId);
H5Dclose(datasetId);
H5Fclose(fileId);
return data;
}
void calcMeanVectorOfMatrix(const char *fileName, float **mean, int &len) {
//read a class of image's matrix(fisher vectors), calculate the mean vector of these vectors
hid_t fileId = H5Fopen(fileName, H5F_ACC_RDONLY, H5P_DEFAULT);
////get dataset 1
hid_t datasetId = H5Dopen1(fileId, "fileName");
hid_t spaceId = H5Dget_space(datasetId);
int ndims = H5Sget_simple_extent_ndims(spaceId);
hsize_t dims[ndims];
herr_t status = H5Sget_simple_extent_dims(spaceId, dims, NULL);
int cap = 1;
int rows = (int)dims[0];
int cols = (int)dims[1];
cap = rows*cols;
float *matrix = (float *)malloc(sizeof(float)*cap);
hid_t memspace = H5Screate_simple(ndims, dims, NULL);
status = H5Dread(datasetId, H5T_NATIVE_FLOAT, memspace, spaceId, H5P_DEFAULT, matrix);
len = cols;
*mean = (float *)malloc(sizeof(float)*cols);
float *meanTmp = *mean;
for (int i=0; i<cols; i++) {
float total = 0;
for (int k=0; k<rows; k++) {
total += *(matrix + k*cols + i);
}
meanTmp[i] = total/rows;
}
H5Sclose(spaceId);
H5Dclose(datasetId);
H5Fclose(fileId);
free(matrix);
}
void saveGmmModel(const char *filename, float *means, float *covariances, float *priors) {
//save gmm model training from all sift descriptors in whole images data
hid_t fileId = H5Fcreate(filename, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
hsize_t dims_means[] = {(hsize_t)GM_COUNT, (hsize_t)SIFT_DIMENSION};
hid_t dataSpaceId = H5Screate_simple(2, dims_means, NULL);
hid_t dataSetId = H5Dcreate1(fileId, "/means", H5T_NATIVE_FLOAT, dataSpaceId, H5P_DEFAULT);
herr_t status = H5Dwrite(dataSetId, H5T_NATIVE_FLOAT, H5S_ALL, dataSpaceId, H5P_DEFAULT, means);
hsize_t dims_convs[] = {(hsize_t)GM_COUNT, (hsize_t)SIFT_DIMENSION};
hid_t dataSpaceId2 = H5Screate_simple(2, dims_convs, NULL);
hid_t dataSetId2 = H5Dcreate1(fileId, "/covs", H5T_NATIVE_FLOAT, dataSpaceId2, H5P_DEFAULT);
status = H5Dwrite(dataSetId2, H5T_NATIVE_FLOAT, H5S_ALL, dataSpaceId2, H5P_DEFAULT, covariances);
hsize_t dims_priors[] = {(hsize_t)GM_COUNT};
hid_t dataSpaceId3 = H5Screate_simple(1, dims_priors, NULL);
hid_t dataSetId3 = H5Dcreate1(fileId, "/priors", H5T_NATIVE_FLOAT, dataSpaceId3, H5P_DEFAULT);
status = H5Dwrite(dataSetId3, H5T_NATIVE_FLOAT, H5S_ALL, dataSpaceId3, H5P_DEFAULT, priors);
H5Dclose(dataSetId);
H5Sclose(dataSpaceId);
H5Dclose(dataSetId2);
H5Sclose(dataSpaceId2);
H5Dclose(dataSetId3);
H5Sclose(dataSpaceId3);
H5Fclose(fileId);
}
void trainEM(Mat wholeData, const char *savePath, int gmm_count, int iterations) {
printf("Begin EM...\r\n");
float * means ;
float * covariances ;
float * priors ;
// create a new instance of a GMM object for float data
VlGMM *gmm = vl_gmm_new (VL_TYPE_FLOAT, SIFT_DIMENSION, gmm_count);
// set the maximum number of EM iterations to 1000
vl_gmm_set_max_num_iterations (gmm, iterations);
// set the initialization to random selection
vl_gmm_set_initialization (gmm, VlGMMRand);
// cluster the data, i.e. learn the GMM
int numData = wholeData.rows;
void *data = wholeData.data;
vl_gmm_cluster (gmm, data, numData);
// get the means, covariances, and priors of the GMM
means = (float *)vl_gmm_get_means(gmm);
covariances = (float *)vl_gmm_get_covariances(gmm);//only saved the diagonal values
priors = (float *)vl_gmm_get_priors(gmm);
for(int i=0; i<gmm_count; i++) {
printf("%f\n", priors[i]);
}
saveGmmModel(savePath, means, covariances, priors);
printf("End EM...\r\n");
}
void readGmmModel(const char *filename, float **means, float **covariances, float **priors) {
hid_t fileId = H5Fopen(filename, H5F_ACC_RDONLY, H5P_DEFAULT);
////get dataset 1
hid_t datasetId = H5Dopen1(fileId, "/means");
hid_t spaceId = H5Dget_space(datasetId);
int ndims = H5Sget_simple_extent_ndims(spaceId);
hsize_t dims[ndims];
herr_t status = H5Sget_simple_extent_dims(spaceId, dims, NULL);
int cap = 1;
for(int i=0; i<ndims; i++) {
cap *= dims[i];
}
*means = (float *)malloc(sizeof(float)*cap);
hid_t memspace = H5Screate_simple(ndims,dims,NULL);
status = H5Dread(datasetId, H5T_NATIVE_FLOAT, memspace, spaceId, H5P_DEFAULT, *means);
status = H5Sclose(spaceId);
status = H5Dclose(datasetId);
////get dataset 2
datasetId = H5Dopen1(fileId, "/covs");
spaceId = H5Dget_space(datasetId);
ndims = H5Sget_simple_extent_ndims(spaceId);
hsize_t dims2[ndims];
status = H5Sget_simple_extent_dims(spaceId, dims2, NULL);
cap = 1;
for (int i=0; i<ndims; i++) {
cap *= dims2[i];
}
*covariances = (float *)malloc(sizeof(float)*cap);
memspace = H5Screate_simple(ndims,dims2,NULL);
status = H5Dread(datasetId, H5T_NATIVE_FLOAT, memspace, spaceId, H5P_DEFAULT, *covariances);
H5Sclose(spaceId);
H5Dclose(datasetId);
////get dataset 3
datasetId = H5Dopen1(fileId, "/priors");
spaceId = H5Dget_space(datasetId);
ndims = H5Sget_simple_extent_ndims(spaceId);
hsize_t dims3[ndims];
status = H5Sget_simple_extent_dims(spaceId, dims3, NULL);
cap = 1;
for (int i=0; i<ndims; i++) {
cap *= dims3[i];
}
*priors = (float *)malloc(sizeof(float)*cap);
memspace = H5Screate_simple(ndims,dims3,NULL);
status = H5Dread(datasetId, H5T_NATIVE_FLOAT, memspace, spaceId, H5P_DEFAULT, *priors);
H5Sclose(spaceId);
H5Dclose(datasetId);
H5Fclose(fileId);
}
Mat computeFisherVector(Mat descriptors, float *means, float *covariances, float *priors) {
//input gmm model and sift descriptors, calculate fisher vector of a picture
float *enc = (float *)vl_malloc(sizeof(float) * FV_DIMENSION);
vl_fisher_encode(enc, VL_TYPE_FLOAT, means, SIFT_DIMENSION, GM_COUNT, covariances, priors, descriptors.data, descriptors.rows, VL_FISHER_FLAG_IMPROVED);
Mat fisherVector; //one picture's fisher vector
fisherVector.create(1, FV_DIMENSION, CV_32F);
memcpy(fisherVector.data, enc, sizeof(float) * FV_DIMENSION);
return fisherVector;
}
Mat getWholeSiftDescriptorsFromDir(const char *rootDir) {
Mat wholeData;
std::vector<std::string> files;
readDirectory(rootDir, files, 0);
for(int j=0;j<files.size();j++) {
IplImage *image = cvLoadImage(files[j].c_str());
if(image==NULL)
continue;
Mat imgMat(image);
cvtColor(imgMat, imgMat, CV_BGR2GRAY);
SiftDescriptorExtractor detector(SIFT_COUNT);
vector<KeyPoint> keypoints;
detector.detect(imgMat, keypoints);
Mat descriptors;
detector.compute(imgMat, keypoints, descriptors);
wholeData.push_back(descriptors);
}
return wholeData;
}
void getWholeAkazeDescriptorAndVectorFromDir(const char *rootDir, vector<Mat> &wholeVector, Mat &wholeData) {
#undef EMBED_DIR
#ifdef EMBED_DIR
std::vector<std::string> folders;
readDirectory(rootDir, folders, 1);
for(int i=0; i<folders.size(); i++) {
printf("%s\n", folders[i].c_str());
std::vector<std::string> files;
readDirectory(folders[i].c_str(), files, 0);
#else
std::vector<std::string> files;
readDirectory(rootDir, files, 0);
#endif
for(int j=0;j<files.size();j++) {
IplImage *image = cvLoadImage(files[j].c_str());
if(image==NULL)
continue;
Mat imgMat = cvarrToMat(image);
cvtColor(imgMat, imgMat, CV_BGR2GRAY);
vector<KeyPoint> kpts1, kpts2;
Mat desc1, desc2;
// Ptr<AKAZE> akaze = AKAZE::create();
// akaze->detectAndCompute(imgMat, noArray(), kpts1, desc1);
// printf("%d, %d, %d\n", (int)kpts1.size(), desc1.cols, desc1.rows);
AKAZEOptions options = AKAZEOptions();
libAKAZE::AKAZE evolution(options);
vector<cv::KeyPoint> keypoints;
cv::Mat descriptors;
evolution.Create_Nonlinear_Scale_Space(imgMat);
evolution.Feature_Detection(keypoints);
evolution.Compute_Descriptors(keypoints, descriptors);
// SiftDescriptorExtractor detector(SIFT_COUNT);
// vector<KeyPoint> keypoints;
// detector.detect(imgMat, keypoints);
// Mat descriptors;
// detector.compute(imgMat, keypoints, descriptors);
wholeData.push_back(descriptors);
wholeVector.push_back(descriptors);
}
#ifdef EMBED_DIR
}
#endif
}
void getWholeDescriptorAndVectorFromDir(const char *rootDir, vector<Mat> &wholeVector, Mat &wholeData) {
#ifdef EMBED_DIR
std::vector<std::string> folders;
readDirectory(rootDir, folders, 1);
for(int i=0; i<folders.size(); i++) {
printf("%s\n", folders[i].c_str());
std::vector<std::string> files;
readDirectory(folders[i].c_str(), files, 0);
#else
std::vector<std::string> files;
readDirectory(rootDir, files, 0);
#endif
for(int j=0;j<files.size();j++) {
IplImage *image = cvLoadImage(files[j].c_str());
if(image==NULL)
continue;
Mat imgMat = cvarrToMat(image);
cvtColor(imgMat, imgMat, CV_BGR2GRAY);
vector<KeyPoint> kpts1, kpts2;
Mat desc1, desc2;
// Ptr<AKAZE> akaze = AKAZE::create();
// akaze->detectAndCompute(imgMat, noArray(), kpts1, desc1);
// printf("%d, %d, %d\n", (int)kpts1.size(), desc1.cols, desc1.rows);
SiftDescriptorExtractor detector(SIFT_COUNT);
vector<KeyPoint> keypoints;
detector.detect(imgMat, keypoints);
Mat descriptors;
detector.compute(imgMat, keypoints, descriptors);
wholeData.push_back(descriptors);
wholeVector.push_back(descriptors);
}
#ifdef EMBED_DIR
}
#endif
}
void siftDescriptorToTrain(const char *rootDir, const char *savePath) {
//gather sift vectors from all pictures, and train gmm, save gmm model
Mat wholeData;
#ifdef EMBED_DIR
std::vector<std::string> folders;
readDirectory(rootDir, folders, 1);
for(int i=0; i<folders.size(); i++) {
printf("%s\n", folders[i].c_str());
std::vector<std::string> files;
readDirectory(folders[i].c_str(), files, 0);
#else
std::vector<std::string> files;
readDirectory(rootDir, files, 0);
#endif
for(int j=0;j<files.size();j++) {
IplImage *image = cvLoadImage(files[j].c_str());
if(image==NULL)
continue;
Mat imgMat(image);
cvtColor(imgMat, imgMat, CV_BGR2GRAY);
SiftDescriptorExtractor detector(SIFT_COUNT);
vector<KeyPoint> keypoints;
detector.detect(imgMat, keypoints);
Mat descriptors;
detector.compute(imgMat, keypoints, descriptors);
wholeData.push_back(descriptors);
// printf("%d, %d\n", descriptors.rows, keypoints.size());
// String standardDir = "/Users/ludong/Desktop/rrr/";
// char name[100] = {0};
// sprintf(name, "standard%02d", j);
// saveMatrix((float *)descriptors.data, descriptors.rows, descriptors.cols, standardDir.append(name).c_str());
//
// int ptCount = (int)keypoints.size();
// float *pointXY = (float *)malloc(ptCount*sizeof(float)*2);
// for(int i=0; i<keypoints.size(); i++) {
// pointXY[i] = keypoints[i].pt.x;
// pointXY[i+ptCount] = keypoints[i].pt.y;
// }
// standardDir = "/Users/ludong/Desktop/lkpt/";
// saveMatrix(pointXY, 2, ptCount, standardDir.append(name).c_str());
}
#ifdef EMBED_DIR
}
#endif
printf("EM rows = %d\r\n", wholeData.rows);
trainEM(wholeData, savePath, GM_COUNT, 1000);
}
void siftDescriptorToTrain_fromH5Mat(const char *rootDir, const char *savePath) {
Mat wholeData;
std::vector<std::string> files;
readDirectory(rootDir, files, 0);
for(int j=0;j<files.size();j++) {
Mat mat = readMatrix(files[j].c_str());
wholeData.push_back(mat);
}
trainEM(wholeData, savePath, GM_COUNT, 1000);
}
void savePCA(const string &file_name,cv::PCA &pca_) {
FileStorage fs(file_name,FileStorage::WRITE);
fs << "mean" << pca_.mean;
fs << "e_vectors" << pca_.eigenvectors;
fs << "e_values" << pca_.eigenvalues;
fs.release();
}
void loadPCA(const string &file_name,cv::PCA &pca_) {
FileStorage fs(file_name,FileStorage::READ);
fs["mean"] >> pca_.mean ;
fs["e_vectors"] >> pca_.eigenvectors ;
fs["e_values"] >> pca_.eigenvalues ;
fs.release();
}
#if 0
int main() {
// const char *gmmModelPath = "/Users/ludong/Desktop/model/gmm.h5";
// const char *trainImgPath = "/Users/ludong/Desktop/pageSamples/trainSamples/trainSamples5";
// const char *fvSavePath = "/Users/ludong/Desktop/model/standardFVs.h5";
const char *gmmModelPath = "/Users/ludong/Desktop/model/stand/gmm.h5";
// const char *trainImgPath = "/Users/ludong/Desktop/frontModel";
const char *trainImgPath = "/Users/ludong/Desktop/pageSamples/trainSamples/trainSamples5";
const char *fvSavePath = "/Users/ludong/Desktop/model/stand/standardFVs.h5";
#undef STEP1
#ifdef STEP1
// //step1: gather images' sift descriptors, train GMM model.
siftDescriptorToTrain(trainImgPath, gmmModelPath);
// siftDescriptorToTrain_fromH5Mat("/Users/ludong/Desktop/luyu", gmmModelPath);
#else
//step2: generate fisher vectors in matrix of images base gmm model.
float *means = NULL, *covariances = NULL, *priors = NULL;
readGmmModel(gmmModelPath, &means, &covariances, &priors);
Mat classData;
//#ifdef EMBED_DIR
// std::vector<std::string> folders;
// readDirectory(trainImgPath, folders, 1);
// for(int i=0; i<folders.size(); i++) {
// printf("%s\n", folders[i].c_str());
// std::vector<std::string> files;
// readDirectory(folders[i].c_str(), files, 0);
//#else
// std::vector<std::string> files;
// readDirectory(trainImgPath, files, 0);
//#endif
// for(int j=0;j<files.size();j++) {
// IplImage *image = cvLoadImage(files[j].c_str());
// if(image==NULL)
// continue;
// Mat imgMat(image);
// cvtColor(imgMat, imgMat, CV_BGR2GRAY);
//
// SiftDescriptorExtractor detector(SIFT_COUNT);
// vector<KeyPoint> keypoints;
// detector.detect(imgMat, keypoints);
// Mat descriptors;
// detector.compute(imgMat, keypoints, descriptors);
//
// float *enc = (float *)vl_malloc(sizeof(float) * FV_DIMENSION);
// vl_fisher_encode(enc, VL_TYPE_FLOAT, means, SIFT_DIMENSION, GM_COUNT, covariances, priors, descriptors.data, descriptors.rows, VL_FISHER_FLAG_IMPROVED);
// Mat fisherVector; //one picture's fisher vector
//
// fisherVector.create(1, FV_DIMENSION, CV_32F);
// memcpy(fisherVector.data, enc, sizeof(float) * FV_DIMENSION);
// free(enc);
// classData.push_back(fisherVector);
// }
//#ifdef EMBED_DIR
// }
//#endif
std::vector<std::string> files;
readDirectory("/Users/ludong/Desktop/rrr", files, 0);
for(int j=0;j<files.size();j++) {
Mat descriptors = readMatrix(files[j].c_str());
float *enc = (float *)vl_malloc(sizeof(float) * FV_DIMENSION);
vl_fisher_encode(enc, VL_TYPE_FLOAT, means, SIFT_DIMENSION, GM_COUNT, covariances, priors, descriptors.data, descriptors.rows, VL_FISHER_FLAG_IMPROVED);
Mat fisherVector; //one picture's fisher vector
fisherVector.create(1, FV_DIMENSION, CV_32F);
memcpy(fisherVector.data, enc, sizeof(float) * FV_DIMENSION);
free(enc);
classData.push_back(fisherVector);
}
#undef ENABLE_PCA
#ifdef ENABLE_PCA
PCA pca(classData, Mat(), CV_PCA_DATA_AS_ROW, MAX_DIMENSION);
Mat compressMat = cvCreateMat(classData.rows, MAX_DIMENSION, classData.type());
pca.project(classData, compressMat);
savePCA("/Users/ludong/Desktop/frontModel/pca.h5", pca);
saveMatrix((float *)compressMat.data, compressMat.rows, compressMat.cols, fvSavePath);
#else
saveMatrix((float *)classData.data, classData.rows, classData.cols, fvSavePath);
#endif
#endif
return 0;
}
void cvtToRootSift(Mat descriptors) {
}
#endif
|
1336249df8c6a3a2b48c1155b9e99697199be4b7 | a31c1f7f4382e89cf1e1db6bc3fb5666b2d40be5 | /Lottery Winners/main.cpp | a5f509e5a36e5880b49998643eeaa2d0b15d0ac6 | [] | no_license | DrakeGerger/Fall_17_Assignment_7_Homework | 1b8fc7d91706706d93db1765da2ed2cdf59afc06 | 7a52e0b8eb1f6e2476e4701943f491f901614609 | refs/heads/master | 2021-08-29T19:52:40.026586 | 2017-12-14T21:02:27 | 2017-12-14T21:02:27 | 113,352,743 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,109 | cpp | main.cpp | /*
* File: main.cpp
* Author: Drake Gerger
* Purpose: Lottery Winners
* Created on December 7, 2017, 2:10 PM
*/
//System Libraries
#include <iostream>
using namespace std;
//User Libraries
//Global Constants
const int NUM_ELEMENTS=10;
bool srchAray(int, int [NUM_ELEMENTS]);
//Function Prototypes
//Execution Begins Here!
int main(){
int winNum[]={ 13579, 26791, 26792, 33445, 55555,
62483, 77777, 79422, 85647, 93121};
int guess=0;
bool found=true;
cout<<"Enter your 5-Digit Lucky Number: ";
cin>>guess;
if (found == srchAray(guess, winNum))
cout<<"Your Lottery Ticket Number "<<guess<<" is a Winner this Week!"<<endl;
else
cout<<"Your Lottery Ticket Number "<<guess<<" is NOT a Winner! Try Again Next Week!"<<endl;
return 0;
}
bool srchAray (int giveVal, int findAray [NUM_ELEMENTS])
{
for (int i=0;i<NUM_ELEMENTS;i++)
{
if (giveVal == findAray[i])
return true;
}
return false;
}
|
6adb6854d2dc31adc617e7e37bf090ca2e1d1b75 | 3b77f50c16ac31bd098df9d9d66c5d1dd4a25488 | /include/vsg/utils/SharedObjects.h | 1935c839e28940566f145201e8ccb59ab09e350a | [
"MIT",
"Apache-2.0"
] | permissive | sbrkopac/VulkanSceneGraph | 949989b64bd72e141980a9eda39445eb82a188bd | 0c16bdf9592af818ccb2f82ce36deedf7a284d41 | refs/heads/master | 2022-12-21T08:50:41.396436 | 2022-12-13T14:11:03 | 2022-12-13T14:11:03 | 366,844,691 | 0 | 0 | MIT | 2021-05-12T20:25:41 | 2021-05-12T20:25:41 | null | UTF-8 | C++ | false | false | 5,847 | h | SharedObjects.h | #pragma once
/* <editor-fold desc="MIT License">
Copyright(c) 2022 Robert Osfield
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
</editor-fold> */
#include <vsg/core/Inherit.h>
#include <vsg/core/compare.h>
#include <vsg/io/stream.h>
#include <map>
#include <mutex>
#include <ostream>
#include <set>
namespace vsg
{
/// class for facilitating the share of instances of objects that have the same properties.
class VSG_DECLSPEC SharedObjects : public Inherit<Object, SharedObjects>
{
public:
SharedObjects();
template<class T>
ref_ptr<T> shared_default()
{
std::scoped_lock<std::recursive_mutex> lock(_mutex);
auto id = std::type_index(typeid(T));
auto& def = _defaults[id];
auto def_T = def.cast<T>(); // should be able to do a static cast
if (!def_T)
{
def_T = T::create();
auto& shared_objects = _sharedObjects[id];
if (auto itr = shared_objects.find(def_T); itr != shared_objects.end())
{
def_T = (static_cast<T*>(itr->get()));
}
else
{
shared_objects.insert(def_T);
}
def = def_T;
}
return def_T;
}
template<class T>
void share(ref_ptr<T>& object)
{
std::scoped_lock<std::recursive_mutex> lock(_mutex);
auto id = std::type_index(typeid(T));
auto& shared_objects = _sharedObjects[id];
if (auto itr = shared_objects.find(object); itr != shared_objects.end())
{
object = ref_ptr<T>(static_cast<T*>(itr->get()));
return;
}
shared_objects.insert(object);
}
template<class T, typename Func>
void share(ref_ptr<T>& object, Func init)
{
std::scoped_lock<std::recursive_mutex> lock(_mutex);
auto id = std::type_index(typeid(T));
auto& shared_objects = _sharedObjects[id];
if (auto itr = shared_objects.find(object); itr != shared_objects.end())
{
object = ref_ptr<T>(static_cast<T*>(itr->get()));
return;
}
init(object);
shared_objects.insert(object);
}
template<class C>
void share(C& container)
{
for (auto& object : container)
{
share(object);
}
}
/// set of lower case file extensions for file types that should not be included in this SharedObjects
std::set<Path> excludedExtensions;
/// return true if the filename is of a type suitable for inclusion this SharedObjects
virtual bool suitable(const Path& filename) const;
/// check for an entry associated with filename.
virtual bool contains(const Path& filename, ref_ptr<const Options> options = {}) const;
/// add entry that matches filename and option.
virtual void add(ref_ptr<Object> object, const Path& filename, ref_ptr<const Options> options = {});
/// remove entry associated with filename.
virtual bool remove(const Path& filename, ref_ptr<const Options> options = {});
/// clear all the internal structures leaving no Objects cached.
void clear();
// clear all the singly referenced objects
void prune();
/// write out stats of objects held, types of objects and their reference counts
void report(std::ostream& out);
protected:
virtual ~SharedObjects();
mutable std::recursive_mutex _mutex;
std::map<std::type_index, ref_ptr<Object>> _defaults;
std::map<std::type_index, std::set<ref_ptr<Object>, DereferenceLess>> _sharedObjects;
};
VSG_type_name(vsg::SharedObjects);
/// Helper class for support sharing of objects loaded from files.
class LoadedObject : public Inherit<Object, LoadedObject>
{
public:
Path filename;
ref_ptr<const Options> options;
ref_ptr<Object> object;
LoadedObject(const Path& in_filename, ref_ptr<const Options> in_options, ref_ptr<Object> in_object = {}) :
filename(in_filename),
options(in_options),
object(in_object) {}
int compare(const Object& rhs_object) const override
{
int result = Object::compare(rhs_object);
if (result != 0) return result;
auto& rhs = static_cast<decltype(*this)>(rhs_object);
if ((result = filename.compare(rhs.filename))) return result;
return compare_pointer(options, rhs.options);
}
};
VSG_type_name(vsg::LoadedObject);
} // namespace vsg
|
18aac7b5366ce5f5a4d0a2293238e0f9d76ade5e | 6e548223f4f410dd7f90dd866a3a9affaf35372d | /08/08/taxCalc.cpp | cfc786e89d1b5e2b7618046c1edebe36d1c5f2ab | [] | no_license | Alex4386-vault/clang-programming | ec1b5695c6d10b5379ff1145b3812d8c0c66f3c7 | 6bf500a5e6ef91074fbcfa1caa25429d9e4c3479 | refs/heads/master | 2023-02-10T02:11:44.458076 | 2021-01-02T03:49:55 | 2021-01-02T03:49:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 167 | cpp | taxCalc.cpp | #include <stdio.h>
float taxRate = 0.65;
int main() {
float salesTax, price;
do {
scanf("%f", &price);
salesTax = taxRate * price;
} while (price >= 0.2);
} |
f8577e6438ea056ef447c03551df16f090e7d663 | b39dba38a99bc970d7c861517ab82bb92f5fc548 | /include/cryptopp/bench.h | 561b657874294a838e76547fdde24b2d1cc83597 | [
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | OpenMPT/openmpt | 711aef385c6a098a9a2aaefa25f6563e4501d2e8 | 41c5bde364ed61afb414ac38792715ee9433c01c | refs/heads/master | 2023-09-01T21:37:18.329917 | 2023-09-01T10:10:22 | 2023-09-01T10:10:22 | 82,913,630 | 501 | 87 | BSD-3-Clause | 2023-07-14T08:47:12 | 2017-02-23T10:04:01 | C++ | UTF-8 | C++ | false | false | 3,654 | h | bench.h | // bench.h - originally written and placed in the public domain by Wei Dai
// CryptoPP::Test namespace added by JW in February 2017
#ifndef CRYPTOPP_BENCH_H
#define CRYPTOPP_BENCH_H
#include "cryptlib.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <ctime>
NAMESPACE_BEGIN(CryptoPP)
NAMESPACE_BEGIN(Test)
// More granular control over benchmarks
enum TestClass {
/// \brief Random number generators
UnkeyedRNG=(1<<0),
/// \brief Message digests
UnkeyedHash=(1<<1),
/// \brief Other unkeyed algorithms
UnkeyedOther=(1<<2),
/// \brief Message authentication codes
SharedKeyMAC=(1<<3),
/// \brief Stream ciphers
SharedKeyStream=(1<<4),
/// \brief Block ciphers ciphers
SharedKeyBlock=(1<<5),
/// \brief Other shared key algorithms
SharedKeyOther=(1<<6),
/// \brief Key agreement algorithms over integers
PublicKeyAgreement=(1<<7),
/// \brief Encryption algorithms over integers
PublicKeyEncryption=(1<<8),
/// \brief Signature algorithms over integers
PublicKeySignature=(1<<9),
/// \brief Other public key algorithms over integers
PublicKeyOther=(1<<10),
/// \brief Key agreement algorithms over EC
PublicKeyAgreementEC=(1<<11),
/// \brief Encryption algorithms over EC
PublicKeyEncryptionEC=(1<<12),
/// \brief Signature algorithms over EC
PublicKeySignatureEC=(1<<13),
/// \brief Other public key algorithms over EC
PublicKeyOtherEC=(1<<14),
Unkeyed=UnkeyedRNG|UnkeyedHash|UnkeyedOther,
SharedKey=SharedKeyMAC|SharedKeyStream|SharedKeyBlock|SharedKeyOther,
PublicKey=PublicKeyAgreement|PublicKeyEncryption|PublicKeySignature|PublicKeyOther,
PublicKeyEC=PublicKeyAgreementEC|PublicKeyEncryptionEC|PublicKeySignatureEC|PublicKeyOtherEC,
All=Unkeyed|SharedKey|PublicKey|PublicKeyEC,
TestFirst=(0), TestLast=(1<<15)
};
extern const double CLOCK_TICKS_PER_SECOND;
extern double g_allocatedTime;
extern double g_hertz;
extern double g_logTotal;
extern unsigned int g_logCount;
extern const byte defaultKey[];
// Test book keeping
extern time_t g_testBegin;
extern time_t g_testEnd;
// Benchmark command handler
void BenchmarkWithCommand(int argc, const char* const argv[]);
// Top level, prints preamble and postamble
void Benchmark(Test::TestClass suites, double t, double hertz);
// Unkeyed systems
void BenchmarkUnkeyedAlgorithms(double t, double hertz);
// Shared key systems
void BenchmarkSharedKeyedAlgorithms(double t, double hertz);
// Public key systems over integers
void BenchmarkPublicKeyAlgorithms(double t, double hertz);
// Public key systems over elliptic curves
void BenchmarkEllipticCurveAlgorithms(double t, double hertz);
// These are defined in bench1.cpp
extern void OutputResultKeying(double iterations, double timeTaken);
extern void OutputResultBytes(const char *name, const char *provider, double length, double timeTaken);
extern void OutputResultOperations(const char *name, const char *provider, const char *operation, bool pc, unsigned long iterations, double timeTaken);
// These are defined in bench1.cpp
extern void BenchMark(const char *name, BufferedTransformation &bt, double timeTotal);
extern void BenchMark(const char *name, StreamTransformation &cipher, double timeTotal);
extern void BenchMark(const char *name, HashTransformation &ht, double timeTotal);
extern void BenchMark(const char *name, RandomNumberGenerator &rng, double timeTotal);
// These are defined in bench2.cpp
extern void BenchMarkKeying(SimpleKeyingInterface &c, size_t keyLength, const NameValuePairs ¶ms);
extern void BenchMark(const char *name, AuthenticatedSymmetricCipher &cipher, double timeTotal);
NAMESPACE_END // Test
NAMESPACE_END // CryptoPP
#endif
|
be8a46d7ac5b4be99a06735fc6c0b606568c35d4 | c2ea0ac6e5fd32c860665d7107eb6c786c4433db | /Traffic Light/Traffic_Light.ino | 589e8daad07ca373e44e13e9a05fa6914a3833e5 | [] | no_license | victor-a-c/ArduinoProj | bb6bfdd0ca6ba6d4e5b59a4050f09c7ec5325e62 | 1eba02ee36e6ff5dad1a2787f2573a1c85d7fc9d | refs/heads/main | 2023-08-17T14:21:39.655237 | 2021-09-28T01:28:56 | 2021-09-28T01:28:56 | 387,040,028 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,375 | ino | Traffic_Light.ino | // Variables for LED pins
int G = 7; // Green, sets pin number for color Green
int Y = 6; // Yellow, sets pin number for color Yellow
int R = 5; // Red, sets pin number for color Red
int PG = 8; // Pedestrian Green light
int PR = 9; // Pedestrian red
//Delay to simulate real traffic light
int del_g = 3000;
int del_y = 1000;
int del_r = 9000;
void setup() {
pinMode(G, OUTPUT);
pinMode(Y, OUTPUT);
pinMode(R, OUTPUT);
pinMode(PG, OUTPUT);
pinMode(PR, OUTPUT);
}
void loop() {
// call methods bellow
tlGreen();
delay(del_g);
tlYellow();
delay(del_y);
tlRed();
delay(del_r);
PGwarn();
}
// methods for traffic light "modes"
void tlGreen()
{
digitalWrite(G, HIGH);
digitalWrite(PR, HIGH);
digitalWrite(Y, LOW);
digitalWrite(R, LOW);
digitalWrite(PG, LOW);
}
void tlYellow()
{
digitalWrite(G, LOW);
digitalWrite(Y, HIGH);
digitalWrite(PR, HIGH);
digitalWrite(R, LOW);
digitalWrite(PG, LOW);
}
void tlRed()
{
digitalWrite(G, LOW);
digitalWrite(Y, LOW);
digitalWrite(R, HIGH);
digitalWrite(PG, HIGH);
digitalWrite(PR, LOW);
}
void PGwarn()
{
//Green pedestrian light blinks to signal that it is about to become red
for(int i = 0; i <= 3; i++)
{
digitalWrite(PG, HIGH);
delay(150);
digitalWrite(PG, LOW);
delay(150);
}
}
|
bfcb09213a0631fd87b5034047aa743b5e757ebd | a90039f2bf987dd365e1fd6025c8ef07972ccad8 | /ProjectLeetEuler/MathUtility.cpp | 99175afeee5518be6af555ec37556332b3fc431a | [] | no_license | codymorg/codevault | 108847cb40f74c187e82e1207ddcbbe97402d4d3 | 3725fe5026a1a44c900e69914019c9c1fe74020f | refs/heads/master | 2021-01-25T09:44:59.536031 | 2019-10-24T04:28:32 | 2019-10-24T04:28:32 | 93,875,914 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,151 | cpp | MathUtility.cpp | /******************************************************************************
* Project Euler Solutions
* Author : Cody Morgan
* Brief : contains utility funstions related to math not computer science
******************************************************************************/
#include "MathUtility.h"
#include "Utility.h"
#include <bitset>
#include <iostream>
using std::cout;
//***** Huge class members *****//
Huge::Huge(unsigned long long init)
{
setValue(init);
}
void Huge::addString(std::string input)
{
std::list<unsigned char>::iterator current = baseArray_.begin();
byte carry = 0;
for (long i = long(input.size() - 1); i >= 0; i--)
{
byte c = input[i];
// size verification
if (current == baseArray_.end())
{
baseArray_.push_back(byte('\0'));
current--;
}
// add this digit
(*current) += c - '0' + carry;
//cout << std::bitset<8>(*current) << '\n';
// carry bit
carry = (*current) / 10;
(*current) %= 10;
//cout << std::bitset<8>(*current) << '\n';
current++;
}
// there could be one more carry
while (carry)
{
if (current == baseArray_.end())
{
baseArray_.push_back(byte('\0'));
current--;
}
// carry bit
(*current) += carry;
carry = (*current) / 10;
(*current) %= 10;
//cout << std::bitset<8>(*current) << '\n';
current++;
}
}
std::list<Huge::byte>::const_iterator Huge::begin() const
{
return baseArray_.begin();
}
std::list<Huge::byte>::const_iterator Huge::end() const
{
return baseArray_.end();
}
void Huge::setValue(unsigned long long value)
{
baseArray_.clear();
std::list<unsigned char>::iterator current = baseArray_.begin();
byte carry = 0;
while (value)
{
byte c = value % 10;
value /= 10;
// size verification
if (current == baseArray_.end())
{
baseArray_.push_back(byte('\0'));
current--;
}
// add this digit
(*current) = c;
(*current) += carry;
//cout << std::bitset<8>(*current) << '\n';
// carry bit
carry = (*current) / 10;
(*current) %= 10;
//cout << std::bitset<8>(*current) << '\n';
current++;
}
// there could be one more carry
while (carry)
{
if (current == baseArray_.end())
{
baseArray_.push_back(byte('\0'));
current--;
}
// carry bit
(*current) += carry;
carry = (*current) / 10;
(*current) %= 10;
//cout << std::bitset<8>(*current) << '\n';
current++;
}
}
unsigned long Huge::size() const
{
return unsigned long(baseArray_.size());
}
//***** Generic math functions *****//
void printHugeFactorial(unsigned number, unsigned until)
{
Huge start(number);
Huge end(number);
Huge factorial(number);
for (unsigned i = number - 1; i > until; i--)
{
factorial *= i;
}
cout << factorial << "\n";
}
unsigned long long factorial(unsigned short number, unsigned short until)
{
unsigned long long f = number;
unsigned long long overflowDetect = f;
for (unsigned long long i = f - 1; i > until; i--)
{
f *= i;
if (f < overflowDetect)
{
throw Exceptions::Overflow(GET_LINE);
}
else
{
overflowDetect = f;
}
}
return f;
}
/******************************************************************************
N choose K determines the number of combinations concerning a given set and
choice of that set. the formula is n! / (k!(n-k)!) and can be simplified to
Π(n->k) / k!
as k! will likely be huge - it is split in have
******************************************************************************/
unsigned long long nChooseK(unsigned short n, unsigned short k)
{
unsigned long long top = factorial(n, k + (k/2)); // get n->k as the factorial on top is canceled
unsigned long long top2 = factorial(k + (k/2), k);
unsigned long long bot = factorial(k / 2); // get half the factorial on bottom as it's going to be big
unsigned long long bot2 = factorial(k, k / 2); // get second half
long double combos = top / double(bot);
combos /= bot2;
combos *= top2;
return unsigned long long(combos);
} |
45afb293796bd199b729595cf32e3c45251fd7c4 | 1834c0796ee324243f550357c67d8bcd7c94de17 | /SDK/TCF_WBP_Notification_Item_classes.hpp | 47813407ddc37b988199198314a37f7d6eb069b2 | [] | no_license | DarkCodez/TCF-SDK | ce41cc7dab47c98b382ad0f87696780fab9898d2 | 134a694d3f0a42ea149a811750fcc945437a70cc | refs/heads/master | 2023-08-25T20:54:04.496383 | 2021-10-25T11:26:18 | 2021-10-25T11:26:18 | 423,337,506 | 1 | 0 | null | 2021-11-01T04:31:21 | 2021-11-01T04:31:20 | null | UTF-8 | C++ | false | false | 4,754 | hpp | TCF_WBP_Notification_Item_classes.hpp | #pragma once
// The Cycle Frontier (1.X) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "TCF_WBP_Notification_Item_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass WBP_Notification_Item.WBP_Notification_Item_C
// 0x0068 (0x02C8 - 0x0260)
class UWBP_Notification_Item_C : public UUserWidget
{
public:
class UWidgetAnimation* WidgetOut_Anim; // 0x0260(0x0008) (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_ZeroConstructor, CPF_Transient, CPF_IsPlainOldData, CPF_RepSkip, CPF_NoDestructor, CPF_HasGetValueTypeHash)
class UWidgetAnimation* WidgetIn_Anim; // 0x0268(0x0008) (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_ZeroConstructor, CPF_Transient, CPF_IsPlainOldData, CPF_RepSkip, CPF_NoDestructor, CPF_HasGetValueTypeHash)
class UImage* Gfx_BackerFill; // 0x0270(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_NoDestructor, CPF_PersistentInstance, CPF_HasGetValueTypeHash)
class UImage* Gfx_BackerFillColorA; // 0x0278(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_NoDestructor, CPF_PersistentInstance, CPF_HasGetValueTypeHash)
class UImage* Gfx_BackerFillColorB; // 0x0280(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_NoDestructor, CPF_PersistentInstance, CPF_HasGetValueTypeHash)
class UImage* Gfx_BackerFillGradient; // 0x0288(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_NoDestructor, CPF_PersistentInstance, CPF_HasGetValueTypeHash)
class UImage* Gfx_BackerFillLight; // 0x0290(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_NoDestructor, CPF_PersistentInstance, CPF_HasGetValueTypeHash)
class UImage* Gfx_Chevrons; // 0x0298(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_NoDestructor, CPF_PersistentInstance, CPF_HasGetValueTypeHash)
class UImage* Icn_NotificationType; // 0x02A0(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_NoDestructor, CPF_PersistentInstance, CPF_HasGetValueTypeHash)
class UImage* Icn_NotificationType_Shadow; // 0x02A8(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_NoDestructor, CPF_PersistentInstance, CPF_HasGetValueTypeHash)
class URichTextBlock* RichTxt_Headline; // 0x02B0(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_NoDestructor, CPF_PersistentInstance, CPF_HasGetValueTypeHash)
class URichTextBlock* RichTxt_Subline; // 0x02B8(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_NoDestructor, CPF_PersistentInstance, CPF_HasGetValueTypeHash)
class UWBP_ProgressBar_C* WBP_ProgressBar; // 0x02C0(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_NoDestructor, CPF_PersistentInstance, CPF_HasGetValueTypeHash)
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("WidgetBlueprintGeneratedClass WBP_Notification_Item.WBP_Notification_Item_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
19ec4a1f3d3854d2363d47afc3b0da892849671b | ee3418a861f9e2e5f30df68a7c8214b4c4cbc995 | /libxkas/arch/snes.cpu.cpp | 259f53755304c6994ac102330a8ad591a0bb1ffd | [
"LicenseRef-scancode-public-domain"
] | permissive | nicklausw/xkas-plus | 4f1afeb571255493259510e4c6c0334a46f689ae | 1ea1b73845755d9ce1426d1c2edc98255d1034ba | refs/heads/master | 2021-01-18T06:08:40.467715 | 2016-04-06T02:45:35 | 2016-04-06T02:45:35 | 55,185,840 | 1 | 0 | null | 2016-03-31T22:01:18 | 2016-03-31T22:01:18 | null | UTF-8 | C++ | false | false | 17,017 | cpp | snes.cpu.cpp | void xkasSNESCPU::init(unsigned pass) {
mapper = NoROM;
header = false;
}
unsigned xkasSNESCPU::archaddr(unsigned addr) {
if(header) addr -= 512;
switch(mapper) {
case NoROM: {
addr = xkasArch::archaddr(addr);
break;
}
case LoROM: {
addr = ((addr & 0x7f8000) << 1) + 0x8000 + (addr & 0x7fff);
break;
}
case HiROM: {
addr = 0xc00000 + (addr & 0x3fffff);
break;
}
case ExLoROM: {
addr = ((addr & 0x7f8000) << 1) + 0x8000 + (addr & 0x7fff) ^ 0x800000;
break;
}
case ExHiROM: {
addr = 0xc00000 + (addr & 0x7fffff);
if (addr >= 0x1000000)
addr ^= 0x1400000;
break;
}
}
return addr;
}
unsigned xkasSNESCPU::fileaddr(unsigned addr) {
switch(mapper) {
case NoROM: {
addr = xkasArch::fileaddr(addr);
break;
}
case LoROM: {
addr = ((addr & 0x7f0000) >> 1) + (addr & 0x7fff);
break;
}
case HiROM: {
addr = addr & 0x3fffff;
break;
}
case ExLoROM: {
addr = (((addr ^ 0x800000) & 0xff0000) >> 1) + (addr & 0x7fff);
break;
}
case ExHiROM: {
if (addr >= 0x800000)
addr &= 0x3fffff;
else
addr = (addr & 0x3fffff) | 0x400000;
break;
}
}
if(header) addr += 512;
return addr;
}
bool xkasSNESCPU::assemble_command(string &s) {
part.qsplit<1>(" ", s);
part[0].lower();
part[0].trim(" ");
if(part.size() > 1) part[1].trim(" ");
if(part[0] == "norom") {
mapper = NoROM;
return true;
}
if(part[0] == "lorom") {
mapper = LoROM;
return true;
}
if(part[0] == "hirom") {
mapper = HiROM;
return true;
}
if(part[0] == "exlorom") {
mapper = ExLoROM;
return true;
}
if(part[0] == "exhirom") {
mapper = ExHiROM;
return true;
}
if(part[0] == "header") {
header = true;
return true;
}
if(part[0] == "noheader") {
header = false;
return true;
}
if(part.size() == 1) {
if(assemble_direct()) return true;
return false;
}
#define match(_l, _r, _fn) \
if (part[1].wildcard(_l "*" _r)) { \
part[1].ltrim<1>(_l); \
part[1].rtrim<1>(_r); \
force_test(); \
return _fn; \
}
match("#", "", assemble_const())
match("", ",s", assemble_sr())
match("(", ",s),y", assemble_sry())
match("(", ",x)", assemble_indirect_x())
match("(", "),y", assemble_indirect_y())
match("(", ")", assemble_indirect())
match("[", "],y", assemble_indirect_long_y())
match("[", "]", assemble_indirect_long())
match("", ",x", assemble_long_x() || assemble_addr_x() || assemble_dp_x())
match("", ",y", assemble_addr_y() || assemble_dp_y())
#undef match
if(part[1].wildcard("*,*")) {
if(assemble_move()) return true;
return false;
}
if(assemble_branch()) return true;
force_test();
if(assemble_long()) return true;
if(assemble_addr()) return true;
if(assemble_dp()) return true;
return false;
}
void xkasSNESCPU::force_test() {
force_byte = force_word = force_long = false;
if(part[0].endswith(".b")) {
force_byte = true;
part[0].rtrim<1>(".b");
} else if(part[0].endswith(".w")) {
force_word = true;
part[0].rtrim<1>(".w");
} else if(part[0].endswith(".l")) {
force_long = true;
part[0].rtrim<1>(".l");
} else {
force_byte = part[1].wildcard("$??");
force_word = part[1].wildcard("$????");
force_long = part[1].wildcard("$??????");
}
}
bool xkasSNESCPU::assemble_direct() {
#define match(str_, hex_) \
if(part[0] == str_ && part.size() == 1) { \
self.write(hex_); \
return true; \
}
match("asl", 0x0a)
match("clc", 0x18)
match("cld", 0xd8)
match("cli", 0x58)
match("clv", 0xb8)
match("dec", 0x3a) match("dea", 0x3a)
match("dex", 0xca)
match("dey", 0x88)
match("inc", 0x1a) match("ina", 0x1a)
match("inx", 0xe8)
match("iny", 0xc8)
match("lsr", 0x4a)
match("nop", 0xea)
match("pha", 0x48)
match("phb", 0x8b)
match("phd", 0x0b)
match("phk", 0x4b)
match("php", 0x08)
match("phx", 0xda)
match("phy", 0x5a)
match("pla", 0x68)
match("plb", 0xab)
match("pld", 0x2b)
match("plp", 0x28)
match("plx", 0xfa)
match("ply", 0x7a)
match("rol", 0x2a)
match("ror", 0x6a)
match("rti", 0x40)
match("rtl", 0x6b)
match("rts", 0x60)
match("sec", 0x38)
match("sed", 0xf8)
match("sei", 0x78)
match("stp", 0xdb)
match("tax", 0xaa)
match("tay", 0xa8)
match("tcd", 0x5b) match("tad", 0x5b)
match("tcs", 0x1b) match("tas", 0x1b)
match("tdc", 0x7b) match("tda", 0x7b)
match("tsc", 0x3b) match("tsa", 0x3b)
match("tsx", 0xba)
match("txa", 0x8a)
match("txs", 0x9a)
match("txy", 0x9b)
match("tya", 0x98)
match("tyx", 0xbb)
match("wai", 0xcb)
match("xba", 0xeb) match("swa", 0xeb)
match("xce", 0xfb)
#undef match
return false;
}
bool xkasSNESCPU::assemble_const() {
if(force_long) return false;
#define match(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
for(unsigned i = 0; i < n; i++) { \
self.write(hex_); \
} \
return true; \
}
#define matchb(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
return true; \
}
#define matchw(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
self.write(n >> 8); \
return true; \
}
#define matchv(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
if(!force_byte) self.write(n >> 8); \
return true; \
}
//repetition matches
match("asl", 0x0a)
match("clc", 0x18)
match("cld", 0xd8)
match("cli", 0x58)
match("clv", 0xb8)
match("dec", 0x3a) match("dea", 0x3a)
match("dex", 0xca)
match("dey", 0x88)
match("inc", 0x1a) match("ina", 0x1a)
match("inx", 0xe8)
match("iny", 0xc8)
match("lsr", 0x4a)
match("nop", 0xea)
match("pha", 0x48)
match("phb", 0x8b)
match("phd", 0x0b)
match("phk", 0x4b)
match("php", 0x08)
match("phx", 0xda)
match("phy", 0x5a)
match("pla", 0x68)
match("plb", 0xab)
match("pld", 0x2b)
match("plp", 0x28)
match("plx", 0xfa)
match("ply", 0x7a)
match("rol", 0x2a)
match("ror", 0x6a)
match("rti", 0x40)
match("rtl", 0x6b)
match("rts", 0x60)
match("sec", 0x38)
match("sed", 0xf8)
match("sei", 0x78)
match("stp", 0xdb)
match("tax", 0xaa)
match("tay", 0xa8)
match("tcd", 0x5b) match("tad", 0x5b)
match("tcs", 0x1b) match("tas", 0x1b)
match("tdc", 0x7b) match("tda", 0x7b)
match("tsc", 0x3b) match("tsa", 0x3b)
match("tsx", 0xba)
match("txa", 0x8a)
match("txs", 0x9a)
match("txy", 0x9b)
match("tya", 0x98)
match("tyx", 0xbb)
match("wai", 0xcb)
match("xba", 0xeb) match("swa", 0xeb)
match("xce", 0xfb)
//const matches
matchv("adc", 0x69)
matchv("and", 0x29)
matchv("bit", 0x89)
matchb("brk", 0x00)
matchv("cmp", 0xc9)
matchb("cop", 0x02)
matchv("cpx", 0xe0)
matchv("cpy", 0xc0)
matchv("eor", 0x49)
matchv("lda", 0xa9)
matchv("ldx", 0xa2)
matchv("ldy", 0xa0)
matchv("ora", 0x09)
matchb("rep", 0xc2)
matchv("sbc", 0xe9)
matchb("sep", 0xe2)
matchb("wdm", 0x42)
#undef match
#undef matchb
#undef matchw
#undef matchv
return false;
}
bool xkasSNESCPU::assemble_indirect_x() {
if(force_long) return false;
#define matchb(str_, hex_) \
if(part[0] == str_ && !force_word) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
return true; \
}
#define matchw(str_, hex_) \
if(part[0] == str_ && !force_byte) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
self.write(n >> 8); \
return true; \
}
matchb("adc", 0x61)
matchb("and", 0x21)
matchb("cmp", 0xc1)
matchb("eor", 0x41)
matchw("jmp", 0x7c)
matchw("jsr", 0xfc)
matchb("lda", 0xa1)
matchb("ora", 0x01)
matchb("sbc", 0xe1)
matchb("sta", 0x81)
#undef matchb
#undef matchw
return false;
}
bool xkasSNESCPU::assemble_indirect_y() {
if(force_word || force_long) return false;
#define match(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
return true; \
}
match("adc", 0x71)
match("and", 0x31)
match("cmp", 0xd1)
match("eor", 0x51)
match("lda", 0xb1)
match("ora", 0x11)
match("sbc", 0xf1)
match("sta", 0x91)
#undef match
return false;
}
bool xkasSNESCPU::assemble_indirect() {
if(force_long) return false;
#define matchb(str_, hex_) \
if(part[0] == str_ && !force_word) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
return true; \
}
#define matchw(str_, hex_) \
if(part[0] == str_ && !force_byte) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
self.write(n >> 8); \
return true; \
}
matchb("adc", 0x72)
matchb("and", 0x32)
matchb("cmp", 0xd2)
matchb("eor", 0x52)
matchw("jmp", 0x6c)
matchb("lda", 0xb2)
matchb("ora", 0x12)
matchb("pei", 0xd4)
matchb("sbc", 0xf2)
matchb("sta", 0x92)
#undef matchb
#undef matchw
return false;
}
bool xkasSNESCPU::assemble_indirect_long_y() {
if(force_word || force_long) return false;
#define match(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
return true; \
}
match("adc", 0x77)
match("and", 0x37)
match("cmp", 0xd7)
match("eor", 0x57)
match("lda", 0xb7)
match("ora", 0x17)
match("sbc", 0xf7)
match("sta", 0x97)
#undef match
return false;
}
bool xkasSNESCPU::assemble_indirect_long() {
if(force_long) return false;
#define matchb(str_, hex_) \
if(part[0] == str_ && !force_word) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
return true; \
}
#define matchw(str_, hex_) \
if(part[0] == str_ && !force_byte) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
self.write(n >> 8); \
return true; \
}
matchb("adc", 0x67)
matchb("and", 0x27)
matchb("cmp", 0xc7)
matchb("eor", 0x47)
matchw("jmp", 0xdc) matchw("jml", 0xdc)
matchb("lda", 0xa7)
matchb("ora", 0x07)
matchb("sbc", 0xe7)
matchb("sta", 0x87)
#undef matchb
#undef matchw
return false;
}
bool xkasSNESCPU::assemble_sr() {
if(force_word || force_long) return false;
#define match(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
return true; \
}
match("adc", 0x63)
match("and", 0x23)
match("cmp", 0xc3)
match("eor", 0x43)
match("lda", 0xa3)
match("ora", 0x03)
match("sbc", 0xe3)
match("sta", 0x83)
#undef match
return false;
}
bool xkasSNESCPU::assemble_sry() {
if(force_word || force_long) return false;
#define match(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
return true; \
}
match("adc", 0x73)
match("and", 0x33)
match("cmp", 0xd3)
match("eor", 0x53)
match("lda", 0xb3)
match("ora", 0x13)
match("sbc", 0xf3)
match("sta", 0x93)
#undef match
return false;
}
bool xkasSNESCPU::assemble_move() {
if(part[0] == "mvn" || part[0] == "mvp") {
//(mvn,mvp) source,dest -> (0x54,0x44) dest source
subpart.split(",", part[1]);
if(subpart.size() > 2) return false;
self.write(part[0] == "mvn" ? 0x54 : 0x44);
self.write(self.decode(subpart[1]));
self.write(self.decode(subpart[0]));
return true;
}
return false;
}
bool xkasSNESCPU::assemble_long_x() {
if(force_byte || force_word) return false;
#define match(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
self.write(n >> 8); \
self.write(n >> 16); \
return true; \
}
match("adc", 0x7f)
match("and", 0x3f)
match("cmp", 0xdf)
match("eor", 0x5f)
match("lda", 0xbf)
match("ora", 0x1f)
match("sbc", 0xff)
match("sta", 0x9f)
#undef match
return false;
}
bool xkasSNESCPU::assemble_addr_x() {
if(force_byte || force_long) return false;
#define match(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
self.write(n >> 8); \
return true; \
}
match("adc", 0x7d)
match("and", 0x3d)
match("asl", 0x1e)
match("bit", 0x3c)
match("cmp", 0xdd)
match("dec", 0xde)
match("eor", 0x5d)
match("inc", 0xfe)
match("lda", 0xbd)
match("ldy", 0xbc)
match("lsr", 0x5e)
match("ora", 0x1d)
match("rol", 0x3e)
match("ror", 0x7e)
match("sbc", 0xfd)
match("sta", 0x9d)
match("stz", 0x9e)
#undef match
return false;
}
bool xkasSNESCPU::assemble_dp_x() {
if(force_word || force_long) return false;
#define match(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
return true; \
}
match("adc", 0x75)
match("and", 0x35)
match("asl", 0x16)
match("bit", 0x34)
match("cmp", 0xd5)
match("dec", 0xd6)
match("eor", 0x55)
match("inc", 0xf6)
match("lda", 0xb5)
match("ldy", 0xb4)
match("lsr", 0x56)
match("ora", 0x15)
match("rol", 0x36)
match("ror", 0x76)
match("sbc", 0xf5)
match("sta", 0x95)
match("sty", 0x94)
match("stz", 0x74)
#undef match
return false;
}
bool xkasSNESCPU::assemble_addr_y() {
if(force_byte || force_long) return false;
#define match(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
self.write(n >> 8); \
return true; \
}
match("adc", 0x79)
match("and", 0x39)
match("cmp", 0xd9)
match("eor", 0x59)
match("lda", 0xb9)
match("ldx", 0xbe)
match("ora", 0x19)
match("sbc", 0xf9)
match("sta", 0x99)
#undef match
return false;
}
bool xkasSNESCPU::assemble_dp_y() {
if(force_word || force_long) return false;
#define match(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
return true; \
}
match("ldx", 0xb6);
match("stx", 0x96);
#undef match
return false;
}
bool xkasSNESCPU::assemble_long() {
if(force_byte || force_word) return false;
#define match(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
self.write(n >> 8); \
self.write(n >> 16); \
return true; \
}
match("adc", 0x6f)
match("and", 0x2f)
match("cmp", 0xcf)
match("eor", 0x4f)
match("jml", 0x5c)
match("jsl", 0x22)
match("lda", 0xaf)
match("ora", 0x0f)
match("sbc", 0xef)
match("sta", 0x8f)
#undef match
return false;
}
bool xkasSNESCPU::assemble_addr() {
if(force_byte || force_long) return false;
#define match(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
self.write(n >> 8); \
return true; \
}
match("adc", 0x6d)
match("and", 0x2d)
match("asl", 0x0e)
match("bit", 0x2c)
match("cmp", 0xcd)
match("cpx", 0xec)
match("cpy", 0xcc)
match("dec", 0xce)
match("eor", 0x4d)
match("inc", 0xee)
match("jmp", 0x4c)
match("jsr", 0x20)
match("lda", 0xad)
match("ldx", 0xae)
match("ldy", 0xac)
match("lsr", 0x4e)
match("ora", 0x0d)
match("pea", 0xf4)
match("per", 0x62)
match("rol", 0x2e)
match("ror", 0x6e)
match("sbc", 0xed)
match("sta", 0x8d)
match("stx", 0x8e)
match("sty", 0x8c)
match("stz", 0x9c)
match("trb", 0x1c)
match("tsb", 0x0c)
#undef match
return false;
}
bool xkasSNESCPU::assemble_dp() {
if(force_word || force_long) return false;
#define match(str_, hex_) \
if(part[0] == str_) { \
unsigned n = self.decode(part[1]); \
self.write(hex_); \
self.write(n); \
return true; \
}
match("adc", 0x65)
match("and", 0x25)
match("asl", 0x06)
match("bit", 0x24)
match("cmp", 0xc5)
match("cpx", 0xe4)
match("cpy", 0xc4)
match("dec", 0xc6)
match("eor", 0x45)
match("inc", 0xe6)
match("lda", 0xa5)
match("ldx", 0xa6)
match("ldy", 0xa4)
match("lsr", 0x46)
match("ora", 0x05)
match("rol", 0x26)
match("ror", 0x66)
match("sbc", 0xe5)
match("sta", 0x85)
match("stx", 0x86)
match("sty", 0x84)
match("stz", 0x64)
match("trb", 0x14)
match("tsb", 0x04)
#undef match
return false;
}
bool xkasSNESCPU::assemble_branch() {
#define match(str_, hex_, word_) \
if(part[0] == str_) { \
int n = self.decode(part[1]); \
if(!word_) { \
if(!part[1].wildcard("$??")) { \
n = n - (self.pc() + 2); \
} \
if(self.pass == 2 && (n < -128 || n > 127)) { \
self.error = "short branch target out of bounds"; \
return false; \
} \
self.write(hex_); \
self.write(n); \
} else { \
if(!part[1].wildcard("$????")) { \
n = n - (self.pc() + 3); \
} \
if(self.pass == 2 && (n < -32768 || n > 32767)) { \
self.error = "long branch target out of bounds"; \
return false; \
} \
self.write(hex_); \
self.write(n); \
self.write(n >> 8); \
} \
return true; \
}
match("brl", 0x82, true)
match("bcc", 0x90, false)
match("bcs", 0xb0, false)
match("beq", 0xf0, false)
match("bne", 0xd0, false)
match("bmi", 0x30, false)
match("bpl", 0x10, false)
match("bvc", 0x50, false)
match("bvs", 0x70, false)
match("bra", 0x80, false)
#undef match
return false;
}
xkasSNESCPU::xkasSNESCPU(xkas &self) : xkasArch(self) {
}
|
aa15382e901426e946cc1be72c44ea2b151d0ecc | 712dae5150a3a150173395457c81b684d5b25115 | /arduino/connector/Connection.h | 5d070dfebeb20c1792922ed785effaac584d3c5b | [
"MIT"
] | permissive | dmitrymark/SpaceshipConnect | 72fb30889d000398061b4692ba332f9b5718a07b | 99b6f49412f499ef9fe71a154f30c2c204409225 | refs/heads/master | 2023-05-06T03:27:09.105216 | 2021-05-23T16:41:20 | 2021-05-23T16:41:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 217 | h | Connection.h | #pragma once
#include <Arduino.h>
#include "protocol.h"
class Connection {
static Stream &stream;
public:
bool readRequest(ConnectorRequest &outRequest);
bool writeReply(ConnectorReply &reply);
};
|
5b8c98578fa50973aa8a4c05ec20b20fd6f40c9b | 440f814f122cfec91152f7889f1f72e2865686ce | /src/game_server/server/extension/item/configure.h | cc9324edc651b85206545478e334c898b8c34845 | [] | no_license | hackerlank/buzz-server | af329efc839634d19686be2fbeb700b6562493b9 | f76de1d9718b31c95c0627fd728aba89c641eb1c | refs/heads/master | 2020-06-12T11:56:06.469620 | 2015-12-05T08:03:25 | 2015-12-05T08:03:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,913 | h | configure.h | //
// Summary: buzz source code.
//
// Author: Tony.
// Email: tonyjobmails@gmail.com.
// Last modify: 2013-05-22 10:56:31.
// File name: configure.h
//
// Description:
// Define class Configure.
//
#ifndef __GAME__SERVER__ITEM__CONFIGURE__H
#define __GAME__SERVER__ITEM__CONFIGURE__H
#include <string>
#include "core/base/types.h"
#include "entity/item_types.h"
#include "game_server/server/extension/item/item_configure.h"
#include "game_server/server/extension/item/load_equipment_configure.h"
#include "game_server/server/extension/item/load_equip_refine_configure.h"
#include "game_server/server/extension/item/load_gem_configure.h"
#include "game_server/server/extension/item/load_hunt_treasure_configure.h"
#include "game_server/server/extension/item/load_intensify_configure.h"
#include "game_server/server/extension/item/load_item_compose_configure.h"
#include "game_server/server/extension/item/load_mall_configure.h"
#include "game_server/server/extension/item/load_material_configure.h"
#include "game_server/server/extension/item/load_medicine_configure.h"
#include "game_server/server/extension/item/load_vip_gifts_configure.h"
#include "game_server/server/extension/item/load_random_attribute.h"
#include "game_server/server/extension/item/load_shop_configure.h"
#include "game_server/server/extension/item/load_suit_configure.h"
#include "game_server/server/extension/item/load_treasure_spend_configure.h"
#include "global/singleton_factory.h"
namespace game {
namespace server {
namespace item {
class Configure : public global::SingletonFactory<Configure> {
friend class global::SingletonFactory<Configure>;
public:
bool LoadConfigure(const std::string &file);
// 获取材料配置
const MaterialCell *GetMaterialConfigure(core::uint32 id) const;
// 获取药品配置
const MedicineCell *GetMedicineConfigure(core::uint32 id) const;
// 获取装备配置
const EquipmentCell *GetEquipmentConfigure(core::uint32 id) const;
// 获取物品配置
const ItemCell *GetItem(core::uint32 id) const;
// 随机出一个属性
const RandomAttributeCell *GetRandomAttribute(core::uint32 random_id) const;
// 获取强化配置
const IntensifyCell *GetIntensifyConfigure(core::int32 equip_level,
core::int32 intensify) const;
// 获取洗练消耗配置
const EquipRefineSpendCell *GetRefineConfigure(core::int32 lv, core::int32 quality) const;
// 获取洗练加锁配置
const EquipRefineSpendLockCell *GetRefineLockConfigure(core::int32 lock_num) const;
// 获取加载随机配置对象
const LoadRandomAttribute &GetLoadRandomeAttribute() {
return this->load_random_attribute_;
}
// 获取商店配置
bool CheckShopTemplateID(core::int32 id);
// 获取宝石配置
const GemCell *GetGem(core::int32 id, core::int32 level) const;
core::int32 GetRandomGemIDByQuality(GemCell::QualityType::type type) const;
// 获取VIP礼包配置
const LoadVipGiftsConfigure::Awards *GetAwards(entity::VipType::type type) const;
// 获取宝石激活点配置
const GemGatheringPointCell *GetGemGatheringPoint(core::int32 id) const;
const GemGatheringPointCell *GetNextGemGatheringPoint(core::int32 id) const;
const GemGatheringPointCell *GetPrevGemGatheringPoint(core::int32 id) const;
const GemGatheringPointCell *GetLastGemGatheringPoint() const;
// 获取商城配置
LoadMallConfigure &GetMallConfigure() {
return this->load_mall_;
}
// 获取道具合成配方配置
const ItemComposeRecipeCell *GetItemComposeRecipe(core::int32 id) const;
// 获取套装配置
const LoadSuitConfigure::EffectVecs *GetSuit(core::int32 suit_id) const;
// 获取寻宝掉落
HuntTreasureRandCell *GetTreasureRandDrop(core::int32 tab_id);
// 获取寻宝消耗
const TreasureSpendCell *GetSpendCell(core::int32 id, core::int32 num) const;
// 获取标签页对应的积分类型
IntegralType::type GetItegralType(core::int32 tab_id);
// 物品对象池初始化数量/扩展数量
int item_initial_number_;
int item_extend_number_;
static const float kIntensifyVar1_;
static const float kIntensifyVar2_;
private:
Configure() {}
~Configure() {}
LoadMaterialConfigure load_material_configure_;
LoadMedicineConfigure load_medicine_configure_;
LoadEquipmentConfigure load_equipment_configure_;
LoadRandomAttribute load_random_attribute_;
LoadIntensifyConfigure load_intensify_;
LoadEquipRefineConfigure load_refine_;
LoadGemConfigure load_gem_;
LoadShopConfigure load_shop_;
LoadMallConfigure load_mall_;
LoadVipGiftsConfigure load_vip_gifts_;
LoadItemComposeConfigure load_item_compose_recipe_;
LoadSuitConfigure load_suit_configure_;
LoadTreasureSpendConfigure load_treasure_spend_;
LoadHuntTreasureConfigure load_hunt_treasure_;
};
} // namespace item
} // namespace server
} // namespace game
#endif // __GAME__SERVER__ITEM__CONFIGURE__H
|
c8a8b8aa429b3899ad430c6e46bc7b4823cf99c5 | ad1e42faf8aaf531c1f39c15d9024b4c438ec91e | /GoogleQuestions/data_structure.cpp | d70aae088de2d191108295ef9297d70463078e4c | [] | no_license | ChokshiUtsav/CompetitiveProgramming | 02c95325a0012d70d899ecfd8822c68cdb678aaf | 1acf2022af9b49214511a863365b41611955df49 | refs/heads/master | 2020-04-17T06:55:19.841229 | 2019-08-28T07:34:29 | 2019-08-28T07:34:29 | 66,943,474 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,002 | cpp | data_structure.cpp | /*
Question :
Create data structure that supports following operations :
1) InsertOrReplace(index, value)
2) FindSmallestIndexFor(value)
Both index and value are integers
*/
/*
Solution Analysis :
Time Complexity :
1) InsertOrReplace -> O(logn)
2) FindSmallestIndexFor -> O(logn)
Space Complexity :
O(n)
*/
/*
Alternate Solution Analysis :
If we would have used mean heap(i.e. priority_queue) for storing index against values then
Time Complexity :
1) InsertOrReplace -> O(n) as deleting element from min heap takes O(n)
2) FindSmallestIndexFor -> O(1)
If we would have used hash set(i.e. unordered_set) for storing index against values then
Time Complexity :
1) InsertOrReplace -> O(1)
2) FindSmallestIndexFor -> O(n) as finding min element from hash set takes O(n)
*/
#include <iostream>
#include <set>
#include <unordered_map>
using namespace std;
class BidirectionalMap{
private:
unordered_map<int,int> indexMap;
unordered_map<int,set<int>> valueMap;
public:
void insertOrReplace(int index, int value){
if(indexMap.find(index) != indexMap.end()){
int oldValue = indexMap[index];
valueMap[oldValue].erase(index);
}
indexMap[index] = value;
if(valueMap.find(value) == valueMap.end()){
valueMap[value] = set<int>();
}
valueMap[value].insert(index);
}
int findSmallestIndexFor(int value){
if(valueMap.find(value) == valueMap.end() || valueMap[value].empty()){
return -1;
}
return *valueMap[value].begin();
}
};
int main(){
BidirectionalMap bidiMap;
bidiMap.insertOrReplace(0,200);
bidiMap.insertOrReplace(2,100);
bidiMap.insertOrReplace(1,100);
assert(1 == bidiMap.findSmallestIndexFor(100));
assert(-1 == bidiMap.findSmallestIndexFor(99));
bidiMap.insertOrReplace(0,100);
assert(0 == bidiMap.findSmallestIndexFor(100));
assert(-1 == bidiMap.findSmallestIndexFor(200));
return 0;
} |
1c675c37678aac929f5b3b615e5dfb68a0dc407c | e12376aadfc081042c5df6eeb9954091b8801493 | /vcf/src/vcf/FoundationKit/OSXSystemToolkit.cpp | d144dfd42d6a3d0c2d650e561b2da3479a072941 | [] | no_license | jimcrafton/visualcomponentframework | 65d5c4a72309884477089ce102ebc44f3eb28e27 | 87d7f44ad15bbf42fac6c8cd5fba3c6ecc51eb45 | refs/heads/master | 2022-11-30T05:44:27.210513 | 2022-11-19T01:29:35 | 2022-11-19T01:29:35 | 181,391,567 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,236 | cpp | OSXSystemToolkit.cpp | //OSXSystemToolkit.cpp
/*
Copyright 2000-2004 The VCF Project.
Please see License.txt in the top level directory
where you installed the VCF.
*/
#include "vcf/FoundationKit/FoundationKit.h"
#include "vcf/FoundationKit/FoundationKitPrivate.h"
#include "vcf/FoundationKit/LocalePeer.h"
#include "vcf/FoundationKit/OSXLocalePeer.h"
#include "vcf/FoundationKit/ResourceBundlePeer.h"
#include "vcf/FoundationKit/OSXResourceBundle.h"
#include "vcf/FoundationKit/OSXLibraryPeer.h"
#include "vcf/FoundationKit/RunLoopPeer.h"
#include "vcf/FoundationKit/OSXRunLoopPeer.h"
#include "vcf/FoundationKit/OSXRunLoopTimerPeer.h"
#include "vcf/FoundationKit/OSXRunLoopSourcePeer.h"
#include "vcf/FoundationKit/ThreadManagerPeer.h"
#include "vcf/FoundationKit/OSXThreadManagerPeer.h"
using namespace VCF;
OSXSystemToolkit::OSXSystemToolkit()
{
}
OSXSystemToolkit::~OSXSystemToolkit()
{
}
ProcessPeer* OSXSystemToolkit::internal_createProcessPeer( Process* process )
{
ProcessPeer* result = NULL;
result = new OSXProcessPeer();
return result;
}
ThreadPeer* OSXSystemToolkit::internal_createThreadPeer( Thread* thread, bool mainThread )
{
return new OSXThread( thread, mainThread );
}
ThreadManagerPeer* OSXSystemToolkit::internal_createThreadManagerPeer()
{
return new OSXThreadManagerPeer();
}
RunLoopPeer* OSXSystemToolkit::internal_createRunLoopPeer( RunLoop* runLoop )
{
return new OSXRunLoopPeer( runLoop );
}
RunLoopTimerPeer* OSXSystemToolkit::internal_createRunLoopTimerPeer( RunLoopTimer* timer )
{
return new OSXRunLoopTimerPeer( timer );
}
RunLoopSourcePeer* OSXSystemToolkit::internal_createRunLoopSourcePeer( RunLoopSource* source )
{
return new OSXRunLoopSourcePeer( source );
}
SystemPeer* OSXSystemToolkit::internal_createSystemPeer()
{
return new OSXSystemPeer();
}
SemaphorePeer* OSXSystemToolkit::internal_createSemaphorePeer( int32 initialCount, int32 maxCount )
{
return new OSXSemaphore( initialCount, maxCount );
}
RegistryPeer* OSXSystemToolkit::internal_createRegistryPeer( Registry* registry )
{
return NULL;//new LinuxRegistry();
}
MutexPeer* OSXSystemToolkit::internal_createMutexPeer( Mutex* mutex )
{
return new OSXMutex( );
}
ConditionPeer* OSXSystemToolkit::internal_createConditionPeer( Condition* condition )
{
return new OSXConditionPeer(condition);
}
LibraryPeer* OSXSystemToolkit::internal_createLibraryPeer( Library* library )
{
return new OSXLibraryPeer();
}
FilePeer* OSXSystemToolkit::internal_createFilePeer( File* file )
{
return new OSXFilePeer( file );
}
FileStreamPeer* OSXSystemToolkit::internal_createFileStreamPeer( const String& filename, const FileStreamAccessType& accessType )
{
return new OSXFileStream( filename, accessType );
}
FileStreamPeer* OSXSystemToolkit::internal_createFileStreamPeer( File* file )
{
return new OSXFileStream( file );
}
ProcessIORedirectionPeer* OSXSystemToolkit::internal_createProcessIORedirectionPeer( ProcessWithRedirectedIO* process )
{
//result->setProcess( process );
return NULL;//result;
}
LocalePeer* OSXSystemToolkit::internal_createLocalePeer()
{
return new OSXLocalePeer();
}
ResourceBundlePeer* OSXSystemToolkit::internal_createResourceBundlePeer()
{
return new OSXResourceBundle();
}
/**
$Id$
*/
|
98e3d7b455dabd2dbd04d2a9fd1cbb3de18d15e6 | c6f7399a05720083f5ead9880eeb5492f28954c4 | /src/pke/unittest/UnitTestSHE.cpp | 000a101cd879d0030ed97e579d8ccea793b6dc8f | [
"BSD-2-Clause"
] | permissive | uishi/Modified_PALISADEv1.9.2 | 88ebf027683ef8eb48a056e1ca2d52a028ccefe1 | d8bf4739144e53340481721b1df83dfff2f65cd8 | refs/heads/master | 2023-03-14T10:31:01.250592 | 2021-02-22T08:12:59 | 2021-02-22T08:12:59 | 341,124,793 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 27,401 | cpp | UnitTestSHE.cpp | /*
* @file
* @author TPOC: contact@palisade-crypto.org
*
* @copyright Copyright (c) 2019, New Jersey Institute of Technology (NJIT)
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "include/gtest/gtest.h"
#include <iostream>
#include <vector>
#include <list>
#include "palisade.h"
#include "cryptocontexthelper.h"
#include "cryptocontextgen.h"
#include "utils/testcasegen.h"
using namespace std;
using namespace lbcrypto;
class UTSHE : public ::testing::Test {
public:
const usint m = 16;
UTSHE() {}
~UTSHE() {}
protected:
void SetUp() {
}
void TearDown() {
CryptoContextFactory<Poly>::ReleaseAllContexts();
CryptoContextFactory<DCRTPoly>::ReleaseAllContexts();
}
};
// This file unit tests the SHE capabilities for all schemes, using all known elements
// FIXME NativePoly SHE tests no bueno on Mult
//GENERATE_PKE_TEST_CASE(x, y, NativePoly, BFV_rlwe, ORD, PTM)
//GENERATE_PKE_TEST_CASE(x, y, NativePoly, BFV_opt, ORD, PTM)
#define GENERATE_TEST_CASES_FUNC(x,y,ORD,PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, Null, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BGV_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BGV_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BFV_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BFVrns_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BFVrns_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BFVrnsB_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BFVrnsB_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, NativePoly, Null, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, NativePoly, BGV_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, NativePoly, BFVrns_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, NativePoly, BFVrns_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, NativePoly, BFVrnsB_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, NativePoly, BFVrnsB_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, Null, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BGV_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BGV_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BFVrns_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BFVrns_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BFVrnsB_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BFVrnsB_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BFV_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, NativePoly, BGV_opt, ORD, PTM)
// For EvalAtIndex
#define GENERATE_TEST_CASES_FUNC_EVALATINDEX(x,y,ORD,PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, Null, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BGV_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BGV_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BFV_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BFVrns_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BFVrns_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BFVrnsB_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BFVrnsB_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, NativePoly, Null, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, NativePoly, BGV_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, NativePoly, BFVrns_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, NativePoly, BFVrns_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, NativePoly, BFVrnsB_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, NativePoly, BFVrnsB_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, Null, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BGV_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BGV_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BFVrns_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BFVrns_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BFVrnsB_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BFVrnsB_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, Poly, BFV_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, NativePoly, BGV_opt, ORD, PTM)
// For EvalSum
#define GENERATE_TEST_CASES_FUNC_EVALSUM(x,y,ORD,PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BFVrns_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BFVrns_opt, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BFVrnsB_rlwe, ORD, PTM) \
GENERATE_PKE_TEST_CASE(x, y, DCRTPoly, BFVrnsB_opt, ORD, PTM)
static vector<string> AllSchemes( {"Null", "BGV", "BFV", /*"BFVrns"*/} );
typedef ::testing::Types<Poly, DCRTPoly, NativePoly> EncryptElementTypes;
// NOTE the SHE tests are all based on these
static const usint ORDER = 16;
static const usint PTMOD = 64;
template<class Element>
static void UnitTest_Add_Packed(const CryptoContext<Element> cc, const string& failmsg) {
std::vector<int64_t> vectorOfInts1 = { 1,0,3,1,0,1,2,1 };
Plaintext plaintext1 = cc->MakeCoefPackedPlaintext(vectorOfInts1);
std::vector<int64_t> vectorOfInts2 = { 2,1,3,2,2,1,3,0 };
Plaintext plaintext2 = cc->MakeCoefPackedPlaintext(vectorOfInts2);
std::vector<int64_t> vectorOfIntsAdd = { 3,1,6,3,2,2,5,1 };
Plaintext plaintextAdd = cc->MakeCoefPackedPlaintext(vectorOfIntsAdd);
std::vector<int64_t> vectorOfIntsSub = { -1,-1,0,-1,-2,0,-1,1 };
Plaintext plaintextSub = cc->MakeCoefPackedPlaintext(vectorOfIntsSub);
LPKeyPair<Element> kp = cc->KeyGen();
Ciphertext<Element> ciphertext1 = cc->Encrypt(kp.publicKey, plaintext1);
Ciphertext<Element> ciphertext2 = cc->Encrypt(kp.publicKey, plaintext2);
Ciphertext<Element> cResult;
Plaintext results;
cResult = cc->EvalAdd(ciphertext1, ciphertext2);
cc->Decrypt(kp.secretKey, cResult, &results);
results->SetLength(plaintextAdd->GetLength());
EXPECT_EQ(plaintextAdd->GetCoefPackedValue(), results->GetCoefPackedValue()) << failmsg << " EvalAdd fails";
cResult = ciphertext1 + ciphertext2;
cc->Decrypt(kp.secretKey, cResult, &results);
results->SetLength(plaintextAdd->GetLength());
EXPECT_EQ(plaintextAdd->GetCoefPackedValue(), results->GetCoefPackedValue()) << failmsg << " operator+ fails";
Ciphertext<Element> caddInplace(ciphertext1);
caddInplace += ciphertext2;
cc->Decrypt(kp.secretKey, caddInplace, &results);
results->SetLength(plaintextAdd->GetLength());
EXPECT_EQ(plaintextAdd->GetCoefPackedValue(), results->GetCoefPackedValue()) << failmsg << " operator+= fails";
cResult = cc->EvalSub(ciphertext1, ciphertext2);
cc->Decrypt(kp.secretKey, cResult, &results);
results->SetLength(plaintextSub->GetLength());
EXPECT_EQ(plaintextSub->GetCoefPackedValue(), results->GetCoefPackedValue()) << failmsg << " EvalSub fails";
cResult = ciphertext1 - ciphertext2;
cc->Decrypt(kp.secretKey, cResult, &results);
results->SetLength(plaintextSub->GetLength());
EXPECT_EQ(plaintextSub->GetCoefPackedValue(), results->GetCoefPackedValue()) << failmsg << " operator- fails";
Ciphertext<Element> csubInplace(ciphertext1);
csubInplace -= ciphertext2;
cc->Decrypt(kp.secretKey, csubInplace, &results);
results->SetLength(plaintextSub->GetLength());
EXPECT_EQ(plaintextSub->GetCoefPackedValue(), results->GetCoefPackedValue()) << failmsg << " operator-= fails";
cResult = cc->EvalAdd(ciphertext1, plaintext2);
cc->Decrypt(kp.secretKey, cResult, &results);
results->SetLength(plaintextAdd->GetLength());
EXPECT_EQ(plaintextAdd->GetCoefPackedValue(), results->GetCoefPackedValue()) << failmsg << " EvalAdd Ct and Pt fails";
cResult = cc->EvalSub(ciphertext1, plaintext2);
cc->Decrypt(kp.secretKey, cResult, &results);
results->SetLength(plaintextSub->GetLength());
EXPECT_EQ(plaintextSub->GetCoefPackedValue(), results->GetCoefPackedValue()) << failmsg << " EvalSub Ct and Pt fails";
}
GENERATE_TEST_CASES_FUNC(UTSHE, UnitTest_Add_Packed, ORDER, PTMOD)
template<class Element>
static void UnitTest_Add_Scalar(const CryptoContext<Element> cc, const string& failmsg) {
Plaintext plaintext1 = cc->MakeScalarPlaintext(1);
Plaintext plaintext2 = cc->MakeScalarPlaintext(2);
Plaintext plaintextAdd = cc->MakeScalarPlaintext(3);
Plaintext plaintextSub = cc->MakeScalarPlaintext(-1);
LPKeyPair<Element> kp = cc->KeyGen();
Ciphertext<Element> ciphertext1 = cc->Encrypt(kp.publicKey, plaintext1);
Ciphertext<Element> ciphertext2 = cc->Encrypt(kp.publicKey, plaintext2);
Ciphertext<Element> cResult;
Plaintext results;
cResult = cc->EvalAdd(ciphertext1, ciphertext2);
cc->Decrypt(kp.secretKey, cResult, &results);
EXPECT_EQ(plaintextAdd->GetScalarValue(), results->GetScalarValue()) << failmsg << " EvalAdd fails";
cResult = ciphertext1 + ciphertext2;
cc->Decrypt(kp.secretKey, cResult, &results);
EXPECT_EQ(plaintextAdd->GetScalarValue(), results->GetScalarValue()) << failmsg << " operator+ fails";
Ciphertext<Element> caddInplace(ciphertext1);
caddInplace += ciphertext2;
cc->Decrypt(kp.secretKey, caddInplace, &results);
EXPECT_EQ(plaintextAdd->GetScalarValue(), results->GetScalarValue()) << failmsg << " operator+= fails";
cResult = cc->EvalSub(ciphertext1, ciphertext2);
cc->Decrypt(kp.secretKey, cResult, &results);
EXPECT_EQ(plaintextSub->GetScalarValue(), results->GetScalarValue()) << failmsg << " EvalSub fails";
cResult = ciphertext1 - ciphertext2;
cc->Decrypt(kp.secretKey, cResult, &results);
EXPECT_EQ(plaintextSub->GetScalarValue(), results->GetScalarValue()) << failmsg << " operator- fails";
Ciphertext<Element> csubInplace(ciphertext1);
csubInplace -= ciphertext2;
cc->Decrypt(kp.secretKey, csubInplace, &results);
EXPECT_EQ(plaintextSub->GetScalarValue(), results->GetScalarValue()) << failmsg << " operator-= fails";
cResult = cc->EvalAdd(ciphertext1, plaintext2);
cc->Decrypt(kp.secretKey, cResult, &results);
EXPECT_EQ(plaintextAdd->GetScalarValue(), results->GetScalarValue()) << failmsg << " EvalAdd Ct and Pt fails";
cResult = cc->EvalSub(ciphertext1, plaintext2);
cc->Decrypt(kp.secretKey, cResult, &results);
EXPECT_EQ(plaintextSub->GetScalarValue(), results->GetScalarValue()) << failmsg << " EvalSub Ct and Pt fails";
}
GENERATE_TEST_CASES_FUNC(UTSHE, UnitTest_Add_Scalar, ORDER, PTMOD)
template<class Element>
static void UnitTest_Add_Integer(const CryptoContext<Element> cc, const string& failmsg) {
Plaintext plaintext1 = cc->MakeIntegerPlaintext(4);
Plaintext plaintext2 = cc->MakeIntegerPlaintext(7);
Plaintext plaintextAdd = cc->MakeIntegerPlaintext(11);
Plaintext plaintextSub = cc->MakeIntegerPlaintext(-3);
LPKeyPair<Element> kp = cc->KeyGen();
Ciphertext<Element> ciphertext1 = cc->Encrypt(kp.publicKey, plaintext1);
Ciphertext<Element> ciphertext2 = cc->Encrypt(kp.publicKey, plaintext2);
Ciphertext<Element> cResult;
Plaintext results;
cResult = cc->EvalAdd(ciphertext1, ciphertext2);
cc->Decrypt(kp.secretKey, cResult, &results);
EXPECT_EQ(plaintextAdd->GetIntegerValue(), results->GetIntegerValue()) << failmsg << " EvalAdd fails";
cResult = ciphertext1 + ciphertext2;
cc->Decrypt(kp.secretKey, cResult, &results);
EXPECT_EQ(plaintextAdd->GetIntegerValue(), results->GetIntegerValue()) << failmsg << " operator+ fails";
Ciphertext<Element> caddInplace(ciphertext1);
caddInplace += ciphertext2;
cc->Decrypt(kp.secretKey, caddInplace, &results);
EXPECT_EQ(plaintextAdd->GetIntegerValue(), results->GetIntegerValue()) << failmsg << " operator+= fails";
cResult = cc->EvalSub(ciphertext1, ciphertext2);
cc->Decrypt(kp.secretKey, cResult, &results);
EXPECT_EQ(plaintextSub->GetIntegerValue(), results->GetIntegerValue()) << failmsg << " EvalSub fails";
cResult = ciphertext1 - ciphertext2;
cc->Decrypt(kp.secretKey, cResult, &results);
EXPECT_EQ(plaintextSub->GetIntegerValue(), results->GetIntegerValue()) << failmsg << " operator- fails";
Ciphertext<Element> csubInplace(ciphertext1);
csubInplace -= ciphertext2;
cc->Decrypt(kp.secretKey, csubInplace, &results);
EXPECT_EQ(plaintextSub->GetIntegerValue(), results->GetIntegerValue()) << failmsg << " operator-= fails";
cResult = cc->EvalAdd(ciphertext1, plaintext2);
cc->Decrypt(kp.secretKey, cResult, &results);
EXPECT_EQ(plaintextAdd->GetIntegerValue(), results->GetIntegerValue()) << failmsg << " EvalAdd Ct and Pt fails";
cResult = cc->EvalSub(ciphertext1, plaintext2);
cc->Decrypt(kp.secretKey, cResult, &results);
EXPECT_EQ(plaintextSub->GetIntegerValue(), results->GetIntegerValue()) << failmsg << " EvalSub Ct and Pt fails";
}
GENERATE_TEST_CASES_FUNC(UTSHE, UnitTest_Add_Integer, ORDER, PTMOD)
template<class Element>
static void UnitTest_Mult_CoefPacked(const CryptoContext<Element> cc, const string& failmsg) {
std::vector<int64_t> vectorOfInts1 = { 1,0,3,1,0,1,2,1 };
Plaintext plaintext1 = cc->MakeCoefPackedPlaintext(vectorOfInts1);
std::vector<int64_t> vectorOfInts2 = { 2,1,3,2,2,1,3,0 };
Plaintext plaintext2 = cc->MakeCoefPackedPlaintext(vectorOfInts2);
// For cyclotomic order != 16, the expected result is the convolution of vectorOfInt21 and vectorOfInts2
std::vector<int64_t> vectorOfIntsMultLong = { 2, 1, 9, 7, 12, 12, 16, 12, 19, 12, 7, 7, 7, 3 };
std::vector<int64_t> vectorOfIntsMult = { -17, -11, 2, 0, 5, 9, 16, 12 };
Plaintext intArray1 = cc->MakeCoefPackedPlaintext(vectorOfInts1);
Plaintext intArray2 = cc->MakeCoefPackedPlaintext(vectorOfInts2);
Plaintext intArrayExpected = cc->MakeCoefPackedPlaintext(cc->GetCyclotomicOrder() == 16 ? vectorOfIntsMult : vectorOfIntsMultLong);
// Initialize the public key containers.
LPKeyPair<Element> kp = cc->KeyGen();
Ciphertext<Element> ciphertext1 = cc->Encrypt(kp.publicKey, intArray1);
Ciphertext<Element> ciphertext2 = cc->Encrypt(kp.publicKey, intArray2);
cc->EvalMultKeyGen(kp.secretKey);
Ciphertext<Element> cResult;
Plaintext results;
cResult = cc->EvalMult(ciphertext1, ciphertext2);
cc->Decrypt(kp.secretKey, cResult, &results);
results->SetLength(intArrayExpected->GetLength());
EXPECT_EQ(intArrayExpected->GetCoefPackedValue(), results->GetCoefPackedValue()) << failmsg << " EvalMult fails";
cResult = ciphertext1 * ciphertext2;
cc->Decrypt(kp.secretKey, cResult, &results);
results->SetLength(intArrayExpected->GetLength());
EXPECT_EQ(intArrayExpected->GetCoefPackedValue(), results->GetCoefPackedValue()) << failmsg << " operator* fails";
Ciphertext<Element> cmulInplace(ciphertext1);
cmulInplace *= ciphertext2;
cc->Decrypt(kp.secretKey, cmulInplace, &results);
results->SetLength(intArrayExpected->GetLength());
EXPECT_EQ(intArrayExpected->GetCoefPackedValue(), results->GetCoefPackedValue()) << failmsg << " operator*= fails";
cResult = cc->EvalMult(ciphertext1, plaintext2);
cc->Decrypt(kp.secretKey, cResult, &results);
results->SetLength(intArrayExpected->GetLength());
EXPECT_EQ(intArrayExpected->GetCoefPackedValue(), results->GetCoefPackedValue()) << failmsg << " EvalMult Ct and Pt fails";
}
GENERATE_TEST_CASES_FUNC(UTSHE, UnitTest_Mult_CoefPacked, ORDER, PTMOD)
template<class Element>
static void UnitTest_Mult_Packed(const CryptoContext<Element> cc, const string& failmsg) {
std::vector<int64_t> vectorOfInts1 = { 1,0,3,1,0,1,2,1 };
Plaintext plaintext1 = cc->MakePackedPlaintext(vectorOfInts1);
std::vector<int64_t> vectorOfInts2 = { 2,1,3,2,2,1,3,1 };
Plaintext plaintext2 = cc->MakePackedPlaintext(vectorOfInts2);
// For cyclotomic order != 16, the expected result is the convolution of vectorOfInt21 and vectorOfInts2
std::vector<int64_t> vectorOfIntsMult = { 2,0, 9, 2, 0, 1, 6, 1 };
Plaintext intArray1 = cc->MakePackedPlaintext(vectorOfInts1);
Plaintext intArray2 = cc->MakePackedPlaintext(vectorOfInts2);
Plaintext intArrayExpected = cc->MakePackedPlaintext(vectorOfIntsMult);
// Initialize the public key containers.
LPKeyPair<Element> kp = cc->KeyGen();
Ciphertext<Element> ciphertext1 = cc->Encrypt(kp.publicKey, intArray1);
Ciphertext<Element> ciphertext2 = cc->Encrypt(kp.publicKey, intArray2);
cc->EvalMultKeyGen(kp.secretKey);
Ciphertext<Element> cResult;
Plaintext results;
cResult = cc->EvalMult(ciphertext1, ciphertext2);
cc->Decrypt(kp.secretKey, cResult, &results);
results->SetLength(intArrayExpected->GetLength());
EXPECT_EQ(intArrayExpected->GetPackedValue(), results->GetPackedValue()) << failmsg << " EvalMult fails";
cResult = ciphertext1 * ciphertext2;
cc->Decrypt(kp.secretKey, cResult, &results);
results->SetLength(intArrayExpected->GetLength());
EXPECT_EQ(intArrayExpected->GetPackedValue(), results->GetPackedValue()) << failmsg << " operator* fails";
Ciphertext<Element> cmulInplace(ciphertext1);
cmulInplace *= ciphertext2;
cc->Decrypt(kp.secretKey, cmulInplace, &results);
results->SetLength(intArrayExpected->GetLength());
EXPECT_EQ(intArrayExpected->GetPackedValue(), results->GetPackedValue()) << failmsg << " operator*= fails";
cResult = cc->EvalMult(ciphertext1, plaintext2);
cc->Decrypt(kp.secretKey, cResult, &results);
results->SetLength(intArrayExpected->GetLength());
EXPECT_EQ(intArrayExpected->GetPackedValue(), results->GetPackedValue()) << failmsg << " EvalMult Ct and Pt fails";
}
GENERATE_TEST_CASES_FUNC_EVALATINDEX(UTSHE, UnitTest_Mult_Packed, 512, 65537)
template<class Element>
static void UnitTest_EvalAtIndex(const CryptoContext<Element> cc, const string& failmsg) {
std::vector<int64_t> vectorOfInts1 = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 };
Plaintext plaintext1 = cc->MakePackedPlaintext(vectorOfInts1);
// Expected results after evaluating EvalAtIndex(3) and EvalAtIndex(-3)
std::vector<int64_t> vectorOfIntsPlus3= { 4,5,6,7,8,9,10,11,12,13,14,15,16,0,0,0 };
std::vector<int64_t> vectorOfIntsMinus3 = {0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13};
Plaintext intArray1 = cc->MakePackedPlaintext(vectorOfInts1);
Plaintext intArrayPlus3 = cc->MakePackedPlaintext(vectorOfIntsPlus3);
Plaintext intArrayMinus3 = cc->MakePackedPlaintext(vectorOfIntsMinus3);
// Initialize the public key containers.
LPKeyPair<Element> kp = cc->KeyGen();
Ciphertext<Element> ciphertext1 = cc->Encrypt(kp.publicKey, intArray1);
cc->EvalAtIndexKeyGen(kp.secretKey,{3,-3});
Ciphertext<Element> cResult1 = cc->EvalAtIndex(ciphertext1, 3);
Ciphertext<Element> cResult2 = cc->EvalAtIndex(ciphertext1, -3);
Plaintext results1;
Plaintext results2;
cc->Decrypt(kp.secretKey, cResult1, &results1);
cc->Decrypt(kp.secretKey, cResult2, &results2);
results1->SetLength(intArrayPlus3->GetLength());
EXPECT_EQ(intArrayPlus3->GetPackedValue(), results1->GetPackedValue()) << failmsg << " EvalAtIndex(3) fails";
results2->SetLength(intArrayMinus3->GetLength());
EXPECT_EQ(intArrayMinus3->GetPackedValue(), results2->GetPackedValue()) << failmsg << " EvalAtIndex(-3) fails";
}
GENERATE_TEST_CASES_FUNC_EVALATINDEX(UTSHE, UnitTest_EvalAtIndex, 512, 65537)
template<class Element>
static void UnitTest_EvalMerge(const CryptoContext<Element> cc, const string& failmsg) {
// Initialize the public key containers.
LPKeyPair<Element> kp = cc->KeyGen();
std::vector<Ciphertext<Element>> ciphertexts;
std::vector<int64_t> vectorOfInts1 = { 32,0,0,0,0,0,0,0, 0, 0 };
Plaintext intArray1 = cc->MakePackedPlaintext(vectorOfInts1);
ciphertexts.push_back(cc->Encrypt(kp.publicKey, intArray1));
std::vector<int64_t> vectorOfInts2 = { 2,0,0,0,0,0,0,0, 0, 0};
Plaintext intArray2 = cc->MakePackedPlaintext(vectorOfInts2);
ciphertexts.push_back(cc->Encrypt(kp.publicKey, intArray2));
std::vector<int64_t> vectorOfInts3 = { 4,0,0,0,0,0,0,0, 0, 0};
Plaintext intArray3 = cc->MakePackedPlaintext(vectorOfInts3);
ciphertexts.push_back(cc->Encrypt(kp.publicKey, intArray3));
std::vector<int64_t> vectorOfInts4 = { 8,0,0,0,0,0,0,0, 0, 0 };
Plaintext intArray4 = cc->MakePackedPlaintext(vectorOfInts4);
ciphertexts.push_back(cc->Encrypt(kp.publicKey, intArray4));
std::vector<int64_t> vectorOfInts5 = { 16,0,0,0,0,0,0,0, 0, 0 };
Plaintext intArray5 = cc->MakePackedPlaintext(vectorOfInts5);
ciphertexts.push_back(cc->Encrypt(kp.publicKey, intArray5));
// Expected results after evaluating EvalAtIndex(3) and EvalAtIndex(-3)
std::vector<int64_t> vectorMerged = { 32,2,4,8,16,0,0,0 };
Plaintext intArrayMerged = cc->MakePackedPlaintext(vectorMerged);
vector<int32_t> indexList = {-1,-2,-3,-4,-5};
cc->EvalAtIndexKeyGen(kp.secretKey, indexList);
auto mergedCiphertext = cc->EvalMerge(ciphertexts);
Plaintext results1;
cc->Decrypt(kp.secretKey, mergedCiphertext, &results1);
results1->SetLength(intArrayMerged->GetLength());
EXPECT_EQ(intArrayMerged->GetPackedValue(), results1->GetPackedValue()) << failmsg << " EvalMerge fails";
}
GENERATE_TEST_CASES_FUNC_EVALATINDEX(UTSHE, UnitTest_EvalMerge, 512, 65537)
template<class Element>
static void UnitTest_EvalSum(const CryptoContext<Element> cc, const string& failmsg) {
// Initialize the public key containers.
LPKeyPair<Element> kp = cc->KeyGen();
std::vector<Ciphertext<Element>> ciphertexts;
uint32_t n = cc->GetRingDimension();
std::vector<int64_t> vectorOfInts1 = { 1,2,3,4,5,6,7,8};
uint32_t dim = vectorOfInts1.size();
vectorOfInts1.resize(n);
for (uint32_t i = dim; i < n; i++)
vectorOfInts1[i] = vectorOfInts1[i % dim];
Plaintext intArray1 = cc->MakePackedPlaintext(vectorOfInts1);
auto ct1 = cc->Encrypt(kp.publicKey, intArray1);
cc->EvalSumKeyGen(kp.secretKey);
auto ctsum1 = cc->EvalSum(ct1,1);
auto ctsum2 = cc->EvalSum(ct1,2);
auto ctsum3 = cc->EvalSum(ct1,8);
std::vector<int64_t> vectorOfInts2 = { 3,5,7,9,11,13,15,9};
vectorOfInts2.resize(n);
for (uint32_t i = dim; i < n; i++)
vectorOfInts2[i] = vectorOfInts2[i % dim];
Plaintext intArray2 = cc->MakePackedPlaintext(vectorOfInts2);
std::vector<int64_t> vectorOfIntsAll = { 36,36,36,36,36,36,36,36};
vectorOfIntsAll.resize(n);
for (uint32_t i = dim; i < n; i++)
vectorOfIntsAll[i] = vectorOfIntsAll[i % dim];
Plaintext intArrayAll = cc->MakePackedPlaintext(vectorOfIntsAll);
Plaintext results1;
cc->Decrypt(kp.secretKey, ctsum1, &results1);
Plaintext results2;
cc->Decrypt(kp.secretKey, ctsum2, &results2);
Plaintext results3;
cc->Decrypt(kp.secretKey, ctsum3, &results3);
intArray1->SetLength(dim);
intArray2->SetLength(dim);
intArrayAll->SetLength(dim);
results1->SetLength(dim);
results2->SetLength(dim);
results3->SetLength(dim);
EXPECT_EQ(intArray1->GetPackedValue(), results1->GetPackedValue()) << failmsg << " EvalSum for batch size = 1 failed";
EXPECT_EQ(intArray2->GetPackedValue(), results2->GetPackedValue()) << failmsg << " EvalSum for batch size = 2 failed";
EXPECT_EQ(intArrayAll->GetPackedValue(), results3->GetPackedValue()) << failmsg << " EvalSum for batch size = 8 failed";
}
GENERATE_TEST_CASES_FUNC_EVALSUM(UTSHE, UnitTest_EvalSum, 512, 65537)
TEST_F(UTSHE, UnitTest_EvalSum_BFVrns_All) {
uint32_t batchSize = 1<<12;
EncodingParams encodingParams(new EncodingParamsImpl(65537));
encodingParams->SetBatchSize(batchSize);
CryptoContext<DCRTPoly> cc = CryptoContextFactory<DCRTPoly>::genCryptoContextBFVrns(encodingParams,
HEStd_128_classic, 3.2, 0, 2, 0, OPTIMIZED, 2, 20, 60, batchSize);
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
// Initialize the public key containers.
LPKeyPair<DCRTPoly> kp = cc->KeyGen();
std::vector<Ciphertext<DCRTPoly>> ciphertexts;
uint32_t n = cc->GetRingDimension();
std::vector<int64_t> vectorOfInts1 = { 1,2,3,4,5,6,7,8};
uint32_t dim = vectorOfInts1.size();
vectorOfInts1.resize(n);
for (uint32_t i = n - dim; i < n; i++)
vectorOfInts1[i] = i;
Plaintext intArray1 = cc->MakePackedPlaintext(vectorOfInts1);
std::vector<int64_t> vectorOfIntsAll = { 32768,32768,32768,32768,32768,32768,32768,32768};
Plaintext intArrayAll = cc->MakePackedPlaintext(vectorOfIntsAll);
auto ct1 = cc->Encrypt(kp.publicKey, intArray1);
cc->EvalSumKeyGen(kp.secretKey);
auto ctsum1 = cc->EvalSum(ct1,batchSize);
Plaintext results1;
cc->Decrypt(kp.secretKey, ctsum1, &results1);
intArrayAll->SetLength(dim);
results1->SetLength(dim);
EXPECT_EQ(intArrayAll->GetPackedValue(), results1->GetPackedValue()) << " BFVrns EvalSum for batch size = All failed";
}
TEST_F(UTSHE, keyswitch_SingleCRT) {
usint m = 512;
float stdDev = 4;
shared_ptr<Poly::Params> params = ElemParamFactory::GenElemParams<Poly::Params>(m, 50);
CryptoContext<Poly> cc = CryptoContextFactory<Poly>::genCryptoContextBGV(params, 256, 1, stdDev);
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
Plaintext plaintext = cc->MakeStringPlaintext("I am good, what are you?! 32 ch");
LPKeyPair<Poly> kp = cc->KeyGen();
Ciphertext<Poly> ciphertext =
cc->Encrypt(kp.publicKey, plaintext);
LPKeyPair<Poly> kp2 = cc->KeyGen();
LPEvalKey<Poly> keySwitchHint;
keySwitchHint = cc->KeySwitchGen(kp.secretKey, kp2.secretKey);
Ciphertext<Poly> newCt = cc->KeySwitch(keySwitchHint, ciphertext);
Plaintext plaintextNew;
cc->Decrypt(kp2.secretKey, newCt, &plaintextNew);
EXPECT_EQ(plaintext->GetStringValue(), plaintextNew->GetStringValue());
}
TEST_F(UTSHE, keyswitch_ModReduce_DCRT) {
usint m = 512;
float stdDev = 4;
usint size = 4;
usint plaintextmodulus = 256;
usint relinWindow = 1;
shared_ptr<ILDCRTParams<BigInteger>> params = GenerateDCRTParams<BigInteger>( m, size, 30 );
CryptoContext<DCRTPoly> cc = CryptoContextFactory<DCRTPoly>::genCryptoContextBGV(params, plaintextmodulus, relinWindow, stdDev);
Plaintext plaintext = cc->MakeStringPlaintext("I am good, what are you?! 32 ch");
cc->Enable(ENCRYPTION);
cc->Enable(LEVELEDSHE);
cc->Enable(SHE);
LPKeyPair<DCRTPoly> kp = cc->KeyGen();
Ciphertext<DCRTPoly> ciphertext =
cc->Encrypt(kp.publicKey, plaintext);
LPKeyPair<DCRTPoly> kp2 = cc->KeyGen();
LPEvalKey<DCRTPoly> keySwitchHint;
keySwitchHint = cc->KeySwitchGen(kp.secretKey, kp2.secretKey);
Ciphertext<DCRTPoly> newCt = cc->KeySwitch(keySwitchHint, ciphertext);
Plaintext plaintextNewKeySwitch;
cc->Decrypt(kp2.secretKey, newCt, &plaintextNewKeySwitch);
EXPECT_EQ(plaintext->GetStringValue(), plaintextNewKeySwitch->GetStringValue()) << "Key-Switched Decrypt fails";
/**************************KEYSWITCH TEST END******************************/
/**************************MODREDUCE TEST BEGIN******************************/
newCt = cc->ModReduce(newCt);
DCRTPoly sk2PrivateElement(kp2.secretKey->GetPrivateElement());
sk2PrivateElement.DropLastElement();
kp2.secretKey->SetPrivateElement(sk2PrivateElement);
Plaintext plaintextNewModReduce;
cc->Decrypt(kp2.secretKey, newCt, &plaintextNewModReduce);
EXPECT_EQ(plaintext->GetStringValue(), plaintextNewModReduce->GetStringValue()) << "Mod Reduced Decrypt fails";
}
|
0e29d85926cef02b1e1e47554a15d04fe583b579 | 1b543619d635b784145d7b1379bae7cd2c4cb1ed | /codigos_aulas/codigos_aula_09/queue_palindrome.cpp | 0bea97c904c71b4d976c5fe4c6a1d3792d1ddc3c | [] | no_license | luiztoledosilva/estruturadedados | 313e98357bef60e7c6b44cfffa6d7085030b1735 | f5d8271785bc6c894d1bbdacd68b019d89c84d91 | refs/heads/main | 2023-08-31T15:59:41.496118 | 2021-10-15T23:02:21 | 2021-10-15T23:02:21 | 417,646,438 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 711 | cpp | queue_palindrome.cpp | #include "queue.h"
#include "stack.h"
#include <iostream>
using namespace std;
int main() {
bool palindrome = true;
char character;
char stackChar;
char queueChar;
Stack stack;
Queue queue;
cout << "Adicione uma string." << endl;
cin.get(character);
while (character != '\n') {
stack.push(character);
queue.enqueue(character);
cin.get(character);
}
while (palindrome && !queue.isEmpty())
{
stackChar = stack.pop();
queueChar = queue.dequeue();
if (stackChar != queueChar)
palindrome = false;
}
if (palindrome)
cout << "String é Palindrome" << endl;
else
cout << "String não é palindrome" << endl;
return 0;
}
|
ec9e07fe3792fa41944c3f8aa664223aeba4f746 | 1e7a8245ee431fc33b96d071943cc0fce813a040 | /문자열07 (baekjoon9996 - 한국이 그리울 땐 서버에 접속하지) .cpp | 82422ca430be95104203c8de003feebea8166a0d | [] | no_license | dlgkrwns213/algorithm | f3b685acb6e7e67b938154ee6f48ae69be45fc0a | 63951838356e09239d0a00155a981351d49a353a | refs/heads/master | 2020-11-28T08:43:18.955403 | 2020-03-06T14:40:52 | 2020-03-06T14:40:52 | 229,759,722 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 782 | cpp | 문자열07 (baekjoon9996 - 한국이 그리울 땐 서버에 접속하지) .cpp | //*이 한개있는 string을 입력받고 *이 있는 곳은 아무 문자나 들어갈수 있다고 설정해준다.
//각 줄마다 들어오는 string이 *이 있는 string으로 표현될 수 있는 확인해보기
#include <iostream>
using namespace std;
int main()
{
int n;
string pt;
cin >> n >> pt;
while(n--)
{
string s;
cin >> s;
int ps = (int)pt.size();
int ss = (int)s.size();
bool yes = true;
if(ps-1>ss)
yes = false;
for(int i=0;i<ps;i++)
{
if(pt[i]=='*')
break;
if(pt[i]!=s[i])
{
yes = false;
break;
}
}
for(int i=0;i<ps;i++)
{
if(pt[ps-i]=='*')
break;
if(pt[ps-i]!=s[ss-i])
{
yes = false;
break;
}
}
if(yes)
cout << "DA" << endl;
else
cout << "NE" << endl;
}
return 0;
}
|
931d91bdfd0fec2c4c836d220f430df71e60c392 | f4f60b0aff487461d64873b2b690fbd9d67c6ad0 | /tests/list_tests.cpp | 2a03dd7204fa150bb0e62512eeb7039ebaf927af | [
"MIT"
] | permissive | napina/containos | eb2dcdc489d96ee098403a7ae3f6d9e6bf872cf0 | 9be97e2f768ffdbed1ec9f893b31c3c63b3ce81a | refs/heads/master | 2020-12-24T08:23:17.671663 | 2016-10-30T06:50:06 | 2016-10-30T06:50:06 | 7,767,992 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 8,743 | cpp | list_tests.cpp | /*=============================================================================
Copyright (c) 2013 Ville Ruusutie
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
=============================================================================*/
#include "unitos/unitos.h"
#include "containos/list.h"
#include <memory>
namespace c = containos;
namespace {
struct IntWrap
{
IntWrap() { m_mem = new int(33); }
IntWrap(int i) { m_mem = new int(i); }
IntWrap(IntWrap const& other) { m_mem = new int(*other.m_mem); }
~IntWrap() { delete m_mem; }
operator int() const { return *m_mem; }
int& operator=(int i) { (*m_mem) = i; return *m_mem; }
bool operator==(int i) const { return *m_mem == i; }
private:
int* m_mem;
};
}
template<> struct allow_memcpy<IntWrap> {
static const bool allowed = false;
};
TEST_SUITE(List)
{
TEST(Empty)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
EXPECT_EQUAL(list.size(), 0u);
EXPECT_EQUAL(list.capacity(), 0u);
}
TEST(Reserve)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
EXPECT_EQUAL(list.size(), 0u);
EXPECT_EQUAL(list.capacity(), 0u);
list.reserve(10);
EXPECT_EQUAL(list.size(), 0u);
EXPECT_EQUAL(list.capacity(), 10u);
}
TEST(ReserveMore)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
EXPECT_EQUAL(list.size(), 0u);
EXPECT_EQUAL(list.capacity(), 0u);
list.reserve(1);
list.insert(13);
EXPECT_EQUAL(list.size(), 1u);
EXPECT_EQUAL(list.capacity(), 1u);
list.reserve(2);
EXPECT_EQUAL(list.size(), 1u);
EXPECT_EQUAL(list.capacity(), 2u);
EXPECT_EQUAL(list[0], 13);
}
TEST(Copy)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
list.reserve(3);
list.insert(3);
list.insert(5);
list.insert(15);
c::List<IntWrap,c::ListGrowRule<0> > list2;
list2.reserve(4);
list2.insert(9);
list2.insert(13);
list2 = list;
EXPECT_EQUAL(list2.size(), 3u);
EXPECT_EQUAL(list2[0], 3);
EXPECT_EQUAL(list2[1], 5);
EXPECT_EQUAL(list2[2], 15);
}
TEST(Insert)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
list.reserve(2);
list.insert(3);
EXPECT_EQUAL(list.size(), 1u);
EXPECT_EQUAL(list[0], 3);
list.insert(7);
EXPECT_EQUAL(list.size(), 2u);
EXPECT_EQUAL(list[1], 7);
}
TEST(InsertOther)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
list.reserve(3);
list.insert(3);
list.insert(5);
c::List<IntWrap,c::ListGrowRule<0> > list2;
list2.reserve(4);
list2.insert(9);
list2.insert(list);
list2.insert(13);
EXPECT_EQUAL(list2.size(), 4u);
EXPECT_EQUAL(list2[0], 9);
EXPECT_EQUAL(list2[1], 3);
EXPECT_EQUAL(list2[2], 5);
EXPECT_EQUAL(list2[3], 13);
}
TEST(Acquire)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
list.reserve(2);
list.acquire() = 3;
EXPECT_EQUAL(list.size(), 1u);
EXPECT_EQUAL(list[0], 3);
list.acquire() = 7;
EXPECT_EQUAL(list.size(), 2u);
EXPECT_EQUAL(list[1], 7);
}
TEST(Remove)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
list.reserve(2);
list.insert(3);
EXPECT_EQUAL(list.size(), 1u);
list.remove(0);
EXPECT_EQUAL(list.size(), 0u);
}
TEST(Pop)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
list.reserve(2);
list.insert(3);
list.insert(7);
EXPECT_EQUAL(list.size(), 2u);
IntWrap result = 1;
EXPECT_TRUE(list.pop(result));
EXPECT_EQUAL(result, 7);
EXPECT_EQUAL(list.size(), 1u);
EXPECT_TRUE(list.pop(result));
EXPECT_EQUAL(result, 3);
EXPECT_EQUAL(list.size(), 0u);
}
TEST(Clear)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
list.reserve(3);
list.insert(3);
list.insert(7);
list.insert(4);
EXPECT_EQUAL(list.size(), 3u);
list.clear();
EXPECT_EQUAL(list.size(), 0u);
}
TEST(ResizeToSmaller)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
list.reserve(2);
list.insert(3);
list.insert(5);
EXPECT_EQUAL(list.size(), 2u);
list.resize(1);
EXPECT_EQUAL(list.size(), 1u);
EXPECT_EQUAL(list[0], 3);
}
TEST(ResizeToBigger)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
list.reserve(2);
list.insert(3);
list.insert(5);
EXPECT_EQUAL(list.size(), 2u);
list.resize(3);
EXPECT_EQUAL(list.size(), 3u);
EXPECT_EQUAL(list[0], 3);
EXPECT_EQUAL(list[1], 5);
EXPECT_EQUAL(list[2], 33);
}
TEST(ResizeToZero)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
list.reserve(2);
list.insert(3);
list.insert(5);
EXPECT_EQUAL(list.size(), 2u);
list.resize(0);
EXPECT_EQUAL(list.size(), 0u);
}
TEST(ResizeNoCopy)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
list.reserve(2);
list.insert(3);
list.insert(5);
EXPECT_EQUAL(list.size(), 2u);
list.resizeNoCopy(4);
EXPECT_EQUAL(list.size(), 4u);
EXPECT_EQUAL(list[0], 33);
EXPECT_EQUAL(list[1], 33);
EXPECT_EQUAL(list[2], 33);
EXPECT_EQUAL(list[3], 33);
}
TEST(ResizeWithIterator)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
list.reserve(5);
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
EXPECT_EQUAL(list.size(), 4u);
c::List<IntWrap,c::ListGrowRule<0> >::iterator it = list.begin();
list.resize(++it);
EXPECT_EQUAL(list.size(), 1u);
EXPECT_EQUAL(list[0], 1);
}
TEST(Iterate)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
list.reserve(3);
list.insert(0);
list.insert(1);
list.insert(2);
c::List<IntWrap,c::ListGrowRule<0> >::iterator it = list.begin();
c::List<IntWrap,c::ListGrowRule<0> >::iterator end = list.end();
int i = 0;
for( ; it != end; ++it, ++i ) {
EXPECT_EQUAL(*it, i);
}
EXPECT_EQUAL(i, 3);
}
TEST(ConstIterate)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
list.reserve(3);
list.insert(0);
list.insert(1);
list.insert(2);
c::List<IntWrap,c::ListGrowRule<0> >::const_iterator it = list.begin();
c::List<IntWrap,c::ListGrowRule<0> >::const_iterator end = list.end();
int i = 0;
for( ; it != end; ++it, ++i ) {
EXPECT_EQUAL(*it, i);
}
EXPECT_EQUAL(i, 3);
}
TEST(DeleteIterator)
{
c::List<IntWrap,c::ListGrowRule<0> > list;
list.reserve(3);
list.insert(0);
list.insert(1);
list.insert(2);
c::List<IntWrap>::iterator it = list.begin();
++it;
list.remove(it);
EXPECT_EQUAL(list.size(), 2u);
EXPECT_EQUAL(list[0], 0);
EXPECT_EQUAL(list[1], 2);
}
TEST(GrowRule)
{
c::List<IntWrap,c::ListGrowRule<8> > list;
list.insert(0);
list.insert(1);
list.insert(2);
EXPECT_EQUAL(list.size(), 3u);
EXPECT_EQUAL(list.capacity(), 8u);
EXPECT_EQUAL(list[0], 0);
EXPECT_EQUAL(list[1], 1);
EXPECT_EQUAL(list[2], 2);
}
}
|
a2f9e6ee8eb502eb46a16a44894c4285384d13ed | 594975831ea01c49bc9a3253ca1ccbac9f4f5eea | /cgfFrame/include/CGF/EntityCreateEvent.h | c9a63de34b53b9d09710817e6efab16ad86f2901 | [] | no_license | WarfareCode/linux | 0344589884de3d345b50fa8ba9cad29e94feb9c6 | a0ef3d4da620f3eeb1cf54fa2a86e14c9b96c65a | refs/heads/master | 2021-10-09T18:32:47.071838 | 2018-12-25T08:14:56 | 2018-12-25T08:14:56 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,514 | h | EntityCreateEvent.h | //EntityCreateEvent.h: interface for the CEntityCreateEvent module.
//!!HDOSE_CLASS(CEntityCreateEvent,CEvt)
//////////////////////////////////////////////////////////////////////
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#if !defined(AFX_EntityCreateEvent_H)
#define AFX_EntityCreateEvent_H
#include "CGFDS.h"
//{{HDOSE_CLS_DES(CEntityCreateEvent)
/*
Author:
Version: 1.0
Descript:
*/
//}}HDOSE_CLS_DES
class HYCGF_API CEntityCreateEvent /*实体创建事件*/ : public CEvt
{
DECLARE_CREATE;
public:
CEntityCreateEvent();
virtual ~CEntityCreateEvent();
static void ClassInit(ClassInfo *clsinfo);
virtual void OnInit();
void SetEntityID(long val){m_EntityID=val;}
long GetEntityID(){return m_EntityID;}
void SetEntityName(char* val){SetValueString("EntityName",val);}
char* GetEntityName(){return GetValueString("EntityName");}
void SetEntityPos(GeoPt val){m_EntityPos=val;}
GeoPt GetEntityPos(){return m_EntityPos;}
void SetEntitySide(long val){m_EntitySide=val;}
long GetEntitySide(){return m_EntitySide;}
void SetEntityType(DtEntityType val){m_EntityType=val;}
DtEntityType GetEntityType(){return m_EntityType;}
//{{HDOSE_MEMBER_FUNCTION(CEntityCreateEvent)
//}}HDOSE_MEMBER_FUNCTION
public:
//{{HDOSE_ATTRIBUTE(CEntityCreateEvent)
long m_EntityID/*实体ID*/;
char* m_EntityName/*实体名称*/;
GeoPt m_EntityPos/*实体产生位置*/;
long m_EntitySide/*实体红蓝属性*/;
DtEntityType m_EntityType/*实体类型*/;
//}}HDOSE_ATTRIBUTE
};
#endif
|
8868ce638e73df13c7f8048dd9ab12537408733c | 72ccec097713e9b06bd3f936c3423cd7b6236d1f | /tabu/VRPTW/Solve.h | 41e9acaa7388ce7a89bd2a43d159e4050c45ab1e | [] | no_license | xinruxiao/vehicle-routing | 07579ad50ef84bb002405dc277e66184067d676c | 1a54ffd529a58effe006c8be4eca24960cc52801 | refs/heads/master | 2022-12-04T14:09:08.074131 | 2020-08-19T04:01:35 | 2020-08-19T04:01:35 | 288,629,131 | 2 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,766 | h | Solve.h | #ifndef SOLVE
#define SOLVE
#include<fstream>
#include<iostream>
using namespace std;
#include"Node.h"
#include"Route.h"
#include"Solution.h"
#include"Insertion.h"
#include<vector>
#include<ctime>
class Solve {
public:
Solve() {};
Solve(Data* d);
/*插入启发式算法*/
void useInsertion();
void initRoute(int flag);
void initInfor();
void updateInfor(Route* route);
void printInfor();
/*生成邻居解决方案的集合*/
void generateNeighbour(int operate, double num, Solution* n_s);
void generate2Exchange(double num, Solution* n_s);
void generateOrExchange(double num, Solution* n_s);
void generateRelocation(double num, Solution* n_s); //只有这种情况有可能会减少路径数
void generateExchange(double num, Solution* n_s);
void generateCrossover(double num, Solution* n_s);
void changeToNeighbour(vector<double>* n, Solution* temp_s);
/*禁忌搜索算法*/
void tabuSearch();
/*禁忌搜索*/
//判断是否在禁忌表中,是则返回true,否则返回false
bool isTabu(vector<double>* n);
void updateTabuList(int iteration);
void addToTabuList(int iteration, vector<double>* n);
void reverseOperate(vector<double>** r_n, vector<double>* n, Solution* n_s);
void record(Solution* temp_s);
private:
//从文件中读取的数据
vector<Customer*>* cus;
Data* data;
//获得的解决方案
Solution s;
/*插入启发式算法需要存储的信息*/
vector<Insertion> infor; /*未加入路径的节点编号;最好的插入位置;插入该节点后增加的开销*/
/*禁忌搜索算法*/
vector<vector<double>*> tabu_list;
int tenure; //禁忌周期
//最好的邻居解决方案的开销
vector<double> best_neighbour;
double g_best_neighbour;
friend class Solution;
};
#endif
|
6bc4f0d7be9da6065b5588835c6c1a4d3835999e | 36954c7d3277126a3ee7343f04138ebcea5e81e5 | /1009/1009/1009.cpp | 2780a3233e663d8525bbbd446e3bb1a8a61240ee | [] | no_license | auruo4ever/timus | 9364ffe247ac6aee703f37cac5f365b365a51ec2 | dc9ec32d77660828364298c8100b97e31007cb5b | refs/heads/main | 2023-08-15T09:09:26.602249 | 2021-09-20T15:31:37 | 2021-09-20T15:31:37 | 408,484,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 435 | cpp | 1009.cpp | #include <iostream>
using namespace std;
int main()
{
int mas[20];
int n, k;
cin >> n >> k;
int num = k - 1; //все цифры данной системы счисления без 0
mas[0] = 1;
mas[1] = num;
for (int i = 2; i <= n; i++) {
mas[i] = (mas[i - 1] * num + mas[i - 2] * num); //отдельно когда добавляем 0 вариантов и не 0 вариантов
}
cout << mas[n];
return 0;
} |
afe9ab706ad58573f17098a857e6c43d7de7eccb | 39eac74fa6a244d15a01873623d05f480f45e079 | /EMRTextDlg.h | 950dfb8da83771faaf8e13dcf7ba671ebc09420c | [] | 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 | 1,314 | h | EMRTextDlg.h | #if !defined(AFX_EMRTEXTDLG_H__89AC719D_FB2D_4DBD_81BB_541BE0BBDDF9__INCLUDED_)
#define AFX_EMRTEXTDLG_H__89AC719D_FB2D_4DBD_81BB_541BE0BBDDF9__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// EMRTextDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CEMRTextDlg dialog
class CEMRTextDlg : public CNxDialog
{
// Construction
public:
CEMRTextDlg(CWnd* pParent); // standard constructor
CString m_text;
// Dialog Data
//{{AFX_DATA(CEMRTextDlg)
enum { IDD = IDD_EMR_TEXT_DLG };
// NOTE: the ClassWizard will add data members here
CNxEdit m_nxeditEditEmrText;
CNxStatic m_nxstaticEmrTextTitle;
CNxIconButton m_btnOK;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CEMRTextDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CEMRTextDlg)
virtual void OnOK();
virtual BOOL OnInitDialog();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_EMRTEXTDLG_H__89AC719D_FB2D_4DBD_81BB_541BE0BBDDF9__INCLUDED_)
|
891961498d9f811266ca3a6090163398e8db16b5 | fd18c0d00c62202c5a972eef96bb8bda3458358e | /c++/src/string/string_util.cpp | 0945387af9085c1f9aa75ffc891dcbd464050ba2 | [] | no_license | fenghaozhang/toolkit | 2537135d8b96d3aaba2bb236cbc7732f05c9ad5f | f0565b564bbe1b841e25ce20656920302da20fd1 | refs/heads/master | 2020-06-26T00:15:44.448863 | 2019-11-20T09:15:33 | 2019-11-20T09:15:33 | 199,464,761 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 24,021 | cpp | string_util.cpp | #include "src/string/string_util.h"
#include <ctype.h>
#include <errno.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <wctype.h>
#include <limits>
#include "src/common/macros.h"
#include "src/string/dmg_fp/dmg_fp.h"
namespace {
const char* kTrueString = "true";
const char* kFalseString = "false";
template <typename STR, typename INT, typename UINT, bool NEG>
struct IntToStringT
{
// This is to avoid a compiler warning about unary minus on unsigned type.
// For example, say you had the following code:
// template <typename INT>
// INT abs(INT value) { return value < 0 ? -value : value; }
// Even though if INT is unsigned, it's impossible for value < 0, so the
// unary minus will never be taken, the compiler will still generate a
// warning. We do a little specialization dance...
template <typename INT2, typename UINT2, bool NEG2>
struct ToUnsignedT {};
template <typename INT2, typename UINT2>
struct ToUnsignedT<INT2, UINT2, false>
{
static UINT2 ToUnsigned(INT2 value)
{
return static_cast<UINT2>(value);
}
};
template <typename INT2, typename UINT2>
struct ToUnsignedT<INT2, UINT2, true>
{
static UINT2 ToUnsigned(INT2 value)
{
return static_cast<UINT2>(value < 0 ? -value : value);
}
};
// This set of templates is very similar to the above templates, but
// for testing whether an integer is negative.
template <typename INT2, bool NEG2>
struct TestNegT {};
template <typename INT2>
struct TestNegT<INT2, false>
{
static bool TestNeg(INT2 value)
{
// value is unsigned, and can never be negative.
return false;
}
};
template <typename INT2>
struct TestNegT<INT2, true>
{
static bool TestNeg(INT2 value)
{
return value < 0;
}
};
static STR IntToString(INT value)
{
// log10(2) ~= 0.3 bytes needed per bit or per byte log10(2**8) ~= 2.4.
// So round up to allocate 3 output characters per byte, plus 1 for '-'.
const int kOutputBufSize = 3 * sizeof(INT) + 1;
// Allocate the whole string right away, we will right back to front,
// and then return the substr of what we ended up using.
STR outbuf(kOutputBufSize, 0);
bool is_neg = TestNegT<INT, NEG>::TestNeg(value);
// Even though is_neg will never be true when INT is parameterized as
// unsigned, even the presence of the unary operation causes a warning.
UINT res = ToUnsignedT<INT, UINT, NEG>::ToUnsigned(value);
for (typename STR::iterator it = outbuf.end();;) {
--it;
*it = static_cast<typename STR::value_type>((res % 10) + '0');
res /= 10;
// We're done..
if (res == 0) {
if (is_neg) {
--it;
*it = static_cast<typename STR::value_type>('-');
}
return STR(it, outbuf.end());
}
}
return STR();
}
};
// Utility to convert a character to a digit in a given base
template<typename CHAR, int BASE, bool BASE_LTE_10>
class BaseCharToDigit
{
};
// Faster specialization for bases <= 10
template<typename CHAR, int BASE>
class BaseCharToDigit<CHAR, BASE, true>
{
public:
static bool Convert(CHAR c, unsigned char* digit) {
if (c >= '0' && c < '0' + BASE) {
*digit = c - '0';
return true;
}
return false;
}
};
// Specialization for bases where 10 < base <= 36
template<typename CHAR, int BASE>
class BaseCharToDigit<CHAR, BASE, false>
{
public:
static bool Convert(CHAR c, unsigned char* digit)
{
if (c >= '0' && c <= '9') {
*digit = c - '0';
} else if (c >= 'a' && c < 'a' + BASE - 10) {
*digit = c - 'a' + 10;
} else if (c >= 'A' && c < 'A' + BASE - 10) {
*digit = c - 'A' + 10;
} else {
return false;
}
return true;
}
};
template<int BASE, typename CHAR>
bool CharToDigit(CHAR c, unsigned char* digit)
{
return BaseCharToDigit<CHAR, BASE, BASE <= 10>::Convert(c, digit);
}
// There is an IsWhitespace for wchars defined in string_util.h, but it is
// locale independent, whereas the functions we are replacing were
// locale-dependent. TBD what is desired, but for the moment let's not introduce
// a change in behaviour.
template<typename CHAR> class WhitespaceHelper
{
};
template<> class WhitespaceHelper<char>
{
public:
static bool Invoke(char c)
{
return 0 != isspace(static_cast<unsigned char>(c));
}
};
template<> class WhitespaceHelper<wchar_t>
{
public:
static bool Invoke(wchar_t c)
{
return 0 != iswspace(c);
}
};
template<typename CHAR> bool LocalIsWhitespace(CHAR c)
{
return WhitespaceHelper<CHAR>::Invoke(c);
}
// IteratorRangeToNumberTraits should provide:
// - a typedef for iterator_type, the iterator type used as input.
// - a typedef for value_type, the target numeric type.
// - static functions min, max (returning the minimum and maximum permitted
// values)
// - constant kBase, the base in which to interpret the input
template<typename IteratorRangeToNumberTraits>
class IteratorRangeToNumber
{
public:
typedef IteratorRangeToNumberTraits traits;
typedef typename traits::iterator_type const_iterator;
typedef typename traits::value_type value_type;
// Generalized iterator-range-to-number conversion.
//
static bool Invoke(const_iterator begin,
const_iterator end,
value_type* output)
{
bool valid = true;
while (begin != end && LocalIsWhitespace(*begin)) {
valid = false;
++begin;
}
if (begin != end && *begin == '-') {
if (!Negative::Invoke(begin + 1, end, output)) {
valid = false;
}
} else {
if (begin != end && *begin == '+') {
++begin;
}
if (!Positive::Invoke(begin, end, output)) {
valid = false;
}
}
return valid;
}
private:
// Sign provides:
// - a static function, CheckBounds, that determines whether the next digit
// causes an overflow/underflow
// - a static function, Increment, that appends the next digit
// appropriately according to the sign of the number being parsed.
template<typename Sign>
class Base
{
public:
static bool Invoke(const_iterator begin, const_iterator end,
typename traits::value_type* output)
{
*output = 0;
if (begin == end) {
return false;
}
// Note: no performance difference was found when using template
// specialization to remove this check in bases other than 16
if (traits::kBase == 16 && end - begin > 2 && *begin == '0' &&
(*(begin + 1) == 'x' || *(begin + 1) == 'X')) {
begin += 2;
}
for (const_iterator current = begin; current != end; ++current) {
unsigned char new_digit = 0;
if (!CharToDigit<traits::kBase>(*current, &new_digit)) {
return false;
}
if (current != begin) {
if (!Sign::CheckBounds(output, new_digit)) {
return false;
}
*output *= traits::kBase;
}
Sign::Increment(new_digit, output);
}
return true;
}
};
class Positive : public Base<Positive>
{
public:
static bool CheckBounds(value_type* output, unsigned char new_digit)
{
value_type baseMax =
static_cast<value_type>(traits::max() / traits::kBase);
if (*output > baseMax ||
(*output == baseMax &&
new_digit > traits::max() % traits::kBase)) {
*output = traits::max();
return false;
}
return true;
}
static void Increment(unsigned char increment, value_type* output)
{
*output += increment;
}
};
class Negative : public Base<Negative>
{
public:
static bool CheckBounds(value_type* output, unsigned char new_digit)
{
if (*output < traits::min() / traits::kBase ||
(*output == traits::min() / traits::kBase &&
new_digit > 0 - traits::min() % traits::kBase)) {
*output = traits::min();
return false;
}
return true;
}
static void Increment(unsigned char increment, value_type* output)
{
*output -= increment;
}
};
};
template<typename ITERATOR, typename VALUE, int BASE>
class BaseIteratorRangeToNumberTraits
{
public:
typedef ITERATOR iterator_type;
typedef VALUE value_type;
static value_type min() {
return std::numeric_limits<value_type>::min();
}
static value_type max() {
return std::numeric_limits<value_type>::max();
}
static const int kBase = BASE;
};
template<typename ITERATOR>
class BaseHexIteratorRangeToIntTraits
: public BaseIteratorRangeToNumberTraits<ITERATOR, int, 16>
{
};
template<typename ITERATOR>
class BaseHexIteratorRangeToInt64Traits
: public BaseIteratorRangeToNumberTraits<ITERATOR, int64_t, 16>
{
};
template<typename ITERATOR>
class BaseHexIteratorRangeToUInt64Traits
: public BaseIteratorRangeToNumberTraits<ITERATOR, uint64_t, 16>
{
};
typedef BaseHexIteratorRangeToIntTraits<std::string::const_iterator>
HexIteratorRangeToIntTraits;
typedef BaseHexIteratorRangeToInt64Traits<std::string::const_iterator>
HexIteratorRangeToInt64Traits;
typedef BaseHexIteratorRangeToUInt64Traits<std::string::const_iterator>
HexIteratorRangeToUInt64Traits;
template<typename STR>
bool HexStringToBytesT(const STR& input, std::vector<unsigned char>* output)
{
size_t count = input.size();
if (count == 0 || (count % 2) != 0)
return false;
for (uintptr_t i = 0; i < count / 2; ++i) {
unsigned char msb = 0; // most significant 4 bits
unsigned char lsb = 0; // least significant 4 bits
if (!CharToDigit<16>(input[i * 2], &msb) ||
!CharToDigit<16>(input[i * 2 + 1], &lsb))
return false;
output->push_back((msb << 4) | lsb);
}
return true;
}
template <typename VALUE, int BASE>
class StringToNumberTraits
: public BaseIteratorRangeToNumberTraits<std::string::const_iterator,
VALUE,
BASE>
{
};
template <typename VALUE>
bool StringToIntImpl(const std::string& input, VALUE* output)
{
return IteratorRangeToNumber<StringToNumberTraits<VALUE, 10> >::Invoke(
input.begin(), input.end(), output);
}
struct Symbol
{
char unit;
uint8_t bits;
};
const Symbol SymbolTable[] = {
{ 'K', 10 },
{ 'M', 20 },
{ 'G', 30 },
{ 'T', 40 },
{ 'P', 50 },
};
} // namespace
std::string IntToString(int value) {
return IntToStringT<std::string, int, unsigned int, true>::
IntToString(value);
}
// std::wstring IntToWString(int value) {
// return IntToStringT<std::wstring, int, unsigned int, true>::
// IntToString(value);
// }
std::string UintToString(unsigned int value) {
return IntToStringT<std::string, unsigned int, unsigned int, false>::
IntToString(value);
}
// std::wstring UintToWString(unsigned int value) {
// return IntToStringT<std::wstring, unsigned int, unsigned int, false>::
// IntToString(value);
// }
std::string Int64ToString(int64_t value) {
return IntToStringT<std::string, int64_t, uint64_t, true>::
IntToString(value);
}
// std::wstring Int64ToWString(int64_t value) {
// return IntToStringT<std::wstring, int64_t, uint64_t, true>::
// IntToString(value);
// }
std::string Uint64ToString(uint64_t value) {
return IntToStringT<std::string, uint64_t, uint64_t, false>::
IntToString(value);
}
// std::wstring Uint64ToWString(uint64_t value) {
// return IntToStringT<std::wstring, uint64_t, uint64_t, false>::
// IntToString(value);
// }
std::string DoubleToString(double value) {
// According to g_fmt.cc, it is sufficient to declare a buffer of size 32.
char buffer[32];
dmg_fp::g_fmt(buffer, value);
return std::string(buffer);
}
bool StringToInt(const std::string& input, int* output) {
return StringToIntImpl(input, output);
}
// bool StringToInt(const std::wstring& input, int* output) {
// return WStringToIntImpl(input, output);
// }
bool StringToUint(const std::string& input, unsigned* output) {
return StringToIntImpl(input, output);
}
// bool StringToUint(const std::wstring& input, unsigned* output) {
// return WStringToIntImpl(input, output);
// }
bool StringToInt64(const std::string& input, int64_t* output) {
return StringToIntImpl(input, output);
}
// bool StringToInt64(const std::wstring& input, int64_t* output) {
// return WStringToIntImpl(input, output);
// }
bool StringToUint64(const std::string& input, uint64_t* output) {
return StringToIntImpl(input, output);
}
// bool StringToUint64(const std::wstring& input, uint64_t* output) {
// return WStringToIntImpl(input, output);
// }
bool StringToSizeT(const std::string& input, size_t* output) {
return StringToIntImpl(input, output);
}
// bool StringToSizeT(const std::wstring& input, size_t* output) {
// return WStringToIntImpl(input, output);
// }
bool StringToDouble(const std::string& input, double* output)
{
errno = 0; // Thread-safe? It is on at least Mac, Linux, and Windows.
char* endptr = NULL;
*output = dmg_fp::strtod(input.c_str(), &endptr);
// Cases to return false:
// - If errno is ERANGE, there was an overflow or underflow.
// - If the input string is empty, there was nothing to parse.
// - If endptr does not point to the end of the string, there are either
// characters remaining in the string after a parsed number, or the
// string
// does not begin with a parseable number. endptr is compared to the
// expected end given the string's stated length to correctly catch cases
// where the string contains embedded NUL characters.
// - If the first character is a space, there was leading whitespace
return errno == 0 &&
!input.empty() &&
input.c_str() + input.length() == endptr &&
!isspace(input[0]);
}
bool StringToBool(const std::string& input, bool* output)
{
std::string lowCase = StringToLowerASCII(input);
bool ret = false;
if (lowCase == kTrueString) {
*output = ret = true;
} else if (lowCase == kFalseString) {
*output = false;
ret = true;
}
return ret;
}
std::string BoolToString(const bool input)
{
if (input == true) {
return kTrueString;
} else {
return kFalseString;
}
}
// Note: if you need to add WStringToDouble, first ask yourself if it's
// really necessary. If it is, probably the best implementation here is to
// convert to 8-bit and then use the 8-bit version.
// Note: if you need to add an iterator range version of StringToDouble, first
// ask yourself if it's really necessary. If it is, probably the best
// implementation here is to instantiate a string and use the string version.
std::string HexEncode(const void* bytes, size_t size)
{
static const char kHexChars[] = "0123456789ABCDEF";
// Each input byte creates two output hex characters.
std::string ret(size * 2, '\0');
for (size_t i = 0; i < size; ++i) {
char b = reinterpret_cast<const char*>(bytes)[i];
ret[(i * 2)] = kHexChars[(b >> 4) & 0xf];
ret[(i * 2) + 1] = kHexChars[b & 0xf];
}
return ret;
}
bool HexStringToInt(const std::string& input, int* output)
{
return IteratorRangeToNumber<HexIteratorRangeToIntTraits>::Invoke(
input.begin(), input.end(), output);
}
bool HexStringToInt64(const std::string& input, int64_t* output)
{
return IteratorRangeToNumber<HexIteratorRangeToInt64Traits>::Invoke(
input.begin(), input.end(), output);
}
bool HexStringToUInt64(const std::string& input, uint64_t* output)
{
return IteratorRangeToNumber<HexIteratorRangeToUInt64Traits>::Invoke(
input.begin(), input.end(), output);
}
bool HexStringToBytes(const std::string& input,
std::vector<unsigned char>* output)
{
return HexStringToBytesT(input, output);
}
bool ParseFromSize(const std::string& s, uint64_t* size)
{
if (s.empty())
{
return false;
}
if (size == NULL)
{
return false;
}
size_t length = s.length();
uint8_t bits = 0;
for (size_t i = 0; i < COUNT_OF(SymbolTable); i++)
{
const Symbol& symbol = SymbolTable[i];
char unit = s[s.length() - 1];
if (toupper(unit) == symbol.unit)
{
bits = symbol.bits;
length = s.length() - 1; // skip last char
break;
}
}
if (!StringToSizeT(s.substr(0, length), size))
{
return false;
}
*size = *size << bits;
return true;
}
template<typename CHAR> struct CaseInsensitiveCompare
{
public:
bool operator()(CHAR x, CHAR y) const
{
return tolower(x) == tolower(y);
}
};
bool StartWith(const std::string& s, const std::string prefix)
{
if (s.length() < prefix.length())
{
return false;
}
for (size_t i = 0; i < prefix.length(); i++)
{
if (s[i] != prefix[i])
{
return false;
}
}
return true;
}
int64_t StringToLongLong(const std::string& s)
{
return atoll(s.c_str());
}
template<typename STR>
static size_t SplitStringT(
const STR& str,
const STR& delimiters,
std::vector<STR>* tokens)
{
tokens->clear();
typename STR::size_type start =
str.find_first_not_of(delimiters);
while (start != STR::npos) {
typename STR::size_type end =
str.find_first_of(delimiters, start + 1);
if (end == STR::npos) {
tokens->push_back(str.substr(start));
break;
} else {
tokens->push_back(str.substr(start, end - start));
start = str.find_first_not_of(delimiters, end + 1);
}
}
return tokens->size();
}
size_t SplitString(const std::string& str,
const std::string& delimiters,
std::vector<std::string>* tokens)
{
return SplitStringT(str, delimiters, tokens);
}
template <typename STR>
bool EndsWithT(const STR& str, const STR& search, bool case_sensitive)
{
typename STR::size_type str_length = str.length();
typename STR::size_type search_length = search.length();
if (search_length > str_length)
return false;
if (case_sensitive) {
return
str.compare(str_length - search_length, search_length, search) == 0;
} else {
return
std::equal(search.begin(), search.end(),
str.begin() + (str_length - search_length),
CaseInsensitiveCompare<typename STR::value_type>());
}
}
bool EndsWith(const std::string& str, const std::string& search,
bool case_sensitive)
{
return EndsWithT(str, search, case_sensitive);
}
std::string LeftTrimString(const std::string& string, const char trimChar)
{
size_t pos = 0;
while (pos < string.size() && string[pos] == trimChar) ++pos;
return string.substr(pos);
}
std::string RightTrimString(const std::string& string, const char trimChar)
{
size_t pos = string.size() - 1;
while (pos != (size_t)-1 && string[pos] == trimChar) --pos;
return string.substr(0, pos+1);
}
std::string TrimString(
const std::string& string,
const char leftTrimChar,
const char rightTrimChar)
{
return LeftTrimString(RightTrimString(string, rightTrimChar), leftTrimChar);
}
static const int kPathChar = '/';
static const int kDotChar = '.';
char* NameOf(const char* filename, char* s, size_t maxChars)
{
const char *t = strrchr(filename, kPathChar);
return strncpy(s, (t == NULL) ? filename : (t + 1), maxChars);
}
char* BaseOf(const char* filename, char* s, size_t maxChars)
{ NameOf(filename, s, maxChars);
char* t = strrchr(s, kDotChar);
if (t == NULL) { return s; }
if (t >= s) { *t = '\0'; }
return s;
}
char* PathOf(const char* filename, char* s, size_t maxChars)
{
const char* t = strrchr(filename, kPathChar);
if (t == NULL)
{
*s = '\0';
}
else
{
const size_t n = std::min<size_t>(maxChars, t + 1 - filename);
strncpy(s, filename, n);
s[n] = '\0';
}
return s;
}
char* ExtnOf(const char* filename, char *s, size_t maxChars)
{
const char* t = strrchr(filename, kDotChar);
if (t == NULL)
{
*s = '\0';
return s;
}
return strncpy(s, t + 1, maxChars);
}
char* FullBaseOf(const char* filename, char* s, size_t maxChars)
{
const char* t = strrchr(filename, kPathChar);
if (t == NULL)
{
BaseOf(filename, s, maxChars);
}
else
{
const size_t n = std::min<size_t>(maxChars, t + 1 - filename);
strncpy(s, filename, n);
BaseOf(filename + n, s + n, maxChars - n);
}
return s;
}
bool RemovePrefix(
const std::string& str,
const std::string& prefix,
std::string* result)
{
if (str.length() < prefix.length())
{
return false;
}
if (memcmp(str.c_str(), prefix.c_str(), prefix.length()) != 0)
{
return false;
}
size_t newLength = str.length() - prefix.length();
result->assign(str, prefix.length(), newLength);
return true;
}
bool RemovePrefixInPlace(std::string* str, const std::string& prefix)
{
return RemovePrefix(*str, prefix, str);
}
bool RemoveSuffix(
const std::string& str,
const std::string& suffix,
std::string* result)
{
if (str.length() < suffix.length())
{
return false;
}
size_t newLength = str.length() - suffix.length();
if (memcmp(&str.c_str()[newLength],
suffix.c_str(), suffix.length()) != 0)
{
return false;
}
result->assign(str, 0, newLength);
return true;
}
bool RemoveSuffixInPlace(
std::string* str,
const std::string& suffix)
{
return RemoveSuffix(*str, suffix, str);
}
std::string ConcatPath(const std::string& s1, const std::string& s2)
{
std::string path = s1;
ConcatPathInPlace(&path, s2);
return path;
}
void ConcatPathInPlace(std::string* s1, const std::string& s2)
{
// The below code is taken from stone/file/file_system.h with slight
// modification.
s1->reserve(s1->size() + s2.size() + 1);
const char seperator = '/';
if (!s1->empty() && (*s1)[s1->size() - 1] != seperator)
{
s1->push_back(seperator);
}
s1->append(s2);
}
inline void StringAppendV(std::string* out, const char* fmt, va_list vl)
{
if (out == NULL)
{
return;
}
char* s = NULL;
int n = vasprintf(&s, fmt, vl);
if (n < 0)
{
return; // format string is wrong
}
out->append(s, n);
free(s);
s = NULL;
}
std::string StringPrintf(const char* fmt, ...)
{
std::string s;
va_list vl;
va_start(vl, fmt);
StringAppendV(&s, fmt, vl);
va_end(vl);
return s;
}
void StringAppendF(std::string* out, const char* fmt, ...)
{
va_list vl;
va_start(vl, fmt);
StringAppendV(out, fmt, vl);
va_end(vl);
}
|
685e1e9733b8accab6405c076e033ffa2a2c953d | 476e47aa429efe36e4c754d63a0bd5fa726d000e | /Assignment 1/Assignment 1 Part 1/include/a1part1.h | dbdf8cbd9f70880f01e7e38b69144a7e77d8804b | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | tig3r66/CMPUT275 | 52cb47be7994b9efc82dc5b541cd5e940c0d6569 | 3d060826e4eaabadf66115fc7f8d1037758d6f73 | refs/heads/good_copy | 2021-07-16T07:24:13.509255 | 2020-03-31T05:47:16 | 2020-03-31T05:47:16 | 236,245,989 | 2 | 1 | MIT | 2020-03-29T23:17:50 | 2020-01-25T23:51:39 | C++ | UTF-8 | C++ | false | false | 10,045 | h | a1part1.h | // =======================================
// Name: Edward (Eddie) Guo
// ID: [redacted]
// CMPUT 275, Winter 2020
//
// Assignment 1 Part 1: Restaurant Finder
// =======================================
#ifndef _A1PART1_H_
#define _A1PART1_H_
// ================================= CONSTANTS =================================
// joystick pins to connect
#define SD_CS 10
#define JOY_VERT A9
#define JOY_HORIZ A8
#define JOY_SEL 53
// touch screen pins, obtained from the documentaion
#define YP A3
#define XM A2
#define YM 9
#define XP 8
// calibration data for the touch screen, obtained from documentation the
// minimum/maximum possible readings from the touch point
#define TS_MINX 100
#define TS_MINY 120
#define TS_MAXX 940
#define TS_MAXY 920
// thresholds to determine if there was a touch
#define MINPRESSURE 10
#define MAXPRESSURE 1000
// memory block on SD card where restaurant data is stored
#define REST_START_BLOCK 4000000
#define NUM_RESTAURANTS 1066
// screen and map dimensions
#define DISPLAY_WIDTH 480
#define DISPLAY_HEIGHT 320
#define YEG_SIZE 2048
#define YEG_MIDDLE_X ((YEG_SIZE - (MAP_DISP_WIDTH)) >> 1)
#define YEG_MIDDLE_Y ((YEG_SIZE - DISPLAY_HEIGHT) >> 1)
#define PADX 60
#define SHIFTED_BORDER 2039
// dimensions of the part allocated to the map display
#define MAP_DISP_WIDTH (DISPLAY_WIDTH - 60)
#define MAP_DISP_HEIGHT DISPLAY_HEIGHT
// more map constants
#define MAP_WIDTH 2048
#define MAP_HEIGHT 2048
#define LAT_NORTH 5361858l
#define LAT_SOUTH 5340953l
#define LON_WEST -11368652l
#define LON_EAST -11333496l
// joystick movement
#define JOY_CENTER 512
#define JOY_DEADZONE 64
// cursor size
#define CURSOR_SIZE 9
// font size
#define FONT_SIZE 15
//number of restuarants listed
#define MAX_LIST 21
// ================================== STRUCTS ==================================
// holds restaurant data read from SD card
struct restaurant {
int32_t lat;
int32_t lon;
// from 0 to 10
uint8_t rating;
char name[55];
};
// holds index of restaurant and Manhattan distance of restaurant data from
// data from the SD card
struct RestDist {
uint16_t index;
uint16_t dist;
};
// =========================== FUNCTION DECLARATIONS ===========================
// ============================== SETUP FUNCTIONS ==============================
/*
Description: initializes important components of Arduino, TFT display, and
SD card.
*/
void setup();
/*
Description: intializes TFT display. Portrait display, draws the centre of
the Edmonton map with the rightmost 60 pixels black, and sets the initial
cursor position to the middle of the map.
*/
void lcd_setup();
// MAIN MODES
/*
Description: allows the user to select a restaurant from the 21 closest
restaurants to the cursor. Once selected, the map of Edmonton is redrawn
with the restaurant centered as much as possible on the TFT display.
*/
void modeOne();
/*
Description: translates joystick inputs to movement of the cursor on the TFT
screen. Constrains the cursor to within the map portion of the screen, and
sets variable speed.
Arguments:
slow (uint8_t): the minimum cursor speed (pixels/loop).
fast (uint8_t): the maximum cursor speed (pixels/loop).
*/
void modeZero(uint8_t, uint8_t);
// =========================== TFT-RELATED FUNCTIONS ===========================
/*
Description: draws a square cursor at the current cursor position.
Arguments:
colour (uint16_t): the colour of the cursor.
*/
void redrawCursor(uint16_t);
/*
Description: redraws the shifted map of Edmonton depending on the cursor
nudge direction.
Arguments:
cursorX0 (uint16_t): the original cursor's X position.
cursorY0 (uint16_t): the original cursor's Y position.
*/
void redrawMap();
/*
Description: draws a small map patch from the old cursor position up to the
new cursor position (i.e., only redraws a rectangle if the cursor did not
move too much).
Arguments:
cursorX0 (uint16_t): the original cursor's X position.
cursorY0 (uint16_t): the original cursor's Y position.
*/
void drawMapPatch(int, int);
/*
Description: helper function for drawMapPatch(). Essentially the
lcd_image_draw() except it assumes the image's memory address is &yegImage
and the TFT object's memory address is &tft.
Arguments:
icol (int): image column.
irow (int): image row.
scol (int): screen column.
srow (int): screen row.
width (int): width of the patch to draw.
height (int): height of the patch to draw.
*/
void lcdYegDraw(int, int, int, int, int, int);
/*
Description: constrains the cursor within the boundaries of the image
displayed on the TFT display. This function assumes the cursor is a square.
Arguments:
cursorX (int*): pointer to the cursor's X position.
cursorY (int*): pointer to the cursor's Y position.
*/
void constrainCursor(int*, int*);
/*
Description: constrains the global shift in X and Y position to within the
physical boundaries of the YEG map.
Arguments:
shiftX (int*): pointer to the X shift.
shiftY (int*): pointer to the Y shift.
*/
void constrainMap(int*, int*);
/*
Description: helper function for redrawMap() which aids with map boundary
clamping and map shifting.
Arguments:
shiftLen (int*): the X or Y shift to store for future map shifts.
mainDir (const char*): user passes in the parameter of movement.
*/
void helperMove(int*, const char*);
/*
Description: initial drawing of the names of the closest 21 restaurants to
the cursor. Highlights the first entry.
*/
void printRestList();
/*
Description: redraws the map of Edmonton centered as much as possible over
the selected restaurant.
Arguments:
selection (uint16_t): the index of the selected restaurant.
*/
void redrawOverRest(uint16_t);
// ======================== MEMORY RETRIEVAL FUNCTIONS ========================
/*
Description: fast implementation of getRestaurant(). Reads data from an SD
card into the global restaurant struct TEMP_BLOCK then stores this
information into a smaller global struct REST_DIST. Reads a block once
for consecutive restaurants on the same block.
Arguments:
restIndex (uint16_t): the restaurant to be read.
restPtr (restaurant*): pointer to the restaurant struct.
*/
void getRestaurantFast(uint16_t, restaurant*);
/*
Description: fast implementation of getRestaurant(). Reads a block once for
consecutive restaurants on the same block.
Arguments:
restIndex (uint16_t): the restaurant to be read.
restPtr (restaurant*): pointer to the restaurant struct.
*/
void getRestaurant(uint16_t, restaurant*);
/*
Description: reads all restaurant data from the SD card.
*/
void readRestData();
// ============ LONGITUDE/LATITUDE CONVERSION TO X/Y MAP POSITIONS ============
/*
Description: converts x position on YEG map to longitudinal data for the
real-world coordinates.
Arguments:
x (int16_t): the x position.
Returns:
map(x, 0, MAP_WIDTH, LON_WEST, LON_EAST) (int32_t): the longitude.
*/
int32_t x_to_lon(int16_t);
/*
Description: converts x position on YEG map to latitudinal data for the
real-world coordinates.
Arguments:
y (int16_t): the y position.
Returns:
map(y, 0, MAP_WIDTH, LON_WEST, LON_EAST) (int32_t): the latitude.
*/
int32_t y_to_lat(int16_t);
/*
Description: converts longitudinal data for the real-world YEG locations to
the x position on the YEG map.
Arguments:
lon (int32_t): the longitude.
Returns:
map(lon, LON_WEST, LON_EAST, 0, MAP_WIDTH) (int16_t): the x position.
*/
int16_t lon_to_x(int32_t);
/*
Description: converts latitudinal data for the real-world YEG locations to
the x position on the YEG map.
Arguments:
lat (int32_t): the latitude.
Returns:
map(lat, LAT_NORTH, LAT_SOUTH, 0, MAP_HEIGHT) (int16_t): the y position.
*/
int16_t lat_to_y(int32_t);
// ============================ SORTING ALGORITHMS ============================
/*
Description: implementation of insertion sort.
Arguments:
array[] (int): pointer to an array.
n (int): the number of items in the array.
Notes:
Need to change this function so it sorts based on the RestDist struct.
*/
void insertionSort(RestDist[], int);
// ============================ SCROLLING FUNCTIONS ============================
/*
Description: processes the joystick movements to move the selection
highlight either up or down.
Arguments:
*selection (uint16_t): pointre to the selected restaurant's index.
*/
void menuProcess(uint16_t*);
/*
Description: highlights the selected restaurant and unhighlights the
previous restaurant.
Arguments:
current (int): the currently selected restaurant.
prev (int): the previously selected restaurant.
*/
void redrawText(int, int);
// ======================= TOUCH SCREEN INPUT FUNCTIONS =======================
/*
Description: processes touches on the TFT display. When the user touches the
map, the closest restaurants to the cursor are drawn as blue dots.
*/
void processTouchScreen();
/*
Description: draws dots over restaurants that are closest to the cursor.
Arguments:
radius (int): the desired radius of the drawn dot.
distance (int): the restaurants at a desired distance from the cursor.
colour (uint16_t): the colour of the dot drawn.
*/
void drawCloseRests(uint8_t, uint16_t, uint16_t);
// =============================== TEMPLATE CODE ===============================
/*
Description: swaps two items x and y.
Arguments:
x (T&): the first item to swap.
y (T&): the second item to swap.
*/
template <typename T>
void custom_swap(T &x, T &y) {
T temp = x;
x = y;
y = temp;
}
#endif
|
12cbceab98cacb877b058fe97500ad87a6558347 | 779a71666ae45220828ca681edb8d10930a0133e | /21-5-12/21-5-12/priority_queue.cpp | d8894079ac2bf404cff832ad41544fbaea46c6cb | [] | no_license | zhanghaoyu020418/winter-practice | 4374a651066bb80f5ca6d7a15093a89f730831f5 | 9b47fbb2dc640e38460c88f9e0a103745ab47326 | refs/heads/master | 2023-06-17T19:42:13.020845 | 2021-07-13T00:32:25 | 2021-07-13T00:32:25 | 331,566,065 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,149 | cpp | priority_queue.cpp | //#define _CRT_SECURE_NO_WARNINGS 1
//#include <iostream>
//#include <algorithm>
//#include <queue>
//
//using namespace std;
//
//const int N = 10001;
//
//int a[N], b[N];
//int n, L, P;
//
//int main()
//{
// cin >> n >> L >> P;
// for (int i = 0; i < n; i++)
// cin >> a[i];
// for (int i = 0; i < n; i++)
// cin >> b[i];
//
// // 终点也视为不能加油的加油站
// a[n] = L;
// b[n] = 0;
// n++;
//
// priority_queue<int> q;
// int ans = 0, pos = 0;// ans是加油的次数,pos是当前所在的位置
//
// for (int i = 0; i < n; i++)
// {
// int d = a[i] - pos;// 需要加的油量
//
// while (P < d)// 当剩余的油量少于路程的时候
// {
// if (q.empty())// 如果没有备用的油就说明不能到达
// {
// cout << "-1" << endl;
// return 0;
// }
// P += q.top();// 将最大的油量加上
// q.pop();
// ans++;// 加油次数++
// }
//
// P -= d;// 剩余的油量减去路程消耗
// pos = a[i];// 更新当前位置
// q.push(b[i]);// 将当前的加油站的油量放入priority_queue中
// }
// cout << ans << endl;
// return 0;
//} |
9e01b6f72e762d4331e3b69474fe744c2862e0d2 | 16bb3284a93720eda61b3a75e2e136c9179e1c0c | /games/lhd/crobotlogicframe.h | c480f834f1d9b207f79bfa49768f38bc4228bdaa | [
"Apache-2.0"
] | permissive | FLynnGame/moleserver | fe3be119c423cd1e62399b20b6ad3d09e75a51eb | d79e84f4afc4017c983deb4d6bfe0f5851eccedd | refs/heads/master | 2022-12-10T22:57:32.462485 | 2020-09-08T10:50:59 | 2020-09-08T10:50:59 | 293,780,551 | 0 | 0 | Apache-2.0 | 2020-09-08T10:45:40 | 2020-09-08T10:45:39 | null | GB18030 | C++ | false | false | 1,390 | h | crobotlogicframe.h | #ifndef _C_ROBOT_LOGIC_FRAME_H_INCLUDE_
#define _C_ROBOT_LOGIC_FRAME_H_INCLUDE_
#include "cdefines.h"
#define IDD_TIMER_GAME_XIAZHU1 IDD_TIMER_GAME_START+1 // 下注
class CRobotLogicFrame : public RobotLogicFrame
{
public:
/// 构造函数
CRobotLogicFrame();
/// 析构函数
~CRobotLogicFrame();
/// 设置当前玩家
virtual void SetGamePlayer(Player* pPlayer,Room* pRoom) { m_g_myself = pPlayer; m_g_myselfRoom = pRoom;}
/// 用于处理用户准备后的消息
virtual void OnProcessPlayerReadyMes(int playerId);
/// 用于处理用户开始游戏开始消息
virtual void OnProcessPlayerGameStartMes();
/// 用于处理用户结束游戏消息
virtual void OnProcessPlayerGameOverMes(void);
/// 用于处理用户进入游戏房间后的消息
virtual void OnProcessPlayerRoomMes(Json::Value &mes);
/// 处理用户进入房间消息
virtual void OnProcessEnterRoomMsg(int playerId);
/// 处理用户离开房间消息
virtual void OnProcessLeaveRoomMsg(int playerId);
/// 处理用户断线重连消息
virtual void OnProcessReEnterRoomMes(int playerId);
/// 处理用户断线消息
virtual void OnProcessOfflineRoomMes(int playerId);
/// 处理用户定时器消息
virtual void OnProcessTimerMsg(int timerId,int curTimer);
private:
Player *m_g_myself;
Room *m_g_myselfRoom;
};
#endif
|
7c4b24196aed3f281d78190a8fa7cdbe66259369 | fa410ebeff97d8752d3e8817632302ede4267c65 | /LifeBrush/Source/LifeBrush/Algorithm/Roveri/OutputCloud.cpp | eab3772b709ccfaa01856273218fd429136ce98a | [
"MIT"
] | permissive | corredD/LifeBrush | 366bc6e9c1402304bfb4add5a81bef3ad1306e47 | 3e4d68823575db3a74be9463fb701fffc58adf63 | refs/heads/master | 2020-05-16T22:02:33.760331 | 2019-04-24T02:20:40 | 2019-04-24T02:20:40 | 183,324,280 | 2 | 0 | null | 2019-04-25T00:10:55 | 2019-04-25T00:10:55 | null | UTF-8 | C++ | false | false | 684 | cpp | OutputCloud.cpp | #include "LifeBrush.h"
#include "stdafx.h"
#include "OutputCloud.h"
using namespace Eigen;
using namespace std;
OutputCloud::OutputCloud(void)
{
}
OutputCloud::~OutputCloud(void)
{
}
void OutputCloud::addSample(Vector3f position, vector<Vector3f> attributes)
{
Sample new_sample(position, attributes);
cloud.samples.push_back(new_sample);
}
void OutputCloud::addSampleWithNormal(Vector3f position, Vector3f normal)
{
vector<Vector3f> attributes;
attributes.push_back(normal);
addSample(position, attributes);
}
void OutputCloud::popSample()
{
cloud.samples.pop_back();
}
void OutputCloud::deleteSample(int index)
{
cloud.samples.erase(cloud.samples.begin() + index);
} |
afcc9ca4b82adad2ea669bb2c390b3cd11501150 | 387549ab27d89668e656771a19c09637612d57ed | /DRGLib UE project/Source/FSD/Public/BoscoWeaponsFoldedInNotify.h | 470a82ed03451b03be12e1155f5038f120a956ad | [
"MIT"
] | permissive | SamsDRGMods/DRGLib | 3b7285488ef98b7b22ab4e00fec64a4c3fb6a30a | 76f17bc76dd376f0d0aa09400ac8cb4daad34ade | refs/heads/main | 2023-07-03T10:37:47.196444 | 2023-04-07T23:18:54 | 2023-04-07T23:18:54 | 383,509,787 | 16 | 5 | MIT | 2023-04-07T23:18:55 | 2021-07-06T15:08:14 | C++ | UTF-8 | C++ | false | false | 303 | h | BoscoWeaponsFoldedInNotify.h | #pragma once
#include "CoreMinimal.h"
#include "Animation/AnimNotifies/AnimNotify.h"
#include "BoscoWeaponsFoldedInNotify.generated.h"
UCLASS(Blueprintable, CollapseCategories)
class UBoscoWeaponsFoldedInNotify : public UAnimNotify {
GENERATED_BODY()
public:
UBoscoWeaponsFoldedInNotify();
};
|
c35cfbfaf53005320c86e49767f721ee0adb71c0 | 78587e4b446ea16f6a9645b6053eec1a01c2fe7a | /directed_graph_defs.hpp | 6430ad3e9bbc81100daf4f4e304dc49cde7917b3 | [] | no_license | kidshuster/ssd-graph | 8254e25c29c0066858794b55a50c87e0b2914b2d | ddd457752840e7578616a75f6cd26f89ef06acd9 | refs/heads/master | 2023-03-18T11:34:47.676302 | 2020-07-31T13:48:14 | 2020-07-31T13:48:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,673 | hpp | directed_graph_defs.hpp | #ifndef DIRECTED_GRAPH_DEFINITIONS_H
#define DIRECTED_GRAPH_DEFINITIONS_H
#include "directed_graph.hpp"
namespace graph
{
template<typename T, typename W>
directed_graph<T, W>::directed_graph() noexcept
{
}
template<typename T, typename W>
directed_graph<T, W>::~directed_graph() noexcept
{
this->_ADJACENCY_LIST_.clear();
this->_id_to_node_.clear();
this->_node_to_id_.clear();
}
template<typename T, typename W>
directed_graph<T, W>::directed_graph(const directed_graph &rhs) noexcept
: graph::undirected_graph<T>(rhs)
{
}
template<typename T, typename W>
directed_graph<T, W>& directed_graph<T, W>::operator=(const directed_graph &rhs) noexcept
{
this->_ADJACENCY_LIST_ = rhs._ADJACENCY_LIST_;
this->_id_to_node_ = rhs._id_to_node_;
this->_node_to_id_ = rhs._node_to_id_;
this->isNegWeighted = rhs.isNegWeighted;
this->isWeighted = rhs.isWeighted;
this->_id_ = rhs._id_;
return *this;
}
template<typename T, typename W>
directed_graph<T, W>::directed_graph(directed_graph &&rhs) noexcept
: graph::undirected_graph<T>(rhs)
{
}
template<typename T, typename W>
directed_graph<T, W>& directed_graph<T, W>::operator=(directed_graph &&rhs) noexcept
{
this->_ADJACENCY_LIST_ = std::move(rhs._ADJACENCY_LIST_);
this->_id_to_node_ = std::move(rhs._id_to_node_);
this->_node_to_id_ = std::move(rhs._node_to_id_);
this->isNegWeighted = std::move(rhs.isNegWeighted);
this->isWeighted = std::move(rhs.isWeighted);
this->_id_ = std::move(rhs._id_);
return *this;
}
template<typename T, typename W>
bool directed_graph<T, W>::addEdge(T vertex1, T vertex2, W weight)
{
try
{
// If vertex1 is not previously there, add it to the list of nodes.
if(this->_node_to_id_.find(vertex1) == this->_node_to_id_.end())
{
this->_id_to_node_.insert(std::make_pair(this->_id_, vertex1));
this->_node_to_id_.insert(std::make_pair(vertex1, this->_id_));
this->_ADJACENCY_LIST_.insert(std::make_pair(this->_id_, std::vector<Node<W>>{}));
(this->_id_)++;
}
// If vertex2 is not previously there, add it to the list of nodes.
if(this->_node_to_id_.find(vertex2) == this->_node_to_id_.end())
{
this->_id_to_node_.insert(std::make_pair(this->_id_, vertex2));
this->_node_to_id_.insert(std::make_pair(vertex2, this->_id_));
this->_ADJACENCY_LIST_.insert(std::make_pair(this->_id_, std::vector<Node<W>>{}));
(this->_id_)++;
}
unsigned int id1 = this->_node_to_id_.at(vertex1);
unsigned int id2 = this->_node_to_id_.at(vertex2);
if(weight < 0)
this->isNegWeighted = true;
if(weight != 1)
this->isWeighted = true;
std::vector<Node<W>> edge_list = this->_ADJACENCY_LIST_.at(id1);
if(std::find(edge_list.begin(), edge_list.end(), Node<W>{id2, weight}) == edge_list.end())
this->_ADJACENCY_LIST_.at(id1).push_back(Node<W>{id2, weight});
return true;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
return false;
}
}
template<typename T, typename W>
bool directed_graph<T, W>::addEdges(const std::vector<std::pair<T, T>> &edges)
{
try
{
for(const std::pair<T, T> &e : edges)
{
T vertex1 = e.first;
T vertex2 = e.second;
// If vertex1 is not previously there, add it to the list of nodes.
if(this->_node_to_id_.find(vertex1) == this->_node_to_id_.end())
{
this->_id_to_node_.insert(std::make_pair(this->_id_, vertex1));
this->_node_to_id_.insert(std::make_pair(vertex1, this->_id_));
this->_ADJACENCY_LIST_.insert(std::make_pair(this->_id_, std::vector<Node<W>>{}));
(this->_id_)++;
}
// If vertex2 is not previously there, add it to the list of nodes.
if(this->_node_to_id_.find(vertex2) == this->_node_to_id_.end())
{
this->_id_to_node_.insert(std::make_pair(this->_id_, vertex2));
this->_node_to_id_.insert(std::make_pair(vertex2, this->_id_));
this->_ADJACENCY_LIST_.insert(std::make_pair(this->_id_, std::vector<Node<W>>{}));
(this->_id_)++;
}
unsigned int id1 = this->_node_to_id_.at(vertex1);
unsigned int id2 = this->_node_to_id_.at(vertex2);
std::vector<Node<W>> edge_list = this->_ADJACENCY_LIST_.at(id1);
if(std::find(edge_list.begin(), edge_list.end(), id2) == edge_list.end())
this->_ADJACENCY_LIST_.at(id1).push_back(Node<W>{id2});
}
return true;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
return false;
}
}
template<typename T, typename W>
bool directed_graph<T, W>::addEdges(const std::vector<std::tuple<T, T, W>> &edges)
{
try
{
for(const std::tuple<T, T, W> &e : edges)
{
T vertex1 = std::get<0>(e);
T vertex2 = std::get<1>(e);
W weight = std::get<2>(e);
// If vertex1 is not previously there, add it to the list of nodes.
if(this->_node_to_id_.find(vertex1) == this->_node_to_id_.end())
{
this->_id_to_node_.insert(std::make_pair(this->_id_, vertex1));
this->_node_to_id_.insert(std::make_pair(vertex1, this->_id_));
this->_ADJACENCY_LIST_.insert(std::make_pair(this->_id_, std::vector<Node<W>>{}));
(this->_id_)++;
}
// If vertex2 is not previously there, add it to the list of nodes.
if(this->_node_to_id_.find(vertex2) == this->_node_to_id_.end())
{
this->_id_to_node_.insert(std::make_pair(this->_id_, vertex2));
this->_node_to_id_.insert(std::make_pair(vertex2, this->_id_));
this->_ADJACENCY_LIST_.insert(std::make_pair(this->_id_, std::vector<Node<W>>{}));
(this->_id_)++;
}
unsigned int id1 = this->_node_to_id_.at(vertex1);
unsigned int id2 = this->_node_to_id_.at(vertex2);
if(weight < 0)
this->isNegWeighted = true;
if(weight != 1)
this->isWeighted = true;
std::vector<Node<W>> edge_list = this->_ADJACENCY_LIST_.at(id1);
if(std::find(edge_list.begin(), edge_list.end(), Node<W>{id2, weight}) == edge_list.end())
this->_ADJACENCY_LIST_.at(id1).push_back(Node<W>{id2, weight});
}
return true;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
return false;
}
}
template<typename T, typename W>
bool directed_graph<T, W>::removeEdge(T vertex1, T vertex2)
{
try
{
if(this->_node_to_id_.find(vertex1) != this->_node_to_id_.end() && this->_node_to_id_.find(vertex2) != this->_node_to_id_.end())
{
// Remove vertex2 from adjacency list of vertex1.
std::vector<Node<W>> &edge_list1 = this->_ADJACENCY_LIST_.at(this->_node_to_id_.at(vertex1));
if(std::find(edge_list1.begin(), edge_list1.end(), this->_node_to_id_.at(vertex2)) != edge_list1.end())
{
edge_list1.erase(std::remove(edge_list1.begin(), edge_list1.end(), this->_node_to_id_.at(vertex2)), edge_list1.end());
}
this->checkGraph();
}
return true;
}
catch(const std::exception& e)
{
std::cout << e.what() << '\n';
return false;
}
}
template<typename T, typename W>
bool directed_graph<T, W>::removeEdges(const std::vector<std::pair<T, T>> &edges)
{
try
{
for(const std::pair<T, T> &e : edges)
{
T vertex1 = e.first;
T vertex2 = e.second;
if(this->_node_to_id_.find(vertex1) != this->_node_to_id_.end() && this->_node_to_id_.find(vertex2) != this->_node_to_id_.end())
{
// Remove vertex2 from adjacency list of vertex1.
std::vector<Node<W>> &edge_list1 = this->_ADJACENCY_LIST_.at(this->_node_to_id_.at(vertex1));
if(std::find(edge_list1.begin(), edge_list1.end(), this->_node_to_id_.at(vertex2)) != edge_list1.end())
{
edge_list1.erase(std::remove(edge_list1.begin(), edge_list1.end(), this->_node_to_id_.at(vertex2)), edge_list1.end());
}
this->checkGraph();
}
}
return true;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
return false;
}
}
template<typename T, typename W>
bool directed_graph<T, W>::removeEdge(T vertex1, T vertex2, W weight)
{
try
{
if(this->_node_to_id_.find(vertex1) != this->_node_to_id_.end() && this->_node_to_id_.find(vertex2) != this->_node_to_id_.end())
{
// Remove vertex2 from adjacency list of vertex1.
std::vector<Node<W>> &edge_list1 = this->_ADJACENCY_LIST_.at(this->_node_to_id_.at(vertex1));
if(std::find(edge_list1.begin(), edge_list1.end(), Node<W>{this->_node_to_id_.at(vertex2), weight}) != edge_list1.end())
{
edge_list1.erase(std::remove(edge_list1.begin(), edge_list1.end(), Node<W>{this->_node_to_id_.at(vertex2), weight}), edge_list1.end());
}
this->checkGraph();
}
return true;
}
catch(const std::exception& e)
{
std::cout << e.what() << '\n';
return false;
}
}
template<typename T, typename W>
bool directed_graph<T, W>::removeEdges(const std::vector<std::tuple<T, T, W>> &edges)
{
try
{
for(const std::tuple<T, T, W> &e : edges)
{
T vertex1 = std::get<0>(e);
T vertex2 = std::get<1>(e);
W weight = std::get<2>(e);
if(this->_node_to_id_.find(vertex1) != this->_node_to_id_.end() && this->_node_to_id_.find(vertex2) != this->_node_to_id_.end())
{
// Remove vertex2 from adjacency list of vertex1.
std::vector<Node<W>> &edge_list1 = this->_ADJACENCY_LIST_.at(this->_node_to_id_.at(vertex1));
if(std::find(edge_list1.begin(), edge_list1.end(), Node<W>{this->_node_to_id_.at(vertex2), weight}) != edge_list1.end())
{
edge_list1.erase(std::remove(edge_list1.begin(), edge_list1.end(), Node<W>{this->_node_to_id_.at(vertex2), weight}), edge_list1.end());
}
this->checkGraph();
}
}
return true;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
return false;
}
}
template<typename T, typename W>
std::vector<std::vector<T>> directed_graph<T, W>::stronglyConnectedComponents() const
{
unsigned int id = 0;
std::stack<unsigned int> S;
std::vector<std::vector<T>> SCC;
std::unordered_set<unsigned int> onStack;
std::unordered_map<unsigned int, unsigned int> Ids; // This also acts as 'Visited' array.
std::unordered_map<unsigned int, unsigned int> Low;
// A SCC is a subtree in a DFS tree. So, start DFS for every tree in DFS forest to find all SCC's.
for(const std::pair<unsigned int, T> &vertex : this->_id_to_node_)
if(Ids.find(vertex.first) == Ids.end())
stronglyConnectedComponentsUtil(vertex.first, id, S, onStack, Ids, Low, SCC);
return SCC;
}
template<typename T, typename W>
void directed_graph<T, W>::stronglyConnectedComponentsUtil(unsigned int current, unsigned int id, std::stack<unsigned int> &S, std::unordered_set<unsigned int> &onStack, std::unordered_map<unsigned int, unsigned int> &Ids, std::unordered_map<unsigned int, unsigned int> &Low, std::vector<std::vector<T>> &SCC) const
{
// As soon as a node is visited, push it onto the stack and assign it an id and a low-link value.
S.push(current);
onStack.insert(current);
Ids[current] = Low[current] = id++;
// Loop through all the neighbours of the current node.
for(const Node<W> &next : this->_ADJACENCY_LIST_.at(current))
{
// Do DFS for unvisited nodes.
if(Ids.find(next.vertex) == Ids.end())
stronglyConnectedComponentsUtil(next.vertex, id, S, onStack, Ids, Low, SCC);
// If the 'next' is on the stack, it means that there is a path from 'next' to 'current' which we used to visit 'current'. But now there is also a path from 'current' to 'next'.
// So, 'current', 'next' belong to same SCC. This step allows low-link values to propagate throughout cycles.
if(onStack.find(next.vertex) != onStack.end())
Low[current] = std::min(Low[current], Low[next.vertex]);
}
// If the low-link value is equal to the id for a node, it is the start of a SCC.
if(Ids[current] == Low[current])
{
// Finding the component by popping off the stack until the start node(current).
std::vector<T> Component;
while(true)
{
unsigned int top = S.top();
S.pop();
Component.push_back(this->_id_to_node_.at(top));
onStack.erase(top);
Low[top] = Ids[current];
if(top == current)
{
SCC.push_back(Component);
break;
}
}
}
}
// Different method for finding cycles in a directed graph. This is based on detecting back-edges in DFS forest.
// template<typename T, typename W>
// bool undirected_graph<T, W>::isCyclic() const
// {
// std::unordered_set<unsigned int> Visited;
// std::unordered_set<unsigned int> recStack;
// for(const std::pair<unsigned int, std::vector<Node<W>>> &edges : this->_ADJACENCY_LIST_)
// if(isCyclicUtil(edges.first, Visited, recStack))
// return true;
// return false;
// }
// template<typename T, typename W>
// bool undirected_graph<T, W>::isCyclicUtil(unsigned int current, std::unordered_set<unsigned int> &Visited, std::unordered_set<unsigned int> &recStack) const
// {
// if(Visited.find(current) == Visited.end())
// {
// Visited.insert(current);
// recStack.insert(current);
// for(const Node<W> &child : this->_ADJACENCY_LIST_.at(current))
// {
// if(Visited.find(child.vertex) == Visited.end())
// if(isCyclicUtil(child.vertex, Visited, recStack))
// return true;
// // Indicates a back-edge. If the 'child' is already on recStack, we have a path from 'child' to 'current'. Now, we found an edge from 'current' to 'child' - Cycle!
// // Visited[child] = true && recStack[child] = true -- Back-edge
// // Visited[child] = true && recStack[child] = false -- 'child' belongs to different DFS tree.
// else if(recStack.find(child.vertex) != recStack.end())
// return true;
// }
// }
// // Remove vertices belonging to different DFS tree.
// recStack.erase(current);
// return false;
// }
template<typename T, typename W>
bool directed_graph<T, W>::isCyclic() const
{
std::unordered_set<unsigned int> whiteSet; // Unvisited
std::unordered_set<unsigned int> greySet; // Visited, but not completely processed.
std::unordered_set<unsigned int> blackSet; // Visited completely.
for(const std::pair<unsigned int, std::vector<Node<W>>> &i : this->_ADJACENCY_LIST_)
whiteSet.insert(i.first);
while(whiteSet.size() > 0)
{
if(isCyclicUtil(*whiteSet.begin(), whiteSet, greySet, blackSet))
return true;
}
return false;
}
template<typename T, typename W>
bool directed_graph<T, W>::isCyclicUtil(unsigned int start, std::unordered_set<unsigned int> &whiteSet, std::unordered_set<unsigned int> &greySet, std::unordered_set<unsigned int> &blackSet) const
{
greySet.insert(start);
whiteSet.erase(start);
for(Node<W> dest : this->_ADJACENCY_LIST_.at(start))
{
if(blackSet.find(dest.vertex) != blackSet.end())
continue;
if(greySet.find(dest.vertex) != greySet.end())
return true;
if(whiteSet.find(dest.vertex) != whiteSet.end() && isCyclicUtil(dest.vertex, whiteSet, greySet, blackSet))
return true;
}
greySet.erase(start);
blackSet.insert(start);
return false;
}
template<typename T, typename W>
std::vector<T> directed_graph<T, W>::topologicalSort() const
{
if(isCyclic())
return std::vector<T>{};
std::unordered_set<unsigned int> Visited;
unsigned int index = this->_ADJACENCY_LIST_.size() - 1;
std::vector<T> TopSort(index + 1);
for(const std::pair<unsigned int, std::vector<Node<W>>> &edges : this->_ADJACENCY_LIST_)
if(Visited.find(edges.first) == Visited.end())
index = topologicalSortUtil(index, edges.first, Visited, TopSort);
return TopSort;
}
template<typename T, typename W>
unsigned int directed_graph<T, W>::topologicalSortUtil(unsigned int index, unsigned int start, std::unordered_set<unsigned int> &Visited, std::vector<T> &TopSort) const
{
Visited.insert(start);
for(Node<W> dest : this->_ADJACENCY_LIST_.at(start))
if(Visited.find(dest.vertex) == Visited.end())
index = topologicalSortUtil(index, dest.vertex, Visited, TopSort);
TopSort[index] = this->_id_to_node_.at(start);
return index - 1;
}
template<typename T, typename W>
std::pair<int, int> directed_graph<T, W>::degree(T vertex) const
{
if(this->_node_to_id_.find(vertex) != this->_node_to_id_.end())
{
unsigned int id = this->_node_to_id_.at(vertex);
int out_degree = this->_ADJACENCY_LIST_.at(id).size();
int in_degree = 0;
for(const std::pair<unsigned int, std::vector<Node<W>>> &edges : this->_ADJACENCY_LIST_)
{
if(std::find(edges.second.begin(), edges.second.end(), id) != edges.second.end())
in_degree++;
}
return std::pair<int, int>(in_degree, out_degree);
}
else
return std::pair<int, int>(-1, -1);
}
}
#include "directed_eulerian.hpp"
#endif |
1ee25e3a846f6f9b097eed2bc323d0b0e85f3324 | 58e631e84062a18a8202fb68f5cce2c754c0fe49 | /Runtime/Animation/TwoColorAnimation.h | ea46f77e4d2393f152072e575d2e1f5d11c99560 | [] | no_license | zhaosiwen1949/Fire_Game_Engine | e816215833cc5a3a006da0c257f0f447c2a7cbbc | f2c13c3f32765fd6df368649fccd1b67564cb3ec | refs/heads/main | 2023-07-06T18:55:12.437310 | 2021-08-06T01:38:12 | 2021-08-06T01:38:12 | 393,214,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 727 | h | TwoColorAnimation.h | #pragma once
#include "Runtime/Math/Vector4.h"
#include "Runtime/Serializer/Animation.serializer.h"
#include "Animation.h"
namespace Alice {
class TwoColorAnimationKeyFrame : public AnimationKeyFrame {
public:
Color4f mLightColor;
Color4f mDarkColor;
void Init(const Serializer::TwoColorAnimationKeyFrame&key_frame_data);
};
class TwoColorAnimation : public AnimationUnit {
public:
virtual void OnUpdateStepAnimation(AnimationKeyFrame*keyframe);
virtual void OnUpdateLinearAnimation(float animation_time, AnimationKeyFrame*start_frame, AnimationKeyFrame*end_frame);
virtual void OnUpdateBezierAnimation(float animation_time, AnimationKeyFrame*start_frame, AnimationKeyFrame*end_frame);
};
} |
609a2e2d0b9dbbc07084ee19ab62fb14388d9565 | 685579c926394c4ec2771975468f2a4bdd94b83d | /test/test_splitdrive.cpp | 1f8c3fd939794df7243929f59bb6d66edaa3272c | [
"BSD-2-Clause"
] | permissive | loooser/ftxpath | e25c926180057de71d12ad9e2f71d50930b54d21 | e4e7494e73b422028ba9b747ed0b7a5cd7e8a068 | refs/heads/master | 2021-01-20T23:45:50.977000 | 2016-02-07T09:51:43 | 2016-02-07T09:51:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,687 | cpp | test_splitdrive.cpp | //
// Created by 王晓辰 on 16/2/6.
//
#include "test_splitdrive.h"
#include <ftxpath.h>
#include "tester.h"
bool test_splitdrive_normal()
{
std::string path = "c:/a/b";
std::string head = "c:";
std::string tail = "/a/b";
auto tuple = ftx::path::splitdrive(path);
std::cout << std::get<0>(tuple) << "\n" << std::get<1>(tuple) << std::endl;
#ifdef WIN32
return head == std::get<0>(tuple) && tail == std::get<1>(tuple);
#else
return "" == std::get<0>(tuple) && path == std::get<1>(tuple);
#endif
}
bool test_splitdrive_unc()
{
std::string path = "//machine/share/a/b/c";
std::string head = "//machine/share";
std::string tail = "/a/b/c";
auto tuple = ftx::path::splitdrive(path);
std::cout << std::get<0>(tuple) << "\n" << std::get<1>(tuple) << std::endl;
#ifdef WIN32
return head == std::get<0>(tuple) && tail == std::get<1>(tuple);
#else
return "" == std::get<0>(tuple) && path == std::get<1>(tuple);
#endif
}
bool test_splitdrive_root()
{
std::string path = "/";
auto tuple = ftx::path::splitdrive(path);
return "" == std::get<0>(tuple) && path == std::get<1>(tuple);
}
bool test_splitdrive_slash()
{
std::string path = "\\\\\\";
auto tuple = ftx::path::splitdrive(path);
return "" == std::get<0>(tuple) && path == std::get<1>(tuple);
}
bool test_splitdrive() {
LOG_TEST_STRING("");
TEST_BOOL_TO_BOOL(test_splitdrive_normal(), "test splitdrive normal case failed");
TEST_BOOL_TO_BOOL(test_splitdrive_unc(), "test splitdrive unc format case failed");
TEST_BOOL_TO_BOOL(test_splitdrive_root(), "test splitdrive root case failed");
TEST_BOOL_TO_BOOL(test_splitdrive_slash(), "test splitdrive slash case failed");
return true;
}
|
6227579aca5906584c1b5a45f5bdc52acdf0c212 | ee7d8fe376ad23664cfe462a7d4e3e4b58be3b04 | /BASE22.CPP | 70dbbf0d3a19d184bcba5615ecac3cb042481f47 | [] | no_license | rohitchoudhary1707/C-notes | 4fc8aec970f8deeea53c6edce471325de19bd702 | aff8b24d4ef26275795529b54695cb6ed64e213b | refs/heads/master | 2020-07-25T02:02:42.473238 | 2019-09-12T19:08:28 | 2019-09-12T19:08:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | cpp | BASE22.CPP | #include<stdio.h>
#include<conio.h>
void main ()
{
int a,b,c,d;
clrscr();
printf("\nenter value of a=");
scanf("%d",&a);
printf("\nenter value of b=");
scanf("%d",&b);
printf("\nenter value of c=");
scanf("%d",&c);
d=a>b&&a>c?a:(b>a&&b>c?b:c);
printf("\nlargest value=%d",d);
getch();
} |
d7e5561ecc3122f5f2ab70b8481d5cfe4728b109 | 7ce50237b28a940883d257df2e1888dbea580f79 | /NodeMCU_MySql_DHT11_DOMO/NodeMCU_MySql_DHT11_DOMO.ino | 072a59837f8928e348937dad3bba81cecfca89ff | [] | no_license | jmgdelgado/Arduino | 43006540e9c18141143634cad0072adbd367b4b7 | fd078b02c108904a6167041d663121f4153ab856 | refs/heads/master | 2021-04-28T19:42:09.831857 | 2018-10-20T10:48:29 | 2018-10-20T10:48:29 | 121,901,840 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,319 | ino | NodeMCU_MySql_DHT11_DOMO.ino | // Esta es la librería para utilizar las funciones de red del ESP8266
#include <ESP8266WiFi.h>
// SENSOR DE TEMPERATURA Y HUMEDAD DHT11
// Sensor DHT11 de Temperatura y Humedad
//
// Se necesita la libreria de Adafruit DHT sensor library.
// ATENCION: Instalar la version 1.2.3 con la 1.3.0 no compila
//
// La pata DATA se conecta a una salida digital
// En Arduino Nano: Pin D2
// En NodeMCU: Pin D4
//
// VCC 5 voltios
#include <DHT.h>
const char* ssid = "EUSKALTEL_D0014804"; // Rellena con el nombre de tu red WiFi
const char* password = "PJKDPHVR"; // Rellena con la contraseña de tu red WiFi
const char* host = "192.168.0.31"; // La IP del equipo donde esta MySql y Apache
const int httpPort = 80; // Puerto HTTP //S
// Wake from deep sleep, in seconds.
#define wakeuptime 900
int powerDHT = D5; // Este pin vamos a utilizarlo para alimentar el sensor solo cuando se vaya a utilizar
int SENSOR = 2; // GPIO2 : D4
int temp, humedad; // La precision es de un grado, no va a dar decimales
DHT dht (SENSOR, DHT11); // Se crea el tipo sensor de tipo dht11
void setup() {
Serial.begin(9600);
delay(10);
pinMode(D5,OUTPUT);
digitalWrite(D5,HIGH);
// Comenzamos el sensor DHT
dht.begin();
// Conectamos a la red WiFi
conectarWifi();
delay(5000);
}
void loop() {
float Temperatura = 0;
float Humedad = 0;
int Sensor = 1;
Humedad = dht.readHumidity();
Temperatura = dht.readTemperature();
sacarEnMonitorSerie(Temperatura,Humedad);
if (Temperatura > -100 && Temperatura < 200)
{
delay(1);
}
else return;
// Creamos el cliente
WiFiClient client;
// Conectamos al Servidor
client = conectarServidor(client);
delay(1);
// Creamos la URL para la petición
String url = crearURL(Sensor,Temperatura,Humedad);
// Enviamos la petición
client = enviarPeticionHTTP(client,url);
// Leemos la respuesta y la enviamos al monitor serie
client = leerRespuestaHTTP(client);
Serial.println("Cerrando la conexión");
client.stop();
// Consutar la memoria libre
// Quedan un poco más de 40 kB
Serial.printf("\nMemoria libre en el ESP8266: %d Bytes\n\n",ESP.getFreeHeap());
// Poner en modo DEEP SLEEP el ESP, tiempo en microsegundos
// Hay que conectar el pin D0 con el pin RST: Reset
// ATENCION: hay que puentearlo despues de cargar el programa sino da error
// Se reinicia todo el programa cuando despierta
digitalWrite(D5,LOW);
dormirDeepSleep(wakeuptime);
// delay(10000);
Serial.println("Despertando");
}
void dormirDeepSleep(int segundos)
{
// Poner en modo DEEP SLEEP el ESP, tiempo en microsegundos
// Hay que conectar el pin D0 con el pin RST: Reset
// ATENCION: hay que puentearlo despues de cargar el programa sino da error
// Se reinicia todo el programa cuando despierta
// Sleep
Serial.println("Going to sleep");
delay(5000);
ESP.deepSleep(segundos * 1000000, WAKE_RF_DEFAULT);
}
void conectarWifi()
{
// Conectamos a la red WiFi
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
/* Configuramos el ESP8266 como cliente WiFi. Si no lo hacemos
se configurará como cliente y punto de acceso al mismo tiempo */
WiFi.mode(WIFI_STA); // Modo cliente WiFi
WiFi.begin(ssid, password);
// Esperamos a que estemos conectados a la red WiFi
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); // Mostramos la IP
return;
}
WiFiClient conectarServidor(WiFiClient client)
{
Serial.print("connecting to ");
Serial.println(host);
if (!client.connect(host, httpPort)) {
// ¿hay algún error al conectar?
Serial.println("Ha fallado la conexión");
delay(1000);
return client;
}
Serial.println("Conectado");
Serial.println("");
delay(1);
return client;
}
WiFiClient enviarPeticionHTTP(WiFiClient client, String url)
{
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Superado el tiempo de espera !");
client.stop();
return client;
}
}
return client;
}
WiFiClient leerRespuestaHTTP(WiFiClient client)
{
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println();
return client;
}
String crearURL(int Sensor, float Temperatura, float Humedad)
{
String url = "/domo/dht_insert.php?temp=";
url += String(Temperatura);
url += "&hume=";
url += String(Humedad);
url += "&sensor=";
url += String(Sensor);
Serial.print("URL de la petición: http://");
Serial.print(host);
Serial.print(":");
Serial.print(httpPort);
Serial.println(url);
Serial.println("");
return url;
}
void sacarEnMonitorSerie(float Temperatura, float Humedad)
{
Serial.print("Temperatura: ");
Serial.print(Temperatura);
Serial.print("ºC Humedad: ");
Serial.print(Humedad);
Serial.print("%");
}
|
a91b26c833702def16eec2c02ce9ed56da3d0f48 | 542b926a8d3632edb9565fb2797cd31030c7e6f8 | /GatewayServer/GatewayTaskManager.h | fe45ef3dc8dce860aab24a4157aafd78c8686175 | [] | no_license | hackerlank/loki | 34cb630957908b753852908b9afb8e4f401e463a | 25a7e83b5d2bbc8a372c9a5f9d672ac6039230f2 | refs/heads/master | 2020-06-14T22:25:05.301832 | 2016-04-22T09:55:34 | 2016-04-22T09:55:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 643 | h | GatewayTaskManager.h | #pragma once
#include "singleton.h"
#include <unordered_map>
#include <mutex>
#include "GatewayTask.h"
#include <unordered_set>
class GatewayTaskManager: public Singleton<GatewayTaskManager>
{
public:
~GatewayTaskManager();
bool uniqueAdd(GatewayTaskPtr& task);
bool uniqueRemove(GatewayTaskPtr& task);
GatewayTaskPtr getTaskByID(const uint32_t n);
uint32_t size();
bool addCountryUser(const GatewayTaskPtr& task);
void removeCountryUser(const GatewayTaskPtr& task);
private:
std::unordered_map<uint32_t, GatewayTaskPtr> tasks_;
std::mutex mutex_;
std::unordered_map<uint32_t, std::unordered_set<uint32_t> > countryindex_;
};
|
d4fc6be471a49109f3c311028bae2ac9c79e5f5a | 676c4450fc61a1f2b514014b97d5ba06ce120f2a | /HEVD/ArbitraryOverwriteTest.cpp | fd0c45131136254069b64b1a3ce84e51d6600a24 | [] | no_license | PleXone2019/Exploits | f1715981eae6604b81e839824f849cba852b3b9d | 59260f85b18ab6972d738b27b6d11dd34989833b | refs/heads/master | 2020-11-30T22:53:38.932042 | 2018-01-14T13:56:51 | 2018-01-14T13:56:51 | 230,502,157 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,649 | cpp | ArbitraryOverwriteTest.cpp | #include "stdafx.h"
#include <stdio.h>
#include <Windows.h>
#include <string.h>
#define HACKSYS_EVD_IOCTL_ARBITRARY_OVERWRITE CTL_CODE(FILE_DEVICE_UNKNOWN, 0x802, METHOD_NEITHER, FILE_ANY_ACCESS)
int _tmain(int argc, _TCHAR* argv[]) {
HANDLE hDevice;
DWORD lpBytesReturned;
PVOID pMemoryAddress = NULL;
PULONG lpInBuffer = NULL;
LPCWSTR lpDeviceName = L"\\\\.\\HackSysExtremeVulnerableDriver";
SIZE_T nInBufferSize = 0x8;
hDevice = CreateFile(
lpDeviceName,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
NULL);
wprintf(L"[*] Author: @OsandaMalith\n[*] Website: https://osandamalith.com\n\n");
wprintf(L"[+] lpDeviceName: %ls\n", lpDeviceName);
if (hDevice == INVALID_HANDLE_VALUE) {
wprintf(L"[!] Failed to get a handle to the driver. 0x%x\n", GetLastError());
return 1;
}
lpInBuffer = (PULONG)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nInBufferSize);
if (!lpInBuffer) {
wprintf(L"[!] Failed to allocated memory. %x", GetLastError());
return 1;
}
RtlFillMemory((PVOID)lpInBuffer, 0x4, 0x41);
RtlFillMemory((PVOID)(lpInBuffer + 1), 0x4, 0x42);
wprintf(L"[+] Sending IOCTL request\n");
DeviceIoControl(
hDevice,
HACKSYS_EVD_IOCTL_ARBITRARY_OVERWRITE,
(LPVOID)lpInBuffer,
(DWORD)nInBufferSize,
NULL,
0,
&lpBytesReturned,
NULL);
HeapFree(GetProcessHeap(), 0, (LPVOID)lpInBuffer);
CloseHandle(hDevice);
return 0;
}
|
283b26afd14d0de7f573154908b0c6a4a6fecaab | d61b1a7034796ac8275fc199e96b0e74914f6cbc | /NxNandManager/utils.h | 92dbd43379da563fae719c19db3a6f49903d420b | [] | no_license | MicrohexHQ/NxNandManager | 238da7baf143378cccbb8a092adcd913185f0c34 | bfcbef779761b462ac39ce537b8b0f180fb58024 | refs/heads/master | 2020-08-08T00:41:56.155239 | 2019-10-08T13:12:37 | 2019-10-08T13:12:37 | 213,645,549 | 0 | 0 | null | 2019-10-08T13:11:54 | 2019-10-08T13:11:54 | null | UTF-8 | C++ | false | false | 5,133 | h | utils.h | #pragma once
#ifndef __utils_h__
#define __utils_h__
#include <stdio.h>
#include <string>
#include <sys/types.h>
#include <windows.h>
#include <winioctl.h>
#include "types.h"
#include <sys/stat.h>
#include <iostream>
#include <chrono>
#include <iomanip>
#include <fstream>
#include <wchar.h>
#include <algorithm>
#include <sstream>
#include <tchar.h>
#include "DiskSector.h"
#include "partitionmanager.h"
typedef std::chrono::duration< double > double_prec_seconds;
typedef std::chrono::time_point< std::chrono::system_clock, double_prec_seconds > timepoint_t;
// MinGW
#if defined(__MINGW32__) || defined(__MINGW64__) || defined(__MSYS__)
#define strcpy_s strcpy
#define sprintf_s snprintf
#endif
//CRYPTO
#define ENCRYPT 1
#define DECRYPT 2
// ERRORS
#define ERR_WRONG_USE -1001
#define ERR_INVALID_INPUT -1002
#define ERR_INVALID_OUTPUT -1003
#define ERR_INVALID_PART -1004
#define ERR_IO_MISMATCH -1005
#define ERR_INPUT_HANDLE -1006
#define ERR_OUTPUT_HANDLE -1007
#define ERR_CRYPTO_MD5 -1008
#define ERR_NO_LIST_DISK -1009
#define ERR_NO_SPACE_LEFT -1010
#define ERR_COPY_SIZE -1011
#define ERR_MD5_COMPARE -1012
#define ERR_INIT_GUI -1013
#define ERR_WORK_RUNNING -1014
#define ERR_WHILE_COPY -1015
#define NO_MORE_BYTES_TO_COPY -1016
#define ERR_RESTORE_TO_SPLIT -1017
#define ERR_DECRYPT_CONTENT -1018
#define ERR_RESTORE_CRYPTO_MISSING -1019
#define ERR_CRYPTO_KEY_MISSING -1020
#define ERR_CRYPTO_GENERIC -1021
#define ERR_CRYPTO_NOT_ENCRYPTED -1022
#define ERR_CRYPTO_ENCRYPTED_YET -1023
#define ERR_CRYPTO_DECRYPTED_YET -1024
#define ERR_RESTORE_CRYPTO_MISSIN2 -1025
#define ERROR_DECRYPT_FAILED -1026
typedef struct ErrorLabel ErrorLabel;
struct ErrorLabel {
int error;
const char* label;
};
static ErrorLabel ErrorLabelArr[] =
{
{ ERR_WORK_RUNNING, "Work already in process"},
{ ERR_INPUT_HANDLE, "Failed to get handle to input file/disk"},
{ ERR_OUTPUT_HANDLE, "Failed to get handle to output file/disk"},
{ ERR_NO_SPACE_LEFT, "Output disk : not enough space !"},
{ ERR_CRYPTO_MD5, "Crypto provider error"},
{ ERR_MD5_COMPARE, "Data integrity error : checksums are differents.\nAn error must have occurred during the copy"},
{ ERR_RESTORE_TO_SPLIT, "Restore to splitted dump is not supported"},
{ ERR_WHILE_COPY, "An error occured during copy"},
{ ERR_IO_MISMATCH, "Input type/size doesn't match output size/type"},
{ ERR_INVALID_INPUT, "Input is not a valid NX storage"},
{ ERR_DECRYPT_CONTENT, "Failed to validate decrypted content (wrong keys ?)"},
{ ERR_RESTORE_CRYPTO_MISSING, "Trying to restore decrypted input to encrypted output and keyset missing to encrypt data"},
{ ERR_RESTORE_CRYPTO_MISSIN2, "Trying to restore encrypted input to decrypted output (decrypt content to restore first)"},
{ ERR_CRYPTO_KEY_MISSING, "Trying to decrypt/encrypt content but some keys are missing (configure keyset)"},
{ ERROR_DECRYPT_FAILED, "Decryption validation failed (wrong keys ?)"},
{ ERR_CRYPTO_NOT_ENCRYPTED, "Input file is not encrypted"},
{ ERR_CRYPTO_ENCRYPTED_YET, "Input file is already encrypted"},
{ ERR_CRYPTO_DECRYPTED_YET, "Input file is already decrypted"}
};
typedef struct KeySet KeySet;
struct KeySet {
char crypt0[33];
char tweak0[33];
char crypt1[33];
char tweak1[33];
char crypt2[33];
char tweak2[33];
char crypt3[33];
char tweak3[33];
};
wchar_t *convertCharArrayToLPCWSTR(const char* charArray);
LPWSTR convertCharArrayToLPWSTR(const char* charArray);
u64 GetFilePointerEx (HANDLE hFile);
unsigned long sGetFileSize(std::string filename);
std::string GetLastErrorAsString();
std::string hexStr(unsigned char *data, int len);
BOOL AskYesNoQuestion(const char* question);
std::string GetReadableSize(u64 size);
std::string GetReadableElapsedTime(std::chrono::duration<double> elapsed_seconds);
void throwException(int rc, const char* errorStr=NULL);
void throwException(const char* errorStr=NULL);
std::string ListPhysicalDrives(BOOL noError=FALSE);
char * flipAndCodeBytes(const char * str, int pos, int flip, char * buf);
std::string ExePath();
HMODULE GetCurrentModule();
bool is_file_exist(const wchar_t *fileName);
int digit_to_int(char d);
template<class T>
T base_name(T const & path, T const & delims = "/\\")
{
return path.substr(path.find_last_of(delims) + 1);
}
template<class T>
T remove_extension(T const & filename)
{
typename T::size_type const p(filename.find_last_of('.'));
return p > 0 && p != T::npos ? filename.substr(0, p) : filename;
}
template<class T>
T get_extension(T const & filename)
{
typename T::size_type const p(filename.find_last_of('.'));
return p > 0 && p != T::npos ? filename.substr(p, T::npos) : filename;
}
template< typename T >
std::string int_to_hex(T i)
{
std::stringstream stream;
stream << "0x"
<< std::setfill('0') //<< std::setw(sizeof(T) * 2)
<< std::uppercase
<< std::hex << i;
return stream.str();
}
std::string ltrim(const std::string& s);
std::string rtrim(const std::string& s);
std::string trim(const std::string& s);
int parseKeySetFile(const char *keyset_file, KeySet *biskeys);
#endif
|
550ab258b52153f535755bda0e24bd0771dee186 | 41984609c3e6176e4e88582e84f93f4d2dff0812 | /vernam/main.cpp | 38fdb56e517c9844ca8e9af7f657e39bfc50afc5 | [] | no_license | alexa1999/alg-abst | f42a737d296c4669e2b1c992d71af09cc70ddc59 | ca38c6de5cd6d91d3d8c744f03e19fc75733248b | refs/heads/master | 2020-07-11T18:27:55.254853 | 2019-10-09T23:09:55 | 2019-10-09T23:09:55 | 204,614,812 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 938 | cpp | main.cpp | #include <iostream>
#include <math.h>
#include <bitset>
#include "Vernam.h"
using namespace std;
int main()
{
// ifstream ficheroEntrada;
// ficheroEntrada.open("mensaje.txt");
// string mensaje;
// getline(ficheroEntrada, mensaje);
// ficheroEntrada.close();
//
// int tam=mensaje.size();
// Vernam as(tam);
// string encriptado=as.Encriptar(mensaje);
string mensaje1="000010001001001011001100010001100000010000001000001101011110110100000010000011010100010011010110110110000011010010100100001111011111000001000000011001101010000001000011100011001100001100000110001001000010010101110100011101000011000011101110000100100101001000011011011010001100011110000101000010";
string clave="fhaedesgbqqgrhtespwadlfrxochhlmkitrqvshkebkvwipxf5";
Vernam ass(clave);
string desenc=ass.Desencriptar(mensaje1);
cout<<"descen:"<< desenc<<endl;
// toBinary(8);
return 0;
}
|
596d22fa2e00def74621e7066bce3115e603129f | 32d0676e86583948774c03841fc198f8443b06b5 | /exercises/ex_5/v2/top.cpp | 7beb3c813e33d43f0ca44bb9a5bc0f14cdaf5406 | [] | no_license | oldgeezr/tfe4171 | 0c2e754c31dcbb14db70db26a03ddb504aebf7dd | 994607e81c52fc46613a4a1ed8575aeeb5c71007 | refs/heads/master | 2016-09-06T17:17:54.935475 | 2015-04-13T11:49:00 | 2015-04-13T11:49:00 | 29,926,935 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,442 | cpp | top.cpp | /* -*- mode: c++ -*-
**
** top.cpp
**
** top level instatiations and simulation control
**
** Made by Kjetil Svarstad
**
*/
#include "fifo.h"
#include "producer.h"
#include "consumer.h"
// Top level module
class top : public sc_module {
public:
// need instances of fifo, producer and consumer
fifo fifo_inst;
producer prod_inst;
consumer cons_inst;
// constructor for top, sends name to sc_module constructor
top (sc_module_name name, int size) : sc_module (name) ,
// and executes the actual
// instantiation of the fifo,
// the producer and consumer
// with their respective
// parameter values
fifo_inst ("fifo", size),
prod_inst ("producer"),
cons_inst ("consumer") {
// Connects the producers writep port to the fifo instance
prod_inst.writep (fifo_inst);
// and then the consumers readp port to the fifo instance
cons_inst.readp (fifo_inst);
}
};
// Main program, running the simulation
int sc_main (int argc , char *argv[]) {
// FIFO size can be set as command line argument
// default is 10
int size = 10;
if (argc > 1)
size = atoi(argv[1]);
if (size < 1)
size = 1;
if (size > 100000)
size = 100000;
// instantiating top module
top top1("Top1", size);
// initializing random number generator
srand ( time(NULL) );
// run simualtion indefinitely until some module calls sc_stop
sc_start();
return 0;
}
|
a7835328d2729097a148d91d11c685dfab73e30d | 85ba56df8b459a2e3c4c7e3d66bf4d96c7f8c9b1 | /Strings/LeetCode/numbersubstringswith1s.cpp | 9b811fa88883685207f066614098c6a4791e208d | [] | no_license | raghavaggarwal99/Competitive | 80c29213a4f81b39a01d5b2b5e70ab22ceb9738c | fa8a472eddf612f969ec67104110bcdfe03332c9 | refs/heads/master | 2021-07-10T09:31:01.666951 | 2020-09-26T17:03:40 | 2020-09-26T17:03:40 | 203,055,409 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 525 | cpp | numbersubstringswith1s.cpp | class Solution {
public:
int numSub(string s) {
long long int ans=0;
long long int count=0;
long long mod=pow(10,9) + 7;
for(int i=0; i<s.size(); i++){
if(s[i]=='1'){
count++;
ans=(ans+count)%mod;
}
else{
count=0;
}
}
return ans%mod;
}
};
|
67657fe60516928a996627138246839854afe800 | eef2846207705a3f1717e69d452a5b2169e7ab51 | /SolvingQuadraticEquation/SolvingQuadraticEquation/main.cpp | 01035eb6abb3cde11020312b76caf8ee0b1e24f5 | [] | no_license | Karrtii/Cpp-Projects | e2205dfe67d6bfd9cb73024bd640cf33e2910efa | 98e0ad0fa4d4c6eb961463d5ef41aa5da407c3ef | refs/heads/main | 2023-04-25T06:40:38.357925 | 2021-05-06T09:57:26 | 2021-05-06T09:57:26 | 344,290,060 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,757 | cpp | main.cpp | #include <iostream>
#include<cmath>
using namespace std;
//Constants to represent type of solutions to an equation
const int NO_SOLUTION = 0;
const int ONE_REAL_SOLUTION = 1;
const int TWO_REAL_SOLUTIONS = 2;
const int ALL_REALS= 3;
const int NO_REAL_SOLUTION = 4;
int quadratic(double a, double b, double c, double& outX1, double& outX2);
int linear(double a, double b, double& outX);
//This program solves a quadratic equation
//Input from user: 3 real numbers, representing coefficients of a quadratic equation
//Output to user: The solutions of the equation, if there are any, or an appropriate message
int main()
{
double a, b, c, x1, x2;
cout << "Enter coefficients of quadratic equation:" << endl;
cin >> a >> b >> c;
cout << "The equation: " << a << "x^2 + " << b << "x + " << c << " = 0" << endl;
switch (quadratic(a, b, c, x1, x2))
{
case TWO_REAL_SOLUTIONS:
cout <<"Solutions: "<<x1<<" "<<x2<< endl;
break;
case ONE_REAL_SOLUTION:
cout << "One solution: "<<x1 << endl;
break;
case NO_REAL_SOLUTION:
cout << "No real solution" << endl;
break;
case NO_SOLUTION:
cout << "No solutions" << endl;
break;
case ALL_REALS:
cout << "All real numbers are solutions" << endl;
break;
default:
cout << "Error" << endl;
break;
}
return 0;
}
//quadratic: Solves the quadratic equation: ax^2+bx+c = 0
//Input: a, b, c - coefficients of equation
//Output: 1. Type of solution (return value)
// 2. outX1, outX2 - solutions to equation (output parameters)
//Assumptions: 1. If equation has one solution it will be returned in outX1
// 2. If equation has no real solutions the values in outX1 and outX2 are not defined
int quadratic(double a, double b, double c, double& outX1, double& outX2)
{
double delta, x1, x2;
if (a != 0.0)
{
delta = b * b - 4 * a * c;
if (delta > 0)
{
x1 = (-b + sqrt(delta)) / (2 * a);
x2 = (-b - sqrt(delta)) / (2 * a);
outX1 = x1;
outX2 = x2;
return TWO_REAL_SOLUTIONS;
}
else if (delta == 0)
{
x1 = -b / (2 * a);
outX1 = x1;
return ONE_REAL_SOLUTION;
}
else
{
return NO_REAL_SOLUTION;
}
}
else
{
return linear(b, c, outX1);
}
}
//linear: Solves the linear equation: ax+b = 0
//Input: a, b - coefficients of equation
//Output: 1. Type of solution (return value)
// 2. outX- solutions to equation (output parameters)
//Assumptions: 1. If equation has one solution it will be returned in outX1
// 2. If equation has no solutions the values in outX is not defined
int linear(double a, double b, double& outX)
{
double x;
if (a != 0)
{
x = -b / a;
outX = x;
return ONE_REAL_SOLUTION;
}
else if ((a == 0) && (b == 0))
{
x = 0;
outX = x;
return ALL_REALS;
}
else
{
return NO_SOLUTION;
}
} |
e852e03eae9cf2e6bc90c24531538016831cac81 | 86d738506fff0e3ef67e048aff2500594f6a76bd | /src/network/tests/acceptor_test.cc | 27a57ccd882c02735123d0f508783106ae01d444 | [
"BSD-3-Clause"
] | permissive | malolk/glue | 07ccaf4edfd14a8088d93e418421318353e3a655 | addb19993ce9964fdd0fd6b3054244b5796d8179 | refs/heads/master | 2020-09-20T09:53:13.622229 | 2017-03-19T02:46:42 | 2017-03-19T02:46:42 | 67,484,814 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,711 | cc | acceptor_test.cc | #include "network/acceptor.h"
#include "network/socket.h"
#include "network/socket_address.h"
#include <string>
void TestCase(const char* ip_str, uint16_t port, bool is_ipv6) {
using namespace network;
SocketAddress server_addr(ip_str, port, is_ipv6);
Acceptor acceptor(server_addr, 0); /* Make listen_fd_ blocking I/O in this test. */
LOG_INFO("Listen on %s ...", server_addr.ToString().c_str());
while (true) {
SocketAddress client_addr;
/* Default I/O is non-blocking, see Socket::Accept() for details. */
int cli_fd = acceptor.Accept();
Socket::EnableNonBlock(cli_fd, 0); /* Make it blocking for this test. */
if (cli_fd >= 0) {
Socket::GetSockName(cli_fd, client_addr);
LOG_INFO("Receive Connect from client: %s ", client_addr.ToString().c_str());
libbase::ByteBuffer buf;
while (true) {
ssize_t read_num = Socket::Receive(cli_fd, buf);
if (read_num == 0) {
Socket::Close(cli_fd);
LOG_INFO("peer: %s closed", client_addr.ToString().c_str());
break;
} else if (read_num > 0) {
LOG_INFO("Received data from peer: %s ", buf.ToString().c_str());
Socket::Send(cli_fd, buf);
} else {
Socket::Close(cli_fd);
LOG_ERROR("Error on receiving from peer : %s on sockfd=%d ",
client_addr.ToString().c_str(), cli_fd);
break;
}
buf.Reset();
}
}
}
}
void TestIpv4(const char* ip_str, uint16_t port) {
TestCase(ip_str, port, 0);
}
void TestIpv6(const char* ip_str, uint16_t port) {
TestCase(ip_str, port, 1);
}
int main() {
// TestIpv4("127.0.0.1", 8080);
TestIpv6("::1", 8080);
return 0;
}
|
de029ea6262fa2984af2bfac6e07e66c7753d0a3 | 41a76318e5b9eef2c69bbf922724f8b191d7d124 | /kokkos-kernels/src/graph/impl/KokkosGraph_Distance2Color_impl.hpp | 2fb646221418e90525a1a07df84fdc78bd73e509 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | zishengye/compadre | d0ff10deca224284e7e153371a738e053e66012a | 75b738a6a613c89e3c3232cbf7b2589a6b28d0a3 | refs/heads/master | 2021-06-25T06:16:38.327543 | 2021-04-02T02:08:48 | 2021-04-02T02:08:48 | 223,650,267 | 0 | 0 | NOASSERTION | 2019-11-23T20:41:03 | 2019-11-23T20:41:02 | null | UTF-8 | C++ | false | false | 80,488 | hpp | KokkosGraph_Distance2Color_impl.hpp | /*
//@HEADER
// ************************************************************************
//
// KokkosKernels 0.9: Linear Algebra and Graph Kernels
// Copyright 2017 Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact William McLendon (wcmclen@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef _KOKKOSGRAPH_DISTANCE2COLOR_IMPL_HPP
#define _KOKKOSGRAPH_DISTANCE2COLOR_IMPL_HPP
#include <iomanip>
#include <stdexcept>
#include <vector>
#include <Kokkos_Atomic.hpp>
#include <Kokkos_Core.hpp>
#include <Kokkos_MemoryTraits.hpp>
#include <Kokkos_UniqueToken.hpp>
#include <KokkosKernels_Uniform_Initialized_MemoryPool.hpp>
#include <KokkosKernels_HashmapAccumulator.hpp>
#include <KokkosSparse_spgemm.hpp>
#include <impl/Kokkos_Timer.hpp>
#include "KokkosGraph_Distance1Color.hpp"
#include "KokkosGraph_Distance1ColorHandle.hpp" // todo: remove this (SCAFFOLDING - WCMCLEN)
#include "KokkosGraph_Distance2ColorHandle.hpp"
#include "KokkosKernels_Handle.hpp"
namespace KokkosGraph {
namespace Impl {
#define VB_D2_COLORING_FORBIDDEN_SIZE 64
#define VBBIT_D2_COLORING_FORBIDDEN_SIZE 64
/*!
* \brief Distance-2 Graph Coloring class
*
* This class supports direct methods for distance-2 graph coloring.
*
*/
template<typename HandleType,
typename lno_row_view_t_,
typename lno_nnz_view_t_,
typename clno_row_view_t_,
typename clno_nnz_view_t_>
class GraphColorDistance2
{
// static_assert( std::is_same< HandleType, KokkosGraph::GraphColorDistance2Handle>::value, "Incorrect HandleType for this
// class.");
public:
using in_lno_row_view_type = lno_row_view_t_;
using in_lno_nnz_view_type = lno_nnz_view_t_;
using color_view_type = typename HandleType::color_view_type;
using color_type = typename HandleType::color_type;
using size_type = typename HandleType::size_type;
using nnz_lno_type = typename HandleType::nnz_lno_type;
using row_lno_host_view_type = typename in_lno_row_view_type::HostMirror;
using nnz_lno_host_view_type = typename in_lno_nnz_view_type::HostMirror;
using color_host_view_type = typename HandleType::color_host_view_type;
using my_exec_space = typename HandleType::HandleExecSpace;
using MyTempMemorySpace = typename HandleType::HandleTempMemorySpace;
using const_size_type = typename HandleType::const_size_type;
using row_lno_view_device_type = typename lno_row_view_t_::device_type;
using const_lno_row_view_type = typename lno_row_view_t_::const_type;
using const_lno_nnz_view_t = typename lno_nnz_view_t_::const_type;
using non_const_lno_nnz_view_type = typename lno_nnz_view_t_::non_const_type;
using const_clno_row_view_t = typename clno_row_view_t_::const_type;
using const_clno_nnz_view_t = typename clno_nnz_view_t_::const_type;
using non_const_clno_nnz_view_t = typename clno_nnz_view_t_::non_const_type;
using nnz_lno_temp_work_view_t = typename HandleType::nnz_lno_temp_work_view_type;
using single_dim_index_view_type = typename Kokkos::View<nnz_lno_type, row_lno_view_device_type>;
using range_policy_type = Kokkos::RangePolicy<my_exec_space>;
using team_policy_type = Kokkos::TeamPolicy<my_exec_space>;
using team_member_type = typename team_policy_type::member_type;
using non_const_1d_bool_view_t = Kokkos::View<bool*>;
using non_const_1d_size_type_view_type = typename HandleType::non_const_1d_size_type_view_type;
using bit_64_forbidden_type = long long int;
// For HashmapAccumulator (EXPERIMENTAL)
using pool_memory_space_t = typename KokkosKernels::Impl::UniformMemoryPool<MyTempMemorySpace, nnz_lno_type>;
protected:
nnz_lno_type nv; // num vertices
nnz_lno_type nr; // num_rows (# verts)
nnz_lno_type nc; // num cols
size_type ne; // # edges
const_lno_row_view_type xadj; // rowmap, transpose of rowmap
const_lno_nnz_view_t adj; // entries, transpose of entries (size = # edges)
const_clno_row_view_t t_xadj; // rowmap, transpose of rowmap
const_clno_nnz_view_t t_adj; // entries, transpose of entries
HandleType* gc_handle; // pointer to the graph coloring handle
private:
int _chunkSize; // the size of the minimum work unit assigned to threads. Changes the convergence on GPUs
int _max_num_iterations;
char _use_color_set; // The VB Algorithm Type: 0: VB, 1: VBCS, 2: VBBIT (1, 2 not implemented).
bool _ticToc; // if true print info in each step
bool _verbose; // if true, print verbose information
public:
/**
* \brief GraphColorDistance2 constructor.
* \param nv_: number of vertices in the graph
* \param ne_: number of edges in the graph
* \param row_map: the xadj array of the graph. Its size is nv_ +1
* \param entries: adjacency array of the graph. Its size is ne_
* \param handle: GraphColoringHandle object that holds the specification about the graph coloring,
* including parameters.
*/
GraphColorDistance2(nnz_lno_type nv_,
nnz_lno_type nc_,
size_type ne_,
const_lno_row_view_type row_map,
const_lno_nnz_view_t entries,
const_clno_row_view_t t_row_map,
const_clno_nnz_view_t t_entries,
HandleType* handle)
: nv(nv_)
, nr(nv_)
, nc(nc_)
, ne(ne_)
, xadj(row_map)
, adj(entries)
, t_xadj(t_row_map)
, t_adj(t_entries)
, gc_handle(handle)
, _chunkSize(handle->get_vb_chunk_size())
, _max_num_iterations(handle->get_max_number_of_iterations())
, _use_color_set(0)
, _ticToc(handle->get_verbose())
, _verbose(handle->get_verbose())
{
}
/**
* \brief GraphColor destructor.
*/
virtual ~GraphColorDistance2() {}
// -----------------------------------------------------------------
//
// GraphColorDistance2::execute()
//
// -----------------------------------------------------------------
/**
* \brief Computes the distance-2 graph coloring.
*/
virtual void compute_distance2_color()
{
color_view_type colors_out("Graph Colors", this->nv);
// If the selected pass is using edge filtering we should set the flag.
bool using_edge_filtering = false;
if(COLORING_D2_VB_BIT_EF == this->gc_handle->get_coloring_algo_type())
{
using_edge_filtering = true;
}
// Data:
// gc_handle = graph coloring handle
// nr = num_rows (scalar)
// nc = num_cols (scalar)
// xadj = row_map (view 1 dimension - [num_verts+1] - entries index into adj )
// adj = entries (view 1 dimension - [num_edges] - adjacency list )
if(this->_ticToc)
{
std::cout << "\tcolor_graph_d2 params:" << std::endl
<< "\t algorithm : " << (int)this->_use_color_set << std::endl
<< "\t ticToc : " << this->_ticToc << std::endl
<< "\t max_num_iterations : " << this->_max_num_iterations << std::endl
<< "\t chunkSize : " << this->_chunkSize << std::endl
<< "\t use_color_set : " << (int)this->_use_color_set << std::endl
<< "\t Edge Filtering Pass? : " << (int)using_edge_filtering << std::endl
<< "\tgraph information:" << std::endl
<< "\t nv : " << this->nv << std::endl
<< "\t ne : " << this->ne << std::endl;
/*
// For extra verbosity if debugging...
prettyPrint1DView(this->xadj, ">>> xadj ", 500);
prettyPrint1DView(this->adj, ">>> adj ", 500);
prettyPrint1DView(this->t_xadj, ">>> t_xadj ", 500);
prettyPrint1DView(this->t_adj, ">>> t_adj ", 500);
*/
}
#if 0
// (EXPERIMENTAL) Distance-2 Degree calculation
// Compute Distance-2 Degree of the vertices.
// -- Keeping this around in case we need to use it later on as an example.
size_t degree_d2_max=0;
size_t degree_d2_sum=0;
non_const_1d_size_type_view_type degree_d2 = non_const_1d_size_type_view_type("degree d2", this->nv);
this->compute_distance2_degree(degree_d2, degree_d2_max, degree_d2_sum);
if(true || _ticToc )
{
prettyPrint1DView(degree_d2, "Degree D2", 150);
std::cout << ">>> Max D2 Degree: " << degree_d2_max << std::endl;
std::cout << ">>> D2 Degree Sum: " << degree_d2_sum<< std::endl;
}
#endif
// conflictlist - store conflicts that can happen when we're coloring in parallel.
nnz_lno_temp_work_view_t current_vertexList =
nnz_lno_temp_work_view_t(Kokkos::ViewAllocateWithoutInitializing("vertexList"), this->nv);
// init conflictlist sequentially.
Kokkos::parallel_for("InitList", range_policy_type(0, this->nv), functorInitList<nnz_lno_temp_work_view_t>(current_vertexList));
// Next iteratons's conflictList
nnz_lno_temp_work_view_t next_iteration_recolorList;
// Size the next iteration conflictList
single_dim_index_view_type next_iteration_recolorListLength;
// Vertices to recolor. Will swap with vertexList
next_iteration_recolorList = nnz_lno_temp_work_view_t(Kokkos::ViewAllocateWithoutInitializing("recolorList"), this->nv);
next_iteration_recolorListLength = single_dim_index_view_type("recolorListLength");
nnz_lno_type numUncolored = this->nv;
nnz_lno_type numUncoloredPreviousIter = this->nv + 1;
nnz_lno_type current_vertexListLength = this->nv;
double time;
double total_time = 0.0;
Kokkos::Impl::Timer timer;
int iter = 0;
for(; (iter < _max_num_iterations) && (numUncolored > 0); iter++)
{
timer.reset();
// Save the # of uncolored from the previous iteration
numUncoloredPreviousIter = numUncolored;
// ------------------------------------------
// Do greedy color
// ------------------------------------------
if(using_edge_filtering)
{
// Temp copy of the adj array (mutable)
// - This is required for edge-filtering passes to avoid
// side effects since edge filtering modifies the adj array.
nnz_lno_temp_work_view_t adj_copy;
adj_copy = nnz_lno_temp_work_view_t(Kokkos::ViewAllocateWithoutInitializing("adj copy"), this->ne);
Kokkos::deep_copy(adj_copy, this->adj);
non_const_clno_nnz_view_t t_adj_copy;
t_adj_copy = non_const_clno_nnz_view_t(Kokkos::ViewAllocateWithoutInitializing("t_adj copy"), this->ne);
Kokkos::deep_copy(t_adj_copy, this->t_adj);
// Debugging
// prettyPrint1DView(t_adj_copy, "t_adj_copy", 100);
// prettyPrint1DView(t_adj, "t_adj", 100);
this->colorGreedyEF(
this->xadj, adj_copy, this->t_xadj, t_adj_copy, colors_out, current_vertexList, current_vertexListLength);
}
else
{
this->colorGreedy(
this->xadj, this->adj, this->t_xadj, this->t_adj, colors_out, current_vertexList, current_vertexListLength);
}
my_exec_space().fence();
if(this->_ticToc)
{
time = timer.seconds();
total_time += time;
std::cout << "\tIteration: " << iter << std::endl
<< "\t - Time speculative greedy phase : " << time << std::endl
<< "\t - Num Uncolored (greedy-color) : " << numUncolored << std::endl;
gc_handle->add_to_overall_coloring_time_phase1(time);
timer.reset();
}
// ------------------------------------------
// Find conflicts
// ------------------------------------------
bool swap_work_arrays = true; // NOTE: swap_work_arrays can go away in this example -- was only ever
// set false in the PPS code in the original D1 coloring...
// NOTE: not using colorset algorithm in this so we don't include colorset data
numUncolored = this->findConflicts(swap_work_arrays,
this->xadj,
this->adj,
this->t_xadj,
this->t_adj,
colors_out,
current_vertexList,
current_vertexListLength,
next_iteration_recolorList,
next_iteration_recolorListLength);
my_exec_space().fence();
if(_ticToc)
{
time = timer.seconds();
total_time += time;
std::cout << "\t - Time conflict detection : " << time << std::endl;
std::cout << "\t - Num Uncolored (conflicts) : " << numUncolored << std::endl;
gc_handle->add_to_overall_coloring_time_phase2(time);
timer.reset();
}
// Swap the work arrays (for conflictlist)
if(swap_work_arrays)
{
// Swap Work Arrays
if(iter + 1 < this->_max_num_iterations)
{
nnz_lno_temp_work_view_t temp = current_vertexList;
current_vertexList = next_iteration_recolorList;
next_iteration_recolorList = temp;
current_vertexListLength = numUncolored;
next_iteration_recolorListLength = single_dim_index_view_type("recolorListLength");
}
}
// Bail out if we didn't make any progress since we're probably stuck and it's better to just clean up in serial.
if(numUncolored == numUncoloredPreviousIter)
break;
} // end for iterations && numUncolored > 0...
// ------------------------------------------
// clean up in serial (resolveConflictsSerial)
// ------------------------------------------
if(numUncolored > 0)
{
this->resolveConflictsSerial(this->nv,
this->xadj,
this->adj,
this->t_xadj,
this->t_adj,
colors_out,
current_vertexList,
current_vertexListLength);
}
my_exec_space().fence();
if(_ticToc)
{
time = timer.seconds();
total_time += time;
std::cout << "\tTime serial conflict resolution : " << time << std::endl;
gc_handle->add_to_overall_coloring_time_phase3(time);
}
// Save the number of phases and vertex colors to the graph coloring handle
this->gc_handle->set_vertex_colors(colors_out);
this->gc_handle->set_num_phases((double)iter);
} // color_graph_d2 (end)
/**
* Validate Distance 2 Graph Coloring
*
* @param[in] validation_flags Is an array of 3 booleans to capture if the graph coloring is invalid, and if so what is
* invalid. validation_flags[0] : True IF the distance-2 coloring is invalid. validation_flags[1] : True IF the coloring is
* bad because vertices are left uncolored. validation_flags[2] : True IF the coloring is bad because at least one pair of
* vertices at distance=2 from each other has the same color. validation_flags[3] : True IF a vertex has a color that is
* greater than number of vertices in the graph. This may not be an INVALID coloring, but can indicate poor quality in
* coloring.
*
* @return boolean that is TRUE if the Distance-2 coloring is valid. False if otherwise.
*/
bool verify_coloring(const_lno_row_view_type xadj_,
const_lno_nnz_view_t adj_,
const_clno_row_view_t t_xadj_,
const_clno_nnz_view_t t_adj_,
color_view_type vertex_colors_,
bool validation_flags[])
{
bool output = true;
validation_flags[ 0 ] = false; // True if an invalid coloring.
validation_flags[ 1 ] = false; // True if uncolored vertices exist.
validation_flags[ 2 ] = false; // True if an invalid color exists.
nnz_lno_type chunkSize_ = this->_chunkSize;
if(nv < 100 * chunkSize_)
{
chunkSize_ = 1;
}
const size_t num_chunks = this->nv / chunkSize_ + 1;
non_const_1d_bool_view_t d_flags("flags", 4);
// Create host mirror view.
non_const_1d_bool_view_t::HostMirror h_flags = Kokkos::create_mirror_view(d_flags);
// Initialize flags on host
for(int i = 0; i < 4; i++) h_flags(i) = false;
// Deep copy initialized flags to device
Kokkos::deep_copy(d_flags, h_flags);
functorVerifyDistance2Coloring vr(this->nv, xadj_, adj_, t_xadj_, t_adj_, vertex_colors_, d_flags, chunkSize_);
Kokkos::parallel_for("ValidateD2Coloring", range_policy_type(0, num_chunks), vr);
// Deep copy flags back to host memory
Kokkos::deep_copy(h_flags, d_flags);
validation_flags[ 0 ] = h_flags[ 0 ];
validation_flags[ 1 ] = h_flags[ 1 ];
validation_flags[ 2 ] = h_flags[ 2 ];
validation_flags[ 3 ] = h_flags[ 3 ];
output = !h_flags[ 0 ];
return output;
} // verify_coloring (end)
/**
* Generate a histogram of the distance-2 colors
*
* @param[out] histogram A Kokkos::View that will contain the histogram.
* Must be of size num_colors+1
*
* @return None
*/
void compute_color_histogram(nnz_lno_temp_work_view_t& histogram)
{
KokkosKernels::Impl::kk_get_histogram<typename HandleType::color_view_type, nnz_lno_temp_work_view_t, my_exec_space>
(this->nv, this->gc_handle->get_vertex_colors(), histogram);
my_exec_space().fence();
}
/**
* Print out the histogram of colors in CSV format.
*/
void print_color_histogram_csv()
{
nnz_lno_type num_colors = this->gc_handle->get_num_colors();
nnz_lno_temp_work_view_t histogram("histogram", num_colors + 1);
this->compute_color_histogram(histogram);
auto h_histogram = Kokkos::create_mirror_view(histogram);
Kokkos::deep_copy(h_histogram, histogram);
size_t i = 0;
for(i = 1; i < h_histogram.extent(0) - 1; i++)
{
std::cout << h_histogram(i) << ",";
}
std::cout << h_histogram(i);
}
/**
* Print out the histogram of colors in a more human friendly format
* This will not print out all the colors if there are many.
*/
void print_color_histogram()
{
nnz_lno_type num_colors = this->gc_handle->get_num_colors();
nnz_lno_temp_work_view_t histogram("histogram", num_colors + 1);
this->compute_color_histogram(histogram);
auto histogram_slice = Kokkos::subview(histogram, std::make_pair((size_t)1, histogram.extent(0)));
std::cout << "Distance-2 Color Histogram (1..N): " << std::endl;
KokkosKernels::Impl::kk_print_1Dview(histogram_slice);
std::cout << std::endl;
}
/**
* Calculate the distance-2 degree of all the vertices in the graph.
*
* @param[out] degree_d2 A mutable view of size |V|
* @param[out] degree_d2_max Saves the max distance-2 degree value in.
*
* @note This is EXPERIMENTAL development code.
* @todo Uses HashMapAccumulator and still needs a lot of tweaking to make performant.
*/
void compute_distance2_degree(non_const_1d_size_type_view_type& degree_d2, size_t& degree_d2_max)
{
// Vertex group chunking
nnz_lno_type v_chunk_size = this->_chunkSize;
nnz_lno_type v_num_chunks = this->nv / v_chunk_size + 1;
std::cout << ">>> this->nv = " << this->nv << std::endl;
std::cout << ">>> v_chunk_size = " << v_chunk_size << std::endl;
std::cout << ">>> v_num_chunks = " << v_num_chunks << std::endl;
// Get the maximum distance-1 degree
nnz_lno_type max_d1_degree = this->compute_max_distance1_degree();
// Round up hash_size to next power of two
nnz_lno_type hash_size = 1;
while(hash_size < max_d1_degree * max_d1_degree) { hash_size *= 2; }
// Max Nonzeros in D2 context can be max_degree(G)^2
nnz_lno_type max_nonzeros = max_d1_degree * max_d1_degree;
// Determine how much we'd need for UniformMemoryPool
nnz_lno_type mem_chunk_size = hash_size; // For hash indices
mem_chunk_size += hash_size; // For hash begins
mem_chunk_size += max_nonzeros; // For hash nexts
mem_chunk_size += max_nonzeros; // For hash keys
// nnz_lno_type mem_chunk_size += max_nonzeros; // For hash_values
/*
std::cout << "num_verts = " << this->nv << std::endl;
std::cout << "v_chunk_size = " << v_chunk_size << std::endl;
std::cout << "v_num_chunks = " << v_num_chunks << std::endl;
std::cout << "max_d1_degree = " << max_d1_degree << std::endl;
std::cout << "mem_chunk_size = " << mem_chunk_size << std::endl;
std::cout << "hash_size = " << hash_size << std::endl;
*/
// HashmapAccumulator requires a memory Pool
KokkosKernels::Impl::PoolType my_pool_type = KokkosKernels::Impl::OneThread2OneChunk;
pool_memory_space_t m_space(v_num_chunks, mem_chunk_size, -1, my_pool_type);
/*
std::cout << std::endl << "Memory Pool:" << std::endl;
m_space.print_memory_pool(true);
*/
functorCalculateD2Degree calculateD2Degree(
this->nv, this->xadj, this->adj, this->t_xadj, this->t_adj, v_chunk_size, degree_d2, m_space, hash_size, max_nonzeros);
Kokkos::parallel_for("Compute Degree D2", range_policy_type(0, v_num_chunks), calculateD2Degree);
// Compute maximum d2 degree
size_t _degree_d2_max = 0;
Kokkos::parallel_reduce(
"Max D2 Degree",
this->nv,
KOKKOS_LAMBDA(const size_t& i, size_t & lmax) { lmax = degree_d2(i) > lmax ? degree_d2(i) : lmax; },
Kokkos::Max<size_t>(_degree_d2_max));
degree_d2_max = _degree_d2_max;
// Tell the handle that coloring has been called.
this->gc_handle->set_coloring_called();
}
private:
// -----------------------------------------------------------------
//
// GraphColorDistance2::colorGreedy()
//
// -----------------------------------------------------------------
void colorGreedy(const_lno_row_view_type xadj_,
const_lno_nnz_view_t adj_,
const_clno_row_view_t t_xadj_,
const_clno_nnz_view_t t_adj_,
color_view_type vertex_colors_,
nnz_lno_temp_work_view_t current_vertexList_,
nnz_lno_type current_vertexListLength_)
{
nnz_lno_type chunkSize_ = this->_chunkSize;
if(current_vertexListLength_ < 100 * chunkSize_)
{
chunkSize_ = 1;
}
// Pick the right coloring algorithm to use based on which algorithm we're using
switch(this->gc_handle->get_coloring_algo_type())
{
// Single level parallelism on chunks
// 1. [P] loop over vertices
// 2. [S] loop over color offset blocks
// 3. [S] loop over vertex neighbors
// 4. [S] loop over vertex neighbors of neighbors
case COLORING_D2:
case COLORING_D2_VB:
{
functorGreedyColorVB gc(
this->nv, xadj_, adj_, t_xadj_, t_adj_, vertex_colors_, current_vertexList_, current_vertexListLength_);
Kokkos::parallel_for("LoopOverChunks", range_policy_type(0, this->nv), gc);
}
break;
// One level Perallelism, BIT Array for coloring
// 1. [P] loop over vertices
// 2. [S] loop over color offset blocks
// 3. [S] loop over vertex neighbors
// 4. [S] loop over vertex neighbors of neighbors
case COLORING_D2_VB_BIT:
{
functorGreedyColorVB_BIT gc(
this->nv, xadj_, adj_, t_xadj_, t_adj_, vertex_colors_, current_vertexList_, current_vertexListLength_);
Kokkos::parallel_for("LoopOverChunks", range_policy_type(0, this->nv), gc);
}
break;
default:
throw std::invalid_argument("Unknown Distance-2 Algorithm Type or invalid for non Edge Filtering mode.");
}
} // colorGreedy (end)
// -----------------------------------------------------------------
//
// GraphColorDistance2::colorGreedyEF()
//
// -----------------------------------------------------------------
void colorGreedyEF(const_lno_row_view_type xadj_,
nnz_lno_temp_work_view_t adj_copy_,
const_clno_row_view_t t_xadj_,
non_const_clno_nnz_view_t t_adj_copy_,
color_view_type vertex_colors_,
nnz_lno_temp_work_view_t current_vertexList_,
nnz_lno_type current_vertexListLength_)
{
// Pick the right coloring algorithm to use based on which algorithm we're using
switch(this->gc_handle->get_coloring_algo_type())
{
// One level Perallelism, BIT Array for coloring + edge filtering
// 1. [P] loop over vertices
// 2. [S] loop over color offset blocks
// 3. [S] loop over vertex neighbors
// 4. [S] loop over vertex neighbors of neighbors
case COLORING_D2_VB_BIT_EF:
{
functorGreedyColorVB_BIT_EF gc(this->nv,
xadj_,
adj_copy_,
t_xadj_,
t_adj_copy_,
vertex_colors_,
current_vertexList_,
current_vertexListLength_);
Kokkos::parallel_for("LoopOverChunks", range_policy_type(0, this->nv), gc);
// prettyPrint1DView(vertex_colors_, "COLORS_GC_VB_BIT",500);
}
break;
default:
throw std::invalid_argument("Unknown Distance-2 Algorithm Type or algorithm does not use Edge Filtering.");
}
} // colorGreedyEF (end)
// -----------------------------------------------------------------
//
// GraphColorDistance2::findConflicts()
//
// -----------------------------------------------------------------
template<typename adj_view_t>
nnz_lno_type findConflicts(bool& swap_work_arrays,
const_lno_row_view_type xadj_,
adj_view_t adj_,
const_clno_row_view_t t_xadj_,
const_clno_nnz_view_t t_adj_,
color_view_type vertex_colors_,
nnz_lno_temp_work_view_t current_vertexList_,
nnz_lno_type current_vertexListLength_,
nnz_lno_temp_work_view_t next_iteration_recolorList_,
single_dim_index_view_type next_iteration_recolorListLength_)
{
swap_work_arrays = true;
nnz_lno_type output_numUncolored = 0;
if(0 == this->_use_color_set)
{
functorFindConflicts_Atomic<adj_view_t> conf(this->nv,
xadj_,
adj_,
t_xadj_,
t_adj_,
vertex_colors_,
current_vertexList_,
next_iteration_recolorList_,
next_iteration_recolorListLength_);
Kokkos::parallel_reduce("FindConflicts", range_policy_type(0, current_vertexListLength_), conf, output_numUncolored);
}
return output_numUncolored;
} // findConflicts (end)
// -----------------------------------------------------------------
//
// GraphColorDistance2::resolveConflictsSerial()
//
// -----------------------------------------------------------------
template<typename adj_view_t>
void resolveConflictsSerial(nnz_lno_type _nv,
const_lno_row_view_type xadj_,
adj_view_t adj_,
const_clno_row_view_t t_xadj_,
const_clno_nnz_view_t t_adj_,
color_view_type vertex_colors_,
nnz_lno_temp_work_view_t current_vertexList_,
size_type current_vertexListLength_)
{
color_type* forbidden = new color_type[ _nv ];
nnz_lno_type vid = 0;
nnz_lno_type end = _nv;
typename nnz_lno_temp_work_view_t::HostMirror h_recolor_list;
end = current_vertexListLength_;
h_recolor_list = Kokkos::create_mirror_view(current_vertexList_);
Kokkos::deep_copy(h_recolor_list, current_vertexList_);
auto h_colors = Kokkos::create_mirror_view(vertex_colors_);
auto h_idx = Kokkos::create_mirror_view(xadj_);
auto h_adj = Kokkos::create_mirror_view(adj_);
auto h_t_idx = Kokkos::create_mirror_view(t_xadj_);
auto h_t_adj = Kokkos::create_mirror_view(t_adj_);
Kokkos::deep_copy(h_colors, vertex_colors_);
Kokkos::deep_copy(h_idx, xadj_);
Kokkos::deep_copy(h_adj, adj_);
Kokkos::deep_copy(h_t_idx, t_xadj_);
Kokkos::deep_copy(h_t_adj, t_adj_);
for(nnz_lno_type k = 0; k < end; k++)
{
vid = h_recolor_list(k);
if(h_colors(vid) > 0)
continue;
// loop over distance-1 neighbors of vid
for(size_type vid_d1_adj = h_idx(vid); vid_d1_adj < h_idx(vid + 1); vid_d1_adj++)
{
size_type vid_d1 = h_adj(vid_d1_adj);
// loop over neighbors of vid_d1 (distance-2 from vid)
for(size_type vid_d2_adj = h_t_idx(vid_d1); vid_d2_adj < h_t_idx(vid_d1 + 1); vid_d2_adj++)
{
nnz_lno_type vid_d2 = h_t_adj(vid_d2_adj);
// skip over loops vid -- x -- vid
if(vid_d2 == vid)
continue;
forbidden[ h_colors(vid_d2) ] = vid;
}
}
// color vertex vid with smallest available color
int c = 1;
while(forbidden[ c ] == vid) c++;
h_colors(vid) = c;
}
Kokkos::deep_copy(vertex_colors_, h_colors);
delete[] forbidden;
} // resolveConflictsSerial (end)
// ------------------------------------------------------
// Functions: Helpers
// ------------------------------------------------------
public:
/**
* Compute the maximum distance-1 degree.
*
* @return Maximum distance1 degree in the graph
*/
nnz_lno_type compute_max_distance1_degree() const
{
nnz_lno_type max_degree = 0;
Kokkos::parallel_reduce("Max D1 Degree",
this->nv,
KOKKOS_LAMBDA(const nnz_lno_type& vid, nnz_lno_type & lmax) {
const nnz_lno_type degree = this->xadj(vid + 1) - this->xadj(vid);
lmax = degree > lmax ? degree : lmax;
},
Kokkos::Max<nnz_lno_type>(max_degree));
return max_degree;
}
// pretty-print a 1D View with label
template<typename kokkos_view_t>
void prettyPrint1DView(kokkos_view_t& view, const char* label, const size_t max_entries = 500) const
{
int max_per_line = 20;
int line_count = 1;
std::cout << label << " = [ \n\t";
for(size_t i = 0; i < view.extent(0); i++)
{
std::cout << std::setw(5) << view(i) << " ";
if(line_count >= max_per_line)
{
std::cout << std::endl << "\t";
line_count = 0;
}
line_count++;
if(i >= max_entries - 1)
{
std::cout << "<snip>";
break;
}
}
if(line_count > 1)
std::cout << std::endl;
std::cout << "\t ]" << std::endl;
} // prettyPrint1DView (end)
// ------------------------------------------------------
// Functors: Distance-2 Graph Coloring
// ------------------------------------------------------
/**
* Functor to init a list sequentialy, that is list[i] = i
*/
template<typename view_type>
struct functorInitList
{
view_type _vertexList;
functorInitList(view_type vertexList) : _vertexList(vertexList) {}
KOKKOS_INLINE_FUNCTION
void operator()(const nnz_lno_type i) const
{
// Natural order
_vertexList(i) = i;
}
}; // struct functorInitList (end)
/**
* Functor for VB algorithm speculative coloring without edge filtering.
* Single level parallelism
*/
struct functorGreedyColorVB
{
nnz_lno_type nv; // num vertices
const_lno_row_view_type _idx; // vertex degree list
const_lno_nnz_view_t _adj; // vertex adjacency list
const_clno_row_view_t _t_idx; // transpose vertex degree list
const_clno_nnz_view_t _t_adj; // transpose vertex adjacency list
color_view_type _colors; // vertex colors
nnz_lno_temp_work_view_t _vertexList; //
nnz_lno_type _vertexListLength; //
nnz_lno_type _chunkSize; //
functorGreedyColorVB(nnz_lno_type nv_,
const_lno_row_view_type xadj_,
const_lno_nnz_view_t adj_,
const_clno_row_view_t t_xadj_,
const_clno_nnz_view_t t_adj_,
color_view_type colors,
nnz_lno_temp_work_view_t vertexList,
nnz_lno_type vertexListLength)
: nv(nv_)
, _idx(xadj_)
, _adj(adj_)
, _t_idx(t_xadj_)
, _t_adj(t_adj_)
, _colors(colors)
, _vertexList(vertexList)
, _vertexListLength(vertexListLength)
{
}
// Color vertex i with smallest available color.
//
// Each thread colors a chunk of vertices to prevent all vertices getting the same color.
//
// This version uses a bool array of size FORBIDDEN_SIZE.
//
// param: ii = vertex id
//
KOKKOS_INLINE_FUNCTION
void operator()(const nnz_lno_type vid) const
{
// If vertex is not already colored...
if(_colors(vid) <= 0)
{
bool foundColor = false; // Have we found a valid color?
const size_type vid_adj_begin = _idx(vid);
const size_type vid_adj_end = _idx(vid + 1);
// Use forbidden array to find available color.
// - should be small enough to fit into fast memory (use Kokkos memoryspace?)
bool forbidden[ VB_D2_COLORING_FORBIDDEN_SIZE ]; // Forbidden Colors
// Do multiple passes if the forbidden array is too small.
// * The Distance-1 code used the knowledge of the degree of the vertex to cap the number of iterations
// but in distance-2 we'd need the total vertices at distance-2 which we don't easily have aprioi.
// This could be as big as all the vertices in the graph if diameter(G)=2...
for(color_type offset = 0; !foundColor && offset < nv; offset += VB_D2_COLORING_FORBIDDEN_SIZE)
{
// initialize
for(int i = 0; i < VB_D2_COLORING_FORBIDDEN_SIZE; i++) { forbidden[ i ] = false; }
// Colors start at 1. 0 is special in that it means a vertex is uncolored.
// For the range 0..63 we mark forbidden[0] as true to take color 0 out of
// consideration.
if(0 == offset)
{
forbidden[ 0 ] = true;
}
// Check neighbors, fill forbidden array.
for(size_type vid_adj = vid_adj_begin; vid_adj < vid_adj_end; vid_adj++)
{
const nnz_lno_type vid_d1 = _adj(vid_adj);
const size_type vid_d1_adj_begin = _t_idx(vid_d1);
const size_type vid_d1_adj_end = _t_idx(vid_d1 + 1);
for(size_type vid_d1_adj = vid_d1_adj_begin; vid_d1_adj < vid_d1_adj_end; vid_d1_adj++)
{
const nnz_lno_type vid_d2 = _t_adj(vid_d1_adj);
// Skip distance-2-self-loops
if(vid_d2 != vid && vid_d2 < nv)
{
const color_type c = _colors(vid_d2);
if((c >= offset) && (c - offset < VB_D2_COLORING_FORBIDDEN_SIZE))
{
forbidden[ c - offset ] = true;
}
}
} // for vid_d1_adj...
} // for vid_adj...
// color vertex i with smallest available color (firstFit)
for(int c = 0; c < VB_D2_COLORING_FORBIDDEN_SIZE; c++)
{
if(!forbidden[ c ])
{
_colors(vid) = offset + c;
foundColor = true;
break;
}
} // for c...
} // for !foundColor...
} // if _colors(vid) <= 0...
} // operator() (end)
}; // struct functorGreedyColorVB (end)
/**
* Functor for VB_BIT algorithm coloring without edge filtering.
* Single level parallelism
*/
struct functorGreedyColorVB_BIT
{
nnz_lno_type nv; // num vertices
const_lno_row_view_type _idx; // vertex degree list
const_lno_nnz_view_t _adj; // vertex adjacency list
const_clno_row_view_t _t_idx; // transpose vertex degree list
const_clno_nnz_view_t _t_adj; // transpose vertex adjacency list
color_view_type _colors; // vertex colors
nnz_lno_temp_work_view_t _vertexList; //
nnz_lno_type _vertexListLength; //
functorGreedyColorVB_BIT(nnz_lno_type nv_,
const_lno_row_view_type xadj_,
const_lno_nnz_view_t adj_,
const_clno_row_view_t t_xadj_,
const_clno_nnz_view_t t_adj_,
color_view_type colors,
nnz_lno_temp_work_view_t vertexList,
nnz_lno_type vertexListLength)
: nv(nv_)
, _idx(xadj_)
, _adj(adj_)
, _t_idx(t_xadj_)
, _t_adj(t_adj_)
, _colors(colors)
, _vertexList(vertexList)
, _vertexListLength(vertexListLength)
{
}
// Color vertex i with smallest available color.
//
// Each thread colors a chunk of vertices to prevent all vertices getting the same color.
//
// This version uses a bool array of size FORBIDDEN_SIZE.
//
// param: ii = vertex id
//
KOKKOS_INLINE_FUNCTION
void operator()(const nnz_lno_type vid) const
{
// If vertex is not colored yet...
if(_colors(vid) == 0)
{
const size_type vid_adj_begin = _idx(vid);
const size_type vid_adj_end = _idx(vid + 1);
bool foundColor = false;
for(color_type offset = 0; !foundColor && offset <= (nv + VBBIT_D2_COLORING_FORBIDDEN_SIZE);
offset += VBBIT_D2_COLORING_FORBIDDEN_SIZE)
{
// Forbidden colors
// - single long int for forbidden colors
bit_64_forbidden_type forbidden = 0;
// If all available colors for this range are unavailable we can break out of the nested loops
bool break_out = false;
// Loop over distance-1 neighbors of vid
for(size_type vid_adj = vid_adj_begin; !break_out && vid_adj < vid_adj_end; ++vid_adj)
{
const nnz_lno_type vid_d1 = _adj(vid_adj);
const size_type vid_d1_adj_begin = _t_idx(vid_d1);
const size_type vid_d1_adj_end = _t_idx(vid_d1 + 1);
// Loop over distance-2 neighbors of vid
for(size_type vid_d1_adj = vid_d1_adj_begin; !break_out && vid_d1_adj < vid_d1_adj_end; ++vid_d1_adj)
{
const nnz_lno_type vid_d2 = _t_adj(vid_d1_adj);
// Ignore Distance-2 Self Loops
if(vid_d2 != vid && vid_d2 < nv)
{
const color_type color = _colors(vid_d2);
const color_type color_offset = color - offset;
// if color is within the current range, or if its color is in a previously traversed
// range
if(color && color_offset <= VBBIT_D2_COLORING_FORBIDDEN_SIZE)
{
// if it is in the current range, then add the color to the banned colors
if(color > offset)
{
// convert color to bit representation
bit_64_forbidden_type ban_color_bit = 1;
ban_color_bit = ban_color_bit << (color_offset - 1);
// add it to forbidden colors
forbidden = forbidden | ban_color_bit;
// if there are no available colors in this range then exit early,
// no need to traverse the rest.
if(0 == ~forbidden)
{
break_out = true;
}
} // if color > offset ...
} // if color && color_offset ...
} // if vid_d2 ...
} // for vid_d1_adj ...
} // for vid_adj ...
forbidden = ~(forbidden);
// check if an available color exists.
if(forbidden)
{
color_type val = 1;
// if there is an available color, choose the first color, using 2s complement.
bit_64_forbidden_type new_color = forbidden & (-forbidden);
// convert it back to decimal color.
while((new_color & 1) == 0)
{
++val;
new_color = new_color >> 1;
}
_colors(vid) = val + offset;
foundColor = true;
break;
}
} // for !foundColor
} // if _colors(vid)==0
} // operator() (end)
}; // struct functorGreedyColorVB_BIT (end)
/**
* Functor for VB_BIT_EF algorithm coloring without edge filtering.
* Single level parallelism
*/
struct functorGreedyColorVB_BIT_EF
{
nnz_lno_type _nv; // num vertices
const_lno_row_view_type _idx; // vertex degree list
nnz_lno_temp_work_view_t _adj; // vertex adjacency list (mutable)
const_clno_row_view_t _t_idx; // transpose vertex degree list
non_const_clno_nnz_view_t _t_adj; // transpose vertex adjacency list (mutable)
color_view_type _colors; // vertex colors
nnz_lno_temp_work_view_t _vertexList; //
nnz_lno_type _vertexListLength; //
functorGreedyColorVB_BIT_EF(nnz_lno_type nv_,
const_lno_row_view_type xadj_,
nnz_lno_temp_work_view_t adj_,
const_clno_row_view_t t_xadj_,
non_const_clno_nnz_view_t t_adj_,
color_view_type colors,
nnz_lno_temp_work_view_t vertexList,
nnz_lno_type vertexListLength)
: _nv(nv_)
, _idx(xadj_)
, _adj(adj_)
, _t_idx(t_xadj_)
, _t_adj(t_adj_)
, _colors(colors)
, _vertexList(vertexList)
, _vertexListLength(vertexListLength)
{
}
// Color vertex i with smallest available color.
//
// Each thread colors a chunk of vertices to prevent all vertices getting the same color.
//
// This version uses a bool array of size FORBIDDEN_SIZE.
//
// param: ii = vertex id
//
KOKKOS_INLINE_FUNCTION
void operator()(const nnz_lno_type vid) const
{
// If vertex is not colored yet..
if(_colors(vid) == 0)
{
size_type vid_adj_begin = _idx(vid);
size_type vid_adj_end = _idx(vid + 1);
bool foundColor = false;
for(color_type offset = 0; !foundColor && offset <= (_nv + VBBIT_D2_COLORING_FORBIDDEN_SIZE);
offset += VBBIT_D2_COLORING_FORBIDDEN_SIZE)
{
// Forbidden colors
// - single long int for forbidden colors
bit_64_forbidden_type forbidden = 0;
// If all available colors for this range are unavailable we can break out of the nested loops
bool offset_colors_full = false;
// Loop over distance-1 neighbors of vid
for(size_type vid_adj = vid_adj_begin; !offset_colors_full && vid_adj < vid_adj_end; ++vid_adj)
{
const nnz_lno_type vid_d1 = _adj(vid_adj);
size_type vid_d1_adj_begin = _t_idx(vid_d1);
const size_type vid_d1_adj_end = _t_idx(vid_d1 + 1);
const size_type degree_vid_d1 = vid_d1_adj_end - vid_d1_adj_begin;
size_type num_vid_d2_colored_in_range = 0;
// Store the maximum color value found in the vertices adjacent to vid_d1
color_type max_color_adj_to_d1 = 0;
// Loop over distance-2 neighbors of vid
for(size_type vid_d1_adj = vid_d1_adj_begin; !offset_colors_full && vid_d1_adj < vid_d1_adj_end;
++vid_d1_adj)
{
const nnz_lno_type vid_d2 = _t_adj(vid_d1_adj);
// Ignore Distance-2 Self Loops
if(vid_d2 != vid && vid_d2 < _nv)
{
color_type color = _colors(vid_d2);
color_type color_offset =
color - offset; // color_offset < 0 means color is from a previous offset.
// Update maximum color adjacent to vid_d1 found so far.
max_color_adj_to_d1 = color > max_color_adj_to_d1 ? color : max_color_adj_to_d1;
// if color is within the current range, or if its color is in a previously traversed
// range
if(color && color_offset <= VBBIT_D2_COLORING_FORBIDDEN_SIZE)
{
num_vid_d2_colored_in_range++;
// if it is in the current range, then add the color to the banned colors
if(color > offset)
{
// convert color to bit representation
bit_64_forbidden_type ban_color_bit = 1;
ban_color_bit = ban_color_bit << (color_offset - 1);
// add it to forbidden colors
forbidden = forbidden | ban_color_bit;
// if there are no available colors in this range then exit early,
// no need to traverse the rest b/c they contribute no new information
// at this offset.
if(0 == ~forbidden)
{
offset_colors_full = true;
// Note: with edge-filtering, this can short-circuit the loop over all
// neighbors of VID and will reduce the number of filtered edges.
}
} // if color > offset
} // if color && color_offset
} // if vid_d2 != vid ...
else
{
// If there's a self-loop then we should increment our 'colored in range' so we don't
// block filtering since we know there must be a (v2,v1) edge
num_vid_d2_colored_in_range++;
}
} // for vid_d1_adj ...
// Edge filtering on the neighbors of vid. We can only do this if ALL neighbors of vid_d1
// have been visited and if all were colored in current offset range or lower.
if(degree_vid_d1 == num_vid_d2_colored_in_range)
{
if(vid_adj_begin > vid_adj)
{
_adj(vid_adj) = _adj(vid_adj_begin);
_adj(vid_adj_begin) = vid_d1;
}
vid_adj_begin++;
}
} // for vid_adj
forbidden = ~(forbidden);
// check if an available color exists.
if(forbidden)
{
// if there is an available color, choose the first color, using 2s complement.
bit_64_forbidden_type new_color = forbidden & (-forbidden);
color_type val = 1;
// convert it back to decimal color.
while((new_color & 1) == 0)
{
++val;
new_color = new_color >> 1;
}
_colors(vid) = val + offset;
foundColor = true;
break;
}
} // for offset=0...
} // if _colors(vid)==0
} // operator() (end)
}; // struct functorGreedyColorVB_BIT_EF (end)
template<typename adj_view_t>
struct functorFindConflicts_Atomic
{
nnz_lno_type nv; // num verts
const_lno_row_view_type _idx;
adj_view_t _adj;
const_clno_row_view_t _t_idx;
const_clno_nnz_view_t _t_adj;
color_view_type _colors;
nnz_lno_temp_work_view_t _vertexList;
nnz_lno_temp_work_view_t _recolorList;
single_dim_index_view_type _recolorListLength;
functorFindConflicts_Atomic(nnz_lno_type nv_,
const_lno_row_view_type xadj_,
adj_view_t adj_,
const_clno_row_view_t t_xadj_,
const_clno_nnz_view_t t_adj_,
color_view_type colors,
nnz_lno_temp_work_view_t vertexList,
nnz_lno_temp_work_view_t recolorList,
single_dim_index_view_type recolorListLength)
: nv(nv_)
, _idx(xadj_)
, _adj(adj_)
, _t_idx(t_xadj_)
, _t_adj(t_adj_)
, _colors(colors)
, _vertexList(vertexList)
, _recolorList(recolorList)
, _recolorListLength(recolorListLength)
{
}
KOKKOS_INLINE_FUNCTION
void operator()(const nnz_lno_type vid_, nnz_lno_type& numConflicts) const
{
using atomic_incr_type = typename std::remove_reference<decltype(_recolorListLength())>::type;
const nnz_lno_type vid = _vertexList(vid_);
const color_type my_color = _colors(vid);
size_type vid_d1_adj = _idx(vid);
const size_type vid_d1_adj_end = _idx(vid + 1);
bool break_out = false;
for(; !break_out && vid_d1_adj < vid_d1_adj_end; vid_d1_adj++)
{
nnz_lno_type vid_d1 = _adj(vid_d1_adj);
for(size_type vid_d2_adj = _t_idx(vid_d1); !break_out && vid_d2_adj < _t_idx(vid_d1 + 1); vid_d2_adj++)
{
const nnz_lno_type vid_d2 = _t_adj(vid_d2_adj);
if(vid != vid_d2 && vid_d2 < nv)
{
if(_colors(vid_d2) == my_color)
{
_colors(vid) = 0; // uncolor vertex
// Atomically add vertex to recolorList
const nnz_lno_type k = Kokkos::atomic_fetch_add(&_recolorListLength(), atomic_incr_type(1));
_recolorList(k) = vid;
numConflicts += 1;
break_out = true;
// break; // Can exit if vertex gets marked as a conflict.
}
} // if vid != vid_d2 ...
} // for vid_d2_adj ...
} // for vid_d1_adj ...
} // operator() (end)
}; // struct functorFindConflicts_Atomic (end)
/**
* functorVerifyDistance2Coloring
* - Validate correctness of the distance-2 coloring
*/
struct functorVerifyDistance2Coloring
{
nnz_lno_type nv; // num vertices
const_lno_row_view_type _idx; // vertex degree list
const_lno_nnz_view_t _adj; // vertex adjacency list
const_clno_row_view_t _t_idx; // transpose vertex degree list
const_clno_nnz_view_t _t_adj; // transpose vertex adjacency list
color_view_type _colors; // vertex colors
non_const_1d_bool_view_t _flags; // [0]: valid or not? [1]=true means something is uncolored. [2]=true means
// something has distance-2 neighbor of same color
nnz_lno_type _chunkSize; //
functorVerifyDistance2Coloring(nnz_lno_type nv_,
const_lno_row_view_type xadj_,
const_lno_nnz_view_t adj_,
const_clno_row_view_t t_xadj_,
const_clno_nnz_view_t t_adj_,
color_view_type colors,
non_const_1d_bool_view_t flags,
nnz_lno_type chunkSize)
: nv(nv_)
, _idx(xadj_)
, _adj(adj_)
, _t_idx(t_xadj_)
, _t_adj(t_adj_)
, _colors(colors)
, _flags(flags)
, _chunkSize(chunkSize)
{
}
KOKKOS_INLINE_FUNCTION
void operator()(const nnz_lno_type chunk_id) const
{
bool has_uncolored_vertex = false;
bool has_invalid_color = false;
bool has_color_bigger_than_num_verts = false;
// Loop over vertices in chunks
for(nnz_lno_type chunk_idx = 0; chunk_idx < _chunkSize; chunk_idx++)
{
bool break_out = false;
nnz_lno_type vid = chunk_id * _chunkSize + chunk_idx;
if(vid < nv)
{
const color_type color_vid = _colors(vid);
const size_type vid_d1_adj_begin = _idx(vid);
const size_type vid_d1_adj_end = _idx(vid + 1);
if(color_vid == 0)
{
has_uncolored_vertex = true;
}
if(color_vid > nv)
{
has_color_bigger_than_num_verts = true;
}
// Loop over neighbors of vid (distance-1 from vid)
for(size_type vid_d1_adj = vid_d1_adj_begin; !break_out && vid_d1_adj < vid_d1_adj_end; ++vid_d1_adj)
{
const nnz_lno_type vid_d1 = _adj(vid_d1_adj);
const size_type vid_d2_adj_begin = _t_idx(vid_d1);
const size_type vid_d2_adj_end = _t_idx(vid_d1 + 1);
// Loop over neighbors of vid_d1 (distance-2 from vid)
for(size_type vid_d2_adj = vid_d2_adj_begin; !break_out && vid_d2_adj < vid_d2_adj_end; ++vid_d2_adj)
{
const nnz_lno_type vid_d2 = _t_adj(vid_d2_adj);
// Ignore Distance-2 self loops
if(vid != vid_d2)
{
const color_type color_d2 = _colors(vid_d2);
// If distance-2 neighbor of vid has the same color as vid, then the coloring is invalid
if(color_vid == color_d2)
{
has_invalid_color = true;
break_out = true;
}
}
}
}
}
}
if(has_uncolored_vertex || has_invalid_color)
Kokkos::atomic_fetch_or(&_flags[ 0 ], has_uncolored_vertex || has_invalid_color);
if(has_uncolored_vertex)
Kokkos::atomic_fetch_or(&_flags[ 1 ], has_uncolored_vertex);
if(has_invalid_color)
Kokkos::atomic_fetch_or(&_flags[ 2 ], has_invalid_color);
if(has_color_bigger_than_num_verts)
Kokkos::atomic_fetch_or(&_flags[ 3 ], has_color_bigger_than_num_verts);
} // operator()
}; // struct functorVerifyDistance2Coloring (end)
/**
* functorCalculateD2Degree
*/
struct functorCalculateD2Degree
{
nnz_lno_type _num_verts; // num vertices
const_lno_row_view_type _idx; // vertex degree list
const_lno_nnz_view_t _adj; // vertex adjacency list
const_clno_row_view_t _t_idx; // transpose vertex degree list
const_clno_nnz_view_t _t_adj; // transpose vertex adjacency list
nnz_lno_type _chunk_size;
non_const_1d_size_type_view_type _degree_d2; // Distance-2 Degree (assumes all are initialized to 0)
// EXPERIMENTAL BEGIN (for HashMapAccumulator)
pool_memory_space_t _m_space;
const nnz_lno_type _hash_size;
const nnz_lno_type _max_nonzeros;
Kokkos::Experimental::UniqueToken<my_exec_space, Kokkos::Experimental::UniqueTokenScope::Global> tokens;
// EXPERIMENTAL END
functorCalculateD2Degree(nnz_lno_type num_verts,
const_lno_row_view_type xadj,
const_lno_nnz_view_t adj,
const_clno_row_view_t t_xadj,
const_clno_nnz_view_t t_adj,
nnz_lno_type chunk_size,
non_const_1d_size_type_view_type& degree_d2,
pool_memory_space_t m_space,
const nnz_lno_type hash_size,
const nnz_lno_type max_nonzeros)
: _num_verts(num_verts)
, _idx(xadj)
, _adj(adj)
, _t_idx(t_xadj)
, _t_adj(t_adj)
, _chunk_size(chunk_size)
, _degree_d2(degree_d2)
, _m_space(m_space)
, _hash_size(hash_size)
, _max_nonzeros(max_nonzeros)
{
}
KOKKOS_INLINE_FUNCTION
void operator()(const nnz_lno_type chunk_id) const
{
// BEGIN EXPERIMENTAL
// Get a unique token since we aren't using TeamPolicy (for UniformMemoryPool, that the HashmapAccumulator requires)
auto tid = tokens.acquire();
volatile nnz_lno_type* tmp = NULL;
while(NULL == tmp) { tmp = (volatile nnz_lno_type*)(_m_space.allocate_chunk(tid)); }
KokkosKernels::Experimental::HashmapAccumulator<nnz_lno_type, nnz_lno_type, nnz_lno_type> hash_map;
// What is globally_used_hash_indices?
nnz_lno_type* globally_used_hash_indices = (nnz_lno_type*)tmp;
tmp += _hash_size;
// set up hash_begins
hash_map.hash_begins = (nnz_lno_type*)(tmp);
tmp += _hash_size;
// set up hash_nexts
hash_map.hash_nexts = (nnz_lno_type*)(tmp);
tmp += _max_nonzeros;
// set up hash_keys
hash_map.keys = (nnz_lno_type*)(tmp);
// Set key and value sizes
hash_map.hash_key_size = _max_nonzeros; // Max # of nonzeros that can be added into the hash table (unused?)
hash_map.max_value_size = _max_nonzeros; // Max # of nonzeros that can be added into the hash table
nnz_lno_type pow2_hash_func = _hash_size - 1;
// END EXPERIMENTAL
for(nnz_lno_type ichunk = 0; ichunk < _chunk_size; ichunk++)
{
nnz_lno_type vid = chunk_id * _chunk_size + ichunk;
if(vid >= _num_verts)
continue;
nnz_lno_type used_hash_size = 0;
nnz_lno_type globally_used_hash_count = 0;
const size_type vid_d1_adj_begin = _idx(vid);
const size_type vid_d1_adj_end = _idx(vid + 1);
// Loop over neighbors of vid (distance-1 from vid)
for(size_type vid_d1_adj = vid_d1_adj_begin; vid_d1_adj < vid_d1_adj_end; ++vid_d1_adj)
{
const nnz_lno_type vid_d1 = _adj(vid_d1_adj);
const size_type vid_d2_adj_begin = _t_idx(vid_d1);
const size_type vid_d2_adj_end = _t_idx(vid_d1 + 1);
// EXPERIMENTAL BEGIN
for(size_type vid_d2_adj = vid_d2_adj_begin; vid_d2_adj < vid_d2_adj_end; ++vid_d2_adj)
{
const nnz_lno_type vid_d2 = _t_adj(vid_d2_adj);
nnz_lno_type hash = vid_d2 & pow2_hash_func;
int r = hash_map.sequential_insert_into_hash_TrackHashes(hash,
vid_d2,
&used_hash_size,
hash_map.max_value_size,
&globally_used_hash_count,
globally_used_hash_indices);
// TODO: Check r to make sure the insertion was successful.
if(r != 0)
{
// Do something if we couldn't insert...
}
}
// EXPERIMENTAL END
} // for vid_d1_adj ...
// EXPERIMENTAL BEGIN
// std::cout << "::: " << vid << " -> " << used_hash_size << std::endl;
_degree_d2(vid) = used_hash_size;
// Clear the Begins values.
for(nnz_lno_type i = 0; i < globally_used_hash_count; i++)
{
nnz_lno_type dirty_hash = globally_used_hash_indices[ i ];
hash_map.hash_begins[ dirty_hash ] = -1;
}
// EXPERIMENTAL END
} // for ichunk ...
_m_space.release_chunk(globally_used_hash_indices);
} // operator() (end)
}; // struct functorCalculateD2Degree (end)
}; // end class GraphColorDistance2
/**
* Compute Distance-2 Degree Stats
*
* Distance-2 Degree of a vertex, v, is the sum of the unique paths from u to v
* where v is 2 hops from u. (i.e., paths like: `u -> * -> v`)
*
* This function calculates the distance-2 degree of all the vertices in the graph,
* the maximum distance-2 degree.
*
* If the graph is symmetric, give the same value for col_map and row_map,
* and for row_entries and col_entries.
*
* @param[in] handle The Kernel Handle
* @param[in] num_rows Number of rows in the matrix (number of vertices)
* @param[in] num_cols Number of columns in the matrix
* @param[in] row_map Row map
* @param[in] row_entries Row entries
* @param[in] col_map Column map
* @param[in] col_entries Column entries
* @param[out] degree_d2_dist View to fill with distance-2 degree information.
* @param[out] degree_d2_max Maximum distance-2 degree found.
*
* @return Nothing
*
* Note: This is currently EXPERIMENTAL.
*/
template<class KernelHandle, typename lno_row_view_t_, typename lno_nnz_view_t_, typename lno_col_view_t_, typename lno_colnnz_view_t_>
void graph_compute_distance2_degree(KernelHandle *handle,
typename KernelHandle::nnz_lno_t num_rows,
typename KernelHandle::nnz_lno_t num_cols,
lno_row_view_t_ row_map,
lno_nnz_view_t_ row_entries,
lno_col_view_t_ col_map,
lno_colnnz_view_t_ col_entries,
typename KernelHandle::GraphColoringHandleType::non_const_1d_size_type_view_t& degree_d2_dist,
size_t& degree_d2_max)
{
typename KernelHandle::GraphColorDistance2HandleType *gch_d2 = handle->get_distance2_graph_coloring_handle();
Impl::GraphColorDistance2<typename KernelHandle::GraphColorDistance2HandleType, lno_row_view_t_, lno_nnz_view_t_, lno_col_view_t_, lno_colnnz_view_t_>
gc(num_rows, num_cols, row_entries.extent(0), row_map, row_entries, col_map, col_entries, gch_d2);
gc.compute_distance2_degree(degree_d2_dist, degree_d2_max);
}
/**
* Validate Distance 2 Graph Coloring
*
* If the graph is symmetric, give the same value for col_map and row_map,
* and for row_entries and col_entries.
*
* @param[in] handle The kernel handle
* @param[in] num_rows Number of rows in the matrix (number of vertices)
* @param[in] num_cols Number of columns in the matrix
* @param[in] row_map The row map
* @param[in] row_entries The row entries
* @param[in] col_map The column map
* @param[in] col_entries The column entries
* @param[out] validation_flags An array of 4 booleans.
* validation_flags[0] : True IF the distance-2 coloring is invalid.
* validation_flags[1] : True IF the coloring is bad because vertices are left uncolored.
* validation_flags[2] : True IF the coloring is bad because at least one pair of vertices
* at distance=2 from each other has the same color.
* validation_flags[3] : True IF a vertex has a color greater than number of vertices in the graph.
* May not be an INVALID coloring, but can indicate poor quality in coloring.
*
* @return boolean that is TRUE if the Distance-2 coloring is valid. False if otherwise.
*/
template<class KernelHandle, typename lno_row_view_t_, typename lno_nnz_view_t_, typename lno_col_view_t_, typename lno_colnnz_view_t_>
bool graph_verify_distance2_color(KernelHandle *handle,
typename KernelHandle::nnz_lno_t num_rows,
typename KernelHandle::nnz_lno_t num_cols,
lno_row_view_t_ row_map,
lno_nnz_view_t_ row_entries,
// If graph is symmetric, simply give same for col_map and row_map, and row_entries and col_entries.
lno_col_view_t_ col_map,
lno_colnnz_view_t_ col_entries,
bool validation_flags[])
{
bool output = true;
typename KernelHandle::GraphColorDistance2HandleType *gch_d2 = handle->get_distance2_graph_coloring_handle();
Impl::GraphColorDistance2<typename KernelHandle::GraphColorDistance2HandleType, lno_row_view_t_, lno_nnz_view_t_, lno_col_view_t_, lno_colnnz_view_t_>
gc(num_rows, num_cols, row_entries.extent(0), row_map, row_entries, col_map, col_entries, gch_d2);
output = gc.verify_coloring(row_map, row_entries, col_map, col_entries, gch_d2->get_vertex_colors(), validation_flags);
return output;
}
/**
* Prints out a histogram of graph colors for Distance-2 Graph Coloring
*
* If the graph is symmetric, give the same value for col_map and row_map,
* and for row_entries and col_entries.
*
* @param[in] handle The kernel handle
* @param[in] num_rows Number of rows in the matrix (number of vertices)
* @param[in] num_cols Number of columns in the matrix
* @param[in] row_map The row map
* @param[in] row_entries The row entries
* @param[in] col_map The column map
* @param[in] col_entries The column entries
* @param[out] validation_flags An array of 4 booleans.
* validation_flags[0] : True IF the distance-2 coloring is invalid.
* validation_flags[1] : True IF the coloring is bad because vertices are left uncolored.
* validation_flags[2] : True IF the coloring is bad because at least one pair of vertices
* at distance=2 from each other has the same color.
* validation_flags[3] : True IF a vertex has a color greater than number of vertices in the graph.
* May not be an INVALID coloring, but can indicate poor quality in coloring.
* @param[in] csv Output in CSV format? Default: false
*
* @return nothing
*/
template<class KernelHandle, typename lno_row_view_t_, typename lno_nnz_view_t_, typename lno_col_view_t_, typename lno_colnnz_view_t_>
void graph_print_distance2_color_histogram(KernelHandle *handle,
typename KernelHandle::nnz_lno_t num_rows,
typename KernelHandle::nnz_lno_t num_cols,
lno_row_view_t_ row_map,
lno_nnz_view_t_ row_entries,
// If graph is symmetric, simply give same for col_map and row_map, and row_entries and col_entries.
lno_col_view_t_ col_map,
lno_colnnz_view_t_ col_entries,
bool csv=false)
{
typename KernelHandle::GraphColorDistance2HandleType *gch_d2 = handle->get_distance2_graph_coloring_handle();
Impl::GraphColorDistance2<typename KernelHandle::GraphColorDistance2HandleType, lno_row_view_t_, lno_nnz_view_t_, lno_col_view_t_, lno_colnnz_view_t_>
gc(num_rows, num_cols, row_entries.extent(0), row_map, row_entries, col_map, col_entries, gch_d2);
if(csv)
{
gc.print_color_histogram_csv();
}
else
{
gc.print_color_histogram();
}
}
} // namespace Impl
} // namespace KokkosGraph
#endif // _KOKKOSGRAPH_DISTANCE2COLOR_IMPL_HPP
|
3c86c24b86e598c5338ded15dd3757effe673261 | 39b561c75833c3971149085f68db733b13e08f62 | /progs/file_progs/link.cpp | a9f005c368a4f1aa063602e5c7873360ada0b79d | [] | no_license | bharatmazire/LinuxSystemProgramming | e1d19794b17902ba584c3dc25eeb843c31a0e63c | d6eab23b872b7ad68d589c400f46f733135ec846 | refs/heads/master | 2021-09-04T11:42:24.182750 | 2018-01-18T11:00:27 | 2018-01-18T11:00:27 | 105,343,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 891 | cpp | link.cpp | #include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<errno.h>
int main(int argc, char *argv[])
{
int ret;
ret = link("test.txt", "link.txt");
if (-1 == ret)
{
printf("link system call failed for error %s\n", strerror(errno));
return -1;
}
printf("link system call success.\n");
sleep(20);
ret = unlink("link.txt");
if (-1 == ret)
{
printf("unlink system call failed for error %s\n", strerror(errno));
return -1;
}
printf("unlink system call success.\n");
sleep(10);
ret = link("mknodtest", "linktest");
if (-1 == ret)
{
printf("link system call failed for error %s\n", strerror(errno));
return -1;
}
printf("link system call success.\n");
sleep(20);
ret = unlink("linktest");
if (-1 == ret)
{
printf("unlink system call failed for error %s\n", strerror(errno));
return -1;
}
printf("unlink system call success.\n");
return 0;
}
|
5b3a4e60e5e141e05f16ba09ee2790aafebcf109 | a7e5d9d0dbd54323935d5ac4af2d1fbab759325e | /heap.cpp | de4892c869a5f9c44a8a6b2394b6ff8a3c118c61 | [] | no_license | clarklee777/CSCE-629 | 5eaf6422317bb9d6534e341468871c0fcd9c6dfa | 4af0ff697a31064668fd3998ad7c0ac706b45d57 | refs/heads/master | 2021-08-22T19:24:30.199673 | 2017-12-01T02:16:47 | 2017-12-01T02:16:47 | 110,496,841 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,070 | cpp | heap.cpp | /*
Utilizes a max-heap to store the graph's edges
This file is for verification of the heap class functionalities
File: heap.hpp
Author: Ho Lee
Date : 2017/11
*/
#include "corrected_heap.hpp"
#include <stdio.h>
#include <stdlib.h>
// Heap functions are :
// heap(), max_weight(), max_vertex, delete_max(), Insert(vertex, weight)
// Delete(vertex), heapify(vertex_bug), heap_size(), change_size(heap_size)
int main(int argc, char *argv[])
{
heap * test_heap;
FILE *fp;
fp = fopen(argv[1], "r");
test_heap = new heap();
//int edge_count = 0;
if(!fp)
{
if(argv[2]) printf("Error 01 : file: %s not found\n",argv[2]);
printf("Error 02 : file open failed.\n");
printf("file: %s not found\n",argv[1]);
printf("proper usage: ./program_name input_filename\nPlease try again...\n\n");
exit(0);
}
else
{
int flag = 0;
while(flag ==0)
{
int v1, v2, w, edge;
fscanf(fp,"%d %d %d", &v1, &v2, &w);
if ((v1== 0)&&(v2==0)&&(w==0))
{
flag = 1;
break;
}
else
{
/* Make the edge name XX_YY, XX is the small vertex number while YY is larger */
if(v1<v2) edge = v1*10000 + v2;
else edge = v2*10000 + v1;
test_heap->Insert(edge, w);
//edge_count++;
//printf("After insert, edge = %d\n", edge_count);
}
}
}
//printf("HERE !!\n");
//test_heap->display_heap();
while(test_heap->heap_size()!=0)
{
EDGE temp = test_heap->extract_max();
int vertex, weight;
int v1, v2;
weight = temp.edge_weight;
vertex = temp.edge_num;
v1 = vertex/10000;
v2 = vertex%10000;
printf("edge = %d <-> %d, weight = %d\n", v1, v2, weight);
}
fclose(fp);
return 0;
}
|
ed6e9799ad7673df08d53925c140823dbd613771 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /content/shell/app/shell_main_mac.cc | 37ae363b23d7f1acbfeadaf06e2b7419d24a2549 | [
"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 | 3,280 | cc | shell_main_mac.cc | // Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <dlfcn.h>
#include <errno.h>
#include <libgen.h>
#include <mach-o/dyld.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory>
#include "base/allocator/early_zone_registration_apple.h"
#if defined(HELPER_EXECUTABLE)
#include "sandbox/mac/seatbelt_exec.h" // nogncheck
#endif // defined(HELPER_EXECUTABLE)
namespace {
using ContentMainPtr = int (*)(int, char**);
} // namespace
int main(int argc, char* argv[]) {
partition_alloc::EarlyMallocZoneRegistration();
uint32_t exec_path_size = 0;
int rv = _NSGetExecutablePath(NULL, &exec_path_size);
if (rv != -1) {
fprintf(stderr, "_NSGetExecutablePath: get length failed\n");
abort();
}
std::unique_ptr<char[]> exec_path(new char[exec_path_size]);
rv = _NSGetExecutablePath(exec_path.get(), &exec_path_size);
if (rv != 0) {
fprintf(stderr, "_NSGetExecutablePath: get path failed\n");
abort();
}
#if defined(HELPER_EXECUTABLE)
sandbox::SeatbeltExecServer::CreateFromArgumentsResult seatbelt =
sandbox::SeatbeltExecServer::CreateFromArguments(exec_path.get(), argc,
argv);
if (seatbelt.sandbox_required) {
if (!seatbelt.server) {
fprintf(stderr, "Failed to create seatbelt sandbox server.\n");
abort();
}
if (!seatbelt.server->InitializeSandbox()) {
fprintf(stderr, "Failed to initialize sandbox.\n");
abort();
}
}
// The Helper app is in the versioned framework directory, so just go up to
// the version folder to locate the dylib.
const char rel_path[] = "../../../../" SHELL_PRODUCT_NAME " Framework";
#else
const char rel_path[] =
"../Frameworks/" SHELL_PRODUCT_NAME
" Framework.framework/" SHELL_PRODUCT_NAME " Framework";
#endif // defined(HELPER_EXECUTABLE)
// Slice off the last part of the main executable path, and append the
// version framework information.
const char* parent_dir = dirname(exec_path.get());
if (!parent_dir) {
fprintf(stderr, "dirname %s: %s\n", exec_path.get(), strerror(errno));
abort();
}
const size_t parent_dir_len = strlen(parent_dir);
const size_t rel_path_len = strlen(rel_path);
// 2 accounts for a trailing NUL byte and the '/' in the middle of the paths.
const size_t framework_path_size = parent_dir_len + rel_path_len + 2;
std::unique_ptr<char[]> framework_path(new char[framework_path_size]);
snprintf(framework_path.get(), framework_path_size, "%s/%s", parent_dir,
rel_path);
void* library =
dlopen(framework_path.get(), RTLD_LAZY | RTLD_LOCAL | RTLD_FIRST);
if (!library) {
fprintf(stderr, "dlopen %s: %s\n", framework_path.get(), dlerror());
abort();
}
const ContentMainPtr content_main =
reinterpret_cast<ContentMainPtr>(dlsym(library, "ContentMain"));
if (!content_main) {
fprintf(stderr, "dlsym ContentMain: %s\n", dlerror());
abort();
}
rv = content_main(argc, argv);
// exit, don't return from main, to avoid the apparent removal of main from
// stack backtraces under tail call optimization.
exit(rv);
}
|
80fb3d6bddd1553f2da875ba4ef52d206fbfc01b | f75bd673623c2656e150bdca89122aa8e536a9ab | /.ccls-cache/@Users@stephen@Documents@C++@algo@cf@problemset/1144f.cpp | d1211eb7b61067b9d597589cf9dfbde84cd6f26d | [] | no_license | shen98/codeforces | 4edab8fc4ef3fff025bec63aded979c69caeaec3 | 2f7cbb87c7d6b9e326d832dd492d71ee0d7b3943 | refs/heads/master | 2022-10-20T14:47:42.757671 | 2020-07-15T16:15:02 | 2020-07-15T16:15:02 | 268,123,811 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,013 | cpp | 1144f.cpp | #include <iostream>
#include <queue>
#include <string>
using namespace std;
typedef pair<int, int> pii;
const int N = 2e5 + 5;
int n, m;
int hd[N], vt[N], s[N << 1], vs[N], u[N], v[N];
struct edge { int to, nx; } e[N << 1];
void addEdge(int u, int v) {
static int cnt = 0;
e[++cnt] = (edge) { v, hd[u] };
hd[u] = cnt;
vt[v]++;
}
void dfs(int u, int d) {
vs[u] = d;
for(int i = hd[u]; i; i = e[i].nx) {
int v = e[i].to;
if(vs[v]) continue;
dfs(v, d == 2 ? 1 : 2);
}
}
int main() {
cin >> n >> m;
for(int i = 1; i <= m; ++i) {
cin >> u[i] >> v[i];
addEdge(u[i], v[i]);
addEdge(v[i], u[i]);
}
for(int i = 1; i <= n; ++i) {
if(!vs[i]) dfs(i, 1);
}
for(int i = 1; i <= m; ++i) {
if(vs[u[i]] == vs[v[i]]) { cout << "NO" << endl; return 0; }
}
cout << "YES" << endl;
for(int i = 1; i <= m; ++i) {
cout << (vs[u[i]] == 1) ? "1" : "0";
}
cout << endl;
return 0;
}
|
82a793dae6378e036d70b2f7d1234f56fb846ac0 | 7f27c0ef3af95aa156e4cf1f3cdf57cd8081e42f | /2015/03-compile-link-debug/calc_test.cpp | f838ebbb14c3d28f4f7f238b3011f7e120a63985 | [] | no_license | khasanovaa/hseos-course | 1433d85bc62f6936ff3e3f7c8aa0519c3fc248a3 | 3acbaec3974205a210511204ffdaeb2043fdef57 | refs/heads/master | 2020-05-17T11:47:25.518115 | 2019-04-23T15:33:40 | 2019-04-23T15:33:40 | 183,694,550 | 1 | 0 | null | 2019-04-26T21:10:31 | 2019-04-26T21:10:31 | null | UTF-8 | C++ | false | false | 211 | cpp | calc_test.cpp | #include "ast.h"
#include "calc.h"
#include "gtest/gtest.h"
TEST(Calculator, Sum) {
ASSERT_EQ(4, Eval(Parse("2 + 2").get()));
}
TEST(Calculator, Product) {
ASSERT_EQ(4, Eval(Parse("2 * 2").get()));
}
|
3febf66ff807ecd711186ae48342d1c79a47351e | e906827cb5921453b6472bba05cccbef84b2149f | /SpaceAdventuresGL/src/SpaceAdventures/States/DeathScreen.cpp | 59c011d268e960831cb3aa16711eecce47fbe6c1 | [] | no_license | djperrone/SpaceAdventuresGL | bb9ff40fb9d07c4b38c2c7a94a7a77d26f21a479 | 3f0695b2d2c3fe1c25581eb83f6135824516f3fb | refs/heads/main | 2023-08-23T23:59:43.250652 | 2021-10-31T21:03:47 | 2021-10-31T21:03:47 | 402,590,084 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,012 | cpp | DeathScreen.cpp | #include "sapch.h"
#include "DeathScreen.h"
#include "Novaura/Novaura.h"
#include "SpaceAdventures/States/MainMenu.h"
#include "SpaceAdventures/States/Level.h"
#include "SpaceAdventures/Actors/Button.h"
#include "Novaura/Core/Application.h"
namespace SpaceAdventures {
DeathScreen::DeathScreen()
{
m_Window = Novaura::InputHandler::GetCurrentWindow();
m_CameraController = Novaura::Application::GetCameraController();
m_StateMachine = Novaura::Application::GetStateMachine();
OnEnter();
}
DeathScreen::DeathScreen(std::shared_ptr<Novaura::Window> window, std::shared_ptr<Novaura::CameraController> cameraController, std::shared_ptr<Novaura::StateMachine> stateMachine)
{
m_Window = window;
m_CameraController = cameraController;
m_StateMachine = stateMachine;
OnEnter();
}
void DeathScreen::OnEnter()
{
m_InputController = Novaura::InputHandler::CreateNewInputController();
Novaura::InputHandler::SetCurrentController(m_InputController);
Novaura::InputHandler::GetCurrentController().BindActionInputEvent(GLFW_PRESS, GLFW_MOUSE_BUTTON_LEFT, &DeathScreen::HandleInput, this);
m_Title = std::make_unique<Novaura::Rectangle>(glm::vec2(0.0f, 0.5f), glm::vec2(2.0f, 0.40f));
m_ButtonList.emplace_back(std::make_unique<UI::ToggleButton>("Assets/Textures/Buttons/ExitButtonLight.png", glm::vec3(0.0f, -0.50f, 0.0f), glm::vec3(1.0f, 0.20f, 0.0f),
Novaura::Command([](){
Novaura::Application::GetStateMachine()->ShutDown(); }
)));
m_ButtonList.emplace_back(std::make_unique<UI::ToggleButton>("Assets/Textures/Buttons/MainMenuLight.png", glm::vec3(0.0f, -0.250f, 0.0f), glm::vec3(1.0f, 0.20f, 0.0f),
Novaura::Command([]() {
Novaura::Application::GetStateMachine()->ClearPastStates();
Novaura::Application::GetStateMachine()->ReplaceCurrentState(std::make_unique<MainMenu>()); }
)));
m_ButtonList.emplace_back(std::make_unique<UI::ToggleButton>("Assets/Textures/Buttons/PlayAgainButtonLight.png", glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(1.0f, 0.20f, 0.0f),
Novaura::Command([]() {Novaura::Application::GetStateMachine()->ReplaceCurrentState(std::make_unique<Level>()); }
)));
}
void DeathScreen::HandleInput()
{
for (auto& button : m_ButtonList)
{
if (button->IsHovered())
{
button->Execute();
}
}
}
void DeathScreen::Update(float deltaTime)
{
for (auto& button : m_ButtonList)
{
button->Update();
}
}
void DeathScreen::Draw(float deltaTime)
{
Novaura::BatchRenderer::SetClearColor(0.05f, 0.05f, 0.05f, 1.0f);
Novaura::BatchRenderer::Clear();
Novaura::BatchRenderer::BeginScene(m_CameraController->GetCamera());
Novaura::BatchRenderer::DrawRectangle(*m_Title, "Assets/Textures/Buttons/DeathScreenRed2.png");
for (auto& button : m_ButtonList)
{
Novaura::BatchRenderer::DrawRectangle(button->GetRectangle(), button->GetTextureFile());
}
Novaura::BatchRenderer::EndScene();
}
void DeathScreen::OnExit()
{
}
void DeathScreen::Pause()
{
}
void DeathScreen::Resume()
{
}
} |
0180f44b21d5634faeb6b649c63fbf32c7fd9ea6 | 9f81d77e028503dcbb6d7d4c0c302391b8fdd50c | /google/cloud/storage/client_notifications_test.cc | 071dc15516d306d45a782833010b0baf11bcc61a | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | googleapis/google-cloud-cpp | b96a6ee50c972371daa8b8067ddd803de95f54ba | 178d6581b499242c52f9150817d91e6c95b773a5 | refs/heads/main | 2023-08-31T09:30:11.624568 | 2023-08-31T03:29:11 | 2023-08-31T03:29:11 | 111,860,063 | 450 | 351 | Apache-2.0 | 2023-09-14T21:52:02 | 2017-11-24T00:19:31 | C++ | UTF-8 | C++ | false | false | 6,449 | cc | client_notifications_test.cc | // Copyright 2018 Google LLC
//
// 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
//
// https://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 "google/cloud/storage/client.h"
#include "google/cloud/storage/internal/notification_metadata_parser.h"
#include "google/cloud/storage/notification_event_type.h"
#include "google/cloud/storage/notification_payload_format.h"
#include "google/cloud/storage/oauth2/google_credentials.h"
#include "google/cloud/storage/retry_policy.h"
#include "google/cloud/storage/testing/canonical_errors.h"
#include "google/cloud/storage/testing/client_unit_test.h"
#include "google/cloud/testing_util/status_matchers.h"
#include <gmock/gmock.h>
namespace google {
namespace cloud {
namespace storage {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace {
using ::google::cloud::internal::CurrentOptions;
using ::google::cloud::storage::testing::canonical_errors::TransientError;
using ::testing::HasSubstr;
using ::testing::Return;
using ms = std::chrono::milliseconds;
/**
* Test the BucketAccessControls-related functions in storage::Client.
*/
class NotificationsTest
: public ::google::cloud::storage::testing::ClientUnitTest {};
TEST_F(NotificationsTest, ListNotifications) {
std::vector<NotificationMetadata> expected{
internal::NotificationMetadataParser::FromString(R"""({
"id": "test-notification-1",
"topic": "test-topic-1"
})""")
.value(),
internal::NotificationMetadataParser::FromString(R"""({
"id": "test-notification-2",
"topic": "test-topic-2"
})""")
.value(),
};
EXPECT_CALL(*mock_, ListNotifications)
.WillOnce(Return(
StatusOr<internal::ListNotificationsResponse>(TransientError())))
.WillOnce([&expected](internal::ListNotificationsRequest const& r) {
EXPECT_EQ(CurrentOptions().get<AuthorityOption>(), "a-default");
EXPECT_EQ(CurrentOptions().get<UserProjectOption>(), "u-p-test");
EXPECT_EQ("test-bucket", r.bucket_name());
return make_status_or(internal::ListNotificationsResponse{expected});
});
auto client = ClientForMock();
StatusOr<std::vector<NotificationMetadata>> actual = client.ListNotifications(
"test-bucket", Options{}.set<UserProjectOption>("u-p-test"));
ASSERT_STATUS_OK(actual);
EXPECT_EQ(expected, actual.value());
}
TEST_F(NotificationsTest, CreateNotification) {
NotificationMetadata expected =
internal::NotificationMetadataParser::FromString(R"""({
"id": "test-notification-1",
"topic": "test-topic-1",
"payload_format": "JSON_API_V1",
"object_prefix": "test-object-prefix-",
"event_type": [ "OBJECT_FINALIZE" ]
})""")
.value();
EXPECT_CALL(*mock_, CreateNotification)
.WillOnce(Return(StatusOr<NotificationMetadata>(TransientError())))
.WillOnce([&expected](internal::CreateNotificationRequest const& r) {
EXPECT_EQ(CurrentOptions().get<AuthorityOption>(), "a-default");
EXPECT_EQ(CurrentOptions().get<UserProjectOption>(), "u-p-test");
EXPECT_EQ("test-bucket", r.bucket_name());
EXPECT_THAT(r.json_payload(), HasSubstr("test-topic-1"));
EXPECT_THAT(r.json_payload(), HasSubstr("JSON_API_V1"));
EXPECT_THAT(r.json_payload(), HasSubstr("test-object-prefix-"));
EXPECT_THAT(r.json_payload(), HasSubstr("OBJECT_FINALIZE"));
return make_status_or(expected);
});
auto client = ClientForMock();
StatusOr<NotificationMetadata> actual = client.CreateNotification(
"test-bucket", "test-topic-1", payload_format::JsonApiV1(),
NotificationMetadata()
.set_object_name_prefix("test-object-prefix-")
.append_event_type(event_type::ObjectFinalize()),
Options{}.set<UserProjectOption>("u-p-test"));
ASSERT_STATUS_OK(actual);
EXPECT_EQ(expected, actual.value());
}
TEST_F(NotificationsTest, GetNotification) {
NotificationMetadata expected =
internal::NotificationMetadataParser::FromString(R"""({
"id": "test-notification-1",
"topic": "test-topic-1",
"payload_format": "JSON_API_V1",
"object_prefix": "test-object-prefix-",
"event_type": [ "OBJECT_FINALIZE" ]
})""")
.value();
EXPECT_CALL(*mock_, GetNotification)
.WillOnce(Return(StatusOr<NotificationMetadata>(TransientError())))
.WillOnce([&expected](internal::GetNotificationRequest const& r) {
EXPECT_EQ(CurrentOptions().get<AuthorityOption>(), "a-default");
EXPECT_EQ(CurrentOptions().get<UserProjectOption>(), "u-p-test");
EXPECT_EQ("test-bucket", r.bucket_name());
EXPECT_EQ("test-notification-1", r.notification_id());
return make_status_or(expected);
});
auto client = ClientForMock();
StatusOr<NotificationMetadata> actual =
client.GetNotification("test-bucket", "test-notification-1",
Options{}.set<UserProjectOption>("u-p-test"));
ASSERT_STATUS_OK(actual);
EXPECT_EQ(expected, actual.value());
}
TEST_F(NotificationsTest, DeleteNotification) {
EXPECT_CALL(*mock_, DeleteNotification)
.WillOnce(Return(StatusOr<internal::EmptyResponse>(TransientError())))
.WillOnce([](internal::DeleteNotificationRequest const& r) {
EXPECT_EQ(CurrentOptions().get<AuthorityOption>(), "a-default");
EXPECT_EQ(CurrentOptions().get<UserProjectOption>(), "u-p-test");
EXPECT_EQ("test-bucket", r.bucket_name());
EXPECT_EQ("test-notification-1", r.notification_id());
return make_status_or(internal::EmptyResponse{});
});
auto client = ClientForMock();
auto status =
client.DeleteNotification("test-bucket", "test-notification-1",
Options{}.set<UserProjectOption>("u-p-test"));
ASSERT_STATUS_OK(status);
}
} // namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace storage
} // namespace cloud
} // namespace google
|
c9f22962ee1a208dc7f92af0959ce7a499e910a8 | 34c6ea938f3ebc74053057884f984bf14950cf10 | /src/gui_dialogs/gui_levelmanager.cpp | 5ea6721f195f23ba6b85a04ac0e035e89feac05b | [] | no_license | mzeilfelder/hc1 | 62e2563e2ed19c35c89083e1e4dd6722e6c6e42e | 6f717b1168a85e17582feb141338aaffc923d26a | refs/heads/master | 2023-08-09T08:40:15.661233 | 2019-10-11T18:28:52 | 2019-10-11T18:28:52 | 272,798,185 | 13 | 5 | null | 2022-11-25T22:53:24 | 2020-06-16T19:47:14 | C | UTF-8 | C++ | false | false | 2,569 | cpp | gui_levelmanager.cpp | // Written by Michael Zeilfelder, please check licenseHCraft.txt for the zlib-style license text.
#include "gui_levelmanager.h"
#include "../gui_ids.h"
#include "../level.h"
#include "../level_manager.h"
#include "../main.h"
using namespace irr;
using namespace gui;
GuiLevelManager::GuiLevelManager(irr::gui::IGUIEnvironment* env_)
: mEnvironment(env_)
, mListLevels(NULL)
{
}
void GuiLevelManager::CloseLevelSelection()
{
IGUIElement* root = mEnvironment->getRootGUIElement();
IGUIElement* e = root->getElementFromId(GUI_WND_LEVEL_SELECTION, true);
if (e)
{
e->remove();
mListLevels = NULL;
}
}
void GuiLevelManager::ShowLevelSelection()
{
CloseLevelSelection();
// create the window
core::rect<s32> wndRect(140,50,500,400);
IGUIWindow* wnd = mEnvironment->addWindow(wndRect, false, L"Levels", 0, GUI_WND_LEVEL_SELECTION);
if ( !wnd )
return;
core::rect<s32> levelsRect(20,30,340,330);
mListLevels = mEnvironment->addListBox(levelsRect, wnd, GUI_LIST_LEVELS );
for ( int i=0; i < APP.GetLevelManager()->GetNumLevels(); ++i )
{
const LevelSettings &levelSettings = APP.GetLevelManager()->GetLevelSettings(i);
mListLevels->addItem( levelSettings.mName.c_str() );
}
}
bool GuiLevelManager::OnEvent(const SEvent &event)
{
switch ( event.EventType )
{
case EET_GUI_EVENT:
{
s32 id = event.GUIEvent.Caller->getID();
switch(event.GUIEvent.EventType)
{
case EGET_LISTBOX_CHANGED:
case EGET_LISTBOX_SELECTED_AGAIN:
{
switch(id)
{
case GUI_LIST_LEVELS:
{
int selected = mListLevels->getSelected();
if ( selected < 0 )
break;
std::wstring name(mListLevels->getListItem(selected));
APP.GetLevelManager()->LoadLevel(name, *APP.GetLevel());
CloseLevelSelection();
return true;
}
break;
default:
break;
}
}
break;
default:
break;
}
}
break;
default:
break;
}
return false;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.