blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 122 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5f4d1df5889021c4d9e58c7219be5dcf720812ad | 26b8309b367aa41551936fde1c13f24e9aecabdf | /№6/№6/№6.cpp | 43c29a0a05ee922442f3c394dddc1619a59a5c49 | [] | no_license | R3str/Cpp | ad412f0cc9d7166ff250e63f5b07c3ca66719f49 | 758732fe7222a513e256e4e080d2f510fcbf9d12 | refs/heads/master | 2020-04-29T11:43:13.115705 | 2019-06-08T12:58:46 | 2019-06-08T12:58:46 | 176,109,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,066 | cpp | #include "pch.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct userAdd
{
string Fio;
double Pay;
int PaidMonth;
int PrepaidMonth;
userAdd()
{
Fio = "NaN";
Pay = -1;
PaidMonth = -1;
PrepaidMonth = -1;
}
userAdd(string fio, int pay, int paidMonth, int prepaidMonth)
{
Fio = fio;
Pay = pay;
PaidMonth = paidMonth;
PrepaidMonth = prepaidMonth;
if (prepaidMonth > 4)
Pay *= 0.93;
}
};
int main()
{
setlocale(LC_ALL, "ru");
const int amount = 10;
userAdd user[amount];
/*user[0] = { "one", 50, 10, 3 };
user[1] = { "two", 45, 26, 7 };
user[2] = { "three", 48, 19, 3 };
user[3] = { "four", 43, 17, 6 };
user[4] = { "five", 57, 4, 1 };
user[5] = { "six", 49, 14, 0 };
user[6] = { "seven", 53, 32, 6 };
user[7] = { "eight", 48, 7, 0 };
user[8] = { "nine", 55, 14, 11 };
user[9] = { "ten", 57, 1, 8 };
ofstream fon("C:\\Users\\Рабочий стол\\source\\repos\\Cpp\\№6\\data.txt", ios::binary);
for (int i = 0; i < amount; i++)
{
fon.write((char*)&user[i].Fio, sizeof(user[i].Fio));
fon.write((char*)&user[i].Pay, sizeof(user[i].Pay));
fon.write((char*)&user[i].PaidMonth, sizeof(user[i].PaidMonth));
fon.write((char*)&user[i].PrepaidMonth, sizeof(user[i].PrepaidMonth));
}
fon.close();*/
ifstream fin("C:\\Users\\Рабочий стол\\source\\repos\\Cpp\\№6\\data.txt", ios::binary);
for (int i = 0; i < amount; i++)
{
fin.read((char*)&user[i].Fio, sizeof(user[i].Fio));
fin.read((char*)&user[i].Pay, sizeof(user[i].Pay));
fin.read((char*)&user[i].PaidMonth, sizeof(user[i].PaidMonth));
fin.read((char*)&user[i].PrepaidMonth, sizeof(user[i].PrepaidMonth));
}
for (int i = 0; i < amount; i++)
{
cout << "\t№" << i + 1 << endl;
cout << "ФИО: " << user[i].Fio << endl;
cout << "Оплата: " << user[i].Pay << endl;
cout << "Кол-во оплаченых месяцев: " << user[i].PaidMonth << endl;
cout << "Кол-во оплаченых наперед месяцев: " << user[i].PrepaidMonth << endl << endl;
}
}
| [
"andrey.kotoman12@gmail.com"
] | andrey.kotoman12@gmail.com |
9bc0ab5eff60861234b9e50054d1b538103e0e7f | 612325535126eaddebc230d8c27af095c8e5cc2f | /src/base/threading/simple_thread.cc | 97cab6e2bf32530e310385cfee19cc394084ae80 | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/proto-quic_1V94 | 1a3a03ac7a08a494b3d4e9857b24bb8f2c2cd673 | feee14d96ee95313f236e0f0e3ff7719246c84f7 | refs/heads/master | 2023-04-01T14:36:53.888576 | 2019-10-17T02:23:04 | 2019-10-17T02:23:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,381 | cc | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/threading/simple_thread.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread_restrictions.h"
namespace base {
SimpleThread::SimpleThread(const std::string& name_prefix)
: SimpleThread(name_prefix, Options()) {}
SimpleThread::SimpleThread(const std::string& name_prefix,
const Options& options)
: name_prefix_(name_prefix),
options_(options),
event_(WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED) {}
SimpleThread::~SimpleThread() {
DCHECK(HasBeenStarted()) << "SimpleThread was never started.";
DCHECK(!options_.joinable || HasBeenJoined())
<< "Joinable SimpleThread destroyed without being Join()ed.";
}
void SimpleThread::Start() {
DCHECK(!HasBeenStarted()) << "Tried to Start a thread multiple times.";
bool success =
options_.joinable
? PlatformThread::CreateWithPriority(options_.stack_size, this,
&thread_, options_.priority)
: PlatformThread::CreateNonJoinableWithPriority(
options_.stack_size, this, options_.priority);
DCHECK(success);
ThreadRestrictions::ScopedAllowWait allow_wait;
event_.Wait(); // Wait for the thread to complete initialization.
}
void SimpleThread::Join() {
DCHECK(options_.joinable) << "A non-joinable thread can't be joined.";
DCHECK(HasBeenStarted()) << "Tried to Join a never-started thread.";
DCHECK(!HasBeenJoined()) << "Tried to Join a thread multiple times.";
PlatformThread::Join(thread_);
thread_ = PlatformThreadHandle();
joined_ = true;
}
bool SimpleThread::HasBeenStarted() {
ThreadRestrictions::ScopedAllowWait allow_wait;
return event_.IsSignaled();
}
void SimpleThread::ThreadMain() {
tid_ = PlatformThread::CurrentId();
// Construct our full name of the form "name_prefix_/TID".
std::string name(name_prefix_);
name.push_back('/');
name.append(IntToString(tid_));
PlatformThread::SetName(name);
// We've initialized our new thread, signal that we're done to Start().
event_.Signal();
Run();
}
DelegateSimpleThread::DelegateSimpleThread(Delegate* delegate,
const std::string& name_prefix)
: DelegateSimpleThread(delegate, name_prefix, Options()) {}
DelegateSimpleThread::DelegateSimpleThread(Delegate* delegate,
const std::string& name_prefix,
const Options& options)
: SimpleThread(name_prefix, options),
delegate_(delegate) {
DCHECK(delegate_);
}
DelegateSimpleThread::~DelegateSimpleThread() = default;
void DelegateSimpleThread::Run() {
DCHECK(delegate_) << "Tried to call Run without a delegate (called twice?)";
// Non-joinable DelegateSimpleThreads are allowed to be deleted during Run().
// Member state must not be accessed after invoking Run().
Delegate* delegate = delegate_;
delegate_ = nullptr;
delegate->Run();
}
DelegateSimpleThreadPool::DelegateSimpleThreadPool(
const std::string& name_prefix,
int num_threads)
: name_prefix_(name_prefix),
num_threads_(num_threads),
dry_(WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED) {}
DelegateSimpleThreadPool::~DelegateSimpleThreadPool() {
DCHECK(threads_.empty());
DCHECK(delegates_.empty());
DCHECK(!dry_.IsSignaled());
}
void DelegateSimpleThreadPool::Start() {
DCHECK(threads_.empty()) << "Start() called with outstanding threads.";
for (int i = 0; i < num_threads_; ++i) {
DelegateSimpleThread* thread = new DelegateSimpleThread(this, name_prefix_);
thread->Start();
threads_.push_back(thread);
}
}
void DelegateSimpleThreadPool::JoinAll() {
DCHECK(!threads_.empty()) << "JoinAll() called with no outstanding threads.";
// Tell all our threads to quit their worker loop.
AddWork(NULL, num_threads_);
// Join and destroy all the worker threads.
for (int i = 0; i < num_threads_; ++i) {
threads_[i]->Join();
delete threads_[i];
}
threads_.clear();
DCHECK(delegates_.empty());
}
void DelegateSimpleThreadPool::AddWork(Delegate* delegate, int repeat_count) {
AutoLock locked(lock_);
for (int i = 0; i < repeat_count; ++i)
delegates_.push(delegate);
// If we were empty, signal that we have work now.
if (!dry_.IsSignaled())
dry_.Signal();
}
void DelegateSimpleThreadPool::Run() {
Delegate* work = NULL;
while (true) {
dry_.Wait();
{
AutoLock locked(lock_);
if (!dry_.IsSignaled())
continue;
DCHECK(!delegates_.empty());
work = delegates_.front();
delegates_.pop();
// Signal to any other threads that we're currently out of work.
if (delegates_.empty())
dry_.Reset();
}
// A NULL delegate pointer signals us to quit.
if (!work)
break;
work->Run();
}
}
} // namespace base
| [
"2100639007@qq.com"
] | 2100639007@qq.com |
305fdd0d5bd8e0f3e3f01286026af4d01b3f124e | 7c7e87ace2557d9305d29be907be538c1a1befa5 | /examples/GeometryLight/GeometryLight.cpp | 9afc9b33a07ee808cf134337163717e01ee5d593 | [] | no_license | wuze/hppv | 94c7993ffe9993d54fa25cb7cbb94bac049c7c5c | e274880ed9c2648377f481b135e6f04241b00062 | refs/heads/master | 2022-10-25T20:06:36.115567 | 2020-06-13T18:05:20 | 2020-06-13T18:05:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,638 | cpp | // ncase.me/sight-and-light
#include <vector>
#include <optional>
#include <algorithm> // std::min, std::max, std::sort
#include <cmath> // std::atan2
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/vector_angle.hpp> // glm::rotate
#include <hppv/Prototype.hpp>
#include <hppv/Renderer.hpp>
#include <hppv/imgui.h>
#include <hppv/Shader.hpp>
#include <hppv/Framebuffer.hpp>
#include <hppv/glad.h>
#include "../run.hpp"
const char* const lightSource = R"(
#fragment
#version 330
in vec4 vColor;
in vec2 vTexCoord;
in vec2 vPos;
uniform sampler2D sampler;
const float radius = 0.5;
const vec2 center = vec2(0.5, 0.5);
out vec4 color;
void main()
{
float distanceFromCenter = length(vPos - center);
float alpha = 1.0 - smoothstep(0.0, radius, distanceFromCenter);
vec4 sample = texture(sampler, vTexCoord);
color = sample * vColor * alpha;
}
)";
std::optional<glm::vec2> findRayEnd(const glm::vec2 rayStart, const glm::vec2 rayDir, const glm::vec2 segStart,
const glm::vec2 segEnd)
{
// todo: handle / eliminate this case
if(rayDir.x == 0.f)
return {};
const auto rayCoeff = rayDir.y / rayDir.x;
glm::vec2 rayEnd;
if(segStart.x == segEnd.x)
{
const auto x = segStart.x;
rayEnd = {x, rayCoeff * x + rayStart.y - rayCoeff * rayStart.x};
if(rayEnd.y < std::min(segStart.y, segEnd.y) || rayEnd.y > std::max(segStart.y, segEnd.y))
return {};
}
else
{
const auto segCoeff = (segEnd.y - segStart.y) / (segEnd.x - segStart.x);
if(rayCoeff == segCoeff)
return {};
const auto x = (segStart.y - segCoeff * segStart.x - rayStart.y + rayCoeff * rayStart.x) / (rayCoeff - segCoeff);
if(x < std::min(segStart.x, segEnd.x) || (x > std::max(segStart.x, segEnd.x)))
return {};
rayEnd = {x, rayCoeff * x + rayStart.y - rayCoeff * rayStart.x};
}
if(rayDir.x * (rayEnd.x - rayStart.x) < 0)
return {};
return rayEnd;
}
class GeometryLight: public hppv::Prototype
{
public:
GeometryLight():
hppv::Prototype({0.f, 0.f, 100.f, 100.f}),
shaderLight_({hppv::Renderer::vInstancesSource, lightSource}, "shaderLight_"),
fb_(GL_RGBA8, 1)
{
setShapes();
}
private:
std::vector<std::vector<glm::vec2>> shapes_; // todo: keep the points in one vector
const hppv::Space border_{10.f, 10.f, 80.f, 80.f};
std::vector<glm::vec2> points_;
glm::vec2 lightPos_;
hppv::Shader shaderLight_;
hppv::Framebuffer fb_;
struct
{
bool drawPoints = true;
bool drawLines = true;
bool drawTriangles = true;
bool release = true;
}
options_;
void setShapes();
void setPoints()
{
points_.clear();
// note: shadowing
// todo: better variable names
for(const auto& shape: shapes_)
{
for(const auto point: shape)
{
for(auto i = -1; i < 2; ++i)
{
const auto rayDir = glm::rotate(point - lightPos_, i * 0.00001f);
auto closestRayEnd = lightPos_ + glm::vec2(1000000.f);
if(i == 0)
{
closestRayEnd = point;
}
for(const auto& shape: shapes_)
{
for(auto it = shape.cbegin(); it < shape.cend(); ++it)
{
// todo?: modulo vs if?
const auto segEnd = (it == shape.end() - 1 ? *shape.begin() : *(it + 1));
if(const auto rayEnd = findRayEnd(lightPos_, rayDir, *it, segEnd))
{
if(glm::length(*rayEnd - lightPos_) < glm::length(closestRayEnd - lightPos_))
{
closestRayEnd = *rayEnd;
}
}
}
}
points_.push_back(closestRayEnd);
}
}
}
std::sort(points_.begin(), points_.end(), [lightPos = lightPos_](const glm::vec2& l, const glm::vec2& r)
{
return std::atan2(l.x - lightPos.x, l.y - lightPos.y) <
std::atan2(r.x - lightPos.x, r.y - lightPos.y);
});
}
void prototypeProcessInput(const hppv::Pinput input) override
{
lightPos_ = hppv::mapCursor(input.cursorPos, space_.projected, this);
lightPos_.x = std::max(lightPos_.x, border_.pos.x + 1);
lightPos_.y = std::max(lightPos_.y, border_.pos.y + 1);
lightPos_.x = std::min(lightPos_.x, border_.pos.x + border_.size.x - 1);
lightPos_.y = std::min(lightPos_.y, border_.pos.y + border_.size.y - 1);
setPoints();
}
void prototypeRender(hppv::Renderer& renderer) override
{
ImGui::Begin(prototype_.imguiWindowName);
{
ImGui::Checkbox("points", &options_.drawPoints);
ImGui::Checkbox("lines", &options_.drawLines);
ImGui::Checkbox("triangles", &options_.drawTriangles);
ImGui::Checkbox("release", &options_.release);
}
ImGui::End();
if(options_.release)
{
fb_.bind();
fb_.setSize(properties_.size);
fb_.clear();
renderer.viewport(fb_);
}
if(options_.drawTriangles || options_.release)
{
renderer.mode(hppv::RenderMode::Vertices);
renderer.shader(hppv::Render::VerticesColor);
renderer.primitive(GL_TRIANGLES);
for(auto it = points_.cbegin(); it < points_.cend(); ++it)
{
const auto last = (it == points_.end() - 1) ? *points_.begin() : *(it + 1);
hppv::Vertex v;
if(options_.release)
{
v.color = {1.f, 0.f, 0.f, 1.f};
}
else
{
v.color = {0.3f, 0.f, 0.f, 1.f};
}
v.pos = lightPos_;
renderer.cache(v);
v.pos = *it;
renderer.cache(v);
v.pos = last;
renderer.cache(v);
}
}
if(options_.release)
{
renderer.flush();
renderer.viewport(this);
fb_.unbind();
renderer.mode(hppv::RenderMode::Instances);
renderer.normalizeTexRect = true;
hppv::Circle c;
c.center = lightPos_;
c.radius = border_.size.x * 0.65f;;
c.texRect = hppv::mapToFramebuffer(c.toVec4(), space_.projected, fb_);
renderer.shader(shaderLight_);
renderer.texture(fb_.getTexture());
renderer.cache(c);
renderer.normalizeTexRect = false;
}
renderer.mode(hppv::RenderMode::Vertices);
renderer.shader(hppv::Render::VerticesColor);
renderer.primitive(GL_LINE_LOOP);
for(const auto& shape: shapes_)
{
for(const auto point: shape)
{
hppv::Vertex v;
v.pos = point;
v.color = {0.5f, 0.5f, 0.5f, 1.f};
renderer.cache(v);
}
renderer.breakBatch();
}
if(options_.release)
return;
if(options_.drawLines)
{
for(const auto point: points_)
{
hppv::Vertex v;
v.pos = point;
v.color = {1.f, 0.f, 0.f, 1.f};
renderer.cache(v);
v.pos = lightPos_;
renderer.cache(v);
renderer.breakBatch();
}
}
if(options_.drawPoints)
{
renderer.mode(hppv::RenderMode::Instances);
renderer.shader(hppv::Render::CircleColor);
for(const auto point: points_)
{
hppv::Circle c;
c.center = point;
c.radius = 0.5f;
c.color = {1.f, 0.f, 0.f, 1.f};
renderer.cache(c);
}
}
}
};
void GeometryLight::setShapes()
{
{
shapes_.emplace_back();
auto& shape = shapes_.back();
shape.emplace_back(30.f, 30.f);
shape.emplace_back(60.f, 40.f);
shape.emplace_back(50.f, 20.f);
}
{
shapes_.emplace_back();
auto& shape = shapes_.back();
shape.emplace_back(70.f, 15.f);
shape.emplace_back(60.f, 25.f);
shape.emplace_back(65.f, 30.f);
}
{
shapes_.emplace_back();
auto& shape = shapes_.back();
shape.emplace_back(20.f, 60.f);
shape.emplace_back(40.f, 60.f);
shape.emplace_back(40.f, 75.f);
shape.emplace_back(30.f, 75.f);
}
{
shapes_.emplace_back();
auto& shape = shapes_.back();
shape.emplace_back(65.f, 40.f);
shape.emplace_back(78.f, 30.f);
shape.emplace_back(70.f, 50.f);
shape.emplace_back(65.f, 45.f);
}
{
shapes_.emplace_back();
auto& shape = shapes_.back();
shape.emplace_back(border_.pos);
shape.emplace_back(border_.pos + glm::vec2(border_.size.x, 0.f));
shape.emplace_back(border_.pos + border_.size);
shape.emplace_back(border_.pos + glm::vec2(0.f, border_.size.y));
}
}
RUN(GeometryLight)
| [
"mateusz.macieja8@gmail.com"
] | mateusz.macieja8@gmail.com |
0997672eb0e40a893f4554fb68d78c22d1467346 | 2654bd5d6e303633633bfe227140d1d92d1a59fb | /src/cs_buffer.cpp | 084a55ec0532cf3db0f563248af75274314e9185 | [
"MIT",
"BSD-3-Clause"
] | permissive | champyen/clscript | d982554962b1d608c098c4cf035b948180c53a19 | ef9112d9a7953ce7b52d744a769dff559db6c9c5 | refs/heads/master | 2021-01-22T20:34:41.975506 | 2014-06-26T12:23:30 | 2014-06-26T12:23:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,233 | cpp | #include "cs_buffer.h"
namespace clscript{
CSBuffer::CSBuffer(CSRuntime *runtime, size_t size, void *hostptr, bool autoSync) :
mRuntime(runtime),
mSize(size),
mHostBuf(hostptr)
{
cl_int status;
cl_mem_flags flags = CL_MEM_READ_WRITE;
if(hostptr){
if(mAutoSync && (mRuntime->mUseSyncFlag)) //autosync
flags |= CL_MEM_USE_HOST_PTR;
else //hostptr is used to initialized
flags |= CL_MEM_COPY_HOST_PTR;
}
CL_CALL(mBuf = clCreateBuffer(runtime->mCtx, flags, size, hostptr, &status));
}
CSBuffer::~CSBuffer()
{
CL_CALL(cl_int status = clReleaseMemObject(mBuf));
}
void* CSBuffer::getHostBuf()
{
return mHostBuf;
}
size_t CSBuffer::getSize()
{
return mSize;
}
void CSBuffer::sync()
{
cl_int status;
if(mHostBuf && mAutoSync && !(mRuntime->mUseSyncFlag)){
//copyback
CL_CALL(status = clEnqueueReadBuffer(mRuntime->mQueue, mBuf, CL_TRUE, 0, mSize, mHostBuf, 0, NULL, NULL));
}
}
void CSBuffer::read(void *buf)
{
cl_int status;
CL_CALL(status = clEnqueueReadBuffer(mRuntime->mQueue, mBuf, CL_TRUE, 0, mSize, buf, 0, NULL, NULL));
}
} //namespace clscript
| [
"champ.yen@gmail.com"
] | champ.yen@gmail.com |
1ce48dc0c3c4cc43cb0fba1213dc258c31cd8598 | 4c3e844382943271a06b933a9dbc3c8b30b08dca | /2nd Sem/C++/Programs/newop1.cpp | 5cd9974bc9fe7651843952fc05a2a49591f16d61 | [] | no_license | vijaykumarrpai/mca-code | 9ec29f8684bb4a3327c63fb48eb0c244eef5e9c7 | ed407c539ff8a33811817b8dfcceea39c68641bd | refs/heads/master | 2022-12-22T11:08:53.960599 | 2020-11-08T13:20:22 | 2020-11-08T13:20:22 | 182,063,526 | 4 | 2 | null | 2022-12-16T12:13:43 | 2019-04-18T10:00:53 | Jupyter Notebook | UTF-8 | C++ | false | false | 391 | cpp | //demonstration of how the memory allocated in heap area in memory
#include <iostream>
int main()
{
int *p;
float *q;
char *r;
p= new int(10); // 2 bytes of memory allocation in heap area and the base address return to p
q= new float(1.5); // 4bytes of memory allocation in heap area & base addr return to q
r= new char('X'); // 1 byte of memory in heap area & base addr return to r
} | [
"vijaykumarrpai@gmail.com"
] | vijaykumarrpai@gmail.com |
8ef35ebaa40c5b687b4718a2ddccf4252a980036 | b19e8f83f47b89b436e268ce369c0e8043c495fb | /docs/source/torch/torchscript/code/scalar-type/alias.cc | 51856af9e0e7d1013afefc76e43eb5728cc8ba89 | [] | no_license | csu-fangjun/notes | 3d09d38925db45cbd57858bacfc7baf24a55217e | 701a025f4e542b759c934776a0f61ff2e0351ce1 | refs/heads/master | 2023-07-08T21:59:43.882911 | 2022-06-20T02:30:12 | 2022-06-20T02:30:12 | 153,248,662 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 660 | cc | // See torch/csrc/api/include/torch/types.h
using Dtype = at::ScalarType;
/// Fixed width dtypes.
constexpr auto kUInt8 = at::kByte;
constexpr auto kInt8 = at::kChar;
constexpr auto kInt16 = at::kShort;
constexpr auto kInt32 = at::kInt;
constexpr auto kInt64 = at::kLong;
constexpr auto kFloat16 = at::kHalf;
constexpr auto kFloat32 = at::kFloat;
constexpr auto kFloat64 = at::kDouble;
/// Rust-style short dtypes.
constexpr auto kU8 = kUInt8;
constexpr auto kI8 = kInt8;
constexpr auto kI16 = kInt16;
constexpr auto kI32 = kInt32;
constexpr auto kI64 = kInt64;
constexpr auto kF16 = kFloat16;
constexpr auto kF32 = kFloat32;
constexpr auto kF64 = kFloat64;
| [
"fangjun.kuang@gmail.com"
] | fangjun.kuang@gmail.com |
15ccb479c0d1e06c46b49a1a3c168c85a8579fae | e6fd74ac5a8283729c08e05dd045dff9fdaeb3cf | /1021.cpp | 980adb1c2eac208b3dd4db7f022d9855c8b0b1b1 | [] | no_license | zenglh666/POJ | 137b7fa8e66ad4ccf660b587065daa1290a1ff9f | d81e1ea1c8119caa58e07ded81faa305f6bf13e6 | refs/heads/master | 2021-01-12T13:39:49.639058 | 2016-09-26T05:15:05 | 2016-09-26T05:15:05 | 69,213,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,583 | cpp | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct position{
int x, y;
}pos[10010];
int w, h, n, map[105][105], sum[2][10010];
int compare(const void*a, const void *b)
{
return *((int *)a) - *((int *)b);
}
int main(){
int T;
scanf("%d", &T);
while (T--){
scanf("%d %d %d", &w, &h, &n);
memset(map, 0, sizeof map);
for (int i = 1; i <= n; i++) {
scanf("%d %d", &pos[i].x, &pos[i].y);
map[pos[i].x][pos[i].y] = 1;
}
for (int i = 1; i <= n; i++){
int xx = pos[i].x, yy = pos[i].y, x, y, cnt = 0;
for (x = xx, y = yy; map[x][y] && y < h; ++y, ++cnt);
for (x = xx, y = yy; map[x][y] && x < w; ++x, ++cnt);
for (x = xx, y = yy; map[x][y] && y >= 0; --y, ++cnt);
for (x = xx, y = yy; map[x][y] && x >= 0; --x, ++cnt);
sum[0][i] = cnt;
}
memset(map, 0, sizeof map);
for (int i = 1; i <= n; i++) {
scanf("%d %d", &pos[i].x, &pos[i].y);
map[pos[i].x][pos[i].y] = 1;
}
for (int i = 1; i <= n; i++){
int xx = pos[i].x, yy = pos[i].y, x, y, cnt = 0;
for (x = xx, y = yy; map[x][y] && y < h; ++y, ++cnt);
for (x = xx, y = yy; map[x][y] && x < w; ++x, ++cnt);
for (x = xx, y = yy; map[x][y] && y >= 0; --y, ++cnt);
for (x = xx, y = yy; map[x][y] && x >= 0; --x, ++cnt);
sum[1][i] = cnt;
}
qsort(sum[0] + 1, n, sizeof(int), compare);
qsort(sum[1] + 1, n, sizeof(int), compare);
int pd = 1;
for (int i = 1; i <= n; i++) if (sum[0][i] != sum[1][i]) {
pd = 0; break;
}
if (!pd) puts("NO");
else puts("YES");
}
return 0;
} | [
"noreply@github.com"
] | zenglh666.noreply@github.com |
f43c3b22b0af0a7c5b2679811a80b85fde2aac58 | 1f40abf77c33ebb9f276f34421ad98e198427186 | /tools/output/stubs/Sim/Projectiles/WeaponProjectiles/EmgProjectile_stub.cpp | 7f9ce2d1a04edd1371adff0aa2b770ce0e28141e | [] | no_license | fzn7/rts | ff0f1f17bc01fe247ea9e6b761738f390ece112e | b63d3f8a72329ace0058fa821f8dd9a2ece1300d | refs/heads/master | 2021-09-04T14:09:26.159157 | 2018-01-19T09:25:56 | 2018-01-19T09:25:56 | 103,816,815 | 0 | 2 | null | 2018-05-22T10:37:40 | 2017-09-17T09:17:14 | C++ | UTF-8 | C++ | false | false | 1,279 | cpp | #include <iostream>
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
#include "EmgProjectile.h"
#include "Game/Camera.h"
#include "Map/Ground.h"
#include "Rendering/GL/VertexArray.h"
#include "Rendering/Textures/TextureAtlas.h"
#include "Sim/Projectiles/ExplosionGenerator.h"
#include "Sim/Projectiles/ProjectileHandler.h"
#include "Sim/Weapons/WeaponDef.h"
#include "System/Sync/SyncTracer.h"
CR_BIND_DERIVED(CEmgProjectile, CWeaponProjectile, )
CR_REG_METADATA(CEmgProjectile,
(CR_SETFLAG(CF_Synced), CR_MEMBER(intensity), CR_MEMBER(color)))
CEmgProjectile::CEmgProjectile(const ProjectileParams& params)
: CWeaponProjectile(params)
{
//stub method
std::cout << _FUNCTION_ << std::endl;
}
void
CEmgProjectile::Update()
{
//stub method
std::cout << _FUNCTION_ << std::endl;
}
void
CEmgProjectile::Draw()
{
//stub method
std::cout << _FUNCTION_ << std::endl;
}
int
CEmgProjectile::ShieldRepulse(const float3& shieldPos,
float shieldForce,
float shieldMaxSpeed)
{
//stub method
std::cout << _FUNCTION_ << std::endl;
}
int
CEmgProjectile::GetProjectilesCount() const
{
//stub method
std::cout << _FUNCTION_ << std::endl;
}
| [
"plotnikov@teamidea.ru"
] | plotnikov@teamidea.ru |
ba17ad4bf7e1146c9057775ceae8bfeec908db6b | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/ThirdParty/ICU/icu4c-53_1/source/test/intltest/dtptngts.cpp | 23786c67e4bb116066aa33ac22574493e7eaf199 | [
"MIT",
"LicenseRef-scancode-proprietary-license",
"ICU",
"NAIST-2003",
"LicenseRef-scancode-unicode",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 54,586 | cpp | /********************************************************************
* COPYRIGHT:
* Copyright (c) 2008-2014, International Business Machines Corporation and
* others. All Rights Reserved.
********************************************************************/
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include <stdio.h>
#include <stdlib.h>
#include "dtptngts.h"
#include "unicode/calendar.h"
#include "unicode/smpdtfmt.h"
#include "unicode/dtfmtsym.h"
#include "unicode/dtptngen.h"
#include "loctest.h"
// This is an API test, not a unit test. It doesn't test very many cases, and doesn't
// try to test the full functionality. It just calls each function in the class and
// verifies that it works on a basic level.
void IntlTestDateTimePatternGeneratorAPI::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ )
{
if (exec) logln("TestSuite DateTimePatternGeneratorAPI");
switch (index) {
TESTCASE(0, testAPI);
TESTCASE(1, testOptions);
TESTCASE(2, testAllFieldPatterns);
default: name = ""; break;
}
}
#define MAX_LOCALE 11
/**
* Test various generic API methods of DateTimePatternGenerator for API coverage.
*/
void IntlTestDateTimePatternGeneratorAPI::testAPI(/*char *par*/)
{
UnicodeString patternData[] = {
UnicodeString("yM"), // 00
UnicodeString("yMMM"), // 01
UnicodeString("yMd"), // 02
UnicodeString("yMMMd"), // 03
UnicodeString("Md"), // 04
UnicodeString("MMMd"), // 05
UnicodeString("MMMMd"), // 06
UnicodeString("yQQQ"), // 07
UnicodeString("hhmm"), // 08
UnicodeString("HHmm"), // 09
UnicodeString("jjmm"), // 10
UnicodeString("mmss"), // 11
UnicodeString("yyyyMMMM"), // 12
UnicodeString("MMMEd"), // 13
UnicodeString("Ed"), // 14
UnicodeString("jmmssSSS"), // 15
UnicodeString("JJmm"), // 16
UnicodeString(),
};
const char* testLocale[MAX_LOCALE][4] = {
{"en", "US", "", ""}, // 0
{"en", "US", "", "calendar=japanese"}, // 1
{"de", "DE", "", ""}, // 2
{"fi", "", "", ""}, // 3
{"es", "", "", ""}, // 4
{"ja", "", "", ""}, // 5
{"ja", "", "", "calendar=japanese"}, // 6
{"zh", "Hans", "CN", ""}, // 7
{"zh", "TW", "", "calendar=roc"}, // 8
{"ru", "", "", ""}, // 9
{"zh", "", "", "calendar=chinese"}, // 10
};
// For Weds, Jan 13, 1999, 23:58:59
UnicodeString patternResults[] = {
// en_US // 0 en_US
UnicodeString("1/1999"), // 00: yM
UnicodeString("Jan 1999"), // 01: yMMM
UnicodeString("1/13/1999"), // 02: yMd
UnicodeString("Jan 13, 1999"), // 03: yMMMd
UnicodeString("1/13"), // 04: Md
UnicodeString("Jan 13"), // 05: MMMd
UnicodeString("January 13"), // 06: MMMMd
UnicodeString("Q1 1999"), // 07: yQQQ
UnicodeString("11:58 PM"), // 08: hhmm
UnicodeString("23:58"), // 09: HHmm
UnicodeString("11:58 PM"), // 10: jjmm
UnicodeString("58:59"), // 11: mmss
UnicodeString("January 1999"), // 12: yyyyMMMM
UnicodeString("Wed, Jan 13"), // 13: MMMEd -> EEE, MMM d
UnicodeString("13 Wed"), // 14: Ed -> d EEE
UnicodeString("11:58:59.123 PM"), // 15: jmmssSSS -> "h:mm:ss.SSS a"
UnicodeString("11:58"), // 16: JJmm
// en_US@calendar=japanese // 1 en_US@calendar=japanese
UnicodeString("1/11 H"), // 0: yM
UnicodeString("Jan 11 Heisei"), // 1: yMMM
UnicodeString("1/13/11 H"), // 2: yMd
UnicodeString("Jan 13, 11 Heisei"), // 3: yMMMd
UnicodeString("1/13"), // 4: Md
UnicodeString("Jan 13"), // 5: MMMd
UnicodeString("January 13"), // 6: MMMMd
UnicodeString("Q1 11 Heisei"), // 7: yQQQ
UnicodeString("11:58 PM"), // 8: hhmm
UnicodeString("23:58"), // 9: HHmm
UnicodeString("11:58 PM"), // 10: jjmm
UnicodeString("58:59"), // 11: mmss
UnicodeString("January 11 Heisei"), // 12: yyyyMMMM
UnicodeString("Wed, Jan 13"), // 13: MMMEd -> EEE, MMM d"
UnicodeString("13 Wed"), // 14: Ed -> d EEE
UnicodeString("11:58:59.123 PM"), // 15: jmmssSSS -> "h:mm:ss.SSS a"
UnicodeString("11:58"), // 16: JJmm
// de_DE // 2 de_DE
UnicodeString("1.1999"), // 00: yM
UnicodeString("Jan. 1999"), // 01: yMMM
UnicodeString("13.1.1999"), // 02: yMd
UnicodeString("13. Jan. 1999"), // 03: yMMMd
UnicodeString("13.1."), // 04: Md
UnicodeString("13. Jan."), // 05: MMMd
UnicodeString("13. Januar"), // 06: MMMMd
UnicodeString("Q1 1999"), // 07: yQQQ
UnicodeString("11:58 nachm."), // 08: hhmm
UnicodeString("23:58"), // 09: HHmm
UnicodeString("23:58"), // 10: jjmm
UnicodeString("58:59"), // 11: mmss
UnicodeString("Januar 1999"), // 12: yyyyMMMM
UnicodeString("Mi., 13. Jan."), // 13: MMMEd -> EEE, d. MMM
UnicodeString("Mi., 13."), // 14: Ed -> EEE d.
UnicodeString("23:58:59,123"), // 15: jmmssSSS -> "HH:mm:ss,SSS"
UnicodeString("23:58"), // 16: JJmm
// fi // 3 fi
UnicodeString("1.1999"), // 00: yM (fixed expected result per ticket:6626:)
UnicodeString("tammi 1999"), // 01: yMMM
UnicodeString("13.1.1999"), // 02: yMd
UnicodeString("13. tammikuuta 1999"), // 03: yMMMd
UnicodeString("13.1."), // 04: Md
UnicodeString("13. tammikuuta"), // 05: MMMd
UnicodeString("13. tammikuuta"), // 06: MMMMd
UnicodeString("1. nelj. 1999"), // 07: yQQQ
UnicodeString("11.58 ip."), // 08: hhmm
UnicodeString("23.58"), // 09: HHmm
UnicodeString("23.58"), // 10: jjmm
UnicodeString("58.59"), // 11: mmss
UnicodeString("tammikuu 1999"), // 12: yyyyMMMM
UnicodeString("ke 13. tammikuuta"), // 13: MMMEd -> EEE d. MMM
UnicodeString("ke 13."), // 14: Ed -> ccc d.
UnicodeString("23.58.59,123"), // 15: jmmssSSS -> "H.mm.ss,SSS"
UnicodeString("23.58"), // 16: JJmm
// es // 4 es
UnicodeString("1/1999"), // 00: yM -> "M/y"
UnicodeString("ene. de 1999"), // 01: yMMM -> "MMM 'de' y"
UnicodeString("13/1/1999"), // 02: yMd -> "d/M/y"
UnicodeString("13 de ene. de 1999"), // 03: yMMMd -> "d 'de' MMM 'de' y"
UnicodeString("13/1"), // 04: Md -> "d/M"
UnicodeString("13 de ene."), // 05: MMMd -> "d 'de' MMM"
UnicodeString("13 de enero"), // 06: MMMMd -> "d 'de' MMMM"
UnicodeString("T1 1999"), // 07: yQQQ -> "QQQ y"
UnicodeString("11:58 p. m."), // 08: hhmm -> "hh:mm a"
UnicodeString("23:58"), // 09: HHmm -> "HH:mm"
UnicodeString("23:58"), // 10: jjmm -> "HH:mm"
UnicodeString("58:59"), // 11: mmss -> "mm:ss"
UnicodeString("enero de 1999"), // 12: yyyyMMMM -> "MMMM 'de' yyyy"
CharsToUnicodeString("mi\\u00E9. 13 de ene."), // 13: MMMEd -> "E d 'de' MMM"
CharsToUnicodeString("mi\\u00E9. 13"), // 14: Ed -> "EEE d"
UnicodeString("23:58:59,123"), // 15: jmmssSSS -> "H:mm:ss,SSS"
UnicodeString("23:58"), // 16: JJmm
// ja // 5 ja
UnicodeString("1999/1"), // 00: yM -> y/M
CharsToUnicodeString("1999\\u5E741\\u6708"), // 01: yMMM -> y\u5E74M\u6708
UnicodeString("1999/1/13"), // 02: yMd -> y/M/d
CharsToUnicodeString("1999\\u5E741\\u670813\\u65E5"), // 03: yMMMd -> y\u5E74M\u6708d\u65E5
UnicodeString("1/13"), // 04: Md -> M/d
CharsToUnicodeString("1\\u670813\\u65E5"), // 05: MMMd -> M\u6708d\u65E5
CharsToUnicodeString("1\\u670813\\u65E5"), // 06: MMMMd -> M\u6708d\u65E5
CharsToUnicodeString("1999/Q1"), // 07: yQQQ -> y/QQQ
CharsToUnicodeString("\\u5348\\u5F8C11:58"), // 08: hhmm
UnicodeString("23:58"), // 09: HHmm -> HH:mm
UnicodeString("23:58"), // 10: jjmm
UnicodeString("58:59"), // 11: mmss -> mm:ss
CharsToUnicodeString("1999\\u5E741\\u6708"), // 12: yyyyMMMM -> y\u5E74M\u6708
CharsToUnicodeString("1\\u670813\\u65E5(\\u6C34)"), // 13: MMMEd -> M\u6708d\u65E5(EEE)
CharsToUnicodeString("13\\u65E5(\\u6C34)"), // 14: Ed -> d\u65E5(EEE)
UnicodeString("23:58:59.123"), // 15: jmmssSSS -> "H:mm:ss.SSS"
UnicodeString("23:58"), // 16: JJmm
// ja@calendar=japanese // 6 ja@calendar=japanese
CharsToUnicodeString("\\u5E73\\u621011/1"), // 00: yM -> Gy/m
CharsToUnicodeString("\\u5E73\\u621011\\u5E741\\u6708"), // 01: yMMM -> Gy\u5E74M\u6708
CharsToUnicodeString("\\u5E73\\u621011/1/13"), // 02: yMd -> Gy/m/d
CharsToUnicodeString("\\u5E73\\u621011\\u5E741\\u670813\\u65E5"), // 03: yMMMd -> Gy\u5E74M\u6708d\u65E5
UnicodeString("1/13"), // 04: Md -> M/d
CharsToUnicodeString("1\\u670813\\u65E5"), // 05: MMMd -> M\u6708d\u65E5
CharsToUnicodeString("1\\u670813\\u65E5"), // 06: MMMMd -> M\u6708d\u65E5
CharsToUnicodeString("\\u5E73\\u6210 11 Q1"), // 07: yQQQ -> G y QQQ
CharsToUnicodeString("\\u5348\\u5F8C11:58"), // 08: hhmm ->
UnicodeString("23:58"), // 09: HHmm -> HH:mm (as for ja)
UnicodeString("23:58"), // 10: jjmm
UnicodeString("58:59"), // 11: mmss -> mm:ss (as for ja)
CharsToUnicodeString("\\u5E73\\u621011\\u5E741\\u6708"), // 12: yyyyMMMM -> Gyyyy\u5E74M\u6708
CharsToUnicodeString("1\\u670813\\u65E5(\\u6C34)"), // 13: MMMEd -> M\u6708d\u65E5(EEE)
CharsToUnicodeString("13\\u65E5(\\u6C34)"), // 14: Ed -> d\u65E5(EEE)
UnicodeString("23:58:59.123"), // 15: jmmssSSS -> "H:mm:ss.SSS"
UnicodeString("23:58"), // 16: JJmm
// zh_Hans_CN // 7 zh_Hans_CN
UnicodeString("1999/1", -1, US_INV), // 00: yM
CharsToUnicodeString("1999\\u5E741\\u6708"), // 01: yMMM -> yyyy\u5E74MMM (fixed expected result per ticket:6626:)
CharsToUnicodeString("1999/1/13"), // 02: yMd
CharsToUnicodeString("1999\\u5E741\\u670813\\u65E5"), // 03: yMMMd -> yyyy\u5E74MMMd\u65E5 (fixed expected result per ticket:6626:)
UnicodeString("1/13"), // 04: Md
CharsToUnicodeString("1\\u670813\\u65E5"), // 05: MMMd -> M\u6708d\u65E5 (fixed expected result per ticket:6626:)
CharsToUnicodeString("1\\u670813\\u65E5"), // 06: MMMMd -> M\u6708d\u65E5
CharsToUnicodeString("1999\\u5E74\\u7B2C1\\u5B63\\u5EA6"), // 07: yQQQ
CharsToUnicodeString("\\u4E0B\\u534811:58"), // 08: hhmm
UnicodeString("23:58"), // 09: HHmm
CharsToUnicodeString("\\u4E0B\\u534811:58"), // 10: jjmm
UnicodeString("58:59"), // 11: mmss
CharsToUnicodeString("1999\\u5E741\\u6708"), // 12: yyyyMMMM -> yyyy\u5E74MMM
CharsToUnicodeString("1\\u670813\\u65E5\\u5468\\u4E09"), // 13: MMMEd -> MMMd\u65E5EEE
CharsToUnicodeString("13\\u65E5\\u5468\\u4E09"), // 14: Ed -> d\u65E5EEE
CharsToUnicodeString("\\u4E0B\\u534811:58:59.123"), // 15: jmmssSSS -> "ah:mm:ss.SSS"
UnicodeString("11:58"), // 16: JJmm
// zh_TW@calendar=roc // 8 zh_TW@calendar=roc
CharsToUnicodeString("\\u6C11\\u570B88/1"), // 00: yM -> Gy/M
CharsToUnicodeString("\\u6C11\\u570B88\\u5E741\\u6708"), // 01: yMMM -> Gy\u5E74M\u6708
CharsToUnicodeString("\\u6C11\\u570B88/1/13"), // 02: yMd -> Gy/M/d
CharsToUnicodeString("\\u6C11\\u570B88\\u5E741\\u670813\\u65E5"), // 03: yMMMd -> Gy\u5E74M\u6708d\u65E5
UnicodeString("1/13"), // 04: Md -> M/d
CharsToUnicodeString("1\\u670813\\u65E5"), // 05: MMMd ->M\u6708d\u65E5
CharsToUnicodeString("1\\u670813\\u65E5"), // 06: MMMMd ->M\u6708d\u65E5
CharsToUnicodeString("\\u6C11\\u570B88\\u5E741\\u5B63"), // 07: yQQQ -> Gy QQQ
CharsToUnicodeString("\\u4E0B\\u534811:58"), // 08: hhmm ->
UnicodeString("23:58"), // 09: HHmm ->
CharsToUnicodeString("\\u4E0B\\u534811:58"), // 10: jjmm
UnicodeString("58:59"), // 11: mmss ->
CharsToUnicodeString("\\u6C11\\u570B88\\u5E741\\u6708"), // 12: yyyyMMMM -> Gy\u5E74M\u670
CharsToUnicodeString("1\\u670813\\u65E5\\u9031\\u4E09"), // 13: MMMEd -> M\u6708d\u65E5EEE
CharsToUnicodeString("13\\u65E5\\uff08\\u9031\\u4E09\\uff09"), // 14: Ed -> d\u65E5\\uff08EEEi\\uff09
CharsToUnicodeString("\\u4E0B\\u534811:58:59.123"), // 15: jmmssSSS -> "ah:mm:ss.SSS"
UnicodeString("11:58"), // 16: JJmm
// ru // 9 ru
UnicodeString("01.1999"), // 00: yM -> MM.y
CharsToUnicodeString("\\u042F\\u043D\\u0432. 1999"), // 01: yMMM -> LLL y
UnicodeString("13.01.1999"), // 02: yMd -> dd.MM.y
CharsToUnicodeString("13 \\u044F\\u043D\\u0432. 1999 \\u0433."), // 03: yMMMd -> d MMM y
UnicodeString("13.01"), // 04: Md -> dd.MM
CharsToUnicodeString("13 \\u044F\\u043D\\u0432."), // 05: MMMd -> d MMM
CharsToUnicodeString("13 \\u044F\\u043D\\u0432\\u0430\\u0440\\u044F"), // 06: MMMMd -> d MMMM
CharsToUnicodeString("1-\\u0439 \\u043A\\u0432. 1999 \\u0433."), // 07: yQQQ -> y QQQ
UnicodeString("11:58 PM"), // 07: hhmm -> hh:mm a
UnicodeString("23:58"), // 09: HHmm -> HH:mm
UnicodeString("23:58"), // 10: jjmm -> HH:mm
UnicodeString("58:59"), // 11: mmss -> mm:ss
CharsToUnicodeString("\\u042F\\u043D\\u0432\\u0430\\u0440\\u044C 1999"), // 12: yyyyMMMM -> LLLL y
CharsToUnicodeString("\\u0421\\u0440, 13 \\u044F\\u043D\\u0432."), // 13: MMMEd -> ccc, d MMM
CharsToUnicodeString("\\u0421\\u0440, 13"), // 14: Ed -> EEE, d
UnicodeString("23:58:59,123"), // 15: jmmssSSS -> "H:mm:ss,SSS"
UnicodeString("23:58"), // 16: JJmm
// zh@calendar=chinese // 10 zh@calendar=chinese
CharsToUnicodeString("\\u620A\\u5BC5\\u5E74\\u51AC\\u6708"), // 00: yMMM
CharsToUnicodeString("\\u620A\\u5BC5\\u5E74\\u51AC\\u6708"), // 01: yMMM
CharsToUnicodeString("\\u620A\\u5BC5\\u5E74\\u51AC\\u670826\\u65E5"), // 02: yMMMd
CharsToUnicodeString("\\u620A\\u5BC5\\u5E74\\u51AC\\u670826\\u65E5"), // 03: yMMMd
UnicodeString("11-26"), // 04: Md
CharsToUnicodeString("\\u51AC\\u670826\\u65E5"), // 05: MMMd
CharsToUnicodeString("\\u51AC\\u670826\\u65E5"), // 06: MMMMd
CharsToUnicodeString("\\u620A\\u5BC5\\u5E74\\u7b2c\\u56db\\u5B63\\u5EA6"), // 07: yQQQ
CharsToUnicodeString("\\u4E0B\\u534811:58"), // 08: hhmm
UnicodeString("23:58"), // 09: HHmm
CharsToUnicodeString("\\u4E0B\\u534811:58"), // 10: jjmm
UnicodeString("58:59"), // 11: mmss
CharsToUnicodeString("\\u620A\\u5BC5\\u5E74\\u51AC\\u6708"), // 12: yyyyMMMM
CharsToUnicodeString("\\u51AC\\u670826\\u65E5\\u5468\\u4E09"), // 13: MMMEd
CharsToUnicodeString("26\\u65E5\\u5468\\u4E09"), // 14: Ed -> d\u65E5EEE
CharsToUnicodeString("\\u4E0B\\u534811:58:59.123"), // 15: jmmssSS
UnicodeString("11:58"), // 16: JJmm
UnicodeString(),
};
UnicodeString patternTests2[] = {
UnicodeString("yyyyMMMdd"),
UnicodeString("yyyyqqqq"),
UnicodeString("yMMMdd"),
UnicodeString("EyyyyMMMdd"),
UnicodeString("yyyyMMdd"),
UnicodeString("yyyyMMM"),
UnicodeString("yyyyMM"),
UnicodeString("yyMM"),
UnicodeString("yMMMMMd"),
UnicodeString("EEEEEMMMMMd"),
UnicodeString("MMMd"),
UnicodeString("MMMdhmm"),
UnicodeString("EMMMdhmms"),
UnicodeString("MMdhmm"),
UnicodeString("EEEEMMMdhmms"),
UnicodeString("yyyyMMMddhhmmss"),
UnicodeString("EyyyyMMMddhhmmss"),
UnicodeString("hmm"),
UnicodeString("hhmm"),
UnicodeString("hhmmVVVV"),
UnicodeString(""),
};
UnicodeString patternResults2[] = {
UnicodeString("Oct 14, 1999"),
UnicodeString("4th quarter 1999"),
UnicodeString("Oct 14, 1999"),
UnicodeString("Thu, Oct 14, 1999"),
UnicodeString("10/14/1999"),
UnicodeString("Oct 1999"),
UnicodeString("10/1999"),
UnicodeString("10/99"),
UnicodeString("O 14, 1999"),
UnicodeString("T, O 14"),
UnicodeString("Oct 14"),
UnicodeString("Oct 14, 6:58 AM"),
UnicodeString("Thu, Oct 14, 6:58:59 AM"),
UnicodeString("10/14, 6:58 AM"),
UnicodeString("Thursday, Oct 14, 6:58:59 AM"),
UnicodeString("Oct 14, 1999, 6:58:59 AM"),
UnicodeString("Thu, Oct 14, 1999, 6:58:59 AM"),
UnicodeString("6:58 AM"),
UnicodeString("6:58 AM"),
UnicodeString("6:58 AM GMT"),
UnicodeString(""),
};
// results for getSkeletons() and getPatternForSkeleton()
const UnicodeString testSkeletonsResults[] = {
UnicodeString("HH:mm"),
UnicodeString("MMMMd"),
UnicodeString("MMMMMdd"),
};
const UnicodeString testBaseSkeletonsResults[] = {
UnicodeString("Hm"),
UnicodeString("MMMMd"),
UnicodeString("MMMMMd"),
};
UnicodeString newDecimal(" "); // space
UnicodeString newAppendItemName("hrs.");
UnicodeString newAppendItemFormat("{1} {0}");
UnicodeString newDateTimeFormat("{1} {0}");
UErrorCode status = U_ZERO_ERROR;
UnicodeString conflictingPattern;
UDateTimePatternConflict conflictingStatus = UDATPG_NO_CONFLICT;
(void)conflictingStatus; // Suppress set but not used warning.
// ======= Test CreateInstance with default locale
logln("Testing DateTimePatternGenerator createInstance from default locale");
DateTimePatternGenerator *instFromDefaultLocale=DateTimePatternGenerator::createInstance(status);
if (U_FAILURE(status)) {
dataerrln("ERROR: Could not create DateTimePatternGenerator (default) - exitting");
return;
}
else {
delete instFromDefaultLocale;
}
// ======= Test CreateInstance with given locale
logln("Testing DateTimePatternGenerator createInstance from French locale");
status = U_ZERO_ERROR;
DateTimePatternGenerator *instFromLocale=DateTimePatternGenerator::createInstance(Locale::getFrench(), status);
if (U_FAILURE(status)) {
dataerrln("ERROR: Could not create DateTimePatternGenerator (Locale::getFrench()) - exitting");
return;
}
// ======= Test clone DateTimePatternGenerator
logln("Testing DateTimePatternGenerator::clone()");
status = U_ZERO_ERROR;
UnicodeString decimalSymbol = instFromLocale->getDecimal();
UnicodeString newDecimalSymbol = UnicodeString("*");
decimalSymbol = instFromLocale->getDecimal();
instFromLocale->setDecimal(newDecimalSymbol);
DateTimePatternGenerator *cloneDTPatternGen=instFromLocale->clone();
decimalSymbol = cloneDTPatternGen->getDecimal();
if (decimalSymbol != newDecimalSymbol) {
errln("ERROR: inconsistency is found in cloned object.");
}
if ( !(*cloneDTPatternGen == *instFromLocale) ) {
errln("ERROR: inconsistency is found in cloned object.");
}
if ( *cloneDTPatternGen != *instFromLocale ) {
errln("ERROR: inconsistency is found in cloned object.");
}
delete instFromLocale;
delete cloneDTPatternGen;
// ======= Test simple use cases
logln("Testing simple use cases");
status = U_ZERO_ERROR;
Locale deLocale=Locale::getGermany();
UDate sampleDate=LocaleTest::date(99, 9, 13, 23, 58, 59);
DateTimePatternGenerator *gen = DateTimePatternGenerator::createInstance(deLocale, status);
if (U_FAILURE(status)) {
dataerrln("ERROR: Could not create DateTimePatternGenerator (Locale::getGermany()) - exitting");
return;
}
UnicodeString findPattern = gen->getBestPattern(UnicodeString("MMMddHmm"), status);
SimpleDateFormat *format = new SimpleDateFormat(findPattern, deLocale, status);
if (U_FAILURE(status)) {
dataerrln("ERROR: Could not create SimpleDateFormat (Locale::getGermany())");
delete gen;
return;
}
TimeZone *zone = TimeZone::createTimeZone(UnicodeString("ECT"));
if (zone==NULL) {
dataerrln("ERROR: Could not create TimeZone ECT");
delete gen;
delete format;
return;
}
format->setTimeZone(*zone);
UnicodeString dateReturned, expectedResult;
dateReturned.remove();
dateReturned = format->format(sampleDate, dateReturned, status);
expectedResult=UnicodeString("14. Okt. 08:58", -1, US_INV);
if ( dateReturned != expectedResult ) {
errln("ERROR: Simple test in getBestPattern with Locale::getGermany()).");
}
// add new pattern
status = U_ZERO_ERROR;
conflictingStatus = gen->addPattern(UnicodeString("d'. von' MMMM", -1, US_INV), true, conflictingPattern, status);
if (U_FAILURE(status)) {
errln("ERROR: Could not addPattern - d\'. von\' MMMM");
}
status = U_ZERO_ERROR;
UnicodeString testPattern=gen->getBestPattern(UnicodeString("MMMMdd"), status);
testPattern=gen->getBestPattern(UnicodeString("MMMddHmm"), status);
format->applyPattern(gen->getBestPattern(UnicodeString("MMMMdHmm"), status));
dateReturned.remove();
dateReturned = format->format(sampleDate, dateReturned, status);
expectedResult=UnicodeString("14. von Oktober 08:58", -1, US_INV);
if ( dateReturned != expectedResult ) {
errln(UnicodeString("ERROR: Simple test addPattern failed!: d\'. von\' MMMM Got: ") + dateReturned + UnicodeString(" Expected: ") + expectedResult);
}
delete format;
// get a pattern and modify it
format = (SimpleDateFormat *)DateFormat::createDateTimeInstance(DateFormat::kFull, DateFormat::kFull,
deLocale);
format->setTimeZone(*zone);
UnicodeString pattern;
pattern = format->toPattern(pattern);
dateReturned.remove();
dateReturned = format->format(sampleDate, dateReturned, status);
expectedResult=CharsToUnicodeString("Donnerstag, 14. Oktober 1999 08:58:59 Mitteleurop\\u00E4ische Sommerzeit");
if ( dateReturned != expectedResult ) {
errln("ERROR: Simple test uses full date format.");
errln(UnicodeString(" Got: ") + dateReturned + UnicodeString(" Expected: ") + expectedResult);
}
// modify it to change the zone.
UnicodeString newPattern = gen->replaceFieldTypes(pattern, UnicodeString("vvvv"), status);
format->applyPattern(newPattern);
dateReturned.remove();
dateReturned = format->format(sampleDate, dateReturned, status);
expectedResult=CharsToUnicodeString("Donnerstag, 14. Oktober 1999 08:58:59 Mitteleurop\\u00E4ische Zeit");
if ( dateReturned != expectedResult ) {
errln("ERROR: Simple test modify the timezone!");
errln(UnicodeString(" Got: ")+ dateReturned + UnicodeString(" Expected: ") + expectedResult);
}
// setDeciaml(), getDeciaml()
gen->setDecimal(newDecimal);
if (newDecimal != gen->getDecimal()) {
errln("ERROR: unexpected result from setDecimal() and getDecimal()!.\n");
}
// setAppenItemName() , getAppendItemName()
gen->setAppendItemName(UDATPG_HOUR_FIELD, newAppendItemName);
if (newAppendItemName != gen->getAppendItemName(UDATPG_HOUR_FIELD)) {
errln("ERROR: unexpected result from setAppendItemName() and getAppendItemName()!.\n");
}
// setAppenItemFormat() , getAppendItemFormat()
gen->setAppendItemFormat(UDATPG_HOUR_FIELD, newAppendItemFormat);
if (newAppendItemFormat != gen->getAppendItemFormat(UDATPG_HOUR_FIELD)) {
errln("ERROR: unexpected result from setAppendItemFormat() and getAppendItemFormat()!.\n");
}
// setDateTimeFormat() , getDateTimeFormat()
gen->setDateTimeFormat(newDateTimeFormat);
if (newDateTimeFormat != gen->getDateTimeFormat()) {
errln("ERROR: unexpected result from setDateTimeFormat() and getDateTimeFormat()!.\n");
}
// ======== Test getSkeleton and getBaseSkeleton
status = U_ZERO_ERROR;
pattern = UnicodeString("dd-MMM");
UnicodeString expectedSkeleton = UnicodeString("MMMdd");
UnicodeString expectedBaseSkeleton = UnicodeString("MMMd");
UnicodeString retSkeleton = gen->getSkeleton(pattern, status);
if(U_FAILURE(status) || retSkeleton != expectedSkeleton ) {
errln("ERROR: Unexpected result from getSkeleton().\n");
errln(UnicodeString(" Got: ") + retSkeleton + UnicodeString(" Expected: ") + expectedSkeleton );
}
retSkeleton = gen->getBaseSkeleton(pattern, status);
if(U_FAILURE(status) || retSkeleton != expectedBaseSkeleton) {
errln("ERROR: Unexpected result from getBaseSkeleton().\n");
errln(UnicodeString(" Got: ") + retSkeleton + UnicodeString(" Expected:")+ expectedBaseSkeleton);
}
pattern = UnicodeString("dd/MMMM/yy");
expectedSkeleton = UnicodeString("yyMMMMdd");
expectedBaseSkeleton = UnicodeString("yMMMMd");
retSkeleton = gen->getSkeleton(pattern, status);
if(U_FAILURE(status) || retSkeleton != expectedSkeleton ) {
errln("ERROR: Unexpected result from getSkeleton().\n");
errln(UnicodeString(" Got: ") + retSkeleton + UnicodeString(" Expected: ") + expectedSkeleton );
}
retSkeleton = gen->getBaseSkeleton(pattern, status);
if(U_FAILURE(status) || retSkeleton != expectedBaseSkeleton) {
errln("ERROR: Unexpected result from getBaseSkeleton().\n");
errln(UnicodeString(" Got: ") + retSkeleton + UnicodeString(" Expected:")+ expectedBaseSkeleton);
}
delete format;
delete zone;
delete gen;
{
// Trac# 6104
status = U_ZERO_ERROR;
pattern = UnicodeString("YYYYMMM");
UnicodeString expR = CharsToUnicodeString("1999\\u5E741\\u6708"); // fixed expected result per ticket:6626:
Locale loc("ja");
UDate testDate1= LocaleTest::date(99, 0, 13, 23, 58, 59);
DateTimePatternGenerator *patGen=DateTimePatternGenerator::createInstance(loc, status);
if(U_FAILURE(status)) {
dataerrln("ERROR: Could not create DateTimePatternGenerator");
return;
}
UnicodeString bPattern = patGen->getBestPattern(pattern, status);
UnicodeString rDate;
SimpleDateFormat sdf(bPattern, loc, status);
rDate.remove();
rDate = sdf.format(testDate1, rDate);
logln(UnicodeString(" ja locale with skeleton: YYYYMMM Best Pattern:") + bPattern);
logln(UnicodeString(" Formatted date:") + rDate);
if ( expR!= rDate ) {
errln(UnicodeString("\nERROR: Test Japanese month hack Got: ") + rDate +
UnicodeString(" Expected: ") + expR );
}
delete patGen;
}
{ // Trac# 6104
Locale loc("zh");
UnicodeString expR = CharsToUnicodeString("1999\\u5E741\\u6708"); // fixed expected result per ticket:6626:
UDate testDate1= LocaleTest::date(99, 0, 13, 23, 58, 59);
DateTimePatternGenerator *patGen=DateTimePatternGenerator::createInstance(loc, status);
if(U_FAILURE(status)) {
dataerrln("ERROR: Could not create DateTimePatternGenerator");
return;
}
UnicodeString bPattern = patGen->getBestPattern(pattern, status);
UnicodeString rDate;
SimpleDateFormat sdf(bPattern, loc, status);
rDate.remove();
rDate = sdf.format(testDate1, rDate);
logln(UnicodeString(" zh locale with skeleton: YYYYMMM Best Pattern:") + bPattern);
logln(UnicodeString(" Formatted date:") + rDate);
if ( expR!= rDate ) {
errln(UnicodeString("\nERROR: Test Chinese month hack Got: ") + rDate +
UnicodeString(" Expected: ") + expR );
}
delete patGen;
}
{
// Trac# 6172 duplicate time pattern
status = U_ZERO_ERROR;
pattern = UnicodeString("hmv");
UnicodeString expR = UnicodeString("h:mm a v"); // avail formats has hm -> "h:mm a" (fixed expected result per ticket:6626:)
Locale loc("en");
DateTimePatternGenerator *patGen=DateTimePatternGenerator::createInstance(loc, status);
if(U_FAILURE(status)) {
dataerrln("ERROR: Could not create DateTimePatternGenerator");
return;
}
UnicodeString bPattern = patGen->getBestPattern(pattern, status);
logln(UnicodeString(" en locale with skeleton: hmv Best Pattern:") + bPattern);
if ( expR!= bPattern ) {
errln(UnicodeString("\nERROR: Test EN time format Got: ") + bPattern +
UnicodeString(" Expected: ") + expR );
}
delete patGen;
}
// ======= Test various skeletons.
logln("Testing DateTimePatternGenerator with various skeleton");
status = U_ZERO_ERROR;
int32_t localeIndex=0;
int32_t resultIndex=0;
UnicodeString resultDate;
UDate testDate= LocaleTest::date(99, 0, 13, 23, 58, 59) + 123.0;
while (localeIndex < MAX_LOCALE )
{
int32_t dataIndex=0;
UnicodeString bestPattern;
Locale loc(testLocale[localeIndex][0], testLocale[localeIndex][1], testLocale[localeIndex][2], testLocale[localeIndex][3]);
logln("\n\n Locale: %s_%s_%s@%s", testLocale[localeIndex][0], testLocale[localeIndex][1], testLocale[localeIndex][2], testLocale[localeIndex][3]);
DateTimePatternGenerator *patGen=DateTimePatternGenerator::createInstance(loc, status);
if(U_FAILURE(status)) {
dataerrln("ERROR: Could not create DateTimePatternGenerator with locale index:%d . - exitting\n", localeIndex);
return;
}
while (patternData[dataIndex].length() > 0) {
log(patternData[dataIndex]);
bestPattern = patGen->getBestPattern(patternData[dataIndex++], status);
logln(UnicodeString(" -> ") + bestPattern);
SimpleDateFormat sdf(bestPattern, loc, status);
resultDate.remove();
resultDate = sdf.format(testDate, resultDate);
if ( resultDate != patternResults[resultIndex] ) {
errln(UnicodeString("\nERROR: Test various skeletons[") + (dataIndex-1) + UnicodeString("], localeIndex ") + localeIndex +
UnicodeString(". Got: \"") + resultDate + UnicodeString("\" Expected: \"") + patternResults[resultIndex] + "\"" );
}
resultIndex++;
}
delete patGen;
localeIndex++;
}
// ======= More tests ticket#6110
logln("Testing DateTimePatternGenerator with various skeleton");
status = U_ZERO_ERROR;
localeIndex=0;
resultIndex=0;
testDate= LocaleTest::date(99, 9, 13, 23, 58, 59);
{
int32_t dataIndex=0;
UnicodeString bestPattern;
logln("\n\n Test various skeletons for English locale...");
DateTimePatternGenerator *patGen=DateTimePatternGenerator::createInstance(Locale::getEnglish(), status);
if(U_FAILURE(status)) {
dataerrln("ERROR: Could not create DateTimePatternGenerator with locale English . - exitting\n");
return;
}
TimeZone *enZone = TimeZone::createTimeZone(UnicodeString("ECT/GMT"));
if (enZone==NULL) {
dataerrln("ERROR: Could not create TimeZone ECT");
delete patGen;
return;
}
SimpleDateFormat *enFormat = (SimpleDateFormat *)DateFormat::createDateTimeInstance(DateFormat::kFull,
DateFormat::kFull, Locale::getEnglish());
enFormat->setTimeZone(*enZone);
while (patternTests2[dataIndex].length() > 0) {
logln(patternTests2[dataIndex]);
bestPattern = patGen->getBestPattern(patternTests2[dataIndex], status);
logln(UnicodeString(" -> ") + bestPattern);
enFormat->applyPattern(bestPattern);
resultDate.remove();
resultDate = enFormat->format(testDate, resultDate);
if ( resultDate != patternResults2[resultIndex] ) {
errln(UnicodeString("\nERROR: Test various skeletons[") + dataIndex
+ UnicodeString("]. Got: ") + resultDate + UnicodeString(" Expected: ") +
patternResults2[resultIndex] );
}
dataIndex++;
resultIndex++;
}
delete patGen;
delete enZone;
delete enFormat;
}
// ======= Test random skeleton
DateTimePatternGenerator *randDTGen= DateTimePatternGenerator::createInstance(status);
if (U_FAILURE(status)) {
dataerrln("ERROR: Could not create DateTimePatternGenerator (Locale::getFrench()) - exitting");
return;
}
UChar newChar;
int32_t i;
for (i=0; i<10; ++i) {
UnicodeString randomSkeleton;
int32_t len = rand() % 20;
for (int32_t j=0; j<len; ++j ) {
while ((newChar = (UChar)(rand()%0x7f))>=(UChar)0x20) {
randomSkeleton += newChar;
}
}
UnicodeString bestPattern = randDTGen->getBestPattern(randomSkeleton, status);
}
delete randDTGen;
// UnicodeString randomString=Unicode
// ======= Test getStaticClassID()
logln("Testing getStaticClassID()");
status = U_ZERO_ERROR;
DateTimePatternGenerator *test= DateTimePatternGenerator::createInstance(status);
if(test->getDynamicClassID() != DateTimePatternGenerator::getStaticClassID()) {
errln("ERROR: getDynamicClassID() didn't return the expected value");
}
delete test;
// ====== Test createEmptyInstance()
logln("Testing createEmptyInstance()");
status = U_ZERO_ERROR;
test = DateTimePatternGenerator::createEmptyInstance(status);
if(U_FAILURE(status)) {
errln("ERROR: Fail to create an empty instance ! - exitting.\n");
delete test;
return;
}
conflictingStatus = test->addPattern(UnicodeString("MMMMd"), true, conflictingPattern, status);
status = U_ZERO_ERROR;
testPattern=test->getBestPattern(UnicodeString("MMMMdd"), status);
conflictingStatus = test->addPattern(UnicodeString("HH:mm"), true, conflictingPattern, status);
conflictingStatus = test->addPattern(UnicodeString("MMMMMdd"), true, conflictingPattern, status); //duplicate pattern
StringEnumeration *output=NULL;
output = test->getRedundants(status);
expectedResult=UnicodeString("MMMMd");
if (output != NULL) {
output->reset(status);
const UnicodeString *dupPattern=output->snext(status);
if ( (dupPattern==NULL) || (*dupPattern != expectedResult) ) {
errln("ERROR: Fail in getRedundants !\n");
}
}
// ======== Test getSkeletons and getBaseSkeletons
StringEnumeration* ptrSkeletonEnum = test->getSkeletons(status);
if(U_FAILURE(status)) {
errln("ERROR: Fail to get skeletons !\n");
}
UnicodeString returnPattern, *ptrSkeleton;
ptrSkeletonEnum->reset(status);
int32_t count=ptrSkeletonEnum->count(status);
for (i=0; i<count; ++i) {
ptrSkeleton = (UnicodeString *)ptrSkeletonEnum->snext(status);
returnPattern = test->getPatternForSkeleton(*ptrSkeleton);
if ( returnPattern != testSkeletonsResults[i] ) {
errln(UnicodeString("ERROR: Unexpected result from getSkeletons and getPatternForSkeleton\nGot: ") + returnPattern
+ UnicodeString("\nExpected: ") + testSkeletonsResults[i]
+ UnicodeString("\n"));
}
}
StringEnumeration* ptrBaseSkeletonEnum = test->getBaseSkeletons(status);
if(U_FAILURE(status)) {
errln("ERROR: Fail to get base skeletons !\n");
}
count=ptrBaseSkeletonEnum->count(status);
for (i=0; i<count; ++i) {
ptrSkeleton = (UnicodeString *)ptrBaseSkeletonEnum->snext(status);
if ( *ptrSkeleton != testBaseSkeletonsResults[i] ) {
errln("ERROR: Unexpected result from getBaseSkeletons() !\n");
}
}
// ========= DateTimePatternGenerator sample code in Userguide
// set up the generator
Locale locale = Locale::getFrench();
status = U_ZERO_ERROR;
DateTimePatternGenerator *generator = DateTimePatternGenerator::createInstance( locale, status);
// get a pattern for an abbreviated month and day
pattern = generator->getBestPattern(UnicodeString("MMMd"), status);
SimpleDateFormat formatter(pattern, locale, status);
zone = TimeZone::createTimeZone(UnicodeString("GMT"));
formatter.setTimeZone(*zone);
// use it to format (or parse)
UnicodeString formatted;
formatted = formatter.format(Calendar::getNow(), formatted, status);
// for French, the result is "13 sept."
formatted.remove();
// cannot use the result from getNow() because the value change evreyday.
testDate= LocaleTest::date(99, 0, 13, 23, 58, 59);
formatted = formatter.format(testDate, formatted, status);
expectedResult=UnicodeString("14 janv.");
if ( formatted != expectedResult ) {
errln("ERROR: Userguide sample code result!");
errln(UnicodeString(" Got: ")+ formatted + UnicodeString(" Expected: ") + expectedResult);
}
delete zone;
delete output;
delete ptrSkeletonEnum;
delete ptrBaseSkeletonEnum;
delete test;
delete generator;
}
/**
* Test handling of options
*
* For reference, as of ICU 4.3.3,
* root/gregorian has
* Hm{"H:mm"}
* Hms{"H:mm:ss"}
* hm{"h:mm a"}
* hms{"h:mm:ss a"}
* en/gregorian has
* Hm{"H:mm"}
* Hms{"H:mm:ss"}
* hm{"h:mm a"}
* be/gregorian has
* HHmmss{"HH.mm.ss"}
* Hm{"HH.mm"}
* hm{"h.mm a"}
* hms{"h.mm.ss a"}
*/
typedef struct DTPtnGenOptionsData {
const char *locale;
const char *skel;
const char *expectedPattern;
UDateTimePatternMatchOptions options;
} DTPtnGenOptionsData;
void IntlTestDateTimePatternGeneratorAPI::testOptions(/*char *par*/)
{
DTPtnGenOptionsData testData[] = {
// locale skel expectedPattern options
{ "en", "Hmm", "HH:mm", UDATPG_MATCH_NO_OPTIONS },
{ "en", "HHmm", "HH:mm", UDATPG_MATCH_NO_OPTIONS },
{ "en", "hhmm", "h:mm a", UDATPG_MATCH_NO_OPTIONS },
{ "en", "Hmm", "HH:mm", UDATPG_MATCH_HOUR_FIELD_LENGTH },
{ "en", "HHmm", "HH:mm", UDATPG_MATCH_HOUR_FIELD_LENGTH },
{ "en", "hhmm", "hh:mm a", UDATPG_MATCH_HOUR_FIELD_LENGTH },
{ "be", "Hmm", "HH.mm", UDATPG_MATCH_NO_OPTIONS },
{ "be", "HHmm", "HH.mm", UDATPG_MATCH_NO_OPTIONS },
{ "be", "hhmm", "h.mm a", UDATPG_MATCH_NO_OPTIONS },
{ "be", "Hmm", "H.mm", UDATPG_MATCH_HOUR_FIELD_LENGTH },
{ "be", "HHmm", "HH.mm", UDATPG_MATCH_HOUR_FIELD_LENGTH },
{ "be", "hhmm", "hh.mm a", UDATPG_MATCH_HOUR_FIELD_LENGTH },
//
{ "en", "yyyy", "yyyy", UDATPG_MATCH_NO_OPTIONS },
{ "en", "YYYY", "YYYY", UDATPG_MATCH_NO_OPTIONS },
{ "en", "U", "y", UDATPG_MATCH_NO_OPTIONS },
{ "en@calendar=japanese", "yyyy", "y G", UDATPG_MATCH_NO_OPTIONS },
{ "en@calendar=japanese", "YYYY", "Y G", UDATPG_MATCH_NO_OPTIONS },
{ "en@calendar=japanese", "U", "y G", UDATPG_MATCH_NO_OPTIONS },
{ "en@calendar=chinese", "yyyy", "U", UDATPG_MATCH_NO_OPTIONS },
{ "en@calendar=chinese", "YYYY", "Y", UDATPG_MATCH_NO_OPTIONS },
{ "en@calendar=chinese", "U", "U", UDATPG_MATCH_NO_OPTIONS },
{ "en@calendar=chinese", "Gy", "U", UDATPG_MATCH_NO_OPTIONS },
{ "en@calendar=chinese", "GU", "U", UDATPG_MATCH_NO_OPTIONS },
{ "en@calendar=chinese", "ULLL", "MMM U", UDATPG_MATCH_NO_OPTIONS },
{ "en@calendar=chinese", "yMMM", "MMM U", UDATPG_MATCH_NO_OPTIONS },
{ "en@calendar=chinese", "GUMMM", "MMM U", UDATPG_MATCH_NO_OPTIONS },
{ "zh@calendar=chinese", "yyyy", "U\\u5E74", UDATPG_MATCH_NO_OPTIONS },
{ "zh@calendar=chinese", "YYYY", "Y\\u5E74", UDATPG_MATCH_NO_OPTIONS },
{ "zh@calendar=chinese", "U", "U\\u5E74", UDATPG_MATCH_NO_OPTIONS },
{ "zh@calendar=chinese", "Gy", "U\\u5E74", UDATPG_MATCH_NO_OPTIONS },
{ "zh@calendar=chinese", "GU", "U\\u5E74", UDATPG_MATCH_NO_OPTIONS },
{ "zh@calendar=chinese", "ULLL", "U\\u5E74MMM", UDATPG_MATCH_NO_OPTIONS },
{ "zh@calendar=chinese", "yMMM", "U\\u5E74MMM", UDATPG_MATCH_NO_OPTIONS },
{ "zh@calendar=chinese", "GUMMM", "U\\u5E74MMM", UDATPG_MATCH_NO_OPTIONS },
};
int count = sizeof(testData) / sizeof(testData[0]);
const DTPtnGenOptionsData * testDataPtr = testData;
for (; count-- > 0; ++testDataPtr) {
UErrorCode status = U_ZERO_ERROR;
Locale locale(testDataPtr->locale);
UnicodeString skel(testDataPtr->skel);
UnicodeString expectedPattern(UnicodeString(testDataPtr->expectedPattern).unescape());
UDateTimePatternMatchOptions options = testDataPtr->options;
DateTimePatternGenerator * dtpgen = DateTimePatternGenerator::createInstance(locale, status);
if (U_FAILURE(status)) {
dataerrln("Unable to create DateTimePatternGenerator instance for locale(%s): %s", locale.getName(), u_errorName(status));
delete dtpgen;
continue;
}
UnicodeString pattern = dtpgen->getBestPattern(skel, options, status);
if (pattern.compare(expectedPattern) != 0) {
errln( UnicodeString("ERROR in getBestPattern, locale ") + UnicodeString(testDataPtr->locale) +
UnicodeString(", skeleton ") + skel +
((options)?UnicodeString(", options!=0"):UnicodeString(", options==0")) +
UnicodeString(", expected pattern ") + expectedPattern +
UnicodeString(", got ") + pattern );
}
delete dtpgen;
}
}
/**
* Test that DTPG can handle all valid pattern character / length combinations
*
*/
#define FIELD_LENGTHS_COUNT 6
#define FIELD_LENGTH_MAX 8
#define MUST_INCLUDE_COUNT 5
typedef struct AllFieldsTestItem {
char patternChar;
int8_t fieldLengths[FIELD_LENGTHS_COUNT+1]; // up to FIELD_LENGTHS_COUNT lengths to try
// (length <=FIELD_LENGTH_MAX) plus 0 terminator
char mustIncludeOneOf[MUST_INCLUDE_COUNT+1];// resulting pattern must include at least one of
// these as a pattern char (0-terminated list)
} AllFieldsTestItem;
void IntlTestDateTimePatternGeneratorAPI::testAllFieldPatterns(/*char *par*/)
{
const char * localeNames[] = {
"root",
"root@calendar=japanese",
"root@calendar=chinese",
"en",
"en@calendar=japanese",
"en@calendar=chinese",
NULL // terminator
};
AllFieldsTestItem testData[] = {
//pat fieldLengths generated pattern must
//chr to test include one of these
{ 'G', {1,2,3,4,5,0}, "G" }, // era
// year
{ 'y', {1,2,3,4,0}, "yU" }, // year
{ 'Y', {1,2,3,4,0}, "Y" }, // year for week of year
{ 'u', {1,2,3,4,5,0}, "yuU" }, // extended year
{ 'U', {1,2,3,4,5,0}, "yU" }, // cyclic year name
// quarter
{ 'Q', {1,2,3,4,0}, "Qq" }, // x
{ 'q', {1,2,3,4,0}, "Qq" }, // standalone
// month
{ 'M', {1,2,3,4,5,0}, "ML" }, // x
{ 'L', {1,2,3,4,5,0}, "ML" }, // standalone
// week
{ 'w', {1,2,0}, "w" }, // week of year
{ 'W', {1,0}, "W" }, // week of month
// day
{ 'd', {1,2,0}, "d" }, // day of month
{ 'D', {1,2,3,0}, "D" }, // day of year
{ 'F', {1,0}, "F" }, // day of week in month
{ 'g', {7,0}, "g" }, // modified julian day
// weekday
{ 'E', {1,2,3,4,5,6}, "Eec" }, // day of week
{ 'e', {1,2,3,4,5,6}, "Eec" }, // local day of week
{ 'c', {1,2,3,4,5,6}, "Eec" }, // standalone local day of week
// day period
// { 'a', {1,0}, "a" }, // am or pm // not clear this one is supposed to work (it doesn't)
// hour
{ 'h', {1,2,0}, "hK" }, // 12 (1-12)
{ 'H', {1,2,0}, "Hk" }, // 24 (0-23)
{ 'K', {1,2,0}, "hK" }, // 12 (0-11)
{ 'k', {1,2,0}, "Hk" }, // 24 (1-24)
{ 'j', {1,2,0}, "hHKk" }, // locale default
// minute
{ 'm', {1,2,0}, "m" }, // x
// second & fractions
{ 's', {1,2,0}, "s" }, // x
{ 'S', {1,2,3,4,0}, "S" }, // fractional second
{ 'A', {8,0}, "A" }, // milliseconds in day
// zone
{ 'z', {1,2,3,4,0}, "z" }, // x
{ 'Z', {1,2,3,4,5,0}, "Z" }, // x
{ 'O', {1,4,0}, "O" }, // x
{ 'v', {1,4,0}, "v" }, // x
{ 'V', {1,2,3,4,0}, "V" }, // x
{ 'X', {1,2,3,4,5,0}, "X" }, // x
{ 'x', {1,2,3,4,5,0}, "x" }, // x
};
const char ** localeNamesPtr = localeNames;
const char * localeName;
while ( (localeName = *localeNamesPtr++) != NULL) {
UErrorCode status = U_ZERO_ERROR;
Locale locale = Locale::createFromName(localeName);
DateTimePatternGenerator * dtpg = DateTimePatternGenerator::createInstance(locale, status);
if (U_SUCCESS(status)) {
const AllFieldsTestItem * testDataPtr = testData;
int itemCount = sizeof(testData) / sizeof(testData[0]);
for (; itemCount-- > 0; ++testDataPtr) {
char skelBuf[FIELD_LENGTH_MAX];
int32_t chrIndx, lenIndx;
for (chrIndx = 0; chrIndx < FIELD_LENGTH_MAX; chrIndx++) {
skelBuf[chrIndx] = testDataPtr->patternChar;
}
for (lenIndx = 0; lenIndx < FIELD_LENGTHS_COUNT; lenIndx++) {
int32_t skelLen = testDataPtr->fieldLengths[lenIndx];
if (skelLen <= 0) {
break;
}
if (skelLen > FIELD_LENGTH_MAX) {
continue;
}
UnicodeString skeleton(skelBuf, skelLen, US_INV);
UnicodeString pattern = dtpg->getBestPattern(skeleton, status);
if (U_FAILURE(status)) {
errln("DateTimePatternGenerator getBestPattern for locale %s, skelChar %c skelLength %d fails: %s",
locale.getName(), testDataPtr->patternChar, skelLen, u_errorName(status));
} else if (pattern.length() <= 0) {
errln("DateTimePatternGenerator getBestPattern for locale %s, skelChar %c skelLength %d produces 0-length pattern",
locale.getName(), testDataPtr->patternChar, skelLen);
} else {
// test that resulting pattern has at least one char in mustIncludeOneOf
UnicodeString mustIncludeOneOf(testDataPtr->mustIncludeOneOf, -1, US_INV);
int32_t patIndx, patLen = pattern.length();
UBool inQuoted = FALSE;
for (patIndx = 0; patIndx < patLen; patIndx++) {
UChar c = pattern.charAt(patIndx);
if (c == 0x27) {
inQuoted = !inQuoted;
} else if (!inQuoted && c <= 0x007A && c >= 0x0041) {
if (mustIncludeOneOf.indexOf(c) >= 0) {
break;
}
}
}
if (patIndx >= patLen) {
errln(UnicodeString("DateTimePatternGenerator getBestPattern for locale ") +
UnicodeString(locale.getName(),-1,US_INV) +
", skeleton " + skeleton +
", produces pattern without required chars: " + pattern);
}
}
}
}
delete dtpg;
} else {
dataerrln("Create DateTimePatternGenerator instance for locale(%s) fails: %s",
locale.getName(), u_errorName(status));
}
}
}
#endif /* #if !UCONFIG_NO_FORMATTING */
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
693472b269ac4b0292b982e9fd0df57e171e31b6 | a523380bc47012b0df53e0699744a95fb0cea92b | /src/LDPC_Simulator_Data_Def.hpp | 9c177f1065036743d9c61d8a087c1ab65d134745 | [] | no_license | gaobingaobingaobin/ADMM_decoder_layered | 05d4e143d4a14156054c798a23dccc4c23818cda | 31b8d0c97c6cccf928f836e92042ab024dcb6e03 | refs/heads/master | 2021-01-19T17:37:48.251476 | 2016-02-15T13:02:12 | 2016-02-15T13:02:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,606 | hpp | // Copyright 2012 Xishuo Liu, Stark C. Draper, Benjamin Recht
//
// This program is distributed under the terms of the GNU General Public License.
//
// This file is part of ADMM Decoder.
//
// ADMM Decoder is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ADMM Decoder 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 ADMM Decoder. If not, see <http://www.gnu.org/licenses/>.
//
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Project: ADMM Decoder
// Files: LDPC_Simulator_Example.cpp, LDPC_Class.cpp,
// LDPC_Simulator_Data_Def.h, LDPC_Class.h,
// MersenneTwister.h
// Date: 8.30.2012
//
// Author: Xishuo Liu, xliu94@wisc.edu
// Thanks to: S. Barman, S. Draper and B. Recht.
//
// Papers: 1. S. Barman, X. Liu, S. Draper and B. Recht,
// "Decomposition Methods for Large Scale LP Decoding"
// http://arxiv.org/abs/1204.0556
// 2. X. Liu, S. Draper and B. Recht,
// "Suppressing Pseudocodewords by Penalizing the Objective of LP Decoding"
// IEEE Information Theory Workshop (ITW), 2012. Lausanne: Switzerland, 2012
///////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
This file contains basic data types and functions for the ADMM decoder classes.
*/
#ifndef BIG_HEADER_HPP_
#define BIG_HEADER_HPP_
#include<iostream>
#include<cmath>
#include<ctime>
#include<fstream>
#include<string>
#include<iomanip>
#include<cstdlib>
#include<algorithm>
#include<sstream>
#include "MersenneTwister.hpp"
using namespace std;
//! Calculate erf function
/*!
erf(z) = 2/sqrt(pi) * Integral(0..x) exp( -t^2) dt
erf(0.01) = 0.0112834772 erf(3.7) = 0.9999998325
Abramowitz/Stegun: p299, |erf(z)-erf| <= 1.5*10^(-7)
*/
inline double myerf(double x)
{
double y = 1.0 / ( 1.0 + 0.3275911 * x);
return 1 - (((((
+ 1.061405429 * y
- 1.453152027) * y
+ 1.421413741) * y
- 0.284496736) * y
+ 0.254829592) * y)
* exp (-x * x);
}
//! True if x = Nan
inline int my_isnan(double x)
{
return x != x;
}
//! True if x = Inf
inline int my_isinf(double x)
{
if ((x == x) && ((x - x) != 0.0)) return (x < 0.0 ? -1 : 1);
else return 0;
}
//! generate random string
/*!
\param length Length of string.
*/
inline string randomStrGen(int length) {
static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
string result;
result.resize(length);
for (int i = 0; i < length; i++)
result[i] = charset[rand() % charset.length()];
return result;
}
//! A struct for sparse matrix structure
typedef struct Triple{
int col; /*!< column index. */
int row; /*!< row index. */
int value; /*!< value index, reserved for non-binary codes*/
}TRIPLE;
//! A struct for keeping sorting indicies
/*!
The idea is to obtain the indicies for sorting not just the final results for sorting.
*/
typedef struct
{
int index;
double value;
}NODE;
//! Sorting definition for struct NODE
bool sort_compare_de(const NODE & a, const NODE & b);
#endif
| [
"imen.debbabi@gmail.com"
] | imen.debbabi@gmail.com |
39c0585816830e234c99231c6e1deb2ea15c0d64 | e71ebf5118040fdbfb6bbd62ad6b7a434eea2c0a | /LabWorks/Lab3Version1/header.h | 2c4eafb4d092c9048d2fa73545bc89bb243b028f | [] | no_license | sviatoslav-vilkovych/OOP-NU-LP | ce577525aa12d941d0db3b7b9621d201f9742ace | 50c75ffd98c4635b5bfd5d2f765380833fb3e5ea | refs/heads/master | 2021-08-27T16:19:46.255774 | 2016-12-26T03:46:48 | 2016-12-26T03:46:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 181 | h | #pragma once
#include <iostream>
#include <string.h>
#include <fstream>
#include <iomanip>
#include <vector>
using namespace std;
#include "CashRegister.h"
#include "ticket.h"
| [
"VilSvat@gmail.com"
] | VilSvat@gmail.com |
1b6c1bdd20da63c90e392c0cb4597e0517bb08d5 | c57819bebe1a3e1d305ae0cb869cdcc48c7181d1 | /src/qt/src/3rdparty/webkit/Source/WebKit/qt/WebCoreSupport/DeviceMotionClientQt.cpp | 4761514302ef8f258f1a5d4ceb9dcaba8b7851dd | [
"LGPL-2.1-only",
"Qt-LGPL-exception-1.1",
"LicenseRef-scancode-generic-exception",
"GPL-3.0-only",
"GPL-1.0-or-later",
"GFDL-1.3-only",
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | blowery/phantomjs | 255829570e90a28d1cd597192e20314578ef0276 | f929d2b04a29ff6c3c5b47cd08a8f741b1335c72 | refs/heads/master | 2023-04-08T01:22:35.426692 | 2012-10-11T17:43:24 | 2012-10-11T17:43:24 | 6,177,895 | 1 | 0 | BSD-3-Clause | 2023-04-03T23:09:40 | 2012-10-11T17:39:25 | C++ | UTF-8 | C++ | false | false | 2,034 | cpp | /*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "DeviceMotionClientQt.h"
#include "DeviceMotionController.h"
#include "DeviceMotionProviderQt.h"
#include "qwebpage.h"
namespace WebCore {
DeviceMotionClientQt::DeviceMotionClientQt(QWebPage* page)
: m_page(page)
, m_controller(0)
, m_provider(new DeviceMotionProviderQt())
{
connect(m_provider, SIGNAL(deviceMotionChanged()), SLOT(changeDeviceMotion()));
}
DeviceMotionClientQt::~DeviceMotionClientQt()
{
disconnect();
delete m_provider;
}
void DeviceMotionClientQt::setController(DeviceMotionController* controller)
{
m_controller = controller;
}
void DeviceMotionClientQt::startUpdating()
{
m_provider->start();
}
void DeviceMotionClientQt::stopUpdating()
{
m_provider->stop();
}
DeviceMotionData* DeviceMotionClientQt::currentDeviceMotion() const
{
return m_provider->currentDeviceMotion();
}
void DeviceMotionClientQt::deviceMotionControllerDestroyed()
{
delete this;
}
void DeviceMotionClientQt::changeDeviceMotion()
{
if (!m_controller)
return;
m_controller->didChangeDeviceMotion(currentDeviceMotion());
}
} // namespace WebCore
#include "moc_DeviceMotionClientQt.cpp"
| [
"ariya.hidayat@gmail.com"
] | ariya.hidayat@gmail.com |
ee0418ab4522ad65c5ffed32c975fa8d2ebe3d80 | 05b39fb01b26776235aeac68d7120c90e2086ce0 | /email/src/emailagent.h | b7e9491529781ef4b5500234aeb3b065d16fcf5c | [] | no_license | veskuh/nemo-qml-plugins | cb1df85f0cd1aa075f07f354842284aeafcc482f | 3fda9fed301dd03cb2a8e474796affab7a186d05 | refs/heads/master | 2021-01-16T20:46:22.245220 | 2012-10-29T14:02:28 | 2012-10-29T14:22:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,524 | h | /*
* Copyright 2011 Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*/
#ifndef EMAILAGENT_H
#define EMAILAGENT_H
/*
#ifdef None
#undef None
#endif
#ifdef Status
#undef Status
#endif
*/
#include <QDeclarativeItem>
#include <QProcess>
#include <QTimer>
#include <qmailaccount.h>
#include <qmailstore.h>
#include <qmailserviceaction.h>
#ifdef HAS_MLITE
#include <mgconfitem.h>
#endif
class EmailAgent : public QDeclarativeItem
{
Q_OBJECT
public:
static EmailAgent *instance();
explicit EmailAgent (QDeclarativeItem *parent = 0);
~EmailAgent();
void sendMessages (const QMailAccountId &id);
bool isSynchronizing() const;
void exportAccountChanges(const QMailAccountId id);
void flagMessages(const QMailMessageIdList &ids, quint64 setMask, quint64 unsetMask);
Q_INVOKABLE void accountsSync();
Q_INVOKABLE void deleteMessage(QVariant id);
Q_INVOKABLE void deleteMessages(const QMailMessageIdList &ids);
Q_INVOKABLE void createFolder (const QString &name, QVariant vMailAccountId, QVariant vParentFolderId);
Q_INVOKABLE void deleteFolder(QVariant vFolderId);
Q_INVOKABLE void renameFolder(QVariant vFolderId, const QString &name);
Q_INVOKABLE void synchronize (QVariant vMailAccountId);
Q_INVOKABLE void cancelSync ();
Q_INVOKABLE void markMessageAsRead (QVariant vMsgId);
Q_INVOKABLE void markMessageAsUnread (QVariant vMsgId);
Q_INVOKABLE void getMoreMessages (QVariant vFolderId);
Q_INVOKABLE QString getSignatureForAccount (QVariant vMailAccountId);
Q_INVOKABLE bool confirmDeleteMail ();
Q_INVOKABLE void downloadAttachment(QVariant vMailMessage, const QString& attachmentDisplayName);
Q_INVOKABLE bool openAttachment(const QString& attachmentDisplayName);
Q_INVOKABLE void openBrowser(const QString& url);
Q_INVOKABLE QString getMessageBodyFromFile(const QString& bodyFilePath);
signals:
void retrievalCompleted();
void sendCompleted();
void syncCompleted();
void syncBegin();
void messagesDeleted(QMailMessageIdList);
void error(const QMailAccountId &id, const QString &msg, int code);
void attachmentDownloadStarted();
void attachmentDownloadCompleted();
void progressUpdate (int percent);
private slots:
void progressChanged(uint value, uint total);
void activityChanged(QMailServiceAction::Activity activity);
void attachmentDownloadActivityChanged(QMailServiceAction::Activity activity);
void exportActivityChanged(QMailServiceAction::Activity activity);
void exportAccounts();
void initMailServer();
void onFoldersAdded (const QMailFolderIdList &);
private:
static EmailAgent *m_instance;
bool m_retrieving;
bool m_transmitting;
bool m_exporting;
bool m_cancelling;
QMailAccountIdList m_retrieveAccounts;
QMailAccountIdList m_transmitAccounts;
QMailAccountIdList m_exportAccounts;
QMailRetrievalAction *const m_retrievalAction;
QMailStorageAction *const m_storageAction;
QMailTransmitAction *const m_transmitAction;
QMailRetrievalAction *const m_exportAction;
QMailRetrievalAction *m_attachmentRetrievalAction;
QMailMessageId m_messageId;
QMailMessagePart m_attachmentPart;
QProcess m_messageServerProcess;
QTimer m_exportTimer;
#ifdef HAS_MLITE
MGConfItem *m_confirmDeleteMail;
#endif
};
#endif
| [
"valerio.valerio@jollamobile.com"
] | valerio.valerio@jollamobile.com |
76785b81bbea7e1eccc1c4ea4762e504edacc02c | 02560d9e9fb24766a63f1b7a39a4f51c4501f7ec | /Joining_realations/sortJoin/readFiles.cpp | eb5dcdb6a4b780fd9fa3f976ea6a7240f259c0b9 | [] | no_license | amanshahi/relationJoin | d39c2a4f5d66821b30c0a23c981f2075e8c927c5 | f4577b7503a3f13b853e07d4cf984f7b23755410 | refs/heads/master | 2021-08-11T11:10:59.870037 | 2017-11-13T16:05:01 | 2017-11-13T16:05:01 | 110,569,879 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 914 | cpp | #include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define PB push_back
#define INS insert
#define MP make_pair
#define LL long long int
#define II int
#define SS string
#define sortArray(n) sort(begin(n), end(n))
#define sortVector(n) sort(n.begin(), n.end())
LL offset=0;
vector<vector<string> > readFiles(II isz, string fileName, II flag){
if(flag == 0) offset = 0;
vector<vector<string> > ret;
vector<string> temp;
string line;
ifstream myfile (fileName);
myfile.seekg(offset);
if (myfile.is_open()){
while (getline (myfile,line)){
offset += line.length()+1;
char sub[100];
std::strcpy(sub, line.c_str());
char *br = strtok(sub," ");
temp.clear();
while(br != NULL){
string str(br);
temp.PB(br);br = strtok(NULL," ");
}
ret.PB(temp);
if(ret.size() == isz) {
myfile.close();
return ret;
}
}
myfile.close();
}
return ret;
}
| [
"amanshahi2016@gmail.com"
] | amanshahi2016@gmail.com |
8c406a09aea904012ed6b78a40706e56614324b3 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_log_1343.cpp | 177f8476ec505ca13fc887ac7cdcd8718f6289ea | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 73 | cpp | archive_set_error(&a->archive, ENOMEM,
"No memory for file entry"); | [
"993273596@qq.com"
] | 993273596@qq.com |
ca116be7902e7f809ce602214246ff4911cf72a4 | 9d9aa867aa9e4eb9f92072c74d850aff8611bf1e | /FINAL PRACTISE/STRING CONCATINATE.cpp | f04cb77d9347a2c7855576492e279cd0236c8c68 | [] | no_license | rajat-29/PRE-UCA | 162fed19f097d4669b2316ac4143b2cb5ac6a034 | f70ebf4e1e0561ebf234ebf428cd73baf823847d | refs/heads/master | 2020-04-12T10:55:13.124220 | 2020-01-31T15:11:43 | 2020-01-31T15:11:43 | 160,946,683 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 666 | cpp | #include<iostream>
#include<string.h>
using namespace std;
class mat
{
private:
int a[20][20];
int m,n;
public:
mat()
{
m=2;
n=2;
}
void read()
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>a[i][j];
}
}
}
mat operator +(mat& b)
{
mat b1;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
b1.a[i][j]=a[i][j]+b.a[i][j];
}
}
return b1;
}
void display()
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cout<<a[i][j]<<" ";
}
}
}
};
int main()
{
mat ob1,ob2,ob3;
ob1.read();
ob2.read();
ob3=ob1+ob2;
ob3.display();
return 0;
}
| [
"rajat295gupta@gmail.com"
] | rajat295gupta@gmail.com |
5f73362a0a5f86360769ee22affb7f6e7d6581e3 | 9030ce2789a58888904d0c50c21591632eddffd7 | /SDK/ARKSurvivalEvolved_DinoCharacterStatusComponent_BP_Beetle_functions.cpp | d42a315917b6c61488870f6fe79a93f9ad4195b0 | [
"MIT"
] | permissive | 2bite/ARK-SDK | 8ce93f504b2e3bd4f8e7ced184980b13f127b7bf | ce1f4906ccf82ed38518558c0163c4f92f5f7b14 | refs/heads/master | 2022-09-19T06:28:20.076298 | 2022-09-03T17:21:00 | 2022-09-03T17:21:00 | 232,411,353 | 14 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,247 | cpp | // ARKSurvivalEvolved (332.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_DinoCharacterStatusComponent_BP_Beetle_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function DinoCharacterStatusComponent_BP_Beetle.DinoCharacterStatusComponent_BP_Beetle_C.ExecuteUbergraph_DinoCharacterStatusComponent_BP_Beetle
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UDinoCharacterStatusComponent_BP_Beetle_C::ExecuteUbergraph_DinoCharacterStatusComponent_BP_Beetle(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function DinoCharacterStatusComponent_BP_Beetle.DinoCharacterStatusComponent_BP_Beetle_C.ExecuteUbergraph_DinoCharacterStatusComponent_BP_Beetle");
UDinoCharacterStatusComponent_BP_Beetle_C_ExecuteUbergraph_DinoCharacterStatusComponent_BP_Beetle_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
724b66d4cbefa6a5b9fe56f4246d021f82911f7d | 045c0ffc40856d36ff3676ec189450c9ffd981ca | /CprE185/wiiwrap/wiimote.cpp | 55e10770e463a3bf26c5ea0bc2629583d3ede8bf | [] | no_license | breber/school | 8e0791cf20543af4492d6a3cc8e1116465c5a811 | ea619b0c1055c7a79b710c508883ec34bf7fa04e | refs/heads/master | 2021-03-24T13:37:01.979431 | 2016-12-03T01:54:02 | 2016-12-03T01:54:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 71,605 | cpp | C// _______________________________________________________________________________
//
// - WiiYourself! - native C++ Wiimote library v0.92b.
// (c) gl.tter 2007 - http://wiiyourself.gl.tter.org
//
// see License.txt for conditions of use. see History.txt for change log.
// _______________________________________________________________________________
//
// wiimote.cpp (tab = 4 spaces)
// disable warning "C++ exception handler used, but unwind semantics are not enabled."
// in <xstring> (I don't use it - or just enable C++ excepionts)
#pragma warning(disable: 4530)
#include "wiimote.h"
#pragma warning(default: 4530)
#include <setupapi.h>
extern "C" {
#include <hidsdi.h> // from WinDDK
}
#include <sys/types.h> // for _start
#include <sys/stat.h> // "
#include <process.h> // for _beginthreadex()
#include <math.h> // for orientation
#include <mmreg.h> // for WAVEFORMATEXTENSIBLE
#include <mmsystem.h> // for timeGetTime()
// auto-link with the necessary libs
#pragma comment(lib, "setupapi.lib")
#pragma comment(lib, "hid.lib") // from WinDDK
#pragma comment(lib, "winmm.lib") // timeGetTime()
#pragma comment(lib, "user32.lib") // MessageBox
#ifdef _DEBUG
# ifdef _UNICODE
# pragma comment(lib, "WiiYourself!_dU.lib")
# else
# pragma comment(lib, "WiiYourself!_d.lib")
# endif
#else // RELEASE
# ifdef _UNICODE
# pragma comment(lib, "WiiYourself!_U.lib")
# else
# pragma comment(lib, "WiiYourself!.lib")
# endif
#endif
// ------------------------------------------------------------------------------------
// helpers
// ------------------------------------------------------------------------------------
template<class T> __forceinline T sign (const T& val) { return (val<0)? T(-1) : T(1); }
template<class T> __forceinline T square(const T& val) { return val*val; }
#define ARRAY_SIZE(array) (sizeof(array)/sizeof(array[0]))
// ------------------------------------------------------------------------------------
// Tracing & Debugging
// ------------------------------------------------------------------------------------
// TRACE and WARN currently use OutputDebugString() (via _TRACE) - change to suit
#define PREFIX _T("Wii : ")
#define TRACE(fmt, ...) _TRACE(PREFIX fmt _T("\n"), __VA_ARGS__)
#define WARN(fmt, ...) _TRACE(PREFIX _T("*") fmt _T("*") _T("\n"), __VA_ARGS__)
// uncomment any of these for deeper debugging
//#define DEEP_TRACE(fmt, ...) _TRACE(PREFIX _T("|") fmt _T("\n"), __VA_ARGS__)
//#define BEEP_DEBUG_READS
//#define BEEP_DEBUG_WRITES
//#define BEEP_ON_ORIENTATION_ESTIMATE
//#define BEEP_ON_PERIODIC_STATUSREFRESH
// internals:
// auto-strip code from these macros if they weren't defined
#ifndef TRACE
# define TRACE(...)
#endif
#ifndef DEEP_TRACE
# define DEEP_TRACE(...)
#endif
#ifndef WARN
# define WARN(...)
#endif
// ------------------------------------------------------------------------------------
static void _cdecl _TRACE (const TCHAR* fmt, ...)
{
static TCHAR buffer[256];
if (!fmt) return;
va_list argptr;
va_start (argptr, fmt);
_vsntprintf_s(buffer, ARRAY_SIZE(buffer), _TRUNCATE, fmt, argptr);
va_end (argptr);
OutputDebugString(buffer);
}
// ------------------------------------------------------------------------------------
static void _cdecl _Message (const TCHAR* fmt, ...)
{
static TCHAR buffer[256];
if (!fmt) return;
va_list argptr;
va_start (argptr, fmt);
_vsntprintf_s(buffer, ARRAY_SIZE(buffer), _TRUNCATE, fmt, argptr);
va_end (argptr);
MessageBox(NULL, buffer, PREFIX, MB_OK|MB_TOPMOST);
}
// ------------------------------------------------------------------------------------
// wiimote
// ------------------------------------------------------------------------------------
// class statics
unsigned wiimote::_TotalConnected = 0;
hidwrite_ptr wiimote::_HidD_SetOutputReport = NULL;
const unsigned wiimote::FreqLookup [10] = // (keep in sync with speaker_freq!)
{ 0, 4200, 3920, 3640, 3360,
3130, 2940, 2760, 2610, 2470 };
const TCHAR* wiimote::ButtonNameFromBit [16] =
{ _T("Left") , _T("Right"), _T("Down"), _T("Up"),
_T("Plus") , _T("??") , _T("??") , _T("??") ,
_T("Two") , _T("One") , _T("B") , _T("A") ,
_T("Minus"), _T("??") , _T("??") , _T("Home") };
const TCHAR* wiimote::ClassicButtonNameFromBit [16] =
{ _T("Up") , _T("Left") , _T("ZR") , _T("X"),
_T("A") , _T("Y") , _T("B") , _T("ZL") ,
_T("??") , _T("TrigR"), _T("Plus"), _T("Home") ,
_T("Minus"), _T("TrigL"), _T("Down"), _T("Right") };
// ------------------------------------------------------------------------------------
wiimote::wiimote ()
:
DataRead (CreateEvent(NULL, FALSE, FALSE, NULL)),
Handle (INVALID_HANDLE_VALUE),
bStatusReceived (false), // for output method detection
bConnectionLost (false), // set if write fails after connection
bUseHIDwrite (false), // if OS supports it
HidDLL (NULL),
ChangedCallback (NULL),
CallbackTriggerFlags (CHANGED_ALL),
CurrentSample (NULL),
HIDwriteThread (NULL),
ReadParseThread (NULL),
SampleThread (NULL),
AsyncRumbleThread (NULL),
AsyncRumbleTimeout (0)
{
_ASSERT(DataRead != INVALID_HANDLE_VALUE);
// clear our public and private state data completely (including deadzones)
Clear (true);
Internal.Clear(true);
// and the state history (for state recording)
memset(&Recording, 0, sizeof(Recording));
// for overlapped IO (Read/WriteFile)
memset(&Overlapped, 0, sizeof(Overlapped));
Overlapped.hEvent = DataRead;
Overlapped.Offset =
Overlapped.OffsetHigh = 0;
// for async HID output method
InitializeCriticalSection(&HIDwriteQueueLock);
// for polling
InitializeCriticalSection(&StateLock);
// request millisecond timer accuracy
timeBeginPeriod(1);
}
// ------------------------------------------------------------------------------------
wiimote::~wiimote ()
{
Disconnect();
// events & critical sections are kept open for the lifetime of the object,
// so tidy them up here:
if(DataRead != INVALID_HANDLE_VALUE)
CloseHandle(DataRead);
DeleteCriticalSection(&HIDwriteQueueLock);
DeleteCriticalSection(&StateLock);
// tidy up timer accuracy request
timeEndPeriod(1);
}
// ------------------------------------------------------------------------------------
bool wiimote::Connect (unsigned wiimote_index, bool force_hidwrites)
{
if(wiimote_index == FIRST_AVAILABLE)
TRACE(_T("Connecting first available Wiimote:"));
else
TRACE(_T("Connecting Wiimote %u:"), wiimote_index);
// auto-disconnect if user is being naughty
if(IsConnected())
Disconnect();
// test if HidD_SetOuputReport is supported (XP+ only)
if(!HidDLL) {
HidDLL = LoadLibrary(_T("hid.dll"));
_ASSERT(HidDLL);
}
if(HidDLL && !_HidD_SetOutputReport) {
_HidD_SetOutputReport = (hidwrite_ptr)
GetProcAddress(HidDLL, "HidD_SetOutputReport");
if(!_HidD_SetOutputReport)
TRACE(_T(".. (OS doesn't support HID writes)."));
}
// get the GUID of the HID class
GUID guid;
HidD_GetHidGuid(&guid);
// get a handle to all devices that are part of the HID class
// Brian: Fun fact: DIGCF_PRESENT worked on my machine just fine. I reinstalled
// Vista, and now it no longer finds the Wiimote with that parameter enabled...
HDEVINFO dev_info = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_DEVICEINTERFACE);// | DIGCF_PRESENT);
if(!dev_info) {
WARN(_T("couldn't get device info"));
return false;
}
// enumerate the devices
SP_DEVICE_INTERFACE_DATA didata;
didata.cbSize = sizeof(didata);
unsigned index = 0;
unsigned wiimotes_found = 0;
while(SetupDiEnumDeviceInterfaces(dev_info, NULL, &guid, index, &didata))
{
// get the buffer size for this device detail instance
DWORD req_size = 0;
SetupDiGetDeviceInterfaceDetail(dev_info, &didata, NULL, 0, &req_size, NULL);
// (bizarre way of doing it) create a buffer large enough to hold the
// fixed-size detail struct components, and the variable string size
SP_DEVICE_INTERFACE_DETAIL_DATA *didetail =
(SP_DEVICE_INTERFACE_DETAIL_DATA*) new BYTE[req_size];
_ASSERT(didetail);
didetail->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
// now actually get the detail struct
if(!SetupDiGetDeviceInterfaceDetail(dev_info, &didata, didetail,
req_size, &req_size, NULL)) {
WARN(_T("couldn't get devinterface info for %u"), index);
break;
}
// open a read/write handle to our device using the device path returned
// ** I've disabled the share flags to easily detect if a particular wiimote
// is already in use - this does mean that it must not be opened by
// another app either, but that wouldn't be a good idea anway **
DEEP_TRACE(_T(".. opening device %s"), didetail->DevicePath);
Handle = CreateFile(didetail->DevicePath, GENERIC_READ|GENERIC_WRITE,
0,//FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED, NULL);
if(Handle == INVALID_HANDLE_VALUE) {
DEEP_TRACE(_T(".... failed (may be in use)."));
goto skip;
}
// get the device attributes
HIDD_ATTRIBUTES attrib;
attrib.Size = sizeof(attrib);
if(HidD_GetAttributes(Handle, &attrib))
{
// is this a wiimote?
if((attrib.VendorID != VID) || (attrib.ProductID != PID))
goto skip;
// yes, but is it the one we're interested in?
wiimotes_found++;
if((wiimote_index != FIRST_AVAILABLE) &&
(wiimote_index != (wiimotes_found-1)))
goto skip;
// the wiimote is installed, but it may not be currently paired:
TRACE(_T(".. wiimote installed - trying to write:"));
// clear the wiimote state & buffers
Clear (false); // preserves existing deadzones
Internal.Clear(false); // "
memset(ReadBuff , 0, sizeof(ReadBuff));
memset(WriteBuff, 0, sizeof(WriteBuff));
bConnectionLost = false;
// enable async reading
BeginAsyncRead();
// autodetect which write method the Bluetooth stack supports,
// by requesting the wiimote status report:
if(force_hidwrites && !_HidD_SetOutputReport) {
TRACE(_T(".. can't force HID writes (not supported)"));
force_hidwrites = false;
}
if(force_hidwrites)
TRACE(_T(".. (HID writes forced)"));
else{
// - try WriteFile() first as it's the most efficient (it uses
// harware interrupts where possible and is async-capable):
bUseHIDwrite = false;
RequestStatusReport();
// and wait for the report to arrive:
DWORD last_time = timeGetTime();
while(!bStatusReceived && ((timeGetTime()-last_time) < 500))
Sleep(5);
TRACE(_T(".. WriteFile() %s."), (bStatusReceived? _T("succeeded") :
_T("failed")));
}
if(!bStatusReceived)
{
// (we didn't get it, so) try with the HID output method:
bUseHIDwrite = true;
RequestStatusReport();
// wait for the report to arrive:
DWORD last_time = timeGetTime();
while(!bStatusReceived && ((timeGetTime()-last_time) < 500))
Sleep(5);
// did we get it?
if(bStatusReceived)
TRACE(_T(".. HID write succeeded."));
else{
TRACE(_T(".. HID write failed."));
WARN(_T("output failed - wiimote is not connected (or confused)."));
Disconnect();
goto skip;
}
}
// connected succesfully:
_TotalConnected++;
// reset it
Reset();
// read the wiimote calibration info
ReadCalibration();
// refresh the public state from the internal one (so that extension
// status etc. is available straight away)
_RefreshState(false);
// and show when we want to trigger the next periodic status request
// (for battery level and connection loss detection)
NextStatusTime = timeGetTime() + REQUEST_STATUS_EVERY_MS;
// tidy up
delete[] (BYTE*)didetail;
break;
}
skip:
// tidy up
delete[] (BYTE*)didetail;
if(Handle != INVALID_HANDLE_VALUE) {
CloseHandle(Handle);
Handle = INVALID_HANDLE_VALUE;
}
// if this was the specified wiimote index, abort
if((wiimote_index != FIRST_AVAILABLE) &&
(wiimote_index == (wiimotes_found-1)))
break;
index++;
}
// clean up our list
SetupDiDestroyDeviceInfoList(dev_info);
if(IsConnected()) {
TRACE(_T(".. Connected!"));
return true;
}
TRACE(_T(".. connection failed."));
return false;
}
// ------------------------------------------------------------------------------------
void wiimote::Disconnect ()
{
if(Handle == INVALID_HANDLE_VALUE)
return;
TRACE(_T("Disconnect()."));
if(IsConnected())
{
_ASSERT(_TotalConnected > 0); // sanity
_TotalConnected--;
if(!bConnectionLost)
Reset();
}
CloseHandle(Handle);
Handle = INVALID_HANDLE_VALUE;
bStatusReceived = false;
// close the read thread
if(ReadParseThread) {
// unblock it so it can realise we're closing and exit straight away
SetEvent(DataRead);
CloseHandle(ReadParseThread);
ReadParseThread = NULL;
}
// close the rumble thread
if(AsyncRumbleThread) {
CloseHandle(AsyncRumbleThread);
AsyncRumbleThread = NULL;
AsyncRumbleTimeout = 0;
}
// and the sample streaming thread
if(SampleThread) {
CloseHandle(SampleThread);
SampleThread = NULL;
}
// release the HID dll
if(HidDLL) {
FreeLibrary(HidDLL);
HidDLL = NULL;
}
// and clear the state
Clear (false); // (preserves deadzones)
Internal.Clear(false); // (preserves deadzones)
}
// ------------------------------------------------------------------------------------
inline void wiimote::Reset ()
{
TRACE(_T("Resetting wiimote."));
// stop updates (by setting report type to non-continous buttons-only)
SetReportType(IN_BUTTONS, false);
SetRumble (false);
SetLEDs (0x00);
MuteSpeaker (true);
EnableSpeaker(false);
Sleep(80); // avoids loosing the extension calibration data on Connect()
}
// ------------------------------------------------------------------------------------
unsigned __stdcall wiimote::ReadParseThreadfunc (void* param)
{
// this thread waits for the async ReadFile() to deliver data & parses it.
// It also requests periodic status updates, deals with connection loss
// and ends state recordings with a specific duration:
_ASSERT(param);
wiimote &remote = *(wiimote*)param;
OVERLAPPED &overlapped = remote.Overlapped;
unsigned exit_code = 0; // (success)
while(1)
{
// wait until the overlapped read completes, or the timeout is reached:
DWORD wait = WaitForSingleObject(overlapped.hEvent, 500);
// before we deal with the result, let's do some housekeeping:
// if we were recently Disconect()ed, exit now
if(remote.Handle == INVALID_HANDLE_VALUE) {
DEEP_TRACE(_T("read thread: wiimote was disconnected"));
break;
}
// ditto if the connection was lost (eg. through a failed write)
if(remote.bConnectionLost)
{
connection_lost:
TRACE(_T("read thread: connection to wiimote was lost"));
remote.Disconnect();
remote.Internal.Polling.Changes = (state_change_flags)
(remote.Internal.Polling.Changes | CONNECTION_LOST);
// report via the callback (if any)
if(remote.ChangedCallback &&
(remote.CallbackTriggerFlags & CONNECTION_LOST))
{
remote._RefreshState(true);
remote.ChangedCallback(remote, CONNECTION_LOST);
}
break;
}
DWORD time = timeGetTime();
// is a periodic status request due? (but not if we're streaming audio,
// we don't want to cause a glitch)
if(remote.IsConnected() && !remote.IsPlayingAudio() &&
(time > remote.NextStatusTime))
{
#ifdef BEEP_ON_PERIODIC_STATUSREFRESH
Beep(2000,50);
#endif
remote.RequestStatusReport();
// and schedule the next one
remote.NextStatusTime = time + REQUEST_STATUS_EVERY_MS;
}
// if we're state recording and have reached the specified duration, stop
if(remote.Recording.bEnabled && (remote.Recording.EndTimeMS != UNTIL_STOP) &&
(time >= remote.Recording.EndTimeMS))
remote.Recording.bEnabled = false;
// now handle the wait result:
// did the wait time out?
if(wait == WAIT_TIMEOUT) {
DEEP_TRACE(_T("read thread: timed out"));
continue; // wait again
}
// did an error occurr?
if(wait != WAIT_OBJECT_0) {
DEEP_TRACE(_T("read thread: error waiting!"));
remote.bConnectionLost = true;
// deal with it straight away to avoid a longer delay
goto connection_lost;
}
// data was received:
#ifdef BEEP_DEBUG_READS
Beep(500,1);
#endif
DWORD read = 0;
// get the data read result
GetOverlappedResult(remote.Handle, &overlapped, &read, TRUE);
// if we read data, parse it
if(read) {
DEEP_TRACE(_T("read thread: parsing data"));
remote.OnReadData(read);
}
else
DEEP_TRACE(_T("read thread: didn't get any data??"));
}
TRACE(_T("(ending read thread)"));
#ifdef BEEP_DEBUG_READS
if(exit_code != 0)
Beep(200,1000);
#endif
return exit_code;
}
// ------------------------------------------------------------------------------------
bool wiimote::BeginAsyncRead ()
{
// (this is also called before we're fully connected)
_ASSERT(Handle != INVALID_HANDLE_VALUE);
DEEP_TRACE(_T(".. starting async read"));
#ifdef BEEP_DEBUG_READS
Beep(1000,1);
#endif
DWORD read;
if (!ReadFile(Handle, ReadBuff, REPORT_LENGTH, &read, &Overlapped)) {
DWORD err = GetLastError();
if(err != ERROR_IO_PENDING) {
DEEP_TRACE(_T(".... ** ReadFile() failed! **"));
return false;
}
}
// launch the completion wait/callback thread
if(!ReadParseThread) {
ReadParseThread = (HANDLE)_beginthreadex(NULL, 0, ReadParseThreadfunc,
this, 0, NULL);
DEEP_TRACE(_T(".... creating read thread"));
_ASSERT(ReadParseThread);
if(!ReadParseThread)
return false;
SetThreadPriority(ReadParseThread, WORKER_THREAD_PRIORITY);
}
// if ReadFile completed while we called, signal the thread to proceed
if(read) {
DEEP_TRACE(_T(".... got data right away"));
SetEvent(DataRead);
}
return true;
}
// ------------------------------------------------------------------------------------
void wiimote::OnReadData (DWORD bytes_read)
{
_ASSERT(bytes_read == REPORT_LENGTH);
// copy our input buffer
BYTE buff [REPORT_LENGTH];
memcpy(buff, ReadBuff, bytes_read);
// start reading again
BeginAsyncRead();
// parse it
ParseInput(buff);
}
// ------------------------------------------------------------------------------------
void wiimote::SetReportType (input_report type, bool continuous)
{
_ASSERT(IsConnected());
if(!IsConnected())
return;
ReportType = type;
switch(type)
{
case IN_BUTTONS_ACCEL_IR:
EnableIR(wiimote_state::ir::EXTENDED);
break;
case IN_BUTTONS_ACCEL_IR_EXT:
EnableIR(wiimote_state::ir::BASIC);
break;
default:
DisableIR();
break;
}
ClearReport();
WriteBuff[0] = OUT_TYPE;
WriteBuff[1] = (continuous ? 0x04 : 0x00) | GetRumbleBit();
WriteBuff[2] = type;
WriteReport();
}
// ------------------------------------------------------------------------------------
void wiimote::SetLEDs (BYTE led_bits)
{
_ASSERT(IsConnected());
if(!IsConnected())
return;
_ASSERT(led_bits <= 0x0f);
led_bits &= 0xf;
ClearReport();
WriteBuff[0] = OUT_LEDs;
WriteBuff[1] = (led_bits<<4) | GetRumbleBit();
WriteReport();
Internal.LED.Bits = led_bits;
}
// ------------------------------------------------------------------------------------
void wiimote::SetRumble (bool on)
{
_ASSERT(IsConnected());
if(!IsConnected())
return;
if(Internal.bRumble == on)
return;
Internal.bRumble = on;
// if we're streaming audio, we don't need to send a report (sending it makes
// the audio glitch, and the rumble bit is sent with every report anyway)
if(IsPlayingAudio())
return;
ClearReport();
WriteBuff[0] = OUT_STATUS;
WriteBuff[1] = on? 0x01 : 0x00;
WriteReport();
}
// ------------------------------------------------------------------------------------
unsigned __stdcall wiimote::AsyncRumbleThreadfunc (void* param)
{
// auto-disables rumble after x milliseconds:
_ASSERT(param);
wiimote &remote = *(wiimote*)param;
while(remote.IsConnected())
{
if(remote.AsyncRumbleTimeout)
{
DWORD current_time = timeGetTime();
if(current_time >= remote.AsyncRumbleTimeout)
{
if(remote.Internal.bRumble)
remote.SetRumble(false);
remote.AsyncRumbleTimeout = 0;
}
Sleep(1);
}
else
Sleep(4);
}
return 0;
}
// ------------------------------------------------------------------------------------
void wiimote::RumbleForAsync (unsigned milliseconds)
{
// rumble for a fixed amount of time
_ASSERT(IsConnected());
if(!IsConnected())
return;
SetRumble(true);
// show how long thread should wait to disable rumble again
// (it it's currently rumbling it will just extend the time)
AsyncRumbleTimeout = timeGetTime() + milliseconds;
// create the thread?
if(AsyncRumbleThread)
return;
AsyncRumbleThread = (HANDLE)_beginthreadex(NULL, 0, AsyncRumbleThreadfunc, this,
0, NULL);
_ASSERT(AsyncRumbleThread);
if(!AsyncRumbleThread) {
WARN(_T("couldn't create rumble thread!"));
return;
}
SetThreadPriority(AsyncRumbleThread, WORKER_THREAD_PRIORITY);
}
// ------------------------------------------------------------------------------------
void wiimote::RequestStatusReport ()
{
// (this can be called before we're fully connected)
_ASSERT(Handle != INVALID_HANDLE_VALUE);
if(Handle == INVALID_HANDLE_VALUE)
return;
ClearReport();
WriteBuff[0] = OUT_STATUS;
WriteBuff[1] = GetRumbleBit();
WriteReport();
}
// ------------------------------------------------------------------------------------
bool wiimote::ReadAddress (int address, short size)
{
// asynchronous
ClearReport();
WriteBuff[0] = OUT_READMEMORY;
WriteBuff[1] = ((address & 0xff000000) >> 24) | GetRumbleBit();
WriteBuff[2] = (address & 0x00ff0000) >> 16;
WriteBuff[3] = (address & 0x0000ff00) >> 8;
WriteBuff[4] = (address & 0x000000ff);
WriteBuff[5] = (size & 0xff00 ) >> 8;
WriteBuff[6] = (size & 0xff);
return WriteReport();
}
// ------------------------------------------------------------------------------------
void wiimote::WriteData (int address, BYTE size, const BYTE* buff)
{
// asynchronous
ClearReport();
WriteBuff[0] = OUT_WRITEMEMORY;
WriteBuff[1] = ((address & 0xff000000) >> 24) | GetRumbleBit();
WriteBuff[2] = (address & 0x00ff0000) >> 16;
WriteBuff[3] = (address & 0x0000ff00) >> 8;
WriteBuff[4] = (address & 0x000000ff);
WriteBuff[5] = size;
memcpy(WriteBuff+6, buff, size);
WriteReport();
}
// ------------------------------------------------------------------------------------
int wiimote::ParseInput (BYTE* buff)
{
int changed = 0;
// lock our internal state (so RefreshState() is blocked until we're done
EnterCriticalSection(&StateLock);
switch(buff[0])
{
case IN_BUTTONS:
DEEP_TRACE(_T(".. parsing buttons."));
changed |= ParseButtons(buff);
break;
case IN_BUTTONS_ACCEL:
DEEP_TRACE(_T(".. parsing buttons/accel."));
changed |= ParseButtons(buff);
changed |= ParseAccel (buff);
break;
case IN_BUTTONS_ACCEL_EXT:
DEEP_TRACE(_T(".. parsing extenion/accel."));
changed |= ParseButtons (buff);
changed |= ParseAccel (buff);
DecryptBuffer (buff, REPORT_LENGTH);
changed |= ParseExtension(buff, 6);
break;
case IN_BUTTONS_ACCEL_IR:
DEEP_TRACE(_T(".. parsing ir/accel."));
changed |= ParseButtons(buff);
changed |= ParseAccel (buff);
changed |= ParseIR (buff);
break;
case IN_BUTTONS_ACCEL_IR_EXT:
DEEP_TRACE(_T(".. parsing ir/extenion/accel."));
changed |= ParseButtons(buff);
changed |= ParseAccel (buff);
changed |= ParseIR (buff);
DecryptBuffer (buff, REPORT_LENGTH);
changed |= ParseExtension(buff, 16);
break;
case IN_READADDRESS:
DEEP_TRACE(_T(".. parsing read address."));
changed |= ParseButtons (buff);
changed |= ParseReadAddress(buff);
break;
case IN_STATUS:
{
DEEP_TRACE(_T(".. parsing status."));
changed |= ParseStatus(buff);
// show that we received the status report (used for output method
// detection during Connect())
bStatusReceived = true;
}
break;
default:
DEEP_TRACE(_T(".. ** Unknown input ** (happens)."));
///_ASSERT(0);
//Debug.WriteLine("Unknown report type: " + type.ToString());
LeaveCriticalSection(&StateLock);
return false;
}
// if we're recording and some state we care about has changed, insert it into
// the state history
if(Recording.bEnabled && (changed & Recording.TriggerFlags))
{
DEEP_TRACE(_T(".. adding state to history"));
state_event event;
event.time_ms = timeGetTime();
event.state = *(wiimote_state*)this;
Recording.StateHistory->push_back(event);
}
// for polling: show which state has changed since the last RefreshState()
Internal.Polling.Changes = (state_change_flags)(Internal.Polling.Changes | changed);
// callbacks: call it (if set & state the app is interested in has changed)
if(ChangedCallback && (changed & CallbackTriggerFlags)) {
_RefreshState(true);
DEEP_TRACE(_T(".. calling state change callback"));
ChangedCallback(*this, (state_change_flags)changed);
}
LeaveCriticalSection(&StateLock);
DEEP_TRACE(_T(".. parse complete."));
return true;
}
// ------------------------------------------------------------------------------------
state_change_flags wiimote::_RefreshState (bool for_callbacks)
{
// nothing changed since the last call?
if(Internal.Polling.Changes == NO_CHANGE)
return NO_CHANGE;
// copy the internal state to our public data:
// synchronise the interal state with the read/parse thread (we don't want
// values changing during the copy)
if(!for_callbacks)
EnterCriticalSection(&StateLock);
// preserve the application-set deadzones (if any)
joystick::deadzone nunchuk_deadzone = Nunchuk.Joystick.DeadZone;
joystick::deadzone classic_joyl_deadzone = ClassicController.JoystickL.DeadZone;
joystick::deadzone classic_joyr_deadzone = ClassicController.JoystickR.DeadZone;
*(wiimote_state*)this = Internal;
if(!for_callbacks)
Internal.Polling.Changes = NO_CHANGE;
// restore the application-set deadzones
Nunchuk.Joystick.DeadZone = nunchuk_deadzone;
ClassicController.JoystickL.DeadZone = classic_joyl_deadzone;
ClassicController.JoystickR.DeadZone = classic_joyr_deadzone;
if(!for_callbacks)
LeaveCriticalSection(&StateLock);
return Polling.Changes;
}
// ------------------------------------------------------------------------------------
void wiimote::InitializeExtension ()
{
WriteData (REGISTER_EXTENSION_INIT, 0x00);
ReadAddress(REGISTER_EXTENSION_TYPE, 2);
}
// ------------------------------------------------------------------------------------
void wiimote::DecryptBuffer (BYTE *buff, unsigned size)
{
for(unsigned i=0; i<size; i++)
buff[i] = ((buff[i] ^ 0x17) + 0x17) & 0xff;
}
// ------------------------------------------------------------------------------------
int wiimote::ParseStatus (BYTE* buff)
{
// parse the buttons
int changed = ParseButtons(buff);
// get the battery level
BYTE battery_raw = buff[6];
if(Internal.BatteryRaw != battery_raw)
changed |= BATTERY_CHANGED;
Internal.BatteryRaw = battery_raw;
// it is *estimated* that 200 is the maximum possible battery level
Internal.BatteryPercent = battery_raw / 2;
// leds
BYTE leds = buff[3] >> 4;
if(leds != Internal.LED.Bits)
changed |= LEDS_CHANGED;
Internal.LED.Bits = leds;
bool extension = ((buff[3] & 0x02) != 0);
if(extension)
{
if(!Internal.bExtension)//(ExtensionType == wiimote_state::NONE))// ||
//(ExtensionType == wiimote_state::PARTIALLY_INSERTED))
{
TRACE(_T("Extension connected:"));
Internal.bExtension = extension;
InitializeExtension();
// reenable reports
// SetReportType(ReportType);
}
}
else if(Internal.bExtension)
{
TRACE(_T("Extension disconnected."));
Internal.bExtension = false;
Internal.ExtensionType = wiimote_state::NONE;
changed |= EXTENSION_DISCONNECTED;
// renable reports
SetReportType(ReportType);
}
return changed;
}
// ------------------------------------------------------------------------------------
int wiimote::ParseButtons (BYTE* buff)
{
int changed = 0;
WORD bits = *(WORD*)(buff+1);
if(bits != Internal.Button.Bits)
changed |= BUTTONS_CHANGED;
Internal.Button.Bits = bits;
return changed;
}
// ------------------------------------------------------------------------------------
bool wiimote::EstimateOrientationFrom (volatile wiimote_state::acceleration &accel)
{
// Orientation estimate from acceleration data (shared between wiimote and nunchuk)
// return true if the orientation was updated
// assume the controller is stationary if the acceleration vector is near
// 1g for several updates (this may not always be correct)
float length_sq = square(accel.X) + square(accel.Y) + square(accel.Z);
// TODO: as I'm comparing squared length, I really need different
// min/max epsilons...
#define DOT(x1,y1,z1, x2,y2,z2) ((x1*x2) + (y1*y2) + (z1*z2))
static const float epsilon = 0.2f;
if((length_sq >= (1.f-epsilon)) && (length_sq <= (1.f+epsilon)))
{
if(++WiimoteNearGUpdates < 2)
return false;
// wiimote seems to be stationary: normalize the current acceleration
// (ie. the assumed gravity vector)
float inv_len = 1.f / sqrtf(length_sq);
float x = accel.X * inv_len;
float y = accel.Y * inv_len;
float z = accel.Z * inv_len;
// copy the values
accel.Orientation.X = x;
accel.Orientation.Y = y;
accel.Orientation.Z = z;
// and extract pitch & roll from them:
// (may not be optimal)
float pitch = -asinf(y) * 57.2957795f;
float roll = asinf(x) * 57.2957795f;
if(z < 0) {
pitch = (y < 0)? 180 - pitch : -180 - pitch;
roll = (x < 0)? -180 - roll : 180 - roll;
}
accel.Orientation.Pitch = pitch;
accel.Orientation.Roll = roll;
// show that we just updated orientation
accel.Orientation.UpdateAge = 0;
#ifdef BEEP_ON_ORIENTATION_ESTIMATE
Beep(2000, 1);
#endif
return true; // updated
}
// not updated this time:
WiimoteNearGUpdates = 0;
// age the last orientation update
accel.Orientation.UpdateAge++;
return false;
}
// ------------------------------------------------------------------------------------
void wiimote::ApplyJoystickDeadZonesAndWrite (volatile wiimote_state::joystick &joy,
float new_x, float new_y)
{
// apply the deadzones to each axis (if set)
if((joy.DeadZone.X > 0.f) && (joy.DeadZone.X <= 1.f))
{
if(fabs(new_x) <= joy.DeadZone.X)
new_x = 0;
else{
new_x -= joy.DeadZone.X * sign(new_x);
new_x /= 1.f - joy.DeadZone.X;
}
}
if((joy.DeadZone.Y > 0.f) && (joy.DeadZone.Y <= 1.f))
{
if(fabs(new_y) <= joy.DeadZone.Y)
new_y = 0;
else{
new_y -= joy.DeadZone.Y * sign(new_y);
new_y /= 1.f - joy.DeadZone.Y;
}
}
// and write the processed values to the state (this must always happen last so
// that no intermediate values are written to the state & possibly read by the app)
joy.X = new_x;
joy.Y = new_y;
}
// ------------------------------------------------------------------------------------
int wiimote::ParseAccel (BYTE* buff)
{
int changed = 0;
BYTE raw_x = buff[3];
BYTE raw_y = buff[4];
BYTE raw_z = buff[5];
if((raw_x != Internal.Acceleration.RawX) ||
(raw_y != Internal.Acceleration.RawY) ||
(raw_z != Internal.Acceleration.RawZ))
changed |= ACCEL_CHANGED;
Internal.Acceleration.RawX = raw_x;
Internal.Acceleration.RawY = raw_y;
Internal.Acceleration.RawZ = raw_z;
Internal.Acceleration.X = ((float)Internal.Acceleration.RawX - Internal.CalibrationInfo.X0) /
((float)Internal.CalibrationInfo.XG - Internal.CalibrationInfo.X0);
Internal.Acceleration.Y = ((float)Internal.Acceleration.RawY - Internal.CalibrationInfo.Y0) /
((float)Internal.CalibrationInfo.YG - Internal.CalibrationInfo.Y0);
Internal.Acceleration.Z = ((float)Internal.Acceleration.RawZ - Internal.CalibrationInfo.Z0) /
((float)Internal.CalibrationInfo.ZG - Internal.CalibrationInfo.Z0);
// see if we can estimate the orientation from the current values
if(EstimateOrientationFrom(Internal.Acceleration))
changed |= ORIENTATION_CHANGED;
return changed;
}
// ------------------------------------------------------------------------------------
int wiimote::ParseIR (BYTE* buff)
{
if(Internal.IR.Mode == wiimote_state::ir::OFF)
return NO_CHANGE;
// take a copy of the existing IR state (so we can detect changes)
wiimote_state::ir prev_ir = Internal.IR;
// only update the other values if the dots are visible (so that the last
// valid values stay unmodified)
switch(Internal.IR.Mode)
{
case wiimote_state::ir::BASIC:
Internal.IR.Dot[0].Size = 0;
Internal.IR.Dot[1].Size = 0;
Internal.IR.Dot[0].bFound = !(buff[6] == 0xff && buff[ 7] == 0xff);
Internal.IR.Dot[1].bFound = !(buff[9] == 0xff && buff[10] == 0xff);
if(Internal.IR.Dot[1].bFound) {
Internal.IR.Dot[1].RawX = buff[ 9] | ((buff[8] >> 0) & 0x03) << 8;
Internal.IR.Dot[1].RawY = buff[10] | ((buff[8] >> 2) & 0x03) << 8;
}
break;
case wiimote_state::ir::EXTENDED:
Internal.IR.Dot[0].bFound = !(buff[6]==0xff && buff[ 7]==0xff && buff[ 8]==0xff);
Internal.IR.Dot[1].bFound = !(buff[9]==0xff && buff[10]==0xff && buff[11]==0xff);
if(Internal.IR.Dot[0].bFound)
Internal.IR.Dot[0].Size = buff[8] & 0x0f;
if(Internal.IR.Dot[1].bFound) {
Internal.IR.Dot[1].RawX = buff[ 9] | ((buff[11] >> 4) & 0x03) << 8;
Internal.IR.Dot[1].RawY = buff[10] | ((buff[11] >> 6) & 0x03) << 8;
Internal.IR.Dot[1].Size = buff[11] & 0x0f;
}
break;
}
// in theory the imager is 1024x768 (and so should report 0-1023 x 0-767)
// in practice I have never seen the reports exceed the values below,
// so I'm using them instead to give the full 0-1 range
// (it's possible that the edge pixels are used for processing, or masked
// out due to being unreliable)
static const unsigned MAX_IR_X = 1016;
static const unsigned MAX_IR_Y = 760;
if(Internal.IR.Dot[0].bFound) {
Internal.IR.Dot[0].RawX = buff[6] | ((buff[8] >> 4) & 0x03) << 8;;
Internal.IR.Dot[0].RawY = buff[7] | ((buff[8] >> 6) & 0x03) << 8;;
Internal.IR.Dot[0].X = 1.f - (Internal.IR.Dot[0].RawX / (float)MAX_IR_X);
Internal.IR.Dot[0].Y = (Internal.IR.Dot[0].RawY / (float)MAX_IR_Y);
#ifdef _DEBUG
// warn developer to report values outside my assumptions
if((Internal.IR.Dot[0].RawX > MAX_IR_X) ||
(Internal.IR.Dot[0].RawY > MAX_IR_Y))
_Message(_T("Wiimote reported raw IR dot0 values larger than expected! :\n")
_T("\n")
_T(" X: %d Y: %d\n")
_T("\n")
_T("Please report these values so I can update the lib:\n")
_T(" glATr-i-lDOTnet\n"), Internal.IR.Dot[0].RawX,
Internal.IR.Dot[0].RawY);
#endif // _DEBUG
}
if(Internal.IR.Dot[1].bFound) {
Internal.IR.Dot[1].X = 1.f - (Internal.IR.Dot[1].RawX / (float)MAX_IR_X);
Internal.IR.Dot[1].Y = (Internal.IR.Dot[1].RawY / (float)MAX_IR_Y);
#ifdef _DEBUG
// warn developer to report values outside my assumptions
if((Internal.IR.Dot[1].RawX > MAX_IR_X) ||
(Internal.IR.Dot[1].RawY > MAX_IR_Y))
_Message(_T("Wiimote reported raw IR dot1 values larger than expected! :\n")
_T("\n")
_T(" X: %d Y: %d\n")
_T("\n")
_T("Please report these values so I can update the lib:\n")
_T(" glATr-i-lDOTnet\n"), Internal.IR.Dot[1].RawX,
Internal.IR.Dot[1].RawY);
#endif // _DEBUG
}
return (memcmp(&prev_ir, &Internal.IR, sizeof(Internal.IR)) != 0)? IR_CHANGED : 0;
}
// ------------------------------------------------------------------------------------
int wiimote::ParseExtension (BYTE *buff, unsigned offset)
{
int changed = 0;
switch(Internal.ExtensionType)
{
case wiimote_state::NUNCHUK:
{
// buttons
bool c = (buff[offset+5] & 0x02) == 0;
bool z = (buff[offset+5] & 0x01) == 0;
if((c != Internal.Nunchuk.C) || (z != Internal.Nunchuk.Z))
changed |= NUNCHUK_BUTTONS_CHANGED;
Internal.Nunchuk.C = c;
Internal.Nunchuk.Z = z;
// acceleration
volatile wiimote_state::acceleration &accel = Internal.Nunchuk.Acceleration;
BYTE raw_x = buff[offset+2];
BYTE raw_y = buff[offset+3];
BYTE raw_z = buff[offset+4];
if((raw_x != accel.RawX) || (raw_y != accel.RawY) || (raw_z != accel.RawZ))
changed |= NUNCHUK_ACCEL_CHANGED;
accel.RawX = raw_x;
accel.RawY = raw_y;
accel.RawZ = raw_z;
accel.X = ((float)accel.RawX - Internal.Nunchuk.CalibrationInfo.X0) /
((float)Internal.Nunchuk.CalibrationInfo.XG -
Internal.Nunchuk.CalibrationInfo.X0);
accel.Y = ((float)accel.RawY - Internal.Nunchuk.CalibrationInfo.Y0) /
((float)Internal.Nunchuk.CalibrationInfo.YG -
Internal.Nunchuk.CalibrationInfo.Y0);
accel.Z = ((float)accel.RawZ - Internal.Nunchuk.CalibrationInfo.Z0) /
((float)Internal.Nunchuk.CalibrationInfo.ZG -
Internal.Nunchuk.CalibrationInfo.Z0);
// try to extract orientation from the accel:
if(EstimateOrientationFrom(accel))
changed |= NUNCHUK_ORIENTATION_CHANGED;
// joystick:
volatile wiimote_state::joystick &joy = Internal.Nunchuk.Joystick;
joy.RawX = buff[offset+0];
joy.RawY = buff[offset+1];
float x,y;
if(Internal.Nunchuk.CalibrationInfo.MaxX != 0x00)
x = ((float)joy.RawX - Internal.Nunchuk.CalibrationInfo.MidX) /
((float)Internal.Nunchuk.CalibrationInfo.MaxX -
Internal.Nunchuk.CalibrationInfo.MinX);
if(Internal.Nunchuk.CalibrationInfo.MaxY != 0x00)
y = ((float)joy.RawY - Internal.Nunchuk.CalibrationInfo.MidY) /
((float)Internal.Nunchuk.CalibrationInfo.MaxY -
Internal.Nunchuk.CalibrationInfo.MinY);
// i prefer the outputs to range -1 - +1 (note this also affects the
// deadzone calculations)
x *= 2; y *= 2;
// apply the deazones (if any) and write the final values to the state
float curr_x = Internal.Nunchuk.Joystick.X;
float curr_y = Internal.Nunchuk.Joystick.Y;
ApplyJoystickDeadZonesAndWrite(joy, x, y);
if((Internal.Nunchuk.Joystick.X != curr_x) ||
(Internal.Nunchuk.Joystick.Y != curr_y))
changed |= NUNCHUK_JOYSTICK_CHANGED;
}
break;
case wiimote_state::CLASSIC:
{
// buttons:
WORD bits = *(WORD*)(buff+4);
if(bits != Internal.ClassicController.Button.Bits)
changed |= CLASSIC_BUTTONS_CHANGED;
Internal.ClassicController.Button.Bits = bits;
// joysticks:
wiimote_state::joystick &joyL = Internal.ClassicController.JoystickL;
wiimote_state::joystick &joyR = Internal.ClassicController.JoystickR;
// copy the current joystick state to detect changes
wiimote_state::joystick curr_joy_l = joyL;
wiimote_state::joystick curr_joy_r = joyR;
joyL.RawX = (float) (buff[offset+0] & 0x3f);
joyL.RawY = (float) (buff[offset+1] & 0x3f);
joyR.RawX = (float)((buff[offset+2] >> 7) |
((buff[offset+1] & 0xc0) >> 5) |
((buff[offset+0] & 0xc0) >> 3));
joyR.RawY = (float) (buff[offset+2] & 0x1f);
float xr, yr, xl, yl;
if(Internal.ClassicController.CalibrationInfo.MaxXL != 0x00)
xl = ((float)joyL.RawX - Internal.ClassicController.CalibrationInfo.MidXL) /
((float)Internal.ClassicController.CalibrationInfo.MaxXL -
Internal.ClassicController.CalibrationInfo.MinXL);
if(Internal.ClassicController.CalibrationInfo.MaxYL != 0x00)
yl = ((float)joyL.RawY - Internal.ClassicController.CalibrationInfo.MidYL) /
((float)Internal.ClassicController.CalibrationInfo.MaxYL -
Internal.ClassicController.CalibrationInfo.MinYL);
if(Internal.ClassicController.CalibrationInfo.MaxXR != 0x00)
xr = ((float)joyR.RawX - Internal.ClassicController.CalibrationInfo.MidXR) /
((float)Internal.ClassicController.CalibrationInfo.MaxXR -
Internal.ClassicController.CalibrationInfo.MinXR);
if(Internal.ClassicController.CalibrationInfo.MaxYR != 0x00)
yr = ((float)joyR.RawY - Internal.ClassicController.CalibrationInfo.MidYR) /
((float)Internal.ClassicController.CalibrationInfo.MaxYR -
Internal.ClassicController.CalibrationInfo.MinYR);
// i prefer the joystick outputs to range -1 - +1 (note this also affects
// the deadzone calculations)
xl *= 2; yl *= 2; xr *= 2; yr *= 2;
// apply the deazones (if any) and write the final values to the state
ApplyJoystickDeadZonesAndWrite(joyL, xl, yl);
ApplyJoystickDeadZonesAndWrite(joyR, xr, yr);
// have the joystick states changed?
if(memcmp(&curr_joy_l, &joyL, sizeof(curr_joy_l)) != 0)
changed |= CLASSIC_JOYSTICK_L_CHANGED;
if(memcmp(&curr_joy_r, &joyR, sizeof(curr_joy_r)) != 0)
changed |= CLASSIC_JOYSTICK_R_CHANGED;
// triggers
BYTE raw_trigger_l = ((buff[offset+2] & 0x60) >> 2) |
(buff[offset+3] >> 5);
BYTE raw_trigger_r = buff[offset+3] & 0x1f;
if((raw_trigger_l != Internal.ClassicController.RawTriggerL) ||
(raw_trigger_r != Internal.ClassicController.RawTriggerR))
changed |= CLASSIC_TRIGGERS_CHANGED;
Internal.ClassicController.RawTriggerL = raw_trigger_l;
Internal.ClassicController.RawTriggerR = raw_trigger_r;
if(Internal.ClassicController.CalibrationInfo.MaxTriggerL != 0x00)
Internal.ClassicController.TriggerL =
(float)Internal.ClassicController.RawTriggerL /
((float)Internal.ClassicController.CalibrationInfo.MaxTriggerL -
Internal.ClassicController.CalibrationInfo.MinTriggerL);
if(Internal.ClassicController.CalibrationInfo.MaxTriggerR != 0x00)
Internal.ClassicController.TriggerR =
(float)Internal.ClassicController.RawTriggerR /
((float)Internal.ClassicController.CalibrationInfo.MaxTriggerR -
Internal.ClassicController.CalibrationInfo.MinTriggerR);
}
break;
}
return changed;
}
// ------------------------------------------------------------------------------------
int wiimote::ParseReadAddress (BYTE* buff)
{
int changed = 0;
if((buff[3] & 0x08) != 0) {
WARN(_T("error: read address not valid."));
_ASSERT(0);
return NO_CHANGE;
}
else if((buff[3] & 0x07) != 0) {
WARN(_T("error: attempt to read from write-only registers."));
_ASSERT(0);
return NO_CHANGE;
}
int size = buff[3] >> 4;
// decode the address that was queried
int address = buff[4]<<8 | buff[5];
// *NOTE*: this is a major (but convenient) hack! The returned data only
// contains the lower two bytes of the address that was queried.
// as these don't collide between any of the addresses/registers
// we currently read, it's OK to match just those two bytes
// and skip the header:
buff += 6;
switch(address)
{
case (REGISTER_CALIBRATION & 0xffff):
{
_ASSERT(size == 6);
Internal.CalibrationInfo.X0 = buff[0];
Internal.CalibrationInfo.Y0 = buff[1];
Internal.CalibrationInfo.Z0 = buff[2];
Internal.CalibrationInfo.XG = buff[4];
Internal.CalibrationInfo.YG = buff[5];
Internal.CalibrationInfo.ZG = buff[6];
//changed |= CALIBRATION_CHANGED;
}
break;
case (REGISTER_EXTENSION_TYPE & 0xffff):
{
_ASSERT(size == 1);
if(*(WORD*)buff == wiimote_state::NUNCHUK)
{
// sometimes it comes in more than once?
if(Internal.ExtensionType == wiimote_state::NUNCHUK)
break;
TRACE(_T(".. Nunchuk!"));
Internal.ExtensionType = wiimote_state::NUNCHUK;
// and start a query for the calibration data
ReadAddress(REGISTER_EXTENSION_CALIBRATION, 16);
}
else if(*(WORD*)buff == wiimote_state::CLASSIC)
{
// sometimes it comes in more than once?
if(Internal.ExtensionType == wiimote_state::CLASSIC)
break;
TRACE(_T(".. Classic Controller!"));
Internal.ExtensionType = wiimote_state::CLASSIC;
// and start a query for the calibration data
ReadAddress(REGISTER_EXTENSION_CALIBRATION, 16);
}
else if(*(WORD*)buff == wiimote_state::PARTIALLY_INSERTED) {
// sometimes it comes in more than once?
if(Internal.ExtensionType == wiimote_state::PARTIALLY_INSERTED)
break;
TRACE(_T(".. partially inserted!"));
Internal.ExtensionType = wiimote_state::PARTIALLY_INSERTED;
changed |= EXTENSION_PARTIALLY_INSERTED;
// try initializing the extension again next time by requesting
// another status report (this usually fixes it)
Internal.bExtension = false;
RequestStatusReport();
}
else{
WARN(_T("unknown extension controller found (0x%x)"), buff[0]);
}
}
break;
case (REGISTER_EXTENSION_CALIBRATION & 0xffff):
{
_ASSERT(size == 15);
DecryptBuffer(buff, 16);
switch(Internal.ExtensionType)
{
case wiimote_state::NUNCHUK:
{
Internal.Nunchuk.CalibrationInfo.X0 = buff[0];
Internal.Nunchuk.CalibrationInfo.Y0 = buff[1];
Internal.Nunchuk.CalibrationInfo.Z0 = buff[2];
Internal.Nunchuk.CalibrationInfo.XG = buff[4];
Internal.Nunchuk.CalibrationInfo.YG = buff[5];
Internal.Nunchuk.CalibrationInfo.ZG = buff[6];
Internal.Nunchuk.CalibrationInfo.MaxX = buff[8];
Internal.Nunchuk.CalibrationInfo.MinX = buff[9];
Internal.Nunchuk.CalibrationInfo.MidX = buff[10];
Internal.Nunchuk.CalibrationInfo.MaxY = buff[11];
Internal.Nunchuk.CalibrationInfo.MinY = buff[12];
Internal.Nunchuk.CalibrationInfo.MidY = buff[13];
changed |= NUNCHUK_CONNECTED;//|NUNCHUK_CALIBRATION_CHANGED;
// reenable reports
SetReportType(ReportType);
}
break;
case wiimote_state::CLASSIC:
{
Internal.ClassicController.CalibrationInfo.MaxXL = buff[ 0] >> 2;
Internal.ClassicController.CalibrationInfo.MinXL = buff[ 1] >> 2;
Internal.ClassicController.CalibrationInfo.MidXL = buff[ 2] >> 2;
Internal.ClassicController.CalibrationInfo.MaxYL = buff[ 3] >> 2;
Internal.ClassicController.CalibrationInfo.MinYL = buff[ 4] >> 2;
Internal.ClassicController.CalibrationInfo.MidYL = buff[ 5] >> 2;
Internal.ClassicController.CalibrationInfo.MaxXR = buff[ 6] >> 3;
Internal.ClassicController.CalibrationInfo.MinXR = buff[ 7] >> 3;
Internal.ClassicController.CalibrationInfo.MidXR = buff[ 8] >> 3;
Internal.ClassicController.CalibrationInfo.MaxYR = buff[ 9] >> 3;
Internal.ClassicController.CalibrationInfo.MinYR = buff[10] >> 3;
Internal.ClassicController.CalibrationInfo.MidYR = buff[11] >> 3;
// this doesn't seem right...
// Internal.ClassicController.CalibrationInfo.MinTriggerL = buff[12] >> 3;
// Internal.ClassicController.CalibrationInfo.MaxTriggerL = buff[14] >> 3;
// Internal.ClassicController.CalibrationInfo.MinTriggerR = buff[13] >> 3;
// Internal.ClassicController.CalibrationInfo.MaxTriggerR = buff[15] >> 3;
Internal.ClassicController.CalibrationInfo.MinTriggerL = 0;
Internal.ClassicController.CalibrationInfo.MaxTriggerL = 31;
Internal.ClassicController.CalibrationInfo.MinTriggerR = 0;
Internal.ClassicController.CalibrationInfo.MaxTriggerR = 31;
changed |= CLASSIC_CONNECTED;//|CLASSIC_CALIBRATION_CHANGED;
// reenable reports
SetReportType(ReportType);
}
break;
}
}
break;
default:
_ASSERT(0); // shouldn't happen
break;
}
return changed;
}
// ------------------------------------------------------------------------------------
void wiimote::ReadCalibration ()
{
// this appears to change the report type to 0x31
ReadAddress(REGISTER_CALIBRATION, 7);
}
// ------------------------------------------------------------------------------------
void wiimote::EnableIR (wiimote_state::ir::mode mode)
{
Internal.IR.Mode = mode;
ClearReport();
WriteBuff[0] = OUT_IR;
WriteBuff[1] = 0x04 | GetRumbleBit();
WriteReport();
ClearReport();
WriteBuff[0] = OUT_IR2;
WriteBuff[1] = 0x04 | GetRumbleBit();
WriteReport();
static const BYTE ir_sens1[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x00, 0xc0};
static const BYTE ir_sens2[] = {0x40, 0x00};
WriteData(REGISTER_IR, 0x08);
WriteData(REGISTER_IR_SENSITIVITY_1, sizeof(ir_sens1), ir_sens1);
WriteData(REGISTER_IR_SENSITIVITY_2, sizeof(ir_sens2), ir_sens2);
WriteData(REGISTER_IR_MODE, mode);
}
// ------------------------------------------------------------------------------------
void wiimote::DisableIR ()
{
Internal.IR.Mode = wiimote_state::ir::OFF;
ClearReport();
WriteBuff[0] = OUT_IR;
WriteBuff[1] = GetRumbleBit();
WriteReport();
ClearReport();
WriteBuff[0] = OUT_IR2;
WriteBuff[1] = GetRumbleBit();
WriteReport();
}
// ------------------------------------------------------------------------------------
unsigned __stdcall wiimote::HIDwriteThreadfunc (void* param)
{
_ASSERT(param);
TRACE(_T("(starting HID write thread)"));
wiimote &remote = *(wiimote*)param;
while(remote.Handle != INVALID_HANDLE_VALUE)
{
// try to write the oldest entry in the queue
if(!remote.HIDwriteQueue.empty())
{
#ifdef BEEP_DEBUG_WRITES
Beep(1500,1);
#endif
EnterCriticalSection(&remote.HIDwriteQueueLock);
BYTE *buff = remote.HIDwriteQueue.front();
LeaveCriticalSection(&remote.HIDwriteQueueLock);
_ASSERT(buff);
if(!_HidD_SetOutputReport(remote.Handle, buff, REPORT_LENGTH))
{
DWORD err = GetLastError();
if((err != ERROR_BUSY) && // "the requested resource is in use"
(err != ERROR_NOT_READY)) // "the device is not ready"
{
if(err == ERROR_NOT_SUPPORTED)
WARN(_T("BT Stack doesn't suport HID writes!"));
else{
DEEP_TRACE(_T("HID write to Wiimote failed (err %u)! - "), err);
// if this worked previously, the connection was probably lost
if(remote.IsConnected())
remote.bConnectionLost = true;
}
//_T("aborting write thread"), err);
//return 911;
}
}
else{
delete[] buff;
EnterCriticalSection(&remote.HIDwriteQueueLock);
remote.HIDwriteQueue.pop();
LeaveCriticalSection(&remote.HIDwriteQueueLock);
}
}
Sleep(1);
}
TRACE(_T("ending HID write thread"));
return 0;
}
// ------------------------------------------------------------------------------------
bool wiimote::WriteReport (BYTE *buff)
{
// NULL means 'use WriteBuff'
if(!buff)
buff = WriteBuff;
#ifdef BEEP_DEBUG_WRITES
Beep(2000,1);
#endif
if(bUseHIDwrite)
{
// HidD_SetOutputReport: +: works on MS Bluetooth stacks (WriteFile doesn't).
// -: is synchronous, so make it async
if(!HIDwriteThread)
{
HIDwriteThread = (HANDLE)_beginthreadex(NULL, 0, HIDwriteThreadfunc,
this, 0, NULL);
_ASSERT(HIDwriteThread);
if(!HIDwriteThread) {
WARN(_T("couldn't create HID write thread!"));
return false;
}
SetThreadPriority(HIDwriteThread, WORKER_THREAD_PRIORITY);
}
// insert the write request into the thread's queue
BYTE *buff_copy = new BYTE[REPORT_LENGTH];
_ASSERT(buff_copy);
memcpy(buff_copy, buff, REPORT_LENGTH);
EnterCriticalSection(&HIDwriteQueueLock);
HIDwriteQueue.push(buff_copy);
LeaveCriticalSection(&HIDwriteQueueLock);
return true;
}
// WriteFile:
DWORD written;
// have we been asked to cancel any pending IO
if(!WriteFile(Handle, buff, REPORT_LENGTH, &written, &Overlapped))
{
DWORD error = GetLastError();
if(error != ERROR_IO_PENDING) {
DEEP_TRACE(_T("WriteFile failed!"));
// if it worked previously, assume we lost the connection
if(IsConnected())
bConnectionLost = true;
return false;
}
}
return true;
}
// ------------------------------------------------------------------------------------
// experimental speaker support:
// ------------------------------------------------------------------------------------
bool wiimote::MuteSpeaker (bool on)
{
_ASSERT(IsConnected());
if(!IsConnected())
return false;
if(Internal.Speaker.bMuted == on)
return true;
if(on) TRACE(_T("muting speaker." ));
else TRACE(_T("unmuting speaker."));
WriteBuff[0] = OUT_SPEAKER_MUTE;
WriteBuff[1] = (on? 0x04 : 0x00) | GetRumbleBit();
if(!WriteReport())
return false;
Internal.Speaker.bMuted = on;
return true;
}
// ------------------------------------------------------------------------------------
bool wiimote::EnableSpeaker (bool on)
{
_ASSERT(IsConnected());
if(!IsConnected())
return false;
if(Internal.Speaker.bEnabled == on)
return true;
if(on) TRACE(_T("enabling speaker.")); else TRACE(_T("disabling speaker."));
WriteBuff[0] = OUT_SPEAKER_ENABLE;
WriteBuff[1] = (on? 0x04 : 0x00) | GetRumbleBit();
if(!WriteReport())
return false;
if(!on) {
Internal.Speaker.Freq = FREQ_NONE;
Internal.Speaker.Volume = 0;
MuteSpeaker(true);
}
Internal.Speaker.bEnabled = on;
return true;
}
// ------------------------------------------------------------------------------------
#ifdef TR4
// TEMP:
extern int hzinc;
#endif
unsigned __stdcall wiimote::SampleStreamThreadfunc (void* param)
{
TRACE(_T("(starting sample thread)"));
// sends a simple square wave sample stream
wiimote &remote = *(wiimote*)param;
static BYTE squarewave_report[REPORT_LENGTH] =
{ OUT_SPEAKER_DATA, 20<<3, 0xC3,0xC3,0xC3,0xC3,0xC3,0xC3,0xC3,0xC3,0xC3,0xC3,
0xC3,0xC3,0xC3,0xC3,0xC3,0xC3,0xC3,0xC3,0xC3,0xC3, };
static BYTE sample_report [REPORT_LENGTH] =
{ OUT_SPEAKER_DATA, 0 };
bool last_playing = false;
DWORD frame = 0;
DWORD frame_start = 0;
unsigned total_samples = 0;
unsigned sample_index = 0;
wiimote_sample *current_sample = NULL;
// TODO: duration!!
while(remote.IsConnected())
{
bool playing = remote.IsPlayingAudio();
if(!playing)
Sleep(1);
else{
const unsigned freq_hz = FreqLookup[remote.Internal.Speaker.Freq];
#ifdef TR4
const float frame_ms = 1000 / ((freq_hz+hzinc) / 40.f); // 20bytes = 40 samples per write
#else
const float frame_ms = 1000 / (freq_hz / 40.f); // 20bytes = 40 samples per write
#endif
// has the sample just changed?
bool sample_changed = (current_sample != remote.CurrentSample);
current_sample = (wiimote_sample*)remote.CurrentSample;
// (attempts to minimise glitches)
#define FIRSTFRAME_IS_SILENT // send all-zero for first frame
#ifdef FIRSTFRAME_IS_SILENT
bool silent_frame = false;
#endif
if(!last_playing || sample_changed) {
frame = 0;
frame_start = timeGetTime();
total_samples = current_sample? current_sample->length : 0;
sample_index = 0;
#ifdef FIRSTFRAME_IS_SILENT
silent_frame = true;
#endif
}
// are we streaming a sample?
if(current_sample)
{
if(sample_index < current_sample->length)
{
// (remember that samples are 4bit, ie. 2 per byte)
unsigned samples_left = (current_sample->length - sample_index);
unsigned report_samples = min(samples_left, 40);
// round the entries up to the nearest multiple of 2
unsigned report_entries = (report_samples+1) >> 1;
sample_report[1] = (report_entries<<3) | remote.GetRumbleBit();
#ifdef FIRSTFRAME_IS_SILENT
if(silent_frame) {
// send all-zeroes
for(unsigned index=0; index<report_entries; index++)
sample_report[2+index] = 0;
remote.WriteReport(sample_report);
}
else
#endif
{
for(unsigned index=0; index<report_entries; index++)
sample_report[2+index] =
current_sample->samples[(sample_index>>1)+index];
remote.WriteReport(sample_report);
sample_index += report_samples;
}
}
else{
// we reached the sample end
remote.CurrentSample = NULL;
current_sample = NULL;
remote.Internal.Speaker.Freq = FREQ_NONE;
remote.Internal.Speaker.Volume = 0;
}
}
// no, a squarewave
else{
squarewave_report[1] = (20<<3) | remote.GetRumbleBit();
remote.WriteReport(squarewave_report);
#if 0
// verify that we're sending at the correct rate (we are)
DWORD elapsed = (timeGetTime()-frame_start);
unsigned total_samples = frame * 40;
float elapsed_secs = elapsed / 1000.f;
float sent_persec = total_samples / elapsed_secs;
#endif
}
frame++;
// send the first two buffers immediately (seems to lessen startup
// startup glitches - presumably we're filling a small sample
// (or general input) buffer on the wiimote)
// if(frame > 2) {
while((timeGetTime()-frame_start) < (unsigned)(frame*frame_ms))
Sleep(1);
// }
}
last_playing = playing;
}
TRACE(_T("(ending sample thread)"));
return 0;
}
// ------------------------------------------------------------------------------------
bool wiimote::Load16bitMonoSampleWAV (const TCHAR* filepath, wiimote_sample &out)
{
// converts unsigned 16bit mono .wav audio data to the 4bit ADPCM variant
// used by the Wiimote, and returns the data in a BYTE array (user must
// delete[] when no longer needed):
memset(&out, 0, sizeof(out));
TRACE(_T("Loading '%s'"), filepath);
FILE *file;
_tfopen_s(&file, filepath, _T("rb"));
_ASSERT(file);
if(!file) {
WARN(_T("Couldn't open '%s"), filepath);
return false;
}
// parse the .wav file
struct riff_chunkheader {
char ckID [4];
DWORD ckSize;
char formType [4];
};
struct chunk_header {
char ckID [4];
DWORD ckSize;
};
union {
WAVEFORMATEX x;
WAVEFORMATEXTENSIBLE xe;
} wf;
riff_chunkheader riff_chunkheader;
chunk_header chunk_header;
#define READ(data) if(fread(&data, sizeof(data), 1, file) != 1) { \
TRACE(_T(".wav file corrupt")); \
fclose(file); \
return false; \
}
#define READ_SIZE(ptr,size) if(fread(ptr, size, 1, file) != 1) { \
TRACE(_T(".wav file corrupt")); \
fclose(file); \
return false; \
}
// read the riff chunk header
READ(riff_chunkheader);
// valid RIFF file?
_ASSERT(!strncmp(riff_chunkheader.ckID, "RIFF", 4));
if(strncmp(riff_chunkheader.ckID, "RIFF", 4))
goto unsupported; // nope
// valid WAV variant?
_ASSERT(!strncmp(riff_chunkheader.formType, "WAVE", 4));
if(strncmp(riff_chunkheader.formType, "WAVE", 4))
goto unsupported; // nope
// find the format & data chunks
speaker_freq freq = FREQ_NONE;
while(1)
{
READ(chunk_header);
if(!strncmp(chunk_header.ckID, "fmt ", 4))
{
// not a valid .wav file?
if(chunk_header.ckSize < 16 ||
chunk_header.ckSize > sizeof(WAVEFORMATEXTENSIBLE))
goto unsupported;
READ_SIZE((BYTE*)&wf.x, chunk_header.ckSize);
// now we know it's true wav file
bool extensible = (wf.x.wFormatTag == WAVE_FORMAT_EXTENSIBLE);
int format = extensible? wf.xe.SubFormat.Data1 :
wf.x .wFormatTag;
// must be uncompressed PCM (the format comparisons also work on
// the 'extensible' header, even though they're named differently)
if(format != WAVE_FORMAT_PCM) {
_TRACE(_T(".. not uncompressed PCM"));
goto unsupported;
}
// must be mono, 16bit
if((wf.x.nChannels != 1) || (wf.x.wBitsPerSample != 16)) {
_TRACE(_T(".. %d bit, %d channel%s"), wf.x.wBitsPerSample,
wf.x.nChannels,
(wf.x.nChannels>1? _T("s"):_T("")));
goto unsupported;
}
// must be _near_ a supported speaker frequency range (but allow some
// tolerance, especially as the values aren't final yet):
unsigned sample_freq = wf.x.nSamplesPerSec;
const unsigned epsilon = 100; // for now
for(unsigned index=1; index<ARRAY_SIZE(FreqLookup); index++)
{
if((sample_freq+epsilon) >= FreqLookup[index] &&
(sample_freq-epsilon) <= FreqLookup[index]) {
freq = (speaker_freq)index;
TRACE(_T(".. using speaker freq %u"), FreqLookup[index]);
break;
}
}
if(freq == FREQ_NONE) {
WARN(_T("Couldn't (loosely) match .wav samplerate %u Hz to speaker"),
sample_freq);
goto unsupported;
}
}
else if(!strncmp(chunk_header.ckID, "data", 4))
{
// grab the data
unsigned total_samples = chunk_header.ckSize / wf.x.nBlockAlign;
if(total_samples == 0)
goto corrupt_file;
short *samples = new short[total_samples];
size_t read = fread(samples, 2, total_samples, file);
fclose(file);
if(read != total_samples)
{
if(read == 0) {
delete[] samples;
goto corrupt_file;
}
// got a different number, but use them anyway
WARN(_T("found %s .wav audio data than expected (%u/%u samples)"),
((read < total_samples)? _T("less") : _T("more")),
read, total_samples);
total_samples = read;
}
// and convert them
bool res = Convert16bitMonoSamples(samples, true, total_samples,
freq, out);
delete[] samples;
return res;
}
else{
// unknown chunk, skip its data
DWORD chunk_bytes = (chunk_header.ckSize + 1) & ~1L;
if(fseek(file, chunk_bytes, SEEK_CUR))
goto corrupt_file;
}
}
corrupt_file:
WARN(_T(".wav file is corrupt"));
fclose(file);
return false;
unsupported:
WARN(_T(".wav file format not supported (must be mono 16bit PCM)"));
fclose(file);
return false;
}
// ------------------------------------------------------------------------------------
bool wiimote::Load16BitMonoSampleRAW (const TCHAR* filepath,
bool _signed,
speaker_freq freq,
wiimote_sample &out)
{
// converts (.wav style) unsigned 16bit mono raw data to the 4bit ADPCM variant
// used by the Wiimote, and returns the data in a BYTE array (user must
// delete[] when no longer needed):
memset(&out, 0, sizeof(out));
// get the length of the file
struct _stat file_info;
if(_tstat(filepath, &file_info)) {
WARN(_T("couldn't get filesize for '%s'"), filepath);
return false;
}
DWORD len = file_info.st_size;
_ASSERT(len);
if(!len) {
WARN(_T("zero-size sample file '%s'"), filepath);
return false;
}
unsigned total_samples = (len+1) / 2; // round up just in case file is corrupt
// allocate a buffer to hold the samples to convert
short *samples = new short[total_samples];
_ASSERT(samples);
if(!samples) {
TRACE(_T("Couldn't open '%s"), filepath);
return false;
}
// load them
FILE *file;
_tfopen_s(&file, filepath, _T("rb"));
_ASSERT(file);
if(!file) {
TRACE(_T("Couldn't open '%s"), filepath);
goto error;
}
bool res = (fread(samples, 1, len, file) == len);
fclose(file);
if(!res) {
WARN(_T("Couldn't load file '%s'"), filepath);
goto error;
}
// and convert them
res = Convert16bitMonoSamples(samples, _signed, total_samples, freq, out);
delete[] samples;
return res;
error:
delete[] samples;
return false;
}
// ------------------------------------------------------------------------------------
bool wiimote::Convert16bitMonoSamples (const short* samples,
bool _signed,
DWORD length,
speaker_freq freq,
wiimote_sample &out)
{
// converts 16bit mono sample data to the native 4bit format used by the Wiimote,
// and returns the data in a BYTE array (caller must delete[] when no
// longer needed):
memset(&out, 0, sizeof(0));
_ASSERT(samples && length);
if(!samples || !length)
return NULL;
// allocate the output buffer
out.samples = new BYTE[length];
_ASSERT(out.samples);
if(!out.samples)
return NULL;
// clear it
memset(out.samples, 0, length);
out.length = length;
out.freq = freq;
// ADPCM code, adapted from
// http://www.wiindows.org/index.php/Talk:Wiimote#Input.2FOutput_Reports
static const int index_table[16] = { -1, -1, -1, -1, 2, 4, 6, 8,
-1, -1, -1, -1, 2, 4, 6, 8 };
static const int diff_table [16] = { 1, 3, 5, 7, 9, 11, 13, 15,
-1, -3, -5, -7, -9, -11, -13, 15 };
static const int step_scale [16] = { 230, 230, 230, 230, 307, 409, 512, 614,
230, 230, 230, 230, 307, 409, 512, 614 };
// Encode to ADPCM, on initialization set adpcm_prev_value to 0 and adpcm_step
// to 127 (these variables must be preserved across reports)
int adpcm_prev_value = 0;
int adpcm_step = 127;
for(size_t i=0; i<length; i++)
{
// convert to 16bit signed
int value = samples[i];// (8bit) << 8);// | samples[i]; // dither it?
if(!_signed)
value -= 32768;
// encode:
int diff = value - adpcm_prev_value;
BYTE encoded_val = 0;
if(diff < 0) {
encoded_val |= 8;
diff = -diff;
}
diff = (diff << 2) / adpcm_step;
if (diff > 7)
diff = 7;
encoded_val |= diff;
adpcm_prev_value += ((adpcm_step * diff_table[encoded_val]) / 8);
if(adpcm_prev_value > 0x7fff)
adpcm_prev_value = 0x7fff;
if(adpcm_prev_value < -0x8000)
adpcm_prev_value = -0x8000;
adpcm_step = (adpcm_step * step_scale[encoded_val]) >> 8;
if(adpcm_step < 127)
adpcm_step = 127;
if(adpcm_step > 24567)
adpcm_step = 24567;
if(i & 1)
out.samples[i>>1] |= encoded_val;
else
out.samples[i>>1] |= encoded_val << 4;
}
return true;
}
// ------------------------------------------------------------------------------------
bool wiimote::PlaySample (const wiimote_sample &sample, BYTE volume,
speaker_freq freq_override)
{
_ASSERT(IsConnected());
if(!IsConnected())
return false;
speaker_freq freq = freq_override? freq_override : sample.freq;
BYTE vol = volume;
TRACE(_T("playing sample."));
EnableSpeaker(true);
MuteSpeaker (true);
#if 0
// combine everything into one write - faster, seems to work?
BYTE bytes[9] = { 0x00, 0x00, 0x00, 10+freq, vol, 0x00, 0x00, 0x01, 0x01 };
WriteData(0x04a20001, sizeof(bytes), bytes);
#else
// Write 0x01 to register 0x04a20009
WriteData(0x04a20009, 0x01);
// Write 0x08 to register 0x04a20001
WriteData(0x04a20001, 0x08);
// Write 7-byte configuration to registers 0x04a20001-0x04a20008
BYTE bytes[7] = { 0x00, 0x00, 0x00, 10+freq, volume, 0x00, 0x00 };
WriteData(0x04a20001, sizeof(bytes), bytes);
// + Write 0x01 to register 0x04a20008
WriteData(0x04a20008, 0x01);
#endif
Internal.Speaker.Freq = freq;
Internal.Speaker.Volume = volume;
CurrentSample = &sample;
MuteSpeaker(false);
return StartSampleThread();
}
// ------------------------------------------------------------------------------------
bool wiimote::StartSampleThread ()
{
if(SampleThread)
return true;
SampleThread = (HANDLE)_beginthreadex(NULL, 0, SampleStreamThreadfunc,
this, 0, NULL);
_ASSERT(SampleThread);
if(!SampleThread) {
WARN(_T("couldn't create sample thread!"));
MuteSpeaker (true);
EnableSpeaker(false);
return false;
}
SetThreadPriority(SampleThread, WORKER_THREAD_PRIORITY);
return true;
}
// ------------------------------------------------------------------------------------
bool wiimote::PlaySquareWave (speaker_freq freq, BYTE volume)
{
_ASSERT(IsConnected());
if(!IsConnected())
return false;
// if we're already playing a sample, stop it first
if(IsPlayingSample())
CurrentSample = NULL;
// if we're already playing a square wave at this freq and volume, return
else if(IsPlayingAudio() && (Internal.Speaker.Freq == freq) &&
(Internal.Speaker.Volume == volume))
return true;
TRACE(_T("playing square wave."));
// stop playing samples
CurrentSample = 0;
EnableSpeaker(true);
MuteSpeaker (true);
#if 0
// combined everything into one write - much faster, seems to work?
BYTE bytes[9] = { 0x00, 0x00, 0x00, freq, volume, 0x00, 0x00, 0x01, 0x1 };
WriteData(0x04a20001, sizeof(bytes), bytes);
#else
// write 0x01 to register 0xa20009
WriteData(0x04a20009, 0x01);
// write 0x08 to register 0xa20001
WriteData(0x04a20001, 0x08);
// write default sound mode (4bit ADPCM, we assume) 7-byte configuration
// to registers 0xa20001-0xa20008
BYTE bytes[7] = { 0x00, 0x00, 0x00, 10+freq, volume, 0x00, 0x00 };
WriteData(0x04a20001, sizeof(bytes), bytes);
// write 0x01 to register 0xa20008
WriteData(0x04a20008, 0x01);
#endif
Internal.Speaker.Freq = freq;
Internal.Speaker.Volume = volume;
MuteSpeaker(false);
return StartSampleThread();
}
// ------------------------------------------------------------------------------------
void wiimote::RecordState (state_history &events_out,
unsigned max_time_ms,
state_change_flags change_trigger)
{
// user being naughty?
if(Recording.bEnabled)
StopRecording();
// clear the list
if(!events_out.empty())
events_out.clear();
// start recording
Recording.StateHistory = &events_out;
Recording.StartTimeMS = timeGetTime();
Recording.EndTimeMS = Recording.StartTimeMS + max_time_ms;
Recording.TriggerFlags = change_trigger;
// (as this call happens outside the read/parse thread, set the boolean
// which will enable reocrding last, so that all params are in place)
Recording.bEnabled = true;
}
// ------------------------------------------------------------------------------------
void wiimote::StopRecording ()
{
if(!Recording.bEnabled)
return;
Recording.bEnabled = false;
// make sure the read/parse thread has time to notice the change (else it might
// still write one more state to the list)
Sleep(10); // too much?
}
// ------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------
| [
"reber.brian@gmail.com"
] | reber.brian@gmail.com |
e468130188f6661af87d620ff23fbf58011ff2c1 | fb01d56184c7d953b8e78aab7b21d31b68619428 | /IOSync/src/networking/networkEngine.h | 3802f2f6c6f133fc7adc1f30fa290e56938d5c88 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | Regal-Internet-Brothers/IOSync | e10a044526fad2fa75f6a0503e7f7ca3810c56c7 | d98b076034bdbd6bedc0f3f1f9dc254a26c310a5 | refs/heads/master | 2023-04-10T08:38:57.328613 | 2023-04-01T09:23:47 | 2023-04-01T09:23:47 | 33,455,756 | 15 | 3 | null | 2015-04-26T12:45:55 | 2015-04-05T21:24:07 | C++ | UTF-8 | C++ | false | false | 29,919 | h | #pragma once
// Includes:
#include "networking.h"
#include "address.h"
#include "reliablePacketManager.h"
#include "player.h"
#include "packets.h"
#include "messages.h"
#include "../exceptions.h"
// Standard library:
#include <string>
#include <stdexcept>
// Namespace(s):
using namespace std;
namespace iosync
{
// Forward declarations:
class application;
// Namespace(s):
namespace networking
{
// Constant variable(s):
// Error/warning log headers:
// The log-header displayed when a message is unsupported.
static const char* UNSUPPORTED_MESSAGE = "Attempted to managed unsupported message: ";
static const char* EXTRA_BYTES_DETECTED = "Extra bytes detected in message: ";
static const char* UNABLE_TO_PARSE_MESSAGE = "Unable to parse incoming message: ";
static const char* UNABLE_TO_FORWARD_PACKET = "Unable to forward packet: ";
// Structures:
// Standard date and time functionality used by 'networkEngines'.
struct networkMetrics
{
// Constructor(s):
networkMetrics
(
milliseconds poll,
milliseconds connection,
milliseconds reliableIDTime,
milliseconds reliableResend,
milliseconds ping = duration_cast<milliseconds>((seconds)1)
);
// Methods:
// Nothing so far.
// Fields:
// The maximum number of milliseconds required to
// wait when polling network information.
milliseconds pollTimeout;
// The maximum number of milliseconds a connection can take,
// before the side requesting a "pong" message closes the connection.
milliseconds connectionTimeout;
// The number of milliseconds required to wait before pruning
// the earliest reliable packet-identifier of a 'player' object.
milliseconds reliablePruneTime;
// The number of milliseconds reliable-packets need to wait before resending.
milliseconds reliableResendTime;
// The number of milliseconds required to wait before a ping message is sent.
// Ideally, this would be a relatively long amount of time.
milliseconds pingInterval;
};
// Classes:
class networkEngine : public reliablePacketManager
{
public:
// Enumerator(s):
enum messageTypes : messageType
{
// This is used to handle final operations for a packet.
// Basically, a header with this type specifies a
// manual packet end, as well as any relevant meta-data.
MESSAGE_TYPE_META = 0,
// This is used by clients when joining a server.
MESSAGE_TYPE_JOIN,
// This is used by clients when leaving a server.
// In addition, this may also be used to formally
// request that clients leave the server.
MESSAGE_TYPE_LEAVE,
// This is used to send a "ping" message.
MESSAGE_TYPE_PING,
// This is used to send a "pong" (Response to "ping") message.
MESSAGE_TYPE_PONG,
// This is used to confirm reliable packets.
MESSAGE_TYPE_CONFIRM_PACKET,
// Custom message-types should start at this location.
MESSAGE_TYPE_CUSTOM_LOCATION,
};
enum connectionTypes : connectionType
{
// This is the default connection-type,
// commonly used for normal players.
CONNECTION_TYPE_PLAYER,
// This is an alternate form of connection,
// which is managed by the parent 'application' object.
CONNECTION_TYPE_ALTERNATE,
// This connection type is reserved for "nodes".
CONNECTION_TYPE_NODE,
};
enum reservedBytes : packetSize_t
{
//PING_MESSAGE_RESERVED_BYTES = 0,
//PONG_MESSAGE_RESERVED_BYTES = PING_MESSAGE_RESERVED_BYTES,
};
enum disconnectionReasons : disconnectionReason
{
// The server/message-origin has forced you to disconnect.
DISCONNECTION_REASON_FORCE = DISCONNECTION_REASON_CUSTOM_LOCATION,
// This is used by clients to accept a disconnection gracefully.
// Leave-messages made with this reason are not always received, and normally unneeded.
DISCONNECTION_REASON_ACCEPT,
// Used in messages sent as last-ditch efforts to formally disconnect a player.
DISCONNECTION_REASON_TIMEDOUT,
// This is used when the connection was manually closed.
DISCONNECTION_REASON_CLOSE,
};
// Functions:
// This command allows you to retrieve a player-entry from the 'players' list.
static inline player* getPlayer(const playerList& players, const address& addr)
{
for (auto p : players)
{
if (p->remoteAddress == addr)
return p;
}
return nullptr;
}
static inline player* getPlayer(const playerList& players, const address& addr, const address& vaddr)
{
for (auto p : players)
{
if (p->remoteAddress == addr && p->vaddr() == vaddr)
return p;
}
return nullptr;
}
static inline bool playerJoined(const playerList& players, const address& addr)
{
return (getPlayer(players, addr) != nullptr);
}
// Constructor(s):
networkEngine(application& parent, const networkMetrics metrics);
virtual bool open();
// Destructor(s):
virtual bool close();
// Methods (Public):
virtual void update();
bool updateSocket(QSocket& socket);
inline bool updateSocket()
{
return updateSocket(this->socket);
}
virtual void updatePacketsInTransit(QSocket& socket);
inline void updatePacketsInTransit()
{
updatePacketsInTransit(this->socket);
return;
}
packetID generateReliableID();
headerInfo beginMessage(QSocket& socket, messageType msgType);
void finishMessage(QSocket& socket, const headerInfo header_Information);
messageFooter finishMessage(QSocket& socket, const headerInfo header_information, const address& forwardAddress, const packetID ID=PACKET_ID_UNRELIABLE);
inline void finishMessage(QSocket& socket, const headerInfo info, player* p)
{
if (p->hasVirtualAddress())
finishMessage(socket, info, p->vaddr());
else
finishMessage(socket, info);
return;
}
/*
This should be used when finishing a reliable message.
The output should be used in order to send a message.
Not sending with the output will result in partially undefined behavior.
Currently this means that the message will only be unreliable,
and the 'outbound_packet' object will be destroyed instantly.
Please do not send a reliable message using an incorrect overload of 'sendMessage'.
*/
outbound_packet finishReliableMessage(QSocket& socket, const address& realAddress, const headerInfo header_information, const address& forwardAddress=address(), const packetID ID=PACKET_ID_AUTOMATIC);
/*
The 'header' and 'footer' arguments should be the message's current arguments.
The read-position should also be after the header (Between the header and footer).
Under normal circumstances, this will be the case.
The "_out" arguments are used as pre-allocated output-variables for the new message.
Those structures should not be pre-constructed if possible.
If you do not wish to allocate these yourself, do not specify them.
If this command returns 'false', then one or more operations could not be completed.
*/
bool rewriteMessage(QSocket& socket, const messageHeader& header, const messageFooter& footer, messageHeader& header_out, messageFooter& footer_out);
// This overload provides pre-allocated header and footer objects.
// The main arguments are the same; please follow the primary implementation's documentation.
inline bool rewriteMessage(QSocket& socket, const messageHeader& header, const messageFooter& footer)
{
// Allocate the output-structures (Also useful for debugging):
messageHeader header_out;
messageFooter footer_out;
// Call the main implementation, then return its response.
return rewriteMessage(socket, header, footer, header_out, footer_out);
}
virtual size_t broadcastMessage(QSocket& socket, networkDestinationCode destinationCode=DESTINATION_ALL, bool resetLength=true) = 0;
// This is a general-purpose automatic send routine for sockets.
// This is useful for situations where an address isn't needed.
virtual size_t sendMessage(QSocket& socket, networkDestinationCode destination=DEFAULT_DESTINATION, bool resetLength=true);
// This may be used to easily send an 'outbound_packet' object.
virtual size_t sendMessage(QSocket& socket, outbound_packet packet, bool alreadyInOutput=true);
// This method may be overridden by inheriting classes.
// For example, must specify extra information in order
// to send messages to specific addresses.
virtual size_t sendMessage(QSocket& socket, const address& remote, bool resetLength=true, networkDestinationCode destinationCode=DEFAULT_DESTINATION);
virtual size_t sendMessage(networkDestinationCode destination=DEFAULT_DESTINATION, bool resetLength=true);
inline size_t sendMessage(QSocket& socket, outbound_packet packet, networkDestinationCode destination, bool alreadyInOutput=true)
{
packet.destinationCode = destination;
return sendMessage(socket, packet, alreadyInOutput);
}
inline size_t sendMessage(QSocket& socket, outbound_packet packet, const player* p, bool alreadyInOutput=true)
{
packet.destination = p;
return sendMessage(socket, packet, alreadyInOutput);
}
virtual bool hasRemoteConnection() const;
// This specifies if this 'networkEngine' can broadcast without first contacting a remote machine.
virtual bool canBroadcastLocally() const;
virtual player* getPlayer(QSocket& socket);
virtual bool alone() const = 0;
virtual size_t connections() const = 0;
inline bool connectedToOthers() const
{
return !alone();
}
// Reliable message related:
// This command is called every time a reliable message is found.
// If this returns 'false', the message will not be parsed, and it will be discarded.
virtual bool onReliableMessage(QSocket& socket, const address& remoteAddress, const messageHeader& header, const messageFooter& footer);
bool addReliablePacket(outbound_packet p);
bool hasReliablePackets() const override;
void removeReliablePacket(packetID ID) override;
bool hasReliablePacket(packetID ID) const override;
// This command allows you to remove a reliable packet agnostic of its internal behavior.
// For example, some reliable packets may provide address or player based "reference routines".
// The return value of this command may specify if the packet was removed.
bool removeReliablePacket(const address& remoteAddress, packetID ID);
// This may be used to manually remove a 'player' object from an
// 'outbound_packet' object's internal reference-container.
// This command is considered "unsafe", as it may rely upon undefined behavior under certain conditions.
bool removeReliablePacket(player* p, outbound_packet& packetInTransit);
// This method passes the message represented by the header specified.
// This will only pass the data-segment of the message; the footer will not be passed.
inline void passMessage(const messageHeader& header)
{
socket.inSeekForward(header.packetSize);
return;
}
// This method passes the message represented by the header and footer specified.
// This is used when unable to read a message.
inline void passMessage(const messageHeader& header, const messageFooter& footer)
{
socket.inSeekForward(header.packetSize + footer.serializedSize);
return;
}
// This will only pass the serialized size of the footer.
inline void passFooter(const messageFooter& footer)
{
socket.inSeekForward(footer.serializedSize);
return;
}
virtual bool onForwardPacket(QSocket& socket, streamLocation startPosition, const address& remoteAddress, const messageHeader& header, const messageFooter& footer);
// The return value of this method indicates the number of messages that were received.
size_t handleMessages(QSocket& socket);
// Parsing/deserialization related:
// When overriding this method, please "call up" to your super-class's implementation.
// The order you do this in is up to you, but it is recommended that you do this first.
virtual bool parseMessage(QSocket& socket, const address& remoteAddress, const messageHeader& header, const messageFooter& footer);
// Player/connection management functionality:
inline bool timedOut(milliseconds connectionTime) const
{
return (connectionTime >= metrics.connectionTimeout);
}
// Serialization related:
void serializeConnectionMessage(QSocket& socket, wstring name);
void serializeLeaveNotice(QSocket& socket, disconnectionReason reason);
void serializePacketConfirmationMessage(QSocket& socket, packetID ID);
// Message generation:
// This command will produce a "ping" message directed at 'realAddress'.
inline outbound_packet generatePingMessage(QSocket& socket, const address& realAddress=address(), const address& forwardAddress=address())
{
return finishReliableMessage(socket, realAddress, beginMessage(socket, MESSAGE_TYPE_PING), forwardAddress);
}
// This command will produce a "pong" message directed at 'realAddress'.
inline outbound_packet generatePongMessage(QSocket& socket, const address& realAddress=address(), const address& forwardAddress=address())
{
return finishReliableMessage(socket, realAddress, beginMessage(socket, MESSAGE_TYPE_PONG), forwardAddress);
}
inline outbound_packet generateLeaveNotice(QSocket& socket, disconnectionReason reason, const address& realAddress = address(), const address& forwardAddress = address())
{
auto info = beginMessage(socket, MESSAGE_TYPE_LEAVE);
serializeLeaveNotice(socket, reason);
return finishReliableMessage(socket, realAddress, info, forwardAddress);
}
inline outbound_packet generateConnectionMessage(QSocket& socket, wstring name, const address& realAddress = address(), const address& forwardAddress = address())
{
auto info = beginMessage(socket, MESSAGE_TYPE_JOIN);
serializeConnectionMessage(socket, name);
return finishReliableMessage(socket, realAddress, info, forwardAddress);
}
inline void generatePacketConfirmationMessage(QSocket& socket, packetID ID)
{
auto info = beginMessage(socket, MESSAGE_TYPE_CONFIRM_PACKET);
serializePacketConfirmationMessage(socket, ID);
finishMessage(socket, info);
return;
}
// Parsing/deserialization related:
virtual disconnectionReason parseLeaveNotice(QSocket& socket, const address& remoteAddress, const address& forwardAddress=address());
virtual packetID parsePacketConfirmationMessage(QSocket& socket, const address& remoteAddress, const messageHeader& header, const messageFooter& footer);
// Sending related:
inline size_t sendPing(QSocket& socket, networkDestinationCode destination=DEFAULT_DESTINATION, bool resetLength=true)
{
return networkEngine::sendMessage(socket, generatePingMessage(socket), destination, resetLength);
}
inline size_t sendPong(QSocket& socket, networkDestinationCode destination=DEFAULT_DESTINATION, bool resetLength=true)
{
return networkEngine::sendMessage(socket, generatePongMessage(socket), destination, resetLength);
}
virtual void pingRemoteConnection(QSocket& socket) = 0;
// Operators:
// This "engine" may be used in place of a 'QSocket'.
inline operator QSocket&()
{
return socket;
}
// Fields (Public):
// The primary socket of this "engine".
QSocket socket;
// Booleans / Flags:
// This variable describes if this "engine" is able to act as a "node".
// This also changes for the real host of the session.
bool isHostNode;
protected:
// Methods (Protected):
// Message generation:
// This is used to finalize a packet, before sending it off.
void finalizeOutput(QSocket& s, networkDestinationCode destinationCode=DEFAULT_DESTINATION);
// Parsing/deserialization related:
virtual networkDestinationCode parseMeta(QSocket& socket, const address& remoteAddress, const messageHeader& header);
// Fields (Protected):
// A reference to the 'application' controlling this object.
application& parentProgram;
// Standard network time-metrics.
networkMetrics metrics;
// A list of outbound packets in transit.
list<outbound_packet> packetsInTransit;
// The next 'packetID' used for reliable packet-handling.
packetID nextReliableID;
// Booleans / Flags:
// This field specifies if this "engine" is the "master server".
bool isMaster;
};
class clientNetworkEngine : public networkEngine
{
public:
// Constructor(s):
clientNetworkEngine
(
application& parent,
wstring username=L"Unknown",
const networkMetrics metrics = networkMetrics
(
(milliseconds)DEFAULT_CONNECTION_POLL_TIMEOUT,
(milliseconds)DEFAULT_CLIENT_CONNECTION_TIMEOUT,
(milliseconds)DEFAULT_RELIABLE_PACKET_WAIT_TIME,
(milliseconds)DEFAULT_CLIENT_RELIABLE_RESEND,
(milliseconds)DEFAULT_CLIENT_PING_INTERVAL
)
);
bool open(string remoteAddress, addressPort remotePort=DEFAULT_PORT, addressPort localPort=DEFAULT_LOCAL_PORT); // const address& remoteAddress
// Destructor(s):
virtual bool close() override;
// Methods (Public):
virtual void update() override;
high_resolution_clock::time_point updateSnapshot() override;
virtual void updatePacketsInTransit(QSocket& socket) override;
virtual bool onForwardPacket(QSocket& socket, streamLocation startPosition, const address& remoteAddress, const messageHeader& header, const messageFooter& footer) override;
// Parsing/deserialization related:
// When calling up to this implementation, it is best to ensure a connection has been properly made beforehand.
virtual bool parseMessage(QSocket& socket, const address& remoteAddress, const messageHeader& header, const messageFooter& footer) override;
inline outbound_packet finishReliableMessage(QSocket& socket, const address& realAddress, const headerInfo header_information, const player* p, packetID ID = PACKET_ID_AUTOMATIC)
{
return networkEngine::finishReliableMessage(socket, realAddress, header_information, p->vaddr(), ID);
}
size_t broadcastMessage(QSocket& socket, networkDestinationCode destinationCode=DESTINATION_ALL, bool resetLength=true) override;
size_t sendMessage(QSocket& socket, const address& remote, bool resetLength=true, networkDestinationCode destinationCode=DEFAULT_DESTINATION) override;
virtual bool hasRemoteConnection() const override;
inline bool timedOut() const
{
return networkEngine::timedOut(connection.connectionTime());
}
// Reliable message related:
virtual bool onReliableMessage(QSocket& socket, const address& remoteAddress, const messageHeader& header, const messageFooter& footer) override;
// Simple messages:
virtual void pingRemoteConnection(QSocket& socket) override;
inline size_t sendLeaveNotice(QSocket& socket, disconnectionReason reason=DISCONNECTION_REASON_UNKNOWN, networkDestinationCode destination=DEFAULT_DESTINATION, bool resetLength=true)
{
return networkEngine::sendMessage(socket, generateLeaveNotice(socket, reason), destination, resetLength);
}
inline size_t sendCourtesyLeaveConfirmation(QSocket& socket, networkDestinationCode destination=DEFAULT_DESTINATION)
{
// Write a one-off message to accept the disconnection.
auto info = beginMessage(socket, MESSAGE_TYPE_LEAVE);
serializeLeaveNotice(socket, DISCONNECTION_REASON_ACCEPT);
finishMessage(socket, info);
return networkEngine::sendMessage(socket, destination);
}
inline size_t sendConnectionMessage(QSocket& socket, wstring playerName=L"Player", networkDestinationCode destination=DEFAULT_DESTINATION, bool resetLength=true)
{
return networkEngine::sendMessage(socket, generateConnectionMessage(socket, playerName), destination, resetLength);
}
inline size_t sendConnectionMessage(QSocket& socket, wstring playerName, const address& forwardAddress, networkDestinationCode destination=DEFAULT_DESTINATION, bool resetLength=true)
{
return networkEngine::sendMessage(socket, generateConnectionMessage(socket, playerName, socket, forwardAddress), destination, resetLength);
}
// Message generation:
inline outbound_packet generateLeaveNotice(QSocket& socket, disconnectionReason reason, const address& forwardAddress = address())
{
return networkEngine::generateLeaveNotice(socket, reason, connection.remoteAddress, forwardAddress);
}
// Serialization related:
// Nothing so far.
// Parsing/deserialization related:
virtual disconnectionReason parseLeaveNotice(QSocket& socket, const address& remoteAddress, const address& forwardAddress=address()) override;
// Connection management functionality:
virtual player* getPlayer(QSocket& socket) override;
virtual bool alone() const;
virtual size_t connections() const;
// Operators:
inline operator player&()
{
return connection;
}
// Fields:
player connection;
/*
This represents the resolved host address. In the event
of a direct connection, this will be the same as 'remote'.
This is used to represent the master/origin server.
This address may be messaged directly with no problems from previous parent-nodes.
Parent-nodes have the option to query either the master/origin server, or the client itself.
An improper disconnection from a non-esential node is unlikely, but it can happen.
If such events arise, the 'master' address will be relied upon.
Parent-nodes are assumed to be represented with 'master', until it can be evaluated.
*/
address master;
// Booleans / Flags:
bool connected = false;
protected:
// Methods (Protected):
// Parsing/deserialization related:
//virtual networkDestinationCode parseMeta(QSocket& socket, const address& remoteAddress, const messageHeader& header) override;
};
class serverNetworkEngine : public networkEngine
{
public:
// Constructor(s):
serverNetworkEngine
(
application& parent,
const networkMetrics metrics = networkMetrics
(
(milliseconds)DEFAULT_CONNECTION_POLL_TIMEOUT,
(milliseconds)DEFAULT_SERVER_CONNECTION_TIMEOUT,
(milliseconds)DEFAULT_RELIABLE_PACKET_WAIT_TIME,
(milliseconds)DEFAULT_SERVER_RELIABLE_RESEND,
(milliseconds)DEFAULT_SERVER_PING_INTERVAL
)
);
// Destructor(s):
virtual bool close() override;
bool open(addressPort port=DEFAULT_PORT);
// Methods (Public):
virtual void update() override;
virtual void updatePacketsInTransit(QSocket& socket) override;
void checkClientTimeouts(QSocket& socket);
inline void checkClientTimeouts()
{
return checkClientTimeouts(this->socket);
}
size_t broadcastMessage(QSocket& socket, playerList players, networkDestinationCode destinationCode=DESTINATION_ALL, bool resetLength=true);
size_t broadcastMessage(QSocket& socket, networkDestinationCode destinationCode=DESTINATION_ALL, bool resetLength=true) override;
inline size_t sendMessageTo(QSocket& socket, player* p)
{
return networkEngine::sendMessage(socket, p->remoteAddress);
}
// Reliable message related:
virtual bool onReliableMessage(QSocket& socket, const address& remoteAddress, const messageHeader& header, const messageFooter& footer) override;
virtual bool onForwardPacket(QSocket& socket, streamLocation startPosition, const address& remoteAddress, const messageHeader& header, const messageFooter& footer) override;
virtual size_t sendMessage(QSocket& socket, outbound_packet packet, bool alreadyInOutput=true) override;
// This is used to manually set the output-destination to a player's address, then send to that address.
inline size_t sendMessage(QSocket& socket, outbound_packet packet, player* p, bool alreadyInOutput=true)
{
packet.destination = p;
return sendMessage(socket, packet, alreadyInOutput);
}
// Parsing/deserialization related:
virtual bool parseMessage(QSocket& socket, const address& remoteAddress, const messageHeader& header, const messageFooter& footer) override;
// Serialization related:
// Nothing so far.
// Message generation:
// This sends a blank 'MESSAGE_TYPE_JOIN' message reliably to the address specified.
// This is used to notify a player that their connection request has been accepted.
inline outbound_packet generatePlayerConfirmationMessage(QSocket& socket, const address& realAddress = address(), const address& forwardAddress = address())
{
return finishReliableMessage(socket, realAddress, beginMessage(socket, MESSAGE_TYPE_JOIN), forwardAddress);
}
inline outbound_packet generateLeaveNotice(QSocket& socket, disconnectionReason reason, player* p)
{
return networkEngine::generateLeaveNotice(socket, reason, p, p->vaddr());
}
// Parsing/deserialization related:
// The return value of this command specifies if the 'player' object was an "indirect" player or not.
bool parseConnectionMessage(QSocket& socket, const address& remoteAddress, const messageHeader& header, const messageFooter& footer);
virtual disconnectionReason parseLeaveNotice(QSocket& socket, const address& remoteAddress, const address& forwardAddress=address()) override;
// Simple messages:
virtual void pingRemoteConnection(QSocket& socket) override;
// This simply sets a different default argument for this method.
inline size_t sendPing(QSocket& socket, networkDestinationCode destination = DESTINATION_ALL, bool resetLength = true)
{
return networkEngine::sendPing(socket, destination, resetLength);
}
// Player/connection management functionality:
virtual bool hasRemoteConnection() const override;
virtual bool canBroadcastLocally() const override;
virtual player* getPlayer(QSocket& socket) override;
virtual bool alone() const;
virtual size_t connections() const;
inline bool timedOut(player* p) const
{
// Call the super-class's implementation.
return networkEngine::timedOut(p->connectionTime());
}
inline bool hasPlayers() const
{
return connectedToOthers(); // !alone();
}
// This command allows you to retrieve a player-entry from the 'players' list.
inline player* getPlayer(const address& addr) const
{
return networkEngine::getPlayer(players, addr);
}
inline player* getPlayer(const address& addr, const address& vaddr) const
{
return networkEngine::getPlayer(players, addr, vaddr);
}
inline bool playerJoined(const address& addr) const
{
return (getPlayer(addr) != nullptr); //networkEngine::playerJoined(players, addr);
}
// The return values of these commands indicate if they were successful:
bool connectPlayer(QSocket& socket, player* p);
bool disconnectPlayer(QSocket& socket, player* p, disconnectionReason reason=DISCONNECTION_REASON_ACCEPT);
void forceDisconnectPlayer(QSocket& socket, player* p, disconnectionReason reason=DISCONNECTION_REASON_FORCE, bool reliable=false, bool autoRemove=true);
// This is called every time 'removePlayer' is called (Internally, or externally).
// This routine does not delete, or otherwise mutate the input.
void onPlayerRemoved(player* p);
// This will force-disconnect all connected players.
void forceDisconnectPlayers(QSocket& socket, disconnectionReason reason=DISCONNECTION_REASON_FORCE, bool reliable=false);
// This will formally disconnect all connected players.
void disconnectPlayers(QSocket& socket, bool reliable=true);
inline void disconnectPlayers()
{
disconnectPlayers(this->socket);
return;
}
/*
inline bool connectPlayer(player* p)
{
return connectPlayer(this->socket, p);
}
inline bool disconnectPlayer(player* p)
{
return disconnectPlayer(this->socket, p);
}
*/
// Objects passed into this command should be assumed as managed internally by this class.
// The only exception being, when an explicit removal is done with intent to externally manage the object.
inline void addPlayer(player* p)
{
players.push_back(p);
return;
}
// This will not delete the 'player' object in question.
inline void removePlayer(player* p, bool autoRemove=true)
{
if (autoRemove)
players.remove(p);
onPlayerRemoved(p);
return;
}
// Fields:
playerList players;
protected:
// Methods (Protected):
// Parsing/deserialization related:
virtual networkDestinationCode parseMeta(QSocket& socket, const address& remoteAddress, const messageHeader& header) override;
};
}
namespace exceptions
{
using namespace networking;
class networkEnded : public iosync_exception
{
public:
// Constructor(s):
networkEnded(networkEngine& target, const string& exception_name="IOSYNC: Network session ended.");
// Methods:
virtual const string message() const throw();
// Fields:
networkEngine& network;
};
class networkClosed : public networkEnded
{
public:
// Constructor(s):
networkClosed(networkEngine& target, const string& exception_name="IOSYNC: Network session closed.");
// Methods:
virtual const string message() const throw() override;
};
}
} | [
"SKIVortex@rocketmail.com"
] | SKIVortex@rocketmail.com |
30acf9b40e24d9f680489029624e3fa2ad17bd8e | c1d8cefebd8f85fe9a70ae18d6726e8e42a6fe3a | /07_学习笔记/HPLSP/手抄代码/send_fd267.cpp | 00e0050c28ad52ba19c0de159be03e821411fe7b | [] | no_license | leomaokai/MyCpp | 7df0b4097561774c9050e9eed27134202b011c3a | e81b0ba50c7de046ee63af47accd2897b5e289ee | refs/heads/master | 2023-02-19T11:14:58.697566 | 2021-01-22T16:50:13 | 2021-01-22T16:50:13 | 289,039,519 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 497 | cpp | #include<sys/socket.h>
#include<fcntl.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
static const int CONTROL_LEN=CMSG_LEN(sizeof(int));
void send_fd(int fd,int fd_to_send)
{
struct iovec iov[1];
struct msghdr msg;
char buf[0];
iov[0].iov_base=buf;
iov[0].iov_len=1;
msg.msg_name=NULL;
msg.msg_namelen=0;
msg.msg_iov=iov;
msg.msg_iovlen=1;
cmsghdr cm;
cm.cmsg_len=CONTROL_LEN;
cm.cmsg_level=SOL_SOKCET;
cm.cmsg_type=SCM_RIGHTS;
| [
"leomaokai@163.com"
] | leomaokai@163.com |
a071e9abf3f6b2675b8acc20c86dcd53cd939afe | 21deed24d8bde9f3b8ec3d5a8962766f7ff1bc2f | /test/unittest/memory/unittest_memory_pool.cpp | ae175fdac904e4c519bd50c972f61d391245b22f | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | permissive | nnstreamer/nntrainer | 64658cc434b42323a21871c33cdb069751770daf | 08a1da0a2c22fd9495239d370cef8dc1d842a4fc | refs/heads/main | 2023-08-19T09:10:39.796512 | 2023-08-17T08:43:39 | 2023-08-18T10:35:14 | 249,615,315 | 134 | 70 | Apache-2.0 | 2023-09-14T12:58:28 | 2020-03-24T04:47:36 | C++ | UTF-8 | C++ | false | false | 10,109 | cpp | // SPDX-License-Identifier: Apache-2.0
/**
* Copyright (C) 2021 Parichay Kapoor <pk.kapoor@samsung.com>
* Copyright (C) 2022 Jiho Chu <jiho.chu@samsung.com>
*
* @file unittest_memory_pool.cpp
* @date 11 August 2021
* @brief Memory Pool Test
* @see https://github.com/nnstreamer/nntrainer
* @author Parichay Kapoor <pk.kapoor@samsung.com>
* @bug No known bugs except for NYI items
*/
#include <cstring>
#include <memory>
#include <random>
#include <vector>
#include <gtest/gtest.h>
#include <basic_planner.h>
#include <cache_pool.h>
#include <memory_pool.h>
#include <nntrainer_test_util.h>
/**
* @brief MemoryPool Test Class
*/
class MemoryPoolTest
: public ::testing::TestWithParam<std::shared_ptr<nntrainer::MemoryPool>> {
public:
void SetUp(void) { pool = GetParam(); }
void TearDown(void) { EXPECT_NO_THROW(pool->clear()); }
std::shared_ptr<nntrainer::MemoryPool> pool;
};
/**
* @brief creation and destruction
*/
TEST_P(MemoryPoolTest, create_destroy) {
EXPECT_NO_THROW(nntrainer::MemoryPool());
}
/**
* @brief request 0 sized memory
*/
TEST_P(MemoryPoolTest, request_mem_01_n) {
nntrainer::MemoryPool pool;
EXPECT_THROW(pool.requestMemory(0, 1, 2), std::invalid_argument);
}
/**
* @brief request memory when starts after it ends
*/
TEST_P(MemoryPoolTest, request_mem_02_n) {
nntrainer::MemoryPool pool;
EXPECT_THROW(pool.requestMemory(1, 3, 2), std::invalid_argument);
}
/**
* @brief request memory with 0 valid time
*/
TEST_P(MemoryPoolTest, request_mem_03_n) {
nntrainer::MemoryPool pool;
EXPECT_THROW(pool.requestMemory(1, 4, 4), std::invalid_argument);
}
/**
* @brief request memory after allocate
*/
TEST(MemoryPool, request_mem_04_n) {
nntrainer::MemoryPool pool;
EXPECT_NO_THROW(pool.requestMemory(1, 4, 5));
EXPECT_NO_THROW(pool.planLayout(nntrainer::BasicPlanner()));
EXPECT_NO_THROW(pool.allocate());
EXPECT_THROW(pool.requestMemory(1, 5, 6), std::invalid_argument);
}
/**
* @brief request memory
*/
TEST_P(MemoryPoolTest, request_mem_04_p) {
nntrainer::MemoryPool pool;
EXPECT_NO_THROW(pool.requestMemory(1, 4, 5));
}
/**
* @brief plan layout without reqeustMemory
*/
TEST_P(MemoryPoolTest, plan_layout_01_n) {
nntrainer::MemoryPool pool;
EXPECT_THROW(pool.planLayout(nntrainer::BasicPlanner()), std::runtime_error);
}
/**
* @brief plan layout after allocate
*/
TEST_P(MemoryPoolTest, plan_layout_02_p) {
nntrainer::MemoryPool pool;
EXPECT_NO_THROW(pool.requestMemory(1, 4, 5));
EXPECT_NO_THROW(pool.planLayout(nntrainer::BasicPlanner()));
EXPECT_NO_THROW(pool.allocate());
EXPECT_THROW(pool.planLayout(nntrainer::BasicPlanner()), std::runtime_error);
}
/**
* @brief plan layout
*/
TEST_P(MemoryPoolTest, plan_layout_03_p) {
nntrainer::MemoryPool pool;
pool.requestMemory(1, 4, 5);
EXPECT_NO_THROW(pool.planLayout(nntrainer::BasicPlanner()));
EXPECT_EQ(1u, pool.size());
pool.requestMemory(1, 4, 5);
EXPECT_NO_THROW(pool.planLayout(nntrainer::BasicPlanner()));
EXPECT_EQ(2u, pool.size());
}
/**
* @brief deallocate
*/
TEST_P(MemoryPoolTest, deallocate_01_p) {
nntrainer::MemoryPool pool;
EXPECT_NO_THROW(pool.deallocate());
pool.requestMemory(1, 4, 5);
EXPECT_NO_THROW(pool.planLayout(nntrainer::BasicPlanner()));
EXPECT_NO_THROW(pool.allocate());
EXPECT_NO_THROW(pool.deallocate());
}
/**
* @brief allocate without requestMemory
*/
TEST_P(MemoryPoolTest, allocate_01_n) {
nntrainer::MemoryPool pool;
EXPECT_THROW(pool.allocate(), std::runtime_error);
}
/**
* @brief allocate without planLayout
*/
TEST_P(MemoryPoolTest, allocate_02_p) {
nntrainer::MemoryPool pool;
pool.requestMemory(1, 4, 5);
EXPECT_THROW(pool.allocate(), std::runtime_error);
}
/**
* @brief allocate aftrer allocate
*/
TEST_P(MemoryPoolTest, allocate_03_n) {
nntrainer::MemoryPool pool;
pool.requestMemory(1, 4, 5);
EXPECT_NO_THROW(pool.planLayout(nntrainer::BasicPlanner()));
EXPECT_NO_THROW(pool.allocate());
EXPECT_THROW(pool.allocate(), std::runtime_error);
EXPECT_NO_THROW(pool.deallocate());
}
/**
* @brief allocate
*/
TEST_P(MemoryPoolTest, allocate_04_n) {
nntrainer::MemoryPool pool;
pool.requestMemory(3, 4, 5);
EXPECT_NO_THROW(pool.planLayout(nntrainer::BasicPlanner()));
EXPECT_EQ(3u, pool.size());
EXPECT_NO_THROW(pool.allocate());
EXPECT_NO_THROW(pool.deallocate());
EXPECT_NO_THROW(pool.allocate());
EXPECT_NO_THROW(pool.deallocate());
}
/**
* @brief size of the pool
*/
TEST_P(MemoryPoolTest, size_01_p) {
nntrainer::MemoryPool pool;
EXPECT_EQ(pool.size(), 0u);
}
/**
* @brief size of the pool
*/
TEST_P(MemoryPoolTest, size_02_p) {
nntrainer::MemoryPool pool;
pool.requestMemory(1, 4, 5);
EXPECT_EQ(pool.size(), 0u);
}
/**
* @brief size of the pool
*/
TEST_P(MemoryPoolTest, size_03_p) {
nntrainer::MemoryPool pool;
pool.requestMemory(1, 4, 5);
EXPECT_EQ(pool.size(), 0u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.size(), 1u);
pool.allocate();
EXPECT_EQ(pool.size(), 1u);
EXPECT_NO_THROW(pool.deallocate());
}
/**
* @brief min requirement
*/
TEST_P(MemoryPoolTest, min_mem_req_01_p) {
nntrainer::MemoryPool pool;
EXPECT_EQ(pool.minMemoryRequirement(), 0u);
}
/**
* @brief min requirement
*/
TEST_P(MemoryPoolTest, min_mem_req_02_p) {
nntrainer::MemoryPool pool;
pool.requestMemory(1, 4, 5);
EXPECT_EQ(pool.minMemoryRequirement(), 1u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 1u);
}
/**
* @brief min requirement
*/
TEST_P(MemoryPoolTest, min_mem_req_03_p) {
nntrainer::MemoryPool pool;
pool.requestMemory(1, 4, 5);
EXPECT_EQ(pool.minMemoryRequirement(), 1u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 1u);
/** exact overlap */
pool.requestMemory(2, 4, 5);
EXPECT_EQ(pool.minMemoryRequirement(), 3u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 3u);
/** ending overlap */
pool.requestMemory(3, 2, 5);
EXPECT_EQ(pool.minMemoryRequirement(), 6u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 6u);
/** start overlap */
pool.requestMemory(4, 4, 8);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 10u);
/** complete overlap */
pool.requestMemory(5, 1, 10);
EXPECT_EQ(pool.minMemoryRequirement(), 15u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 15u);
}
/**
* @brief min requirement
*/
TEST_P(MemoryPoolTest, min_mem_req_04_p) {
nntrainer::MemoryPool pool;
pool.requestMemory(1, 5, 10);
EXPECT_EQ(pool.minMemoryRequirement(), 1u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 1u);
/** partial overlap */
pool.requestMemory(2, 1, 8);
EXPECT_EQ(pool.minMemoryRequirement(), 3u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 3u);
/** ending overlap */
pool.requestMemory(3, 7, 12);
EXPECT_EQ(pool.minMemoryRequirement(), 6u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 6u);
}
/**
* @brief min requirement
*/
TEST_P(MemoryPoolTest, min_mem_req_05_p) {
nntrainer::MemoryPool pool;
pool.requestMemory(1, 5, 10);
EXPECT_EQ(pool.minMemoryRequirement(), 1u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 1u);
/** partial overlap */
pool.requestMemory(2, 1, 8);
EXPECT_EQ(pool.minMemoryRequirement(), 3u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 3u);
/** ending overlap with matching ends */
pool.requestMemory(3, 8, 12);
EXPECT_EQ(pool.minMemoryRequirement(), 4u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 4u);
}
/**
* @brief min requirement
*/
TEST_P(MemoryPoolTest, min_mem_req_06_p) {
nntrainer::MemoryPool pool;
pool.requestMemory(1, 5, 10);
EXPECT_EQ(pool.minMemoryRequirement(), 1u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 1u);
/** partial overlap */
pool.requestMemory(2, 1, 5);
EXPECT_EQ(pool.minMemoryRequirement(), 2u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 2u);
/** ending overlap with matching ends */
pool.requestMemory(3, 10, 12);
EXPECT_EQ(pool.minMemoryRequirement(), 3u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 3u);
/** ending overlap with matching ends */
pool.requestMemory(1, 12, 13);
EXPECT_EQ(pool.minMemoryRequirement(), 3u);
pool.planLayout(nntrainer::BasicPlanner());
EXPECT_EQ(pool.minMemoryRequirement(), 3u);
}
/**
* @brief get memory
*/
TEST_P(MemoryPoolTest, get_memory_01_n) {
nntrainer::MemoryPool pool;
EXPECT_THROW(pool.getMemory(1), std::invalid_argument);
}
/**
* @brief get memory
*/
TEST_P(MemoryPoolTest, get_memory_02_n) {
nntrainer::MemoryPool pool;
auto idx = pool.requestMemory(1, 4, 5);
EXPECT_THROW(pool.getMemory(idx), std::invalid_argument);
}
/**
* @brief get memory
*/
TEST_P(MemoryPoolTest, get_memory_03_n) {
nntrainer::MemoryPool pool;
auto idx = pool.requestMemory(1, 4, 5);
EXPECT_NO_THROW(pool.planLayout(nntrainer::BasicPlanner()));
EXPECT_NO_THROW(pool.allocate());
EXPECT_ANY_THROW(pool.getMemory(idx + 1));
EXPECT_NO_THROW(pool.deallocate());
}
/**
* @brief get memory
*/
TEST_P(MemoryPoolTest, get_memory_04_p) {
nntrainer::MemoryPool pool;
std::shared_ptr<nntrainer::MemoryData<float>> mem;
auto idx = pool.requestMemory(1, 4, 5);
EXPECT_NO_THROW(pool.planLayout(nntrainer::BasicPlanner()));
EXPECT_NO_THROW(pool.allocate());
EXPECT_NO_THROW(mem = pool.getMemory(idx));
EXPECT_NE(mem, nullptr);
EXPECT_NO_THROW(pool.deallocate());
}
GTEST_PARAMETER_TEST(
MemoryPool, MemoryPoolTest,
::testing::Values(std::make_shared<nntrainer::MemoryPool>(),
std::make_shared<nntrainer::CachePool>("tmp pool")));
| [
"jijoong.moon@samsung.com"
] | jijoong.moon@samsung.com |
e97aa6b680d2eab49fa34b54e96ae43dbee335fa | 3e281f43ce594db119338d4ea76a19b6f767c3e6 | /ClientTest/snap7.h | 853d9cb7c41b36d0b38e2748926d55669ae53a81 | [] | no_license | ghazivakili/DIIG-OPC-IoT | c6aacf18fd8c55337b1af4eac6235ad7a0beb9fa | d14731e5b527bfb35efe970cd69310d4032b8d1b | refs/heads/master | 2022-10-11T16:53:51.101284 | 2019-03-15T20:05:26 | 2019-03-15T20:05:26 | 165,261,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,396 | h | /*=============================================================================|
| PROJECT Simense Driver 0.01 |
|==============================================================================|
| Copyright (C) 2016 Mohammad Ghazivakili |
| All rights reserved. |
|==============================================================================|
| |
| C++ Snap 7 classes Implementation |
| |
|=============================================================================*/
#ifndef snap7_h
#define snap7_h
//---------------------------------------------------------------------------
// Platform detection
//---------------------------------------------------------------------------
#if defined (_WIN32)||defined(_WIN64)||defined(__WIN32__)||defined(__WINDOWS__)
# define OS_WINDOWS
#endif
// Visual Studio needs this to use the correct time_t size
#if defined (_WIN32) && !defined(_WIN64)
# define _USE_32BIT_TIME_T
#endif
#if defined(unix) || defined(__unix__) || defined(__unix)
# define PLATFORM_UNIX
#endif
#if defined(__SVR4) || defined(__svr4__)
# define OS_SOLARIS
#endif
#if BSD>=0
# define OS_BSD
#endif
#if defined(__APPLE__)
# define OS_OSX
#endif
#if defined(PLATFORM_UNIX) || defined(OS_OSX)
# include <unistd.h>
# if defined(_POSIX_VERSION)
# define POSIX
# endif
#endif
//---------------------------------------------------------------------------
// C++ Library
//---------------------------------------------------------------------------
#ifdef __cplusplus
#include <string>
#include <time.h>
// Visual C++ not C99 compliant (VS2008--)
#ifdef _MSC_VER
# if _MSC_VER >= 1600
# include <stdint.h> // VS2010++ have it
# else
typedef signed __int8 int8_t;
typedef signed __int16 int16_t;
typedef signed __int32 int32_t;
typedef signed __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
#ifdef _WIN64
typedef unsigned __int64 uintptr_t;
#else
typedef unsigned __int32 uintptr_t;
#endif
# endif
#else
# include <stdint.h>
#endif
extern "C" {
#endif
//---------------------------------------------------------------------------
// C exact length types
//---------------------------------------------------------------------------
#ifndef __cplusplus
#ifdef OS_BSD
# include <stdint.h>
# include <time.h>
#endif
#ifdef OS_OSX
# include <stdint.h>
# include <time.h>
#endif
#ifdef OS_SOLARIS
# include <stdint.h>
# include <time.h>
#endif
#if defined(_UINTPTR_T_DEFINED)
# include <stdint.h>
# include <time.h>
#endif
#if !defined(_UINTPTR_T_DEFINED) && !defined(OS_SOLARIS) && !defined(OS_BSD) && !defined(OS_OSX)
typedef unsigned char uint8_t; // 8 bit unsigned integer
typedef unsigned short uint16_t; // 16 bit unsigned integer
typedef unsigned int uint32_t; // 32 bit unsigned integer
typedef unsigned long uintptr_t;// 64 bit unsigned integer
#endif
#endif
#ifdef OS_WINDOWS
# define S7API __stdcall
#else
# define S7API
#endif
#pragma pack(1)
//******************************************************************************
// COMMON
//******************************************************************************
// Exact length types regardless of platform/processor
typedef uint8_t byte;
typedef uint16_t word;
typedef uint32_t longword;
typedef byte *pbyte;
typedef word *pword;
typedef uintptr_t S7Object; // multi platform/processor object reference
// DON'T CONFUSE IT WITH AN OLE OBJECT, IT'S SIMPLY
// AN INTEGER VALUE (32 OR 64 BIT) USED AS HANDLE.
#ifndef __cplusplus
typedef struct
{
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
}tm;
typedef int bool;
#define false 0;
#define true 1;
#endif
const int errLibInvalidParam = -1;
const int errLibInvalidObject = -2;
// CPU status
#define S7CpuStatusUnknown 0x00
#define S7CpuStatusRun 0x08
#define S7CpuStatusStop 0x04
// ISO Errors
const longword errIsoConnect = 0x00010000; // Connection error
const longword errIsoDisconnect = 0x00020000; // Disconnect error
const longword errIsoInvalidPDU = 0x00030000; // Bad format
const longword errIsoInvalidDataSize = 0x00040000; // Bad Datasize passed to send/recv buffer is invalid
const longword errIsoNullPointer = 0x00050000; // Null passed as pointer
const longword errIsoShortPacket = 0x00060000; // A short packet received
const longword errIsoTooManyFragments = 0x00070000; // Too many packets without EoT flag
const longword errIsoPduOverflow = 0x00080000; // The sum of fragments data exceded maximum packet size
const longword errIsoSendPacket = 0x00090000; // An error occurred during send
const longword errIsoRecvPacket = 0x000A0000; // An error occurred during recv
const longword errIsoInvalidParams = 0x000B0000; // Invalid TSAP params
const longword errIsoResvd_1 = 0x000C0000; // Unassigned
const longword errIsoResvd_2 = 0x000D0000; // Unassigned
const longword errIsoResvd_3 = 0x000E0000; // Unassigned
const longword errIsoResvd_4 = 0x000F0000; // Unassigned
// Tag Struct
typedef struct{
int Area;
int DBNumber;
int Start;
int Size;
int WordLen;
}TS7Tag, *PS7Tag;
//------------------------------------------------------------------------------
// PARAMS LIST
//------------------------------------------------------------------------------
const int p_u16_LocalPort = 1;
const int p_u16_RemotePort = 2;
const int p_i32_PingTimeout = 3;
const int p_i32_SendTimeout = 4;
const int p_i32_RecvTimeout = 5;
const int p_i32_WorkInterval = 6;
const int p_u16_SrcRef = 7;
const int p_u16_DstRef = 8;
const int p_u16_SrcTSap = 9;
const int p_i32_PDURequest = 10;
const int p_i32_MaxClients = 11;
const int p_i32_BSendTimeout = 12;
const int p_i32_BRecvTimeout = 13;
const int p_u32_RecoveryTime = 14;
const int p_u32_KeepAliveTime = 15;
// Client/Partner Job status
const int JobComplete = 0;
const int JobPending = 1;
//******************************************************************************
// CLIENT
//******************************************************************************
// Error codes
const longword errNegotiatingPDU = 0x00100000;
const longword errCliInvalidParams = 0x00200000;
const longword errCliJobPending = 0x00300000;
const longword errCliTooManyItems = 0x00400000;
const longword errCliInvalidWordLen = 0x00500000;
const longword errCliPartialDataWritten = 0x00600000;
const longword errCliSizeOverPDU = 0x00700000;
const longword errCliInvalidPlcAnswer = 0x00800000;
const longword errCliAddressOutOfRange = 0x00900000;
const longword errCliInvalidTransportSize = 0x00A00000;
const longword errCliWriteDataSizeMismatch = 0x00B00000;
const longword errCliItemNotAvailable = 0x00C00000;
const longword errCliInvalidValue = 0x00D00000;
const longword errCliCannotStartPLC = 0x00E00000;
const longword errCliAlreadyRun = 0x00F00000;
const longword errCliCannotStopPLC = 0x01000000;
const longword errCliCannotCopyRamToRom = 0x01100000;
const longword errCliCannotCompress = 0x01200000;
const longword errCliAlreadyStop = 0x01300000;
const longword errCliFunNotAvailable = 0x01400000;
const longword errCliUploadSequenceFailed = 0x01500000;
const longword errCliInvalidDataSizeRecvd = 0x01600000;
const longword errCliInvalidBlockType = 0x01700000;
const longword errCliInvalidBlockNumber = 0x01800000;
const longword errCliInvalidBlockSize = 0x01900000;
const longword errCliDownloadSequenceFailed = 0x01A00000;
const longword errCliInsertRefused = 0x01B00000;
const longword errCliDeleteRefused = 0x01C00000;
const longword errCliNeedPassword = 0x01D00000;
const longword errCliInvalidPassword = 0x01E00000;
const longword errCliNoPasswordToSetOrClear = 0x01F00000;
const longword errCliJobTimeout = 0x02000000;
const longword errCliPartialDataRead = 0x02100000;
const longword errCliBufferTooSmall = 0x02200000;
const longword errCliFunctionRefused = 0x02300000;
const longword errCliDestroying = 0x02400000;
const longword errCliInvalidParamNumber = 0x02500000;
const longword errCliCannotChangeParam = 0x02600000;
const int MaxVars = 20; // Max vars that can be transferred with MultiRead/MultiWrite
// Client Connection Type
const word CONNTYPE_PG = 0x0001; // Connect to the PLC as a PG
const word CONNTYPE_OP = 0x0002; // Connect to the PLC as an OP
const word CONNTYPE_BASIC = 0x0003; // Basic connection
// Area ID
const byte S7AreaPE = 0x81;
const byte S7AreaPA = 0x82;
const byte S7AreaMK = 0x83;
const byte S7AreaDB = 0x84;
const byte S7AreaCT = 0x1C;
const byte S7AreaTM = 0x1D;
// Word Length
const int S7WLBit = 0x01;
const int S7WLByte = 0x02;
const int S7WLWord = 0x04;
const int S7WLDWord = 0x06;
const int S7WLReal = 0x08;
const int S7WLCounter = 0x1C;
const int S7WLTimer = 0x1D;
// Block type
const byte Block_OB = 0x38;
const byte Block_DB = 0x41;
const byte Block_SDB = 0x42;
const byte Block_FC = 0x43;
const byte Block_SFC = 0x44;
const byte Block_FB = 0x45;
const byte Block_SFB = 0x46;
// Sub Block Type
const byte SubBlk_OB = 0x08;
const byte SubBlk_DB = 0x0A;
const byte SubBlk_SDB = 0x0B;
const byte SubBlk_FC = 0x0C;
const byte SubBlk_SFC = 0x0D;
const byte SubBlk_FB = 0x0E;
const byte SubBlk_SFB = 0x0F;
// Block languages
const byte BlockLangAWL = 0x01;
const byte BlockLangKOP = 0x02;
const byte BlockLangFUP = 0x03;
const byte BlockLangSCL = 0x04;
const byte BlockLangDB = 0x05;
const byte BlockLangGRAPH = 0x06;
// Read/Write Multivars
typedef struct{
int Area;
int WordLen;
int Result;
int DBNumber;
int Start;
int Amount;
void *pdata;
} TS7DataItem, *PS7DataItem;
//typedef int TS7ResultItems[MaxVars];
//typedef TS7ResultItems *PS7ResultItems;
// List Blocks
typedef struct {
int OBCount;
int FBCount;
int FCCount;
int SFBCount;
int SFCCount;
int DBCount;
int SDBCount;
} TS7BlocksList, *PS7BlocksList;
// Blocks info
typedef struct {
int BlkType; // Block Type (OB, DB)
int BlkNumber; // Block number
int BlkLang; // Block Language
int BlkFlags; // Block flags
int MC7Size; // The real size in bytes
int LoadSize; // Load memory size
int LocalData; // Local data
int SBBLength; // SBB Length
int CheckSum; // Checksum
int Version; // Block version
// Chars info
char CodeDate[11]; // Code date
char IntfDate[11]; // Interface date
char Author[9]; // Author
char Family[9]; // Family
char Header[9]; // Header
} TS7BlockInfo, *PS7BlockInfo ;
typedef word TS7BlocksOfType[0x2000];
typedef TS7BlocksOfType *PS7BlocksOfType;
// Order code
typedef struct {
char Code[21];
byte V1;
byte V2;
byte V3;
} TS7OrderCode, *PS7OrderCode;
// CPU Info
typedef struct {
char ModuleTypeName[33];
char SerialNumber[25];
char ASName[25];
char Copyright[27];
char ModuleName[25];
} TS7CpuInfo, *PS7CpuInfo;
// CP Info
typedef struct {
int MaxPduLengt;
int MaxConnections;
int MaxMpiRate;
int MaxBusRate;
} TS7CpInfo, *PS7CpInfo;
// See §33.1 of "System Software for S7-300/400 System and Standard Functions"
// and see SFC51 description too
typedef struct {
word LENTHDR;
word N_DR;
} SZL_HEADER, *PSZL_HEADER;
typedef struct {
SZL_HEADER Header;
byte Data[0x4000-4];
} TS7SZL, *PS7SZL;
// SZL List of available SZL IDs : same as SZL but List items are big-endian adjusted
typedef struct {
SZL_HEADER Header;
word List[0x2000-2];
} TS7SZLList, *PS7SZLList;
// See §33.19 of "System Software for S7-300/400 System and Standard Functions"
typedef struct {
word sch_schal;
word sch_par;
word sch_rel;
word bart_sch;
word anl_sch;
} TS7Protection, *PS7Protection;
// Client completion callback
typedef void (S7API *pfn_CliCompletion) (void *usrPtr, int opCode, int opResult);
//------------------------------------------------------------------------------
// Import prototypes
//------------------------------------------------------------------------------
S7Object S7API Cli_Create();
void S7API Cli_Destroy(S7Object *Client);
int S7API Cli_ConnectTo(S7Object Client, const char *Address, int Rack, int Slot);
int S7API Cli_SetConnectionParams(S7Object Client, const char *Address, word LocalTSAP, word RemoteTSAP);
int S7API Cli_SetConnectionType(S7Object Client, word ConnectionType);
int S7API Cli_Connect(S7Object Client);
int S7API Cli_Disconnect(S7Object Client);
int S7API Cli_GetParam(S7Object Client, int ParamNumber, void *pValue);
int S7API Cli_SetParam(S7Object Client, int ParamNumber, void *pValue);
int S7API Cli_SetAsCallback(S7Object Client, pfn_CliCompletion pCompletion, void *usrPtr);
// Data I/O main functions
int S7API Cli_ReadArea(S7Object Client, int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
int S7API Cli_WriteArea(S7Object Client, int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
int S7API Cli_ReadMultiVars(S7Object Client, PS7DataItem Item, int ItemsCount);
int S7API Cli_WriteMultiVars(S7Object Client, PS7DataItem Item, int ItemsCount);
// Data I/O Lean functions
int S7API Cli_DBRead(S7Object Client, int DBNumber, int Start, int Size, void *pUsrData);
int S7API Cli_DBWrite(S7Object Client, int DBNumber, int Start, int Size, void *pUsrData);
int S7API Cli_MBRead(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_MBWrite(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_EBRead(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_EBWrite(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_ABRead(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_ABWrite(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_TMRead(S7Object Client, int Start, int Amount, void *pUsrData);
int S7API Cli_TMWrite(S7Object Client, int Start, int Amount, void *pUsrData);
int S7API Cli_CTRead(S7Object Client, int Start, int Amount, void *pUsrData);
int S7API Cli_CTWrite(S7Object Client, int Start, int Amount, void *pUsrData);
// Directory functions
int S7API Cli_ListBlocks(S7Object Client, TS7BlocksList *pUsrData);
int S7API Cli_GetAgBlockInfo(S7Object Client, int BlockType, int BlockNum, TS7BlockInfo *pUsrData);
int S7API Cli_GetPgBlockInfo(S7Object Client, void *pBlock, TS7BlockInfo *pUsrData, int Size);
int S7API Cli_ListBlocksOfType(S7Object Client, int BlockType, TS7BlocksOfType *pUsrData, int *ItemsCount);
// Blocks functions
int S7API Cli_Upload(S7Object Client, int BlockType, int BlockNum, void *pUsrData, int *Size);
int S7API Cli_FullUpload(S7Object Client, int BlockType, int BlockNum, void *pUsrData, int *Size);
int S7API Cli_Download(S7Object Client, int BlockNum, void *pUsrData, int Size);
int S7API Cli_Delete(S7Object Client, int BlockType, int BlockNum);
int S7API Cli_DBGet(S7Object Client, int DBNumber, void *pUsrData, int *Size);
int S7API Cli_DBFill(S7Object Client, int DBNumber, int FillChar);
// Date/Time functions
int S7API Cli_GetPlcDateTime(S7Object Client, tm *DateTime);
int S7API Cli_SetPlcDateTime(S7Object Client, tm *DateTime);
int S7API Cli_SetPlcSystemDateTime(S7Object Client);
// System Info functions
int S7API Cli_GetOrderCode(S7Object Client, TS7OrderCode *pUsrData);
int S7API Cli_GetCpuInfo(S7Object Client, TS7CpuInfo *pUsrData);
int S7API Cli_GetCpInfo(S7Object Client, TS7CpInfo *pUsrData);
int S7API Cli_ReadSZL(S7Object Client, int ID, int Index, TS7SZL *pUsrData, int *Size);
int S7API Cli_ReadSZLList(S7Object Client, TS7SZLList *pUsrData, int *ItemsCount);
// Control functions
int S7API Cli_PlcHotStart(S7Object Client);
int S7API Cli_PlcColdStart(S7Object Client);
int S7API Cli_PlcStop(S7Object Client);
int S7API Cli_CopyRamToRom(S7Object Client, int Timeout);
int S7API Cli_Compress(S7Object Client, int Timeout);
int S7API Cli_GetPlcStatus(S7Object Client, int *Status);
// Security functions
int S7API Cli_GetProtection(S7Object Client, TS7Protection *pUsrData);
int S7API Cli_SetSessionPassword(S7Object Client, char *Password);
int S7API Cli_ClearSessionPassword(S7Object Client);
// Low level
int S7API Cli_IsoExchangeBuffer(S7Object Client, void *pUsrData, int *Size);
// Misc
int S7API Cli_GetExecTime(S7Object Client, int *Time);
int S7API Cli_GetLastError(S7Object Client, int *LastError);
int S7API Cli_GetPduLength(S7Object Client, int *Requested, int *Negotiated);
int S7API Cli_ErrorText(int Error, char *Text, int TextLen);
// 1.1.0
int S7API Cli_GetConnected(S7Object Client, int *Connected);
//------------------------------------------------------------------------------
// Async functions
//------------------------------------------------------------------------------
int S7API Cli_AsReadArea(S7Object Client, int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
int S7API Cli_AsWriteArea(S7Object Client, int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
int S7API Cli_AsDBRead(S7Object Client, int DBNumber, int Start, int Size, void *pUsrData);
int S7API Cli_AsDBWrite(S7Object Client, int DBNumber, int Start, int Size, void *pUsrData);
int S7API Cli_AsMBRead(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_AsMBWrite(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_AsEBRead(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_AsEBWrite(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_AsABRead(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_AsABWrite(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_AsTMRead(S7Object Client, int Start, int Amount, void *pUsrData);
int S7API Cli_AsTMWrite(S7Object Client, int Start, int Amount, void *pUsrData);
int S7API Cli_AsCTRead(S7Object Client, int Start, int Amount, void *pUsrData);
int S7API Cli_AsCTWrite(S7Object Client, int Start, int Amount, void *pUsrData);
int S7API Cli_AsListBlocksOfType(S7Object Client, int BlockType, TS7BlocksOfType *pUsrData, int *ItemsCount);
int S7API Cli_AsReadSZL(S7Object Client, int ID, int Index, TS7SZL *pUsrData, int *Size);
int S7API Cli_AsReadSZLList(S7Object Client, TS7SZLList *pUsrData, int *ItemsCount);
int S7API Cli_AsUpload(S7Object Client, int BlockType, int BlockNum, void *pUsrData, int *Size);
int S7API Cli_AsFullUpload(S7Object Client, int BlockType, int BlockNum, void *pUsrData, int *Size);
int S7API Cli_AsDownload(S7Object Client, int BlockNum, void *pUsrData, int Size);
int S7API Cli_AsCopyRamToRom(S7Object Client, int Timeout);
int S7API Cli_AsCompress(S7Object Client, int Timeout);
int S7API Cli_AsDBGet(S7Object Client, int DBNumber, void *pUsrData, int *Size);
int S7API Cli_AsDBFill(S7Object Client, int DBNumber, int FillChar);
int S7API Cli_CheckAsCompletion(S7Object Client, int *opResult);
int S7API Cli_WaitAsCompletion(S7Object Client, int Timeout);
//******************************************************************************
// SERVER
//******************************************************************************
const int OperationRead = 0;
const int OperationWrite = 1;
const int mkEvent = 0;
const int mkLog = 1;
// Server Area ID (use with Register/unregister - Lock/unlock Area)
const int srvAreaPE = 0;
const int srvAreaPA = 1;
const int srvAreaMK = 2;
const int srvAreaCT = 3;
const int srvAreaTM = 4;
const int srvAreaDB = 5;
// Errors
const longword errSrvCannotStart = 0x00100000; // Server cannot start
const longword errSrvDBNullPointer = 0x00200000; // Passed null as PData
const longword errSrvAreaAlreadyExists = 0x00300000; // Area Re-registration
const longword errSrvUnknownArea = 0x00400000; // Unknown area
const longword errSrvInvalidParams = 0x00500000; // Invalid param(s) supplied
const longword errSrvTooManyDB = 0x00600000; // Cannot register DB
const longword errSrvInvalidParamNumber = 0x00700000; // Invalid param (srv_get/set_param)
const longword errSrvCannotChangeParam = 0x00800000; // Cannot change because running
// TCP Server Event codes
const longword evcServerStarted = 0x00000001;
const longword evcServerStopped = 0x00000002;
const longword evcListenerCannotStart = 0x00000004;
const longword evcClientAdded = 0x00000008;
const longword evcClientRejected = 0x00000010;
const longword evcClientNoRoom = 0x00000020;
const longword evcClientException = 0x00000040;
const longword evcClientDisconnected = 0x00000080;
const longword evcClientTerminated = 0x00000100;
const longword evcClientsDropped = 0x00000200;
const longword evcReserved_00000400 = 0x00000400; // actually unused
const longword evcReserved_00000800 = 0x00000800; // actually unused
const longword evcReserved_00001000 = 0x00001000; // actually unused
const longword evcReserved_00002000 = 0x00002000; // actually unused
const longword evcReserved_00004000 = 0x00004000; // actually unused
const longword evcReserved_00008000 = 0x00008000; // actually unused
// S7 Server Event Code
const longword evcPDUincoming = 0x00010000;
const longword evcDataRead = 0x00020000;
const longword evcDataWrite = 0x00040000;
const longword evcNegotiatePDU = 0x00080000;
const longword evcReadSZL = 0x00100000;
const longword evcClock = 0x00200000;
const longword evcUpload = 0x00400000;
const longword evcDownload = 0x00800000;
const longword evcDirectory = 0x01000000;
const longword evcSecurity = 0x02000000;
const longword evcControl = 0x04000000;
const longword evcReserved_08000000 = 0x08000000; // actually unused
const longword evcReserved_10000000 = 0x10000000; // actually unused
const longword evcReserved_20000000 = 0x20000000; // actually unused
const longword evcReserved_40000000 = 0x40000000; // actually unused
const longword evcReserved_80000000 = 0x80000000; // actually unused
// Masks to enable/disable all events
const longword evcAll = 0xFFFFFFFF;
const longword evcNone = 0x00000000;
// Event SubCodes
const word evsUnknown = 0x0000;
const word evsStartUpload = 0x0001;
const word evsStartDownload = 0x0001;
const word evsGetBlockList = 0x0001;
const word evsStartListBoT = 0x0002;
const word evsListBoT = 0x0003;
const word evsGetBlockInfo = 0x0004;
const word evsGetClock = 0x0001;
const word evsSetClock = 0x0002;
const word evsSetPassword = 0x0001;
const word evsClrPassword = 0x0002;
// Event Params : functions group
const word grProgrammer = 0x0041;
const word grCyclicData = 0x0042;
const word grBlocksInfo = 0x0043;
const word grSZL = 0x0044;
const word grPassword = 0x0045;
const word grBSend = 0x0046;
const word grClock = 0x0047;
const word grSecurity = 0x0045;
// Event Params : control codes
const word CodeControlUnknown = 0x0000;
const word CodeControlColdStart = 0x0001;
const word CodeControlWarmStart = 0x0002;
const word CodeControlStop = 0x0003;
const word CodeControlCompress = 0x0004;
const word CodeControlCpyRamRom = 0x0005;
const word CodeControlInsDel = 0x0006;
// Event Result
const word evrNoError = 0x0000;
const word evrFragmentRejected = 0x0001;
const word evrMalformedPDU = 0x0002;
const word evrSparseBytes = 0x0003;
const word evrCannotHandlePDU = 0x0004;
const word evrNotImplemented = 0x0005;
const word evrErrException = 0x0006;
const word evrErrAreaNotFound = 0x0007;
const word evrErrOutOfRange = 0x0008;
const word evrErrOverPDU = 0x0009;
const word evrErrTransportSize = 0x000A;
const word evrInvalidGroupUData = 0x000B;
const word evrInvalidSZL = 0x000C;
const word evrDataSizeMismatch = 0x000D;
const word evrCannotUpload = 0x000E;
const word evrCannotDownload = 0x000F;
const word evrUploadInvalidID = 0x0010;
const word evrResNotFound = 0x0011;
typedef struct{
time_t EvtTime; // Timestamp
int EvtSender; // Sender
longword EvtCode; // Event code
word EvtRetCode; // Event result
word EvtParam1; // Param 1 (if available)
word EvtParam2; // Param 2 (if available)
word EvtParam3; // Param 3 (if available)
word EvtParam4; // Param 4 (if available)
}TSrvEvent, *PSrvEvent;
// Server Events callback
typedef void (S7API *pfn_SrvCallBack)(void *usrPtr, PSrvEvent PEvent, int Size);
// Server Read/Write callback
typedef int(S7API *pfn_RWAreaCallBack)(void *usrPtr, int Sender, int Operation, PS7Tag PTag, void *pUsrData);
S7Object S7API Srv_Create();
void S7API Srv_Destroy(S7Object *Server);
int S7API Srv_GetParam(S7Object Server, int ParamNumber, void *pValue);
int S7API Srv_SetParam(S7Object Server, int ParamNumber, void *pValue);
int S7API Srv_StartTo(S7Object Server, const char *Address);
int S7API Srv_Start(S7Object Server);
int S7API Srv_Stop(S7Object Server);
int S7API Srv_RegisterArea(S7Object Server, int AreaCode, word Index, void *pUsrData, int Size);
int S7API Srv_UnregisterArea(S7Object Server, int AreaCode, word Index);
int S7API Srv_LockArea(S7Object Server, int AreaCode, word Index);
int S7API Srv_UnlockArea(S7Object Server, int AreaCode, word Index);
int S7API Srv_GetStatus(S7Object Server, int *ServerStatus, int *CpuStatus, int *ClientsCount);
int S7API Srv_SetCpuStatus(S7Object Server, int CpuStatus);
int S7API Srv_ClearEvents(S7Object Server);
int S7API Srv_PickEvent(S7Object Server, TSrvEvent *pEvent, int *EvtReady);
int S7API Srv_GetMask(S7Object Server, int MaskKind, longword *Mask);
int S7API Srv_SetMask(S7Object Server, int MaskKind, longword Mask);
int S7API Srv_SetEventsCallback(S7Object Server, pfn_SrvCallBack pCallback, void *usrPtr);
int S7API Srv_SetReadEventsCallback(S7Object Server, pfn_SrvCallBack pCallback, void *usrPtr);
int S7API Srv_SetRWAreaCallback(S7Object Server, pfn_RWAreaCallBack pCallback, void *usrPtr);
int S7API Srv_EventText(TSrvEvent *Event, char *Text, int TextLen);
int S7API Srv_ErrorText(int Error, char *Text, int TextLen);
//******************************************************************************
// PARTNER
//******************************************************************************
// Status
const int par_stopped = 0; // stopped
const int par_connecting = 1; // running and active connecting
const int par_waiting = 2; // running and waiting for a connection
const int par_linked = 3; // running and connected : linked
const int par_sending = 4; // sending data
const int par_receiving = 5; // receiving data
const int par_binderror = 6; // error starting passive server
// Errors
const longword errParAddressInUse = 0x00200000;
const longword errParNoRoom = 0x00300000;
const longword errServerNoRoom = 0x00400000;
const longword errParInvalidParams = 0x00500000;
const longword errParNotLinked = 0x00600000;
const longword errParBusy = 0x00700000;
const longword errParFrameTimeout = 0x00800000;
const longword errParInvalidPDU = 0x00900000;
const longword errParSendTimeout = 0x00A00000;
const longword errParRecvTimeout = 0x00B00000;
const longword errParSendRefused = 0x00C00000;
const longword errParNegotiatingPDU = 0x00D00000;
const longword errParSendingBlock = 0x00E00000;
const longword errParRecvingBlock = 0x00F00000;
const longword errParBindError = 0x01000000;
const longword errParDestroying = 0x01100000;
const longword errParInvalidParamNumber = 0x01200000; // Invalid param (par_get/set_param)
const longword errParCannotChangeParam = 0x01300000; // Cannot change because running
const longword errParBufferTooSmall = 0x01400000; // Raised by LabVIEW wrapper
// Brecv Data incoming Callback
typedef void (S7API *pfn_ParRecvCallBack)(void * usrPtr, int opResult, longword R_ID, void *pData, int Size);
// BSend Completion Callback
typedef void (S7API *pfn_ParSendCompletion)(void * usrPtr, int opResult);
S7Object S7API Par_Create(int Active);
void S7API Par_Destroy(S7Object *Partner);
int S7API Par_GetParam(S7Object Partner, int ParamNumber, void *pValue);
int S7API Par_SetParam(S7Object Partner, int ParamNumber, void *pValue);
int S7API Par_StartTo(S7Object Partner, const char *LocalAddress, const char *RemoteAddress,
word LocTsap, word RemTsap);
int S7API Par_Start(S7Object Partner);
int S7API Par_Stop(S7Object Partner);
// BSend
int S7API Par_BSend(S7Object Partner, longword R_ID, void *pUsrData, int Size);
int S7API Par_AsBSend(S7Object Partner, longword R_ID, void *pUsrData, int Size);
int S7API Par_CheckAsBSendCompletion(S7Object Partner, int *opResult);
int S7API Par_WaitAsBSendCompletion(S7Object Partner, longword Timeout);
int S7API Par_SetSendCallback(S7Object Partner, pfn_ParSendCompletion pCompletion, void *usrPtr);
// BRecv
int S7API Par_BRecv(S7Object Partner, longword *R_ID, void *pData, int *Size, longword Timeout);
int S7API Par_CheckAsBRecvCompletion(S7Object Partner, int *opResult, longword *R_ID,
void *pData, int *Size);
int S7API Par_SetRecvCallback(S7Object Partner, pfn_ParRecvCallBack pCompletion, void *usrPtr);
// Stat
int S7API Par_GetTimes(S7Object Partner, longword *SendTime, longword *RecvTime);
int S7API Par_GetStats(S7Object Partner, longword *BytesSent, longword *BytesRecv,
longword *SendErrors, longword *RecvErrors);
int S7API Par_GetLastError(S7Object Partner, int *LastError);
int S7API Par_GetStatus(S7Object Partner, int *Status);
int S7API Par_ErrorText(int Error, char *Text, int TextLen);
#pragma pack()
#ifdef __cplusplus
}
#endif // __cplusplus
#ifdef __cplusplus
//******************************************************************************
// CLIENT CLASS DEFINITION
//******************************************************************************
class TS7Client
{
private:
S7Object Client;
public:
TS7Client();
~TS7Client();
// Control functions
int Connect();
int ConnectTo(const char *RemAddress, int Rack, int Slot);
int SetConnectionParams(const char *RemAddress, word LocalTSAP, word RemoteTSAP);
int SetConnectionType(word ConnectionType);
int Disconnect();
int GetParam(int ParamNumber, void *pValue);
int SetParam(int ParamNumber, void *pValue);
// Data I/O Main functions
int ReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
int WriteArea(int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
int ReadMultiVars(PS7DataItem Item, int ItemsCount);
int WriteMultiVars(PS7DataItem Item, int ItemsCount);
// Data I/O Lean functions
int DBRead(int DBNumber, int Start, int Size, void *pUsrData);
int DBWrite(int DBNumber, int Start, int Size, void *pUsrData);
int MBRead(int Start, int Size, void *pUsrData);
int MBWrite(int Start, int Size, void *pUsrData);
int EBRead(int Start, int Size, void *pUsrData);
int EBWrite(int Start, int Size, void *pUsrData);
int ABRead(int Start, int Size, void *pUsrData);
int ABWrite(int Start, int Size, void *pUsrData);
int TMRead(int Start, int Amount, void *pUsrData);
int TMWrite(int Start, int Amount, void *pUsrData);
int CTRead(int Start, int Amount, void *pUsrData);
int CTWrite(int Start, int Amount, void *pUsrData);
// Directory functions
int ListBlocks(PS7BlocksList pUsrData);
int GetAgBlockInfo(int BlockType, int BlockNum, PS7BlockInfo pUsrData);
int GetPgBlockInfo(void *pBlock, PS7BlockInfo pUsrData, int Size);
int ListBlocksOfType(int BlockType, TS7BlocksOfType *pUsrData, int *ItemsCount);
// Blocks functions
int Upload(int BlockType, int BlockNum, void *pUsrData, int *Size);
int FullUpload(int BlockType, int BlockNum, void *pUsrData, int *Size);
int Download(int BlockNum, void *pUsrData, int Size);
int Delete(int BlockType, int BlockNum);
int DBGet(int DBNumber, void *pUsrData, int *Size);
int DBFill(int DBNumber, int FillChar);
// Date/Time functions
int GetPlcDateTime(tm *DateTime);
int SetPlcDateTime(tm *DateTime);
int SetPlcSystemDateTime();
// System Info functions
int GetOrderCode(PS7OrderCode pUsrData);
int GetCpuInfo(PS7CpuInfo pUsrData);
int GetCpInfo(PS7CpInfo pUsrData);
int ReadSZL(int ID, int Index, PS7SZL pUsrData, int *Size);
int ReadSZLList(PS7SZLList pUsrData, int *ItemsCount);
// Control functions
int PlcHotStart();
int PlcColdStart();
int PlcStop();
int CopyRamToRom(int Timeout);
int Compress(int Timeout);
// Security functions
int GetProtection(PS7Protection pUsrData);
int SetSessionPassword(char *Password);
int ClearSessionPassword();
// Properties
int ExecTime();
int LastError();
int PDURequested();
int PDULength();
int PlcStatus();
bool Connected();
// Async functions
int SetAsCallback(pfn_CliCompletion pCompletion, void *usrPtr);
bool CheckAsCompletion(int *opResult);
int WaitAsCompletion(longword Timeout);
int AsReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
int AsWriteArea(int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
int AsListBlocksOfType(int BlockType, PS7BlocksOfType pUsrData, int *ItemsCount);
int AsReadSZL(int ID, int Index, PS7SZL pUsrData, int *Size);
int AsReadSZLList(PS7SZLList pUsrData, int *ItemsCount);
int AsUpload(int BlockType, int BlockNum, void *pUsrData, int *Size);
int AsFullUpload(int BlockType, int BlockNum, void *pUsrData, int *Size);
int AsDownload(int BlockNum, void *pUsrData, int Size);
int AsCopyRamToRom(int Timeout);
int AsCompress(int Timeout);
int AsDBRead(int DBNumber, int Start, int Size, void *pUsrData);
int AsDBWrite(int DBNumber, int Start, int Size, void *pUsrData);
int AsMBRead(int Start, int Size, void *pUsrData);
int AsMBWrite(int Start, int Size, void *pUsrData);
int AsEBRead(int Start, int Size, void *pUsrData);
int AsEBWrite(int Start, int Size, void *pUsrData);
int AsABRead(int Start, int Size, void *pUsrData);
int AsABWrite(int Start, int Size, void *pUsrData);
int AsTMRead(int Start, int Amount, void *pUsrData);
int AsTMWrite(int Start, int Amount, void *pUsrData);
int AsCTRead(int Start, int Amount, void *pUsrData);
int AsCTWrite(int Start, int Amount, void *pUsrData);
int AsDBGet(int DBNumber, void *pUsrData, int *Size);
int AsDBFill(int DBNumber, int FillChar);
};
typedef TS7Client *PS7Client;
//******************************************************************************
// SERVER CLASS DEFINITION
//******************************************************************************
class TS7Server
{
private:
S7Object Server;
public:
TS7Server();
~TS7Server();
// Control
int Start();
int StartTo(const char *Address);
int Stop();
int GetParam(int ParamNumber, void *pValue);
int SetParam(int ParamNumber, void *pValue);
// Events
int SetEventsCallback(pfn_SrvCallBack PCallBack, void *UsrPtr);
int SetReadEventsCallback(pfn_SrvCallBack PCallBack, void *UsrPtr);
int SetRWAreaCallback(pfn_RWAreaCallBack PCallBack, void *UsrPtr);
bool PickEvent(TSrvEvent *pEvent);
void ClearEvents();
longword GetEventsMask();
longword GetLogMask();
void SetEventsMask(longword Mask);
void SetLogMask(longword Mask);
// Resources
int RegisterArea(int AreaCode, word Index, void *pUsrData, word Size);
int UnregisterArea(int AreaCode, word Index);
int LockArea(int AreaCode, word Index);
int UnlockArea(int AreaCode, word Index);
// Properties
int ServerStatus();
int GetCpuStatus();
int SetCpuStatus(int Status);
int ClientsCount();
};
typedef TS7Server *PS7Server;
//******************************************************************************
// PARTNER CLASS DEFINITION
//******************************************************************************
class TS7Partner
{
private:
S7Object Partner; // Partner Handle
public:
TS7Partner(bool Active);
~TS7Partner();
// Control
int GetParam(int ParamNumber, void *pValue);
int SetParam(int ParamNumber, void *pValue);
int Start();
int StartTo(const char *LocalAddress,
const char *RemoteAddress,
int LocalTSAP,
int RemoteTSAP);
int Stop();
// Data I/O functions : BSend
int BSend(longword R_ID, void *pUsrData, int Size);
int AsBSend(longword R_ID, void *pUsrData, int Size);
bool CheckAsBSendCompletion(int *opResult);
int WaitAsBSendCompletion(longword Timeout);
int SetSendCallback(pfn_ParSendCompletion pCompletion, void *usrPtr);
// Data I/O functions : BRecv
int BRecv(longword *R_ID, void *pUsrData, int *Size, longword Timeout);
bool CheckAsBRecvCompletion(int *opResult, longword *R_ID, void *pUsrData, int *Size);
int SetRecvCallback(pfn_ParRecvCallBack pCallback, void *usrPtr);
// Properties
int Status();
int LastError();
int GetTimes(longword *SendTime, longword *RecvTime);
int GetStats(longword *BytesSent,
longword *BytesRecv,
longword *ErrSend,
longword *ErrRecv);
bool Linked();
};
typedef TS7Partner *PS7Partner;
//******************************************************************************
// TEXT ROUTINES
// Only for C++, for pure C use xxx_ErrorText() which uses *char
//******************************************************************************
#define TextLen 1024
// String type
// Here we define generic TextString (by default mapped onto std::string).
// So you can change it if needed (Unicodestring, Ansistring etc...)
typedef std::string TextString;
TextString CliErrorText(int Error);
TextString SrvErrorText(int Error);
TextString ParErrorText(int Error);
TextString SrvEventText(TSrvEvent *Event);
#endif // __cplusplus
#endif // snap7_h
| [
"m.ghazivakili@gmail.com"
] | m.ghazivakili@gmail.com |
708a02b868d34bd6adc50ba1b0fbece3d393e01b | 2f67b4db64a6063ba6c5d80986d27ff52319818b | /ASSG2_B130353CS_DATTA/ASSG2_B130353CS_DATTA_2.cpp | 5b24aa2f16e866e287dc47fa3bd02f0306275100 | [] | no_license | dattathallam/DSA-Lab | 0094d16beaabc11d070aa34a558c0717843ee366 | 54de6cb4eb59916c303a52a650deac897eb83bb1 | refs/heads/master | 2021-01-10T12:45:34.834131 | 2016-01-04T14:01:28 | 2016-01-04T14:01:28 | 48,999,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,418 | cpp | #include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <climits>
#include <ctime>
using namespace std;
int arr[100000000];
int transition_search(int a[],int p,int q)
{
int mid;
if(p > q)
return -1;
mid = floor((p+q)/2);
if(a[mid] > a[mid+1])
return mid;
else
{
if(a[p] > a[mid])
transition_search(a,p,mid-1);
else
transition_search(a,mid+1,q);
}
}
int binary_search(int a[],int p,int q,int k)
{
int mid;
if(p > q)
return -1;
mid = floor((p+q)/2);
if(k == a[mid])
return mid;
else
{
if(k <= a[mid])
binary_search(a,p,mid-1,k);
else
binary_search(a,mid+1,q,k);
}
}
int main()
{
int d,k,n;
char term;
if(!(cin >> n))
{
cout << "invalid input\n";
return 0 ;
}
if(n <= 0)
{
cout << "array size can not be negative or zero\n";
return 0 ;
}
for (int i = 0; i < n-1; ++i)
{
if(scanf("%d%c",&arr[i],&term) != 2 || term == ' ')
{
cout <<"invalid input \n";
return 0;
}
}
cin >> arr[n-1];
cin >> k;
clock_t t;
t = clock();
int index = transition_search(arr,1,n);
// cout << "the transition occurs at element " << index+1 << endl;
if(arr[0] <= k)
d = binary_search(arr,1,index,k);
else
d = binary_search(arr,index+1,n,k);
t = clock() - t;
cout << "the element is found at index : " << d << endl;
printf ("Running time : %f seconds.\n",((float)t)/CLOCKS_PER_SEC);
return 0;
} | [
"tssd19@gmail.com"
] | tssd19@gmail.com |
2285f0c981f741afe5213de439c1b07f83e7f038 | faded56040026d10940117411b277d975e60bc30 | /cpp_fs/ComplexNum/complex_num_test.cpp | efc1c6693c1b49cfc8ffb2d5e8afddee60b6ef93 | [] | no_license | RotemKadosh/projects | ad3ad74dcd9006ae4b698f7f7cd3b0406969d045 | 6fed371d09e108d640715b0566db3696e3e27d5b | refs/heads/master | 2023-04-07T16:33:12.280168 | 2021-03-04T15:43:35 | 2021-03-04T15:43:35 | 323,014,733 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,653 | cpp | #include "cmplx_num.hpp"
#include "cmplx_num_impl.hpp"
#include "../../ds/utils/test.h" // RUNTEST REQUIRE
using namespace ilrd;
test_status_t CreateTest();
test_status_t SubTest();
test_status_t MultTest();
test_status_t IOTest();
test_status_t EqualityTest();
test_status_t AdvanceTest();
test_status_t DivTest();
test_status_t AddTest();
int main()
{
RUNTEST(CreateTest);
RUNTEST(EqualityTest);
RUNTEST(AddTest);
RUNTEST(SubTest);
RUNTEST(MultTest);
RUNTEST(DivTest);
RUNTEST(IOTest);
RUNTEST(AdvanceTest);
Complex c1(1);
Complex c2(0);
for(int i = 0; i < 100000; i++)
{
c2 += c1;
}
return PASSED;
}
test_status_t CreateTest()
{
Complex c1(10, 2);
Complex c2(0, 0);
Complex c3(100, -172.6);
Complex c4(-736.9, 8372.1837);
Complex c5(7.5);
REQUIRE(c1.GetReal() - 10 < 0.001);
REQUIRE(c1.GetImaginary() - 2 < 0.001);
REQUIRE(c2.GetReal() - 0 < 0.001);
REQUIRE(c2.GetImaginary() - 0 < 0.001);
REQUIRE(c3.GetReal() - 100 < 0.001);
REQUIRE(c3.GetImaginary() - (-172.6) < 0.001);
REQUIRE(c4.GetReal() - (-736.9) < 0.001);
REQUIRE(c4.GetImaginary() - (8372.1837) < 0.001);
REQUIRE(c5.GetReal() - 7.5 < 0.001);
REQUIRE(c5.GetImaginary() - 0 < 0.001);
return PASSED;
}
test_status_t EqualityTest()
{
Complex c1(10, 2);
Complex c11(10, 2);
Complex c2(0, 0);
Complex c22(0, 0);
Complex c3(100, -172.6);
Complex c33(100, -172.6);
Complex c4(-736.9, 8372.1837);
Complex c5(7.5);
Complex c6(7.5);
REQUIRE(c1 == c11);
REQUIRE(c11 == c1);
REQUIRE(c11 != c2);
REQUIRE(c2 == c22);
REQUIRE(c22 == c2);
REQUIRE(c2 != c3);
REQUIRE(c3 == c33);
REQUIRE(c33 == c33);
REQUIRE(c11 != c2);
REQUIRE(c4 == c4);
REQUIRE(c4 != c5);
REQUIRE(c5 == c5);
return PASSED;
}
test_status_t MultTest()
{
Complex c1(10, 2);
Complex c11(10, 2);
Complex ans1(c1 * c11);
Complex cmp1(96, 40);
REQUIRE(ans1 == cmp1);
Complex ans(20, 4);
REQUIRE(ans == (2 * c1));
Complex c2(0, 1);
Complex c22(12, 0);
Complex ans2(c2 * c22);
Complex cmp2(0, 12);
REQUIRE(ans2 == cmp2);
Complex c3(100, -172.6);
Complex c33(98745, -5458.6);
Complex ans3(c3 * c33);
Complex cmp3(8932345.64, -17589247);
REQUIRE(ans3 == cmp3);
Complex c4(-736.9, 8372.1837);
Complex c44(7.5);
Complex ans4(c4 * c44);
Complex cmp4(-5526.75, 62791.37775);
REQUIRE(ans4 == cmp4);
return PASSED;
}
test_status_t DivTest()
{
Complex cmp1(12, 5);
Complex cmp2(1.6, 5.3);
Complex cmp3(-2);
Complex ans = cmp1 / cmp2;
REQUIRE(0.00001 > ans.GetReal() - 1.4910277 && -0.00001 < ans.GetReal() - 1.4910277);
REQUIRE(0.00001 > ans.GetImaginary() + 1.8140294 && -0.00001 < ans.GetImaginary() + 1.8140294);
REQUIRE(-6 == (cmp1 / cmp3).GetReal());
REQUIRE(-2.5 == (cmp1 / cmp3).GetImaginary());
REQUIRE(-0.8 == (cmp2 / cmp3).GetReal());
REQUIRE(-2.65 == (cmp2 / cmp3).GetImaginary());
return PASSED;
}
test_status_t IOTest()
{
Complex c1(9);
Complex c2(10, -18);
Complex c3(-9474, 892);
std::cout << c1;
std::cout << c2;
std::cout << c3;
std::cin >> c1;
std::cout << c1;
std::cin >> c2;
std::cout << c2;
return PASSED;
}
test_status_t AdvanceTest()
{
Complex c1(10, 2);
c1 *= c1;
REQUIRE(c1 == Complex(96, 40));
c1 *= 12;
REQUIRE(c1 == Complex(1152,480));
c1 += 7;
c1 += Complex(15,-902);
REQUIRE(c1 == Complex(1174,-422));
c1 -= 9;
REQUIRE(c1 == Complex(1165,-422));
c1 -= Complex(28,89);
REQUIRE(c1 == Complex(1137,-511));
c1 /= 10;
REQUIRE(c1 == Complex(113.7,-51.1));
return PASSED;
}
test_status_t AddTest()
{
Complex cmp1(12, 5);
Complex cmp2(1.6, 5.3);
Complex cmp3(2);
REQUIRE(13.6 == (cmp1 + cmp2).GetReal());
REQUIRE(10.3 == (cmp1 + cmp2).GetImaginary());
REQUIRE(14 == (cmp1 + cmp3).GetReal());
REQUIRE(5 == (cmp1 + cmp3).GetImaginary());
REQUIRE(3.6 == (cmp2 + cmp3).GetReal());
REQUIRE(5.3 == (cmp2 + cmp3).GetImaginary());
return PASSED;
}
test_status_t SubTest()
{
Complex cmp1(12, 5);
Complex cmp2(1.6, 5.3);
Complex cmp3(-2);
REQUIRE(10.4 == (cmp1 - cmp2).GetReal());
REQUIRE(0.000001 > (cmp1 - cmp2).GetImaginary() - 0.3);
REQUIRE(14 == (cmp1 - cmp3).GetReal());
REQUIRE(5 == (cmp1 - cmp3).GetImaginary());
REQUIRE(3.6 == (cmp2 - cmp3).GetReal());
REQUIRE(5.3 == (cmp2 - cmp3).GetImaginary());
return PASSED;
}
| [
"rotemkadosh27@gmail.com"
] | rotemkadosh27@gmail.com |
bd534fcf7d0f1503bfe0e98efa6cba5f6b997d52 | 7847b028ab7075d22548c6e80776c23d01a23f22 | /player.h | 2029e1090e9d15cb66d0ed74334255e99ad8b342 | [] | no_license | ravenheartss/CPSC441_F19_Project | 0817c30fee4a5df524ed8a9fc8c5d12a6b20804c | 713243302dc4ee2625ae8293f00281f027a4d671 | refs/heads/master | 2020-08-27T05:03:59.636155 | 2019-11-29T22:22:37 | 2019-11-29T22:22:37 | 217,251,720 | 0 | 2 | null | 2019-11-29T16:39:12 | 2019-10-24T08:38:22 | C++ | UTF-8 | C++ | false | false | 174 | h | //
// Created by Shankar Ganesh on 2019-10-26.
//
struct player{
int socket;
std::string player_name;
int pos;
int rate;
int n_typed;
int errors;
};
| [
"sankarasubramanian.g@cs.ucalgary.ca"
] | sankarasubramanian.g@cs.ucalgary.ca |
72cf11828365c1148a52523252e7ec32d7db0124 | ffddbcfbc8c4823176481927db4015af8f2f4099 | /QUSBPort.h | b44d2d41d76b36213acd9e60dc590077c98e1e20 | [
"MIT"
] | permissive | MichealWen/QtUSB-1 | cbd1a13c3c19eaa32f25285dd2ac0be9e528220c | 2d2b41ceb643e9e4873b4c1e53786c5116315e83 | refs/heads/master | 2020-07-31T05:23:43.493229 | 2018-03-09T19:07:03 | 2018-03-09T19:07:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,230 | h | #pragma once
//Copyright 2018 Austin Simpson
// 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 "QtUSB_global.h"
class QTUSBSHARED_EXPORT QUSBPort
{
public:
QUSBPort();
};
| [
"noreply@github.com"
] | MichealWen.noreply@github.com |
94119b33413bd25cd2371afba1713fee91816cdb | cdab3905cf5aa6272dab91244bf3139433234f30 | /Utilities/Command/ctreestateadddoublecut.h | b5b1aa09c1db5fe8743e21390d033e457cb6355b | [
"MIT"
] | permissive | Bram-Hub/egg | ca937d2eef1a2311ceba2a06aaf61e3a157a5a51 | 63716d8f190a03e9cad42e41e20b00f523d343e9 | refs/heads/master | 2020-04-16T17:18:28.405374 | 2019-01-15T02:34:38 | 2019-01-15T02:34:38 | 165,771,413 | 0 | 0 | MIT | 2019-01-15T02:33:38 | 2019-01-15T02:33:37 | null | UTF-8 | C++ | false | false | 674 | h | #ifndef CTREESTATEADDDOUBLECUT_H
#define CTREESTATEADDDOUBLECUT_H
#include "itreestateadd.h"
/*
* This command adds a double cut to a TreeState
*/
class CTreeStateAddDoubleCut : public ITreeStateAdd
{
public:
/* Constructor */
CTreeStateAddDoubleCut(TreeState* t) {
text = "Add double cut";
tree = t; }
/* Destructor */
~CTreeStateAddDoubleCut() {}
/* Override the add() function of the ITreeStateAdd interface */
void add() { tree->addChildDoubleCut(); }
/* Override the copy() function of the ICommand interface */
ICommand* copy() { return new CTreeStateAddDoubleCut(tree); }
};
#endif // CTREESTATEADDDOUBLECUT_H
| [
"youngcc3157@gmail.com"
] | youngcc3157@gmail.com |
d7100dc8d7a56ebe5d608a81b356ee89753ad24c | 572da0542a662d96776cd2f368dc83aa5bac4185 | /testing_algorithm/generation_backtracking_nhanhCan/list_arranges.cpp | 3befdf2f5ce7c832dcb984d61e57a074845acdaf | [] | no_license | nguyenhieu008/training_algorithm | a771f8f968fdf6b09fb0e7ac32c9a5f793bd2a8c | eeb08a7f83ec27c6a886f3b86ded9c70fc31932f | refs/heads/master | 2022-12-13T09:31:20.313200 | 2020-09-17T17:13:14 | 2020-09-17T17:13:14 | 277,419,817 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | cpp | #include <iostream>
using namespace std;
namespace list_arranges {
int n, k;
int x[30] = {0, };
bool free_[30];
void printResult() {
for (int i = 1; i <= k; ++i) {
cout << x[i] << " ";
}
cout << endl;
}
void backTrackingMethod(int i) {
if (i > k) {
printResult();
return;
}
for (int j = 1; j <= n; ++j) {
if (free_[j]) {
x[i] = j;
free_[j] = false;
backTrackingMethod(i + 1);
free_[j] = true;
}
}
}
int main() {
cout << "Enter n k:" << endl;
cin >> n >> k;
fill_n(free_, 30, true);
backTrackingMethod(1);
cin >> k;
return 0;
}
} | [
"nguyenhieu008@gmail.com"
] | nguyenhieu008@gmail.com |
8727b71c97734dcd2492e6082afe8de19a7f7ea2 | 4b6aee802117c87307d1e01a511db04d9e67bb46 | /leetcode/src/leetcode0085.cpp | 8c19ac00a44763d18d7c5c6fdf29aca8aee62cf4 | [] | no_license | zencher/algorithms_gym | eec3dfe5d9205a914bea3b935cc2a9c23f790d54 | bc9ac173a4e73c0002f9135b8efe6566e71b9745 | refs/heads/master | 2021-06-03T15:25:29.126708 | 2020-02-22T15:21:50 | 2020-02-22T15:21:50 | 146,380,069 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,619 | cpp | // leetcode085.cpp
//
// Maximal Rectangle
// Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
#include <vector>
using namespace std;
class Solution
{
public:
int maximalRectangle(vector<vector<char> > &matrix)
{
if ( matrix.size() == 0 || matrix[0].size() == 0)
{
return 0;
}
if(matrix.size()<1){
return 0;
}
int max=0;
int mask[matrix.size()][matrix[0].size()];
memset(mask,0,sizeof(mask));
for(int i=0;i<matrix.size();i++){
int count=0;
for(int j=0;j<matrix[0].size();j++){
if(matrix[i][j]=='1'){
count++;
mask[i][j]=count;
}else{
count=0;
mask[i][j]=0;
}
}
}
bool isvisit[matrix.size()][matrix[0].size()];
memset(isvisit,1,sizeof(isvisit));
for(int j=0;j<matrix[0].size();j++){
for(int i=0;i<matrix.size();i++){
if(!isvisit[i][j]){
continue;
}
int lpos=i-1;
int rpos=i+1;
while(lpos>=0&&mask[lpos][j]>=mask[i][j]){
if(mask[lpos][j]==mask[i][j]){
isvisit[lpos][j]=false;
}
lpos--;
}
while(rpos<matrix.size()&&mask[rpos][j]>=mask[i][j]){
if(mask[rpos][j]==mask[i][j]){
isvisit[rpos][j]=false;
}
rpos++;
}
int ans=(rpos-lpos-1)*mask[i][j];
max=max>ans?max:ans;
}
}
return max;
}
};
int main()
{
vector<vector<char> > m;
vector<char> item;
item.push_back( '1' ); item.push_back( '0' ); item.push_back( '1' ); item.push_back( '0' ); item.push_back( '0' );
m.push_back( item ); item.clear();
item.push_back( '1' ); item.push_back( '0' ); item.push_back( '1' ); item.push_back( '1' ); item.push_back( '1' );
m.push_back( item ); item.clear();
item.push_back( '1' ); item.push_back( '1' ); item.push_back( '1' ); item.push_back( '1' ); item.push_back( '1' );
m.push_back( item ); item.clear();
item.push_back( '1' ); item.push_back( '0' ); item.push_back( '0' ); item.push_back( '1' ); item.push_back( '0' );
m.push_back( item ); item.clear();
Solution s;
int r = s.maximalRectangle( m );
printf("%d", r);
return 0;
}
| [
"zch3156@163.com"
] | zch3156@163.com |
8280e3514761a2bd874714609cc6b5dd86e443f8 | 4b19f2755b5891e55bc981fd3bc3965d4fe47218 | /Main Programs/Drifter_V1/parser.ino | a0ce48a5d1ee5f142cf6595966ee95083eae69fc | [] | no_license | nathikazad/Internship | 9292cde9e244f95d1afc8c5c08a1caf0030b5bdb | 8da7e7441a1291450fade9c0df9c80e058c8962e | refs/heads/master | 2020-09-14T13:03:23.195100 | 2016-08-25T17:09:34 | 2016-08-25T17:09:34 | 66,577,657 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,223 | ino | #include <PString.h>
#define HANDHELD_ID "RB0008915B"
#define DRIFTER_ID_PREF "SD"
char drifterIdChar = '2';
uint8_t hour, minute, seconds, year, month, day;
uint16_t milliseconds;
// Floating point latitude and longitude value in degrees.
float latitude, longitude;
// Fixed point latitude and longitude value with degrees stored in units of 1/100000 degrees,
// and minutes stored in units of 1/100000 degrees. See pull #13 for more details:
// https://github.com/adafruit/Adafruit-GPS-Library/pull/13
int32_t latitude_fixed, longitude_fixed;
float latitudeDegrees, longitudeDegrees;
float geoidheight, altitude;
float speed, angle, magvariation, HDOP;
char lat, lon, mag;
boolean fix;
uint8_t fixquality, satellites;
boolean parser()
{
char* nmea=gps_buffer;
int32_t degree;
long minutes;
char degreebuff[10];
char *p = nmea;
// get time
p = strchr(p, ',')+1;
float timef = atof(p);
uint32_t time = timef;
hour = time / 10000;
minute = (time % 10000) / 100;
seconds = (time % 100);
milliseconds = fmod(timef, 1.0) * 1000;
p = strchr(p, ',')+1;
// Serial.println(p);
if (p[0] == 'A')
fix = true;
else if (p[0] == 'V')
fix = false;
else
return false;
// parse out latitude
p = strchr(p, ',')+1;
if (',' != *p)
{
strncpy(degreebuff, p, 2);
p += 2;
degreebuff[2] = '\0';
long degree = atol(degreebuff) * 10000000;
strncpy(degreebuff, p, 2); // minutes
p += 3; // skip decimal point
strncpy(degreebuff + 2, p, 4);
degreebuff[6] = '\0';
long minutes = 50 * atol(degreebuff) / 3;
latitude_fixed = degree + minutes;
latitude = degree / 100000 + minutes * 0.000006F;
latitudeDegrees = (latitude-100*int(latitude/100))/60.0;
latitudeDegrees += int(latitude/100);
}
p = strchr(p, ',')+1;
if (',' != *p)
{
if (p[0] == 'S') latitudeDegrees *= -1.0;
if (p[0] == 'N') lat = 'N';
else if (p[0] == 'S') lat = 'S';
else if (p[0] == ',') lat = 0;
else return false;
}
// parse out longitude
p = strchr(p, ',')+1;
if (',' != *p)
{
strncpy(degreebuff, p, 3);
p += 3;
degreebuff[3] = '\0';
degree = atol(degreebuff) * 10000000;
strncpy(degreebuff, p, 2); // minutes
p += 3; // skip decimal point
strncpy(degreebuff + 2, p, 4);
degreebuff[6] = '\0';
minutes = 50 * atol(degreebuff) / 3;
longitude_fixed = degree + minutes;
longitude = degree / 100000 + minutes * 0.000006F;
longitudeDegrees = (longitude-100*int(longitude/100))/60.0;
longitudeDegrees += int(longitude/100);
}
p = strchr(p, ',')+1;
if (',' != *p)
{
if (p[0] == 'W') longitudeDegrees *= -1.0;
if (p[0] == 'W') lon = 'W';
else if (p[0] == 'E') lon = 'E';
else if (p[0] == ',') lon = 0;
else return false;
}
// speed
p = strchr(p, ',')+1;
if (',' != *p)
{
speed = atof(p);
}
// angle
p = strchr(p, ',')+1;
if (',' != *p)
{
angle = atof(p);
}
p = strchr(p, ',')+1;
if (',' != *p)
{
uint32_t fulldate = atof(p);
day = fulldate / 10000;
month = (fulldate % 10000) / 100;
year = (fulldate % 100);
}
// we dont parse the remaining, yet!
return true;
}
int format_gps_string_and_send_to_iridium()
{
parser();
char retrieveMessage[ 50 ];
PString retMessageStr( retrieveMessage, sizeof(retrieveMessage));
retMessageStr.begin();
retMessageStr.print(HANDHELD_ID);
retMessageStr.print(drifterIdChar);
retMessageStr.print(" ");
retMessageStr.print(getDegree(latitude));
retMessageStr.print(" ");
retMessageStr.print(getMin(latitude),2);
retMessageStr.print(lat);
retMessageStr.print(" ");
retMessageStr.print(getDegree(longitude));
retMessageStr.print(" ");
retMessageStr.print(getMin(longitude),2);
retMessageStr.print(lon);
retMessageStr.print(" ");
retMessageStr.print(hour);
retMessageStr.print(":");
retMessageStr.println(minute);
memory_card.print("Sending String: ");
memory_card.println(retrieveMessage);
return iridium.sendSBDText(retrieveMessage);
//
}
float getMin( float degMin ){
return fmod( (double)degMin, 100.0);
}
int getDegree( float degMin ){
return (int) (degMin / 100);
}
| [
"nathikazad@nathikimac.local"
] | nathikazad@nathikimac.local |
05ab660b9c61ead37758e8d3f11c621f8d101616 | 86c02a0bd69f5263233d9af84399dec8164570e3 | /MAIN_FILE.cpp | e1f327cacf8563db886ee0d785ffa0aeb59d1a49 | [] | no_license | CodeHuman96/udaan-CodeHuman96 | c2285624baf340f0c7542bd8a80806d6b56d1470 | f728d1d2c58ad8883439b078031c03925a9cc0de | refs/heads/master | 2021-04-26T22:56:54.939157 | 2018-03-05T12:12:25 | 2018-03-05T12:12:25 | 123,900,887 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,019 | cpp | #include <bits/stdc++.h>
using namespace std;
char ch3;
class book_d
{
public:
string author_name;
string book_name;
bool avai;
string stud_id;
book_d()
{
stud_id="";
avai=1;
}
};
bool search(char ch1, string str)
{
bool flag = false;
ifstream file;
file.open("DATA.TXT", ios::in | ios::app);
book_d book_obj;
file.read((char*)&book_obj, sizeof(book_obj));
while(!file.eof() || !flag )
{
if(book_obj.avai==false) return false;
if(ch1=='1')
if(book_obj.author_name==str)
flag = true;
else if(ch1=='2')
if(book_obj.book_name==str)
flag =true;
}
return flag;
}
void reserve_book()
{
ifstream file;
file.open("DATA.TXT", ios::in | ios::app);
string stud_id;
cout<<"\nEnter Student ID:";
cin>>stud_id;
char ch1;
cout<<"Search by:\n1.)Book name\n2.)Author Name";
cin>>ch1;
string str;
cout<<"Enter the string:\n";
cin>>str;
bool flag = false;
book_d book_obj;
file.read((char*)&book_obj, sizeof(book_obj));
while(!file.eof())
if(book_obj.avai==false) break;
if(ch1=='1')
if(book_obj.author_name==str)
flag = true;
else if(ch1=='2')
if(book_obj.book_name==str)
flag =true;
if(flag)
{
book_obj.stud_id=stud_id;
book_obj.avai = 0;
cout<<"\nBook Issues to :"<<stud_id;
return ;
}
cout<<"\nBook not available";
return ;
}
//
void return_book()
{
string stud_id;
cout<<"\nEnter Student ID:";
cin>>stud_id;
bool flag= false;
ifstream file;
file.open("DATA.TXT", ios::in | ios::app);
book_d book_obj;
file.read((char*)&book_obj, sizeof(book_obj));
while(!file.eof() || !flag )
{
if(book_obj.avai==false && book_obj.stud_id==stud_id)
{
cout<<"\nBook returned";
book_obj.avai=1;
return ;
}
}
cout<<"\nError: file not found or book never issued";
return ;
}
void record_print()
{
ifstream file;
file.open("DATA.TXT", ios::in | ios::app);
cout<<"\n\n\n#################################################################";
cout<<"\nBook Records";
string line;
while( getline(file,line))
{
cout<<line<<endl;
}
cout<<"\n\n__________________________________________________________________________";
return ;
}
int main()
{
ch3='y';
do{
ifstream file;
file.open("DATA.TXT", ios::in | ios::app);
int ch;
cout<<"Menu:\n1.)Search\n2.)Reserve\n3.)Return book\n4.)Records of all the books\n";
cin>>ch;
if(ch==1)
{
char ch1,ch2;
cout<<"Search by:\n1.)Book name\n2.)Author Name";
cin>>ch1;
string str;
cout<<"Enter the string:\n";
cin>>str;
if(search(ch1, str )==false)
{
cout<<"\nBook not available";
break;
}
cout<<"Book found: enter 1 to reserve:";
cin>>ch2;
if(ch2=='1')
reserve_book();
}
else if(ch==2) reserve_book();
else if(ch==3) return_book();
else if(ch==4) record_print();
else cout<<"Enter valid option!!";
cout<<"\n\nTo continue enter y|Y";
cin>>ch3;
} while(ch3=='Y' || ch3== 'y');
return 0;
}
| [
"noreply@github.com"
] | CodeHuman96.noreply@github.com |
2677653448d125b56828e508c162c5ea4637bb1d | a6c493fc02f380852a334612e7a97604853c07f5 | /39.组合总和.cpp | 4bec011fc333c91fd115614aeb32e7d4a5b2cca0 | [] | no_license | PanAndy/leetcode-c- | e66b1f82bdf360e027feb9d363743ddb5695c1b7 | 5d03bb555e3c28f0348a5205ecae30e4b28cee8a | refs/heads/master | 2021-04-10T21:07:40.667185 | 2020-08-04T09:54:24 | 2020-08-04T09:54:24 | 248,966,072 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 877 | cpp | /*
* @lc app=leetcode.cn id=39 lang=cpp
*
* [39] 组合总和
*/
// @lc code=start
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<vector<int> > ans;
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
ans.clear();
vector<int> path;
backtracking(candidates, path, target, 0, 0);
return ans;
}
void backtracking(vector<int> &candidates, vector<int> &path, int target, int s, int b)
{
if(s==target){
ans.push_back(path);
return;
}else if(s>target){
return;
}
for(int i=b;i<candidates.size();i++)
{
path.push_back(candidates[i]);
backtracking(candidates, path, target, s+candidates[i], i);
path.pop_back();
}
}
};
// @lc code=end
| [
"1163962054@qq.com"
] | 1163962054@qq.com |
69a03619ef5b16722e3674dc74269eed8ade328e | d496d05d421ddec8d6cc08728aa112e0aa8cfa9b | /作业2/进制转换.cpp | a6dfc21a9565479542ef945b1f071b4a66049928 | [] | no_license | small-Qing/data-structure | 6500d5530e351cb5483bb1e22c4af852404dae39 | 7cac4746394d440a9f396fdaec25c4c68b3d8f66 | refs/heads/master | 2021-08-19T22:24:45.444714 | 2017-11-27T15:40:42 | 2017-11-27T15:40:42 | 109,482,936 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,509 | cpp | #include<fstream>
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
//#include"stdafx.h"
using namespace std;
#define OVERFLOW -2
#define TRUE 1
#define FALSE 0
#define INFEASIBLE -1
#define ERROR 0
#define mod 2
/*************定义栈**************/
typedef struct stack{
int *base,*top;
int size;
}qstack;
/*在64位机器上,int是4个字节,指针是8个字节,将指针的值赋给int型就汇报错了,64位机器上long是8字节的,因此需要改为long型**/
/**************创建空栈**************/
void initstack(qstack &l){
l.base=(int*)malloc(sizeof(int));//只能返回void(指针型)
if(!l.base)exit(OVERFLOW);
l.top=l.base;
l.size=100;
}
/*********压入栈**********/
void push(qstack &l,int e){
if(l.top-l.base>=l.size){//栈满
l.base=(int*)realloc(l.base,(l.size+100)*sizeof(int));
if(!l.base)exit(OVERFLOW);
l.top=l.base+l.size;
l.size+=100;
}
*l.top=e;//指针所在的空间被赋值为e
l.top++;
}
/*******栈为空判断********/
bool stackempty(qstack &l){
if(l.base==l.top)return true;
return false;
}
/******去除并取出栈顶******/
int pop(qstack &s){
if(s.base==s.top)return ERROR;
s.top--;
int ans=*s.top;
//free(*s.top);
return ans;
}
/*****转换********/
void conversion(){
int n;
qstack s;
initstack(s);
scanf("%d",&n);
while(n){
push(s,n%mod);
//printf("%d\n",*s.base);
n=n/mod;
}
while(!stackempty(s)){
printf("%d",pop(s));
}
}
/******主函数****/
int main(){
conversion();
return 0;
}
| [
"www798312803@gmail.com"
] | www798312803@gmail.com |
4a900253d54734a946e9035a8e37147429faa8e2 | f21cc5d79650eda497a2c22213afce7951d64bca | /Codigo_Arduino/MCP/3_Funciones_MCP_LED.ino | 8300cb69ca6c231653a6207cb7fd53f49a0130ba | [] | no_license | sebascarm/Arduino_C | c396d8a1296c467047613e4af4f6e5a71f69cf8c | 741bd0685b4837eb996e2ff4e89fe7611ebea47b | refs/heads/master | 2022-11-06T16:08:35.805294 | 2020-06-25T06:52:33 | 2020-06-25T06:52:33 | 267,954,555 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 861 | ino | void Func_MCP_LED() {
ledFD1.CargarComando();
ledAT.CargarComando();
ledN1.CargarComando();
ledSPEED.CargarComando();
ledVNAV.CargarComando();
ledLVLCHG.CargarComando();
ledHDGSEL.CargarComando();
ledLNAV.CargarComando();
ledVORLOC.CargarComando();
ledAPP.CargarComando();
ledALTHLD.CargarComando();
ledVS.CargarComando();
ledCMDA.CargarComando();
ledCWSA.CargarComando();
ledCMDB.CargarComando();
ledCWSB.CargarComando();
ledFD2.CargarComando();
}
void Func_MCP_DISPLAY() {
DispCOURSE1.CargarComando();
DispHEADING.CargarComando();
DispIASMACH.CargarComando();
DispALTITUDE.CargarComando();
DispVS.CargarComando();
DispCOURSE2.CargarComando();
}
void Func_MCP_FLASH(){
DispIASMACH.CargarBlinker();
}
void Func_MCP_OFF(){
DispIASMACH.CargarApagado();
DispVS.CargarApagado();
}
////
void Func_MCP_Loop(){
DispIASMACH.Blinkeador();
}
| [
"sebascarm@gmail.com"
] | sebascarm@gmail.com |
94817e1a3dd78103fc0b02b4a6f33740247a465d | 56cf62ab61a0c7d7eecf0e95476ddfdeeea9cfba | /Picking_Example/PickingExample.cpp | 96a220d481913e2084dc235e8d0c0078ea6dd161 | [] | no_license | zrlu/cs488-opengl-project | f3aed44a7d7fb3953c8578ef1a1a5a9f295df64f | b5ed12912188db09f036380880ee6e2a082cb00f | refs/heads/master | 2021-06-27T13:57:54.364766 | 2020-09-23T03:28:11 | 2020-09-23T03:28:11 | 152,065,771 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,862 | cpp | #include "PickingExample.hpp"
using namespace std;
#include "cs488-framework/GlErrorCheck.hpp"
#include "cs488-framework/MathUtils.hpp"
#include <imgui/imgui.h>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/io.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <random>
#include <iostream>
using namespace glm;
static bool show_gui = true;
//----------------------------------------------------------------------------------------
// Constructor
PickingExample::PickingExample()
: m_positionAttribLocation(0),
m_normalAttribLocation(0),
m_vao_meshData(0),
m_vbo_vertexPositions(0),
m_vbo_vertexNormals(0)
{
}
//----------------------------------------------------------------------------------------
// Destructor
PickingExample::~PickingExample()
{
}
//----------------------------------------------------------------------------------------
/*
* Called once, at program start.
*/
void PickingExample::init()
{
// Set the background colour.
glClearColor(0.35, 0.35, 0.35, 1.0);
createShaderProgram();
glGenVertexArrays(1, &m_vao_meshData);
enableVertexShaderInputSlots();
// Load and decode all .obj files at once here. You may add additional .obj files to
// this list in order to support rendering additional mesh types. All vertex
// positions, and normals will be extracted and stored within the MeshConsolidator
// class.
unique_ptr<MeshConsolidator> meshConsolidator (new MeshConsolidator{
getAssetFilePath("cube.obj")
});
// Acquire the BatchInfoMap from the MeshConsolidator.
meshConsolidator->getBatchInfoMap(m_batchInfoMap);
// Take all vertex data within the MeshConsolidator and upload it to VBOs on the GPU.
uploadVertexDataToVbos(*meshConsolidator);
mapVboDataToVertexShaderInputLocations();
initPerspectiveMatrix();
initViewMatrix();
initLightSources();
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0.0,1.0);
for( size_t idx = 0; idx < 100; ++idx ) {
glm::mat4 T = glm::translate( glm::mat4(), glm::vec3(
(distribution(generator) - 0.5) * 5.0,
(distribution(generator) - 0.5) * 5.0,
distribution(generator) * -5.0 - 5.0 ) );
glm::vec3 col( distribution(generator), distribution(generator), distribution(generator) );
xforms.push_back( T );
cols.push_back( col );
selected.push_back( false );
}
do_picking = false;
// Exiting the current scope calls delete automatically on meshConsolidator freeing
// all vertex data resources. This is fine since we already copied this data to
// VBOs on the GPU. We have no use for storing vertex data on the CPU side beyond
// this point.
}
//----------------------------------------------------------------------------------------
void PickingExample::createShaderProgram()
{
m_shader.generateProgramObject();
m_shader.attachVertexShader( getAssetFilePath("VertexShader.vs").c_str() );
m_shader.attachFragmentShader( getAssetFilePath("FragmentShader.fs").c_str() );
m_shader.link();
}
//----------------------------------------------------------------------------------------
void PickingExample::enableVertexShaderInputSlots()
{
//-- Enable input slots for m_vao_meshData:
{
glBindVertexArray(m_vao_meshData);
// Enable the vertex shader attribute location for "position" when rendering.
m_positionAttribLocation = m_shader.getAttribLocation("position");
glEnableVertexAttribArray(m_positionAttribLocation);
// Enable the vertex shader attribute location for "normal" when rendering.
m_normalAttribLocation = m_shader.getAttribLocation("normal");
glEnableVertexAttribArray(m_normalAttribLocation);
CHECK_GL_ERRORS;
}
// Restore defaults
glBindVertexArray(0);
}
//----------------------------------------------------------------------------------------
void PickingExample::uploadVertexDataToVbos (
const MeshConsolidator & meshConsolidator
) {
// Generate VBO to store all vertex position data
{
glGenBuffers(1, &m_vbo_vertexPositions);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo_vertexPositions);
glBufferData(GL_ARRAY_BUFFER, meshConsolidator.getNumVertexPositionBytes(),
meshConsolidator.getVertexPositionDataPtr(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
CHECK_GL_ERRORS;
}
// Generate VBO to store all vertex normal data
{
glGenBuffers(1, &m_vbo_vertexNormals);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo_vertexNormals);
glBufferData(GL_ARRAY_BUFFER, meshConsolidator.getNumVertexNormalBytes(),
meshConsolidator.getVertexNormalDataPtr(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
CHECK_GL_ERRORS;
}
}
//----------------------------------------------------------------------------------------
void PickingExample::mapVboDataToVertexShaderInputLocations()
{
// Bind VAO in order to record the data mapping.
glBindVertexArray(m_vao_meshData);
// Tell GL how to map data from the vertex buffer "m_vbo_vertexPositions" into the
// "position" vertex attribute location for any bound vertex shader program.
glBindBuffer(GL_ARRAY_BUFFER, m_vbo_vertexPositions);
glVertexAttribPointer(m_positionAttribLocation, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
// Tell GL how to map data from the vertex buffer "m_vbo_vertexNormals" into the
// "normal" vertex attribute location for any bound vertex shader program.
glBindBuffer(GL_ARRAY_BUFFER, m_vbo_vertexNormals);
glVertexAttribPointer(m_normalAttribLocation, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
//-- Unbind target, and restore default values:
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
CHECK_GL_ERRORS;
}
//----------------------------------------------------------------------------------------
void PickingExample::initPerspectiveMatrix()
{
float aspect = ((float)m_windowWidth) / m_windowHeight;
m_perpsective = glm::perspective(degreesToRadians(60.0f), aspect, 0.1f, 100.0f);
}
//----------------------------------------------------------------------------------------
void PickingExample::initViewMatrix() {
m_view = glm::lookAt(vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 0.0f, -1.0f),
vec3(0.0f, 1.0f, 0.0f));
}
//----------------------------------------------------------------------------------------
void PickingExample::initLightSources() {
// World-space position
m_light.position = vec3(-2.0f, 5.0f, 0.5f);
m_light.rgbIntensity = vec3(0.8f); // White light
}
//----------------------------------------------------------------------------------------
void PickingExample::uploadCommonSceneUniforms()
{
m_shader.enable();
{
//-- Set Perpsective matrix uniform for the scene:
GLint location = m_shader.getUniformLocation("Perspective");
glUniformMatrix4fv(location, 1, GL_FALSE, value_ptr(m_perpsective));
CHECK_GL_ERRORS;
location = m_shader.getUniformLocation("picking");
glUniform1i( location, do_picking ? 1 : 0 );
//-- Set LightSource uniform for the scene:
if( !do_picking ) {
location = m_shader.getUniformLocation("light.position");
glUniform3fv(location, 1, value_ptr(m_light.position));
location = m_shader.getUniformLocation("light.rgbIntensity");
glUniform3fv(location, 1, value_ptr(m_light.rgbIntensity));
CHECK_GL_ERRORS;
location = m_shader.getUniformLocation("ambientIntensity");
vec3 ambientIntensity(0.05f);
glUniform3fv(location, 1, value_ptr(ambientIntensity));
CHECK_GL_ERRORS;
}
}
m_shader.disable();
}
//----------------------------------------------------------------------------------------
/*
* Called once per frame, before guiLogic().
*/
void PickingExample::appLogic()
{
// Place per frame, application logic here ...
uploadCommonSceneUniforms();
}
//----------------------------------------------------------------------------------------
/*
* Called once per frame, after appLogic(), but before the draw() method.
*/
void PickingExample::guiLogic()
{
if( !show_gui ) {
return;
}
static bool firstRun(true);
if (firstRun) {
ImGui::SetNextWindowPos(ImVec2(50, 50));
firstRun = false;
}
static bool showDebugWindow(true);
ImGuiWindowFlags windowFlags(ImGuiWindowFlags_AlwaysAutoResize);
float opacity(0.5f);
ImGui::Begin("Properties", &showDebugWindow, ImVec2(100,100), opacity,
windowFlags);
// Add more gui elements here here ...
// Create Button, and check if it was clicked:
if( ImGui::Button( "Quit Application" ) ) {
glfwSetWindowShouldClose(m_window, GL_TRUE);
}
ImGui::Text( "Framerate: %.1f FPS", ImGui::GetIO().Framerate );
ImGui::End();
}
//----------------------------------------------------------------------------------------
// Update mesh specific shader uniforms:
void PickingExample::updateShaderUniforms(
const glm::mat4& MV, unsigned int idx, const glm::vec3& col )
{
m_shader.enable();
//-- Set ModelView matrix:
GLint location = m_shader.getUniformLocation("ModelView");
mat4 modelView = MV;
glUniformMatrix4fv(location, 1, GL_FALSE, value_ptr(modelView));
CHECK_GL_ERRORS;
if( do_picking ) {
float r = float(idx&0xff) / 255.0f;
float g = float((idx>>8)&0xff) / 255.0f;
float b = float((idx>>16)&0xff) / 255.0f;
location = m_shader.getUniformLocation("material.kd");
glUniform3f( location, r, g, b );
CHECK_GL_ERRORS;
} else {
//-- Set NormMatrix:
location = m_shader.getUniformLocation("NormalMatrix");
mat3 normalMatrix = glm::transpose(glm::inverse(mat3(modelView)));
glUniformMatrix3fv(location, 1, GL_FALSE, value_ptr(normalMatrix));
CHECK_GL_ERRORS;
//-- Set Material values:
location = m_shader.getUniformLocation("material.kd");
glUniform3fv(location, 1, value_ptr(col));
CHECK_GL_ERRORS;
}
m_shader.disable();
}
//----------------------------------------------------------------------------------------
/*
* Called once per frame, after guiLogic().
*/
void PickingExample::draw() {
glEnable( GL_DEPTH_TEST );
glBindVertexArray( m_vao_meshData );
for( size_t idx = 0; idx < xforms.size(); ++idx ) {
const glm::mat4& T = xforms[idx];
glm::vec3 col = cols[idx];
if( selected[idx] ) {
col = glm::vec3( 1.0, 1.0, 0.0 );
}
updateShaderUniforms( m_view * T, (unsigned int)idx, col );
BatchInfo batchInfo = m_batchInfoMap[ "cube" ];
m_shader.enable();
glDrawArrays( GL_TRIANGLES, batchInfo.startIndex, batchInfo.numIndices );
m_shader.disable();
}
glBindVertexArray( 0 );
glDisable( GL_DEPTH_TEST );
}
//----------------------------------------------------------------------------------------
/*
* Called once, after program is signaled to terminate.
*/
void PickingExample::cleanup()
{
}
//----------------------------------------------------------------------------------------
/*
* Event handler. Handles cursor entering the window area events.
*/
bool PickingExample::cursorEnterWindowEvent (
int entered
) {
bool eventHandled(false);
// Fill in with event handling code...
return eventHandled;
}
//----------------------------------------------------------------------------------------
/*
* Event handler. Handles mouse cursor movement events.
*/
bool PickingExample::mouseMoveEvent (
double xPos,
double yPos
) {
bool eventHandled(false);
// Fill in with event handling code...
return eventHandled;
}
//----------------------------------------------------------------------------------------
/*
* Event handler. Handles mouse button events.
*/
bool PickingExample::mouseButtonInputEvent (
int button,
int actions,
int mods
) {
bool eventHandled(false);
if (button == GLFW_MOUSE_BUTTON_LEFT && actions == GLFW_PRESS) {
double xpos, ypos;
glfwGetCursorPos( m_window, &xpos, &ypos );
do_picking = true;
uploadCommonSceneUniforms();
glClearColor(1.0, 1.0, 1.0, 1.0 );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glClearColor(0.35, 0.35, 0.35, 1.0);
draw();
// I don't know if these are really necessary anymore.
// glFlush();
// glFinish();
CHECK_GL_ERRORS;
// Ugly -- FB coordinates might be different than Window coordinates
// (e.g., on a retina display). Must compensate.
xpos *= double(m_framebufferWidth) / double(m_windowWidth);
// WTF, don't know why I have to measure y relative to the bottom of
// the window in this case.
ypos = m_windowHeight - ypos;
ypos *= double(m_framebufferHeight) / double(m_windowHeight);
GLubyte buffer[ 4 ] = { 0, 0, 0, 0 };
// A bit ugly -- don't want to swap the just-drawn false colours
// to the screen, so read from the back buffer.
glReadBuffer( GL_BACK );
// Actually read the pixel at the mouse location.
glReadPixels( int(xpos), int(ypos), 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, buffer );
CHECK_GL_ERRORS;
// Reassemble the object ID.
unsigned int what = buffer[0] + (buffer[1] << 8) + (buffer[2] << 16);
if( what < xforms.size() ) {
selected[what] = !selected[what];
}
do_picking = false;
CHECK_GL_ERRORS;
}
return eventHandled;
}
//----------------------------------------------------------------------------------------
/*
* Event handler. Handles mouse scroll wheel events.
*/
bool PickingExample::mouseScrollEvent (
double xOffSet,
double yOffSet
) {
bool eventHandled(false);
// Fill in with event handling code...
return eventHandled;
}
//----------------------------------------------------------------------------------------
/*
* Event handler. Handles window resize events.
*/
bool PickingExample::windowResizeEvent (
int width,
int height
) {
bool eventHandled(false);
initPerspectiveMatrix();
return eventHandled;
}
//----------------------------------------------------------------------------------------
/*
* Event handler. Handles key input events.
*/
bool PickingExample::keyInputEvent (
int key,
int action,
int mods
) {
bool eventHandled(false);
if( action == GLFW_PRESS ) {
if( key == GLFW_KEY_M ) {
show_gui = !show_gui;
eventHandled = true;
}
}
// Fill in with event handling code...
return eventHandled;
}
| [
"zeranlu@hotmail.com"
] | zeranlu@hotmail.com |
29f28eed0ccfdb3cfef8a77e07b59df834613642 | 75d3a914d5f78977576dff7cf8ff6b7cd2aad8e3 | /11week/11week/11weekView.cpp | 84356b822bfeca75ac38b14120b9a8eae8b70cf9 | [] | no_license | long-jl618/Test | d0df358094431992aed223f01ffd3bb81a9377e0 | 7b2714c04adea048f52a1ddc406e51839e55bda6 | refs/heads/master | 2021-07-17T09:42:50.708574 | 2020-06-08T06:31:01 | 2020-06-08T06:31:01 | 247,626,761 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,810 | cpp |
// 11weekView.cpp : CMy11weekView 类的实现
//
#include "stdafx.h"
// SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的
// ATL 项目中进行定义,并允许与该项目共享文档代码。
#ifndef SHARED_HANDLERS
#include "11week.h"
#endif
#include "11weekSet.h"
#include "11weekDoc.h"
#include "11weekView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMy11weekView
IMPLEMENT_DYNCREATE(CMy11weekView, CRecordView)
BEGIN_MESSAGE_MAP(CMy11weekView, CRecordView)
// 标准打印命令
ON_COMMAND(ID_FILE_PRINT, &CRecordView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, &CRecordView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CRecordView::OnFilePrintPreview)
END_MESSAGE_MAP()
// CMy11weekView 构造/析构
CMy11weekView::CMy11weekView()
: CRecordView(IDD_MY11WEEK_FORM)
, ID(0)
, name(_T(""))
, sno(_T(""))
, age(_T(""))
, phone(_T(""))
{
m_pSet = NULL;
// TODO: 在此处添加构造代码
}
CMy11weekView::~CMy11weekView()
{
}
void CMy11weekView::DoDataExchange(CDataExchange* pDX)
{
CRecordView::DoDataExchange(pDX);
// 可以在此处插入 DDX_Field* 函数以将控件“连接”到数据库字段,例如
// DDX_FieldText(pDX, IDC_MYEDITBOX, m_pSet->m_szColumn1, m_pSet);
// DDX_FieldCheck(pDX, IDC_MYCHECKBOX, m_pSet->m_bColumn2, m_pSet);
// 有关详细信息,请参阅 MSDN 和 ODBC 示例
DDX_Text(pDX, IDC_EDIT1, m_pSet->m_ID);
DDX_Text(pDX, IDC_EDIT2, m_pSet->m_1);
DDX_Text(pDX, IDC_EDIT4, m_pSet->m_2);
DDX_Text(pDX, IDC_EDIT3, m_pSet->m_3);
DDX_Text(pDX, IDC_EDIT5, m_pSet->m_4);
}
BOOL CMy11weekView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return CRecordView::PreCreateWindow(cs);
}
void CMy11weekView::OnInitialUpdate()
{
m_pSet = &GetDocument()->m_My11weekSet;
CRecordView::OnInitialUpdate();
}
// CMy11weekView 打印
BOOL CMy11weekView::OnPreparePrinting(CPrintInfo* pInfo)
{
// 默认准备
return DoPreparePrinting(pInfo);
}
void CMy11weekView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 添加额外的打印前进行的初始化过程
}
void CMy11weekView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 添加打印后进行的清理过程
}
// CMy11weekView 诊断
#ifdef _DEBUG
void CMy11weekView::AssertValid() const
{
CRecordView::AssertValid();
}
void CMy11weekView::Dump(CDumpContext& dc) const
{
CRecordView::Dump(dc);
}
CMy11weekDoc* CMy11weekView::GetDocument() const // 非调试版本是内联的
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMy11weekDoc)));
return (CMy11weekDoc*)m_pDocument;
}
#endif //_DEBUG
// CMy11weekView 数据库支持
CRecordset* CMy11weekView::OnGetRecordset()
{
return m_pSet;
}
// CMy11weekView 消息处理程序
| [
"1725058773@qq.com"
] | 1725058773@qq.com |
f3eeff1baaab5659653077b83060ad6d280f2032 | ee143635ff958ea6bfeb18d6d2c6af7c016aa741 | /src/BreakoutSDK/modem/OwlModemPDN.cpp | f687aa892b184f8a15d717cf6281888bca456763 | [
"Apache-2.0"
] | permissive | dsghi/Breakout_Arduino_Library | 4b50173172de22a7a7b56e39dc8474a2b98716b6 | 4438eb7f3e6f2807cb32a47e1491dd54e9ca17de | refs/heads/master | 2020-04-02T09:53:31.264487 | 2018-10-18T19:00:05 | 2018-10-18T19:00:05 | 154,314,843 | 0 | 0 | Apache-2.0 | 2018-10-23T11:17:15 | 2018-10-23T11:17:14 | null | UTF-8 | C++ | false | false | 2,563 | cpp | /*
* OwlModemPDN.cpp
* Twilio Breakout SDK
*
* Copyright (c) 2018 Twilio, Inc.
*
* 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 OwlModemPDN.cpp - API for managing the Packet Data Network (aka APN configuration)
*/
#include "OwlModemPDN.h"
#include <stdio.h>
#include "OwlModem.h"
OwlModemPDN::OwlModemPDN(OwlModem *owlModem) : owlModem(owlModem) {
}
static str s_cgpaddr = STRDECL("+CGPADDR: ");
int OwlModemPDN::getAPNIPAddress(uint8_t cid, uint8_t ipv4[4], uint8_t ipv6[16]) {
int cnt = 0;
str token = {0};
str token_ip = {0};
str token_number = {0};
if (ipv4) bzero(ipv4, 4);
if (ipv6) bzero(ipv6, 16);
char buf[64];
snprintf(buf, 64, "AT+CGPADDR=%d", cid);
int result = owlModem->doCommand(buf, 3000, &pdn_response, MODEM_PDN_RESPONSE_BUFFER_SIZE) == AT_Result_Code__OK;
if (!result) return 0;
owlModem->filterResponse(s_cgpaddr, &pdn_response);
while (str_tok(pdn_response, ",\r\n", &token)) {
switch (cnt) {
case 0:
// cid, ignore
break;
case 1:
while (str_tok(token, " \"", &token_ip)) {
if (token_ip.len <= 15) {
/* IPv4 */
int digit = 0;
while (str_tok(token_ip, ".", &token_number))
ipv4[digit++] = str_to_uint32_t(token_number, 10);
if (digit != 4) {
LOG(L_ERR, "IPv4 [%.*s] has invalid number of tokens\r\n", token_ip.len, token_ip.s, digit);
return 0;
}
} else {
/* IPv6 */
int digit = 0;
while (str_tok(token_ip, ".", &token_number))
ipv6[digit++] = str_to_uint32_t(token_number, 10);
if (digit != 16) {
LOG(L_ERR, "IPv6 [%.*s] has invalid number of tokens\r\n", token_ip.len, token_ip.s, digit);
return 0;
}
}
}
break;
default:
LOG(L_ERR, "Not handled %d(-th) token [%.*s]\r\n", cnt, token.len, token.s);
return 0;
}
cnt++;
}
return 1;
}
| [
"rbeiter@twilio.com"
] | rbeiter@twilio.com |
1ba8decb8a4dc19ee7bac9dc3fbef252183acd89 | 3aa9a68026ab10ced85dec559b6b4dfcb74ae251 | /love babbar series/Strings/split_0_1.cpp | 4786227c6ec644fbebc4d3a9a5a649bc0729a2ce | [] | no_license | kushuu/competitive_programming_all | 10eee29c3ca0656a2ffa37b142df680c3a022f1b | 5edaec66d2179a012832698035bdfb0957dbd806 | refs/heads/master | 2023-08-17T15:09:48.492816 | 2021-10-04T20:09:37 | 2021-10-04T20:09:37 | 334,891,360 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,060 | cpp | /****************************************************************
Author: kushuu File: split_0_1.cpp Date: Sat Nov 07 2020
****************************************************************/
#include <bits/stdc++.h>
//shorts
#define ll long long int
#define sll stack<long long int>
#define vll vector<long long int>
#define ld long double
#define pb push_back
#define mp make_pair
#define vpll vector<pair<long long int, long long int>>
#define fastIO ios_base::sync_with_stdio(false); cin.tie(NULL);
#define fo(i,x,y) for(long long i = x; i < y; i++)
#define MOD 1000000007
#define endl "\n"
#define F first
#define S second
#define s(a) a.size()
//program specific shorts (if any)
//
using namespace std;
ll getlcm(ll a, ll b) {
return (a*b)/__gcd(a, b);
}
int main() {
fastIO;
ll t; cin >> t;
while(t--) {
string s; cin >> s;
ll check = 0, ans = 0;
for(auto i : s) {
if(i == '0') check++;
else check--;
if(!check) ans++;
}
cout << ans;
}
return 0;
} | [
"sonikushu007@gmail.com"
] | sonikushu007@gmail.com |
b1cb4e68b7b600255090e5d5db7b156a9b8fa76b | 67dc3fbe8ed0e1a0d53786b61691c624eddbbaf0 | /chrome/browser/page_load_metrics/observers/resource_prefetch_predictor_page_load_metrics_observer.cc | 34762b326a29f98b4a62d0e4f2f10681a9c60b01 | [
"BSD-3-Clause"
] | permissive | lehoon/chromium | 55f7f126fdc4d92f5fdfad61fb55c284e5cae8a8 | 2f746c5c4260329c7ef5a850ce1b72d78da106a6 | refs/heads/master | 2023-01-16T06:49:50.291538 | 2017-03-21T20:07:51 | 2017-03-21T20:07:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,161 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/page_load_metrics/observers/resource_prefetch_predictor_page_load_metrics_observer.h"
#include "base/memory/ptr_util.h"
#include "chrome/browser/page_load_metrics/page_load_metrics_util.h"
#include "chrome/browser/predictors/resource_prefetch_predictor.h"
#include "chrome/browser/predictors/resource_prefetch_predictor_factory.h"
#include "content/public/browser/web_contents.h"
namespace internal {
const char kHistogramResourcePrefetchPredictorFirstContentfulPaint[] =
"PageLoad.Clients.ResourcePrefetchPredictor.PaintTiming."
"NavigationToFirstContentfulPaint.Prefetchable";
const char kHistogramResourcePrefetchPredictorFirstMeaningfulPaint[] =
"PageLoad.Clients.ResourcePrefetchPredictor.PaintTiming."
"NavigationToFirstMeaningfulPaint.Prefetchable";
} // namespace internal
// static
std::unique_ptr<ResourcePrefetchPredictorPageLoadMetricsObserver>
ResourcePrefetchPredictorPageLoadMetricsObserver::CreateIfNeeded(
content::WebContents* web_contents) {
predictors::ResourcePrefetchPredictor* predictor =
predictors::ResourcePrefetchPredictorFactory::GetForProfile(
web_contents->GetBrowserContext());
if (!predictor)
return nullptr;
return base::MakeUnique<ResourcePrefetchPredictorPageLoadMetricsObserver>(
predictor);
}
ResourcePrefetchPredictorPageLoadMetricsObserver::
ResourcePrefetchPredictorPageLoadMetricsObserver(
predictors::ResourcePrefetchPredictor* predictor)
: predictor_(predictor) {
DCHECK(predictor_);
}
ResourcePrefetchPredictorPageLoadMetricsObserver::
~ResourcePrefetchPredictorPageLoadMetricsObserver() {}
page_load_metrics::PageLoadMetricsObserver::ObservePolicy
ResourcePrefetchPredictorPageLoadMetricsObserver::OnStart(
content::NavigationHandle* navigation_handle,
const GURL& currently_commited_url,
bool started_in_foreground) {
return (started_in_foreground &&
predictor_->IsUrlPrefetchable(navigation_handle->GetURL()))
? CONTINUE_OBSERVING
: STOP_OBSERVING;
}
page_load_metrics::PageLoadMetricsObserver::ObservePolicy
ResourcePrefetchPredictorPageLoadMetricsObserver::OnHidden(
const page_load_metrics::PageLoadTiming& timing,
const page_load_metrics::PageLoadExtraInfo& extra_info) {
return STOP_OBSERVING;
}
void ResourcePrefetchPredictorPageLoadMetricsObserver::OnFirstContentfulPaint(
const page_load_metrics::PageLoadTiming& timing,
const page_load_metrics::PageLoadExtraInfo& extra_info) {
PAGE_LOAD_HISTOGRAM(
internal::kHistogramResourcePrefetchPredictorFirstContentfulPaint,
timing.first_contentful_paint.value());
}
void ResourcePrefetchPredictorPageLoadMetricsObserver::OnFirstMeaningfulPaint(
const page_load_metrics::PageLoadTiming& timing,
const page_load_metrics::PageLoadExtraInfo& extra_info) {
PAGE_LOAD_HISTOGRAM(
internal::kHistogramResourcePrefetchPredictorFirstMeaningfulPaint,
timing.first_meaningful_paint.value());
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
f6d176621a86ec90beff35df3441bed7da6ade70 | 9f253e6dd5809c780f2dc5b36bf91171bb2fd72e | /helper functions/infix_postfix.cpp | 631f8f987044b549c6a5eadc26038af5f69aed43 | [] | no_license | mbikas/ACM | ab41bb3ea7c5402758bdc56c3109807c64537b3a | d4185d5168a1391d7989f9a947dfa65198b27df9 | refs/heads/master | 2021-01-18T19:33:58.990020 | 2016-10-27T08:00:03 | 2016-10-27T08:00:03 | 72,075,809 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,275 | cpp | #include<stdio.h>
#include<string.h>
#define sz 10000
char op[6]="+-*/^";
//1=+,- : 2=*,/ 3=^
int prior[5]={1,0,2,1,3};
int top=0,count=0,len,i;
char in[sz],stack[sz],post[sz],c;
int isOp(char c){
int j;
for(j=0;j<6;j++)
if(c==op[j])
return 1;
return 0;
}
void push(char ch)
{
stack[top++]=ch;
}
char pop()
{
top--;
return stack[top];
}
void postorder(void)
{
top=0;
//strcpy(post,"");
count=0;
len=strlen(in);
in[len]=')';
stack[top++]='(';
for(i=0;i<len+1;i++){
if(in[i]=='(')push(in[i]);
else if(in[i]==')'){
while(1){
c=pop();if(c=='(')break;
post[count++]=c;
}
}
else if(isOp(in[i])){
while(1){
c=pop();
if(( prior[c%5]>
prior[in[i]%5]-1) && isOp(c)) post[count++]=c;
else{
top++;push(in[i]);break;
}
}
}
else post[count++]=in[i];
}
post [count]=0;
}
int main()
{
//freopen("infix.in","r",stdin);
//freopen("postfix.out","w",stdout);
int test;
char expression[sz],a[sz];
scanf("%d",&test);
while(test--)
{
strcpy(in,"");
scanf(" %[^\n]",in);
top=0;
postorder();
printf("%s\n",post);
}
return 0;
}
| [
"mbikas2@uic.edu"
] | mbikas2@uic.edu |
2f1f3a3870045e6c5564a5f528d5c7ac416709a9 | 5ab7032615235c10c68d738fa57aabd5bc46ea59 | /monk_in_the_grass_fields.cpp | 478fecfc5a5e71dae8dbf9db06d3815efb230b24 | [] | no_license | g-akash/spoj_codes | 12866cd8da795febb672b74a565e41932abf6871 | a2bf08ecd8a20f896537b6fbf96a2542b8ecf5c0 | refs/heads/master | 2021-09-07T21:07:17.267517 | 2018-03-01T05:41:12 | 2018-03-01T05:41:12 | 66,132,917 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,226 | cpp | #include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
#include <math.h>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
using namespace std;
#define ll long long int
#define ull unsigned ll
#define umm(x,y) unordered_map<x,y >
#define mm(x,y) map<x,y >
#define pb push_back
#define foi(n) for(int i=0;i<n;i++)
#define foj(n) for(int j=0;j<n;j++)
#define foi1(n) for(int i=1;i<=n;i++)
#define foj1(n) for(int j=1;j<=n;j++)
#define vi vector<int>
#define vb vector<bool>
#define vvi vector<vi >
#define vvb vector<vb >
#define vll vector<ll>
#define vvll vector<vll >
#define si size()
int main()
{
int t;
cin>>t;
while(t--)
{
ll n,k;
cin>>n>>k;
vvll vec(n);
foi(n)vec[i].resize(n);
vll rows(n),cols(n);
foi(n)
{
foj(n)
{
cin>>vec[i][j];
rows[i]+=vec[i][j];
cols[j]+=vec[i][j];
}
}
ll ans=0;
foj(k)
{
ll rmin=0,cmin=0;
foi(n)if(rows[i]<rows[rmin])rmin=i;
foi(n)if(cols[i]<cols[cmin])cmin=i;
if(rows[rmin]<cols[cmin])
{
ans+=rows[rmin];
rows[rmin]+=n;
foi(n)cols[i]+=1;
}
else
{
ans+=cols[cmin];
cols[cmin]+=n;
foi(n)rows[i]+=1;
}
}
cout<<ans<<endl;
}
} | [
"akash.garg2007@gmail.com"
] | akash.garg2007@gmail.com |
6131fa298987fb41c11748aed3d1b43fc62da2e1 | f67b83eaea2999c89bab8819ec252ec4f2e21884 | /src/Producers/BoostRestFrameProducer.cc | 0b2477a3ee547773ae9a616831b063a44746b35d | [] | no_license | KIT-CMS/KITHiggsToTauTau | c2ef71b5e25ec9c2734c754939c03486a44548c1 | 140415158182562432715c38f783ba3dd5a5a3ce | refs/heads/reduced_trigger_objects | 2021-12-22T17:20:00.221747 | 2021-12-17T14:14:06 | 2021-12-17T14:14:06 | 99,792,165 | 1 | 7 | null | 2021-05-25T06:25:07 | 2017-08-09T09:45:59 | Python | UTF-8 | C++ | false | false | 5,462 | cc |
#include "Artus/Consumer/interface/LambdaNtupleConsumer.h"
#include "Artus/Utility/interface/DefaultValues.h"
#include "Artus/Utility/interface/SafeMap.h"
#include "HiggsAnalysis/KITHiggsToTauTau/interface/Producers/BoostRestFrameProducer.h"
std::string BoostRestFrameProducer::GetProducerId() const
{
return "BoostRestFrameProducer";
}
void BoostRestFrameProducer::Init(setting_type const& settings)
{
ProducerBase<HttTypes>::Init(settings);
for (size_t leptonIndex = 0; leptonIndex < 2; ++leptonIndex)
{
std::string leptonIndexString = std::to_string(leptonIndex+1);
LambdaNtupleConsumer<HttTypes>::AddRMFLVQuantity("lep"+leptonIndexString+"LVBoostToDiLeptonSystem", [leptonIndex](event_type const& event, product_type const& product)
{
return SafeMap::GetWithDefault(product.m_leptonsBoostToDiLeptonSystem, product.m_flavourOrderedLeptons.at(leptonIndex), DefaultValues::UndefinedRMFLV);
});
LambdaNtupleConsumer<HttTypes>::AddRMFLVQuantity("lep"+leptonIndexString+"LVBoostToDiTauSystem", [leptonIndex](event_type const& event, product_type const& product)
{
return SafeMap::GetWithDefault(product.m_leptonsBoostToDiTauSystem, product.m_flavourOrderedLeptons.at(leptonIndex), DefaultValues::UndefinedRMFLV);
});
LambdaNtupleConsumer<HttTypes>::AddRMFLVQuantity("tau"+leptonIndexString+"LVBoostToDiTauSystem", [leptonIndex](event_type const& event, product_type const& product)
{
KLepton* lepton = product.m_flavourOrderedLeptons.at(leptonIndex);
RMFLV* tau = (Utility::Contains(product.m_hhKinFitTaus, lepton) ? const_cast<RMFLV*>(&SafeMap::Get(product.m_hhKinFitTaus, lepton)) : nullptr);
return (tau ? SafeMap::GetWithDefault(product.m_tausBoostToDiTauSystem, tau, DefaultValues::UndefinedRMFLV) : DefaultValues::UndefinedRMFLV);
});
LambdaNtupleConsumer<HttTypes>::AddRMFLVQuantity("genMatchedTau"+leptonIndexString+"VisibleLVBoostToGenDiLeptonSystem", [leptonIndex](event_type const& event, product_type const& product)
{
KGenTau* genTau = SafeMap::GetWithDefault(product.m_genTauMatchedLeptons, product.m_flavourOrderedLeptons.at(leptonIndex), static_cast<KGenTau*>(nullptr));
return (genTau ? SafeMap::GetWithDefault(product.m_genVisTausBoostToGenDiLeptonSystem, genTau, DefaultValues::UndefinedRMFLV) : DefaultValues::UndefinedRMFLV);
});
LambdaNtupleConsumer<HttTypes>::AddRMFLVQuantity("genMatchedTau"+leptonIndexString+"LVBoostToGenDiLeptonSystem", [leptonIndex](event_type const& event, product_type const& product)
{
KGenTau* genTau = SafeMap::GetWithDefault(product.m_genTauMatchedLeptons, product.m_flavourOrderedLeptons.at(leptonIndex), static_cast<KGenTau*>(nullptr));
return (genTau ? SafeMap::GetWithDefault(product.m_genTausBoostToGenDiLeptonSystem, genTau, DefaultValues::UndefinedRMFLV) : DefaultValues::UndefinedRMFLV);
});
LambdaNtupleConsumer<HttTypes>::AddRMFLVQuantity("genMatchedTau"+leptonIndexString+"LVBoostToGenDiTauSystem", [leptonIndex](event_type const& event, product_type const& product)
{
KGenTau* genTau = SafeMap::GetWithDefault(product.m_genTauMatchedLeptons, product.m_flavourOrderedLeptons.at(leptonIndex), static_cast<KGenTau*>(nullptr));
return (genTau ? SafeMap::GetWithDefault(product.m_genTausBoostToGenDiTauSystem, genTau, DefaultValues::UndefinedRMFLV) : DefaultValues::UndefinedRMFLV);
});
}
}
void BoostRestFrameProducer::Produce(event_type const& event, product_type& product,
setting_type const& settings) const
{
// built systems of multiple particles
RMFLV leptonSystem;
RMFLV tauSystem;
RMFLV genLeptonSystem;
RMFLV genTauSystem;
for (std::vector<KLepton*>::iterator lepton = product.m_flavourOrderedLeptons.begin();
lepton != product.m_flavourOrderedLeptons.end(); ++lepton)
{
leptonSystem += (*lepton)->p4;
if (Utility::Contains(product.m_hhKinFitTaus, *lepton))
{
tauSystem += SafeMap::Get(product.m_hhKinFitTaus, *lepton);
}
KGenTau* genTau = SafeMap::GetWithDefault(product.m_genTauMatchedLeptons, *lepton, static_cast<KGenTau*>(nullptr));
if (genTau)
{
genLeptonSystem += genTau->visible.p4;
genTauSystem += genTau->p4;
}
}
// get boosts into these systems
ROOT::Math::Boost leptonSystemBoost(leptonSystem.BoostToCM());
ROOT::Math::Boost tauSystemBoost(tauSystem.BoostToCM());
ROOT::Math::Boost genLeptonSystemBoost(genLeptonSystem.BoostToCM());
ROOT::Math::Boost genTauSystemBoost(genTauSystem.BoostToCM());
// boost particles to rest frames of these systems
for (std::vector<KLepton*>::iterator lepton = product.m_flavourOrderedLeptons.begin();
lepton != product.m_flavourOrderedLeptons.end(); ++lepton)
{
product.m_leptonsBoostToDiLeptonSystem[*lepton] = leptonSystemBoost * (*lepton)->p4;
product.m_leptonsBoostToDiTauSystem[*lepton] = tauSystemBoost * (*lepton)->p4;
if (Utility::Contains(product.m_hhKinFitTaus, *lepton))
{
RMFLV* tau = &SafeMap::Get(product.m_hhKinFitTaus, *lepton);
product.m_tausBoostToDiTauSystem[tau] = tauSystemBoost * (*tau);
}
KGenTau* genTau = SafeMap::GetWithDefault(product.m_genTauMatchedLeptons, *lepton, static_cast<KGenTau*>(nullptr));
if (genTau)
{
product.m_genVisTausBoostToGenDiLeptonSystem[genTau] = genLeptonSystemBoost * genTau->visible.p4;
product.m_genTausBoostToGenDiLeptonSystem[genTau] = genTauSystemBoost * genTau->visible.p4;
product.m_genTausBoostToGenDiTauSystem[genTau] = genTauSystemBoost * genTau->p4;
}
}
}
| [
"t.muller@cern.ch"
] | t.muller@cern.ch |
e0a3c32c0661f78a9a33be61cdf398d2db555b94 | 1880ae99db197e976c87ba26eb23a20248e8ee51 | /ecm/include/tencentcloud/ecm/v20190719/model/ModifyLoadBalancerAttributesRequest.h | d8761ffefcbdc9e62723b56f1138b66dd27ec111 | [
"Apache-2.0"
] | permissive | caogenwang/tencentcloud-sdk-cpp | 84869793b5eb9811bb1eb46ed03d4dfa7ce6d94d | 6e18ee6622697a1c60a20a509415b0ddb8bdeb75 | refs/heads/master | 2023-08-23T12:37:30.305972 | 2021-11-08T01:18:30 | 2021-11-08T01:18:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,368 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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.
*/
#ifndef TENCENTCLOUD_ECM_V20190719_MODEL_MODIFYLOADBALANCERATTRIBUTESREQUEST_H_
#define TENCENTCLOUD_ECM_V20190719_MODEL_MODIFYLOADBALANCERATTRIBUTESREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/ecm/v20190719/model/LoadBalancerInternetAccessible.h>
namespace TencentCloud
{
namespace Ecm
{
namespace V20190719
{
namespace Model
{
/**
* ModifyLoadBalancerAttributes请求参数结构体
*/
class ModifyLoadBalancerAttributesRequest : public AbstractModel
{
public:
ModifyLoadBalancerAttributesRequest();
~ModifyLoadBalancerAttributesRequest() = default;
std::string ToJsonString() const;
/**
* 获取负载均衡的唯一ID
* @return LoadBalancerId 负载均衡的唯一ID
*/
std::string GetLoadBalancerId() const;
/**
* 设置负载均衡的唯一ID
* @param LoadBalancerId 负载均衡的唯一ID
*/
void SetLoadBalancerId(const std::string& _loadBalancerId);
/**
* 判断参数 LoadBalancerId 是否已赋值
* @return LoadBalancerId 是否已赋值
*/
bool LoadBalancerIdHasBeenSet() const;
/**
* 获取负载均衡实例名称
* @return LoadBalancerName 负载均衡实例名称
*/
std::string GetLoadBalancerName() const;
/**
* 设置负载均衡实例名称
* @param LoadBalancerName 负载均衡实例名称
*/
void SetLoadBalancerName(const std::string& _loadBalancerName);
/**
* 判断参数 LoadBalancerName 是否已赋值
* @return LoadBalancerName 是否已赋值
*/
bool LoadBalancerNameHasBeenSet() const;
/**
* 获取网络计费及带宽相关参数
* @return InternetChargeInfo 网络计费及带宽相关参数
*/
LoadBalancerInternetAccessible GetInternetChargeInfo() const;
/**
* 设置网络计费及带宽相关参数
* @param InternetChargeInfo 网络计费及带宽相关参数
*/
void SetInternetChargeInfo(const LoadBalancerInternetAccessible& _internetChargeInfo);
/**
* 判断参数 InternetChargeInfo 是否已赋值
* @return InternetChargeInfo 是否已赋值
*/
bool InternetChargeInfoHasBeenSet() const;
/**
* 获取Target是否放通来自ELB的流量。开启放通(true):只验证ELB上的安全组;不开启放通(false):需同时验证ELB和后端实例上的安全组。
* @return LoadBalancerPassToTarget Target是否放通来自ELB的流量。开启放通(true):只验证ELB上的安全组;不开启放通(false):需同时验证ELB和后端实例上的安全组。
*/
bool GetLoadBalancerPassToTarget() const;
/**
* 设置Target是否放通来自ELB的流量。开启放通(true):只验证ELB上的安全组;不开启放通(false):需同时验证ELB和后端实例上的安全组。
* @param LoadBalancerPassToTarget Target是否放通来自ELB的流量。开启放通(true):只验证ELB上的安全组;不开启放通(false):需同时验证ELB和后端实例上的安全组。
*/
void SetLoadBalancerPassToTarget(const bool& _loadBalancerPassToTarget);
/**
* 判断参数 LoadBalancerPassToTarget 是否已赋值
* @return LoadBalancerPassToTarget 是否已赋值
*/
bool LoadBalancerPassToTargetHasBeenSet() const;
private:
/**
* 负载均衡的唯一ID
*/
std::string m_loadBalancerId;
bool m_loadBalancerIdHasBeenSet;
/**
* 负载均衡实例名称
*/
std::string m_loadBalancerName;
bool m_loadBalancerNameHasBeenSet;
/**
* 网络计费及带宽相关参数
*/
LoadBalancerInternetAccessible m_internetChargeInfo;
bool m_internetChargeInfoHasBeenSet;
/**
* Target是否放通来自ELB的流量。开启放通(true):只验证ELB上的安全组;不开启放通(false):需同时验证ELB和后端实例上的安全组。
*/
bool m_loadBalancerPassToTarget;
bool m_loadBalancerPassToTargetHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_ECM_V20190719_MODEL_MODIFYLOADBALANCERATTRIBUTESREQUEST_H_
| [
"tencentcloudapi@tenent.com"
] | tencentcloudapi@tenent.com |
5dd1eac089ce0c1e359139c3f8beb5b08eae9c58 | cce1a6b0a8eedac4ad1ed903126dad6fc9e10235 | /main (7).cpp | fd7248879ee59bd443af7b7fb2670b24e1c6f2c8 | [] | no_license | 11aw/homework1 | ec25c611f6eb7dc474b4c8476be5b969f43afbd6 | 1615470e8d72abcd477d3df6b822db9e462d335d | refs/heads/master | 2021-06-12T20:52:23.144734 | 2020-04-09T14:36:15 | 2020-04-09T14:36:15 | 254,394,949 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,081 | cpp | /******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <iostream>
using namespace std;
int main()
{
int m = 5;
int n = 6;
int a[m][n];
int sum1 = 0;
int sum2 = 0;
for(int i = 0; i<m; i++){
for(int j = 0; j<n; j++){
a[i][j] = rand()%10-5;
}
}
for(int i = 0; i<m; i++){
for(int j = 0; j<n; j++){
cout << a[i][j] << " ";
}
cout<<endl;
}
cout<<endl;
for (int i = 0; i < m; ++i){
for (int j = 0; j < n; ++j){
if(a[i][j]>0){
sum1+=a[i][j];
}
if(a[i][j]<0){
sum2+=a[i][j];
}
}
}
cout<<"Sum > 0: " << sum1 << endl << "Sum < 0: " << sum2;
}
| [
"noreply@github.com"
] | 11aw.noreply@github.com |
daa7bc9f5c773a19f2f44d599ea5b1b46e9daae8 | 48d5dbf4475448f5df6955f418d7c42468d2a165 | /SDK/SoT_AD_ThirdPerson_PlayerPirate_Female_Large_classes.hpp | 4a6dea420f9699edff566b366cdf8efe742d6a06 | [] | no_license | Outshynd/SoT-SDK-1 | 80140ba84fe9f2cdfd9a402b868099df4e8b8619 | 8c827fd86a5a51f3d4b8ee34d1608aef5ac4bcc4 | refs/heads/master | 2022-11-21T04:35:29.362290 | 2020-07-10T14:50:55 | 2020-07-10T14:50:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 870 | hpp | #pragma once
// Sea of Thieves (1.4.16) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_AD_ThirdPerson_PlayerPirate_Female_Large_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass AD_ThirdPerson_PlayerPirate_Female_Large.AD_ThirdPerson_PlayerPirate_Female_Large_C
// 0x0000 (0x0738 - 0x0738)
class UAD_ThirdPerson_PlayerPirate_Female_Large_C : public UAD_ThirdPerson_PlayerPirate_Female_Default_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass AD_ThirdPerson_PlayerPirate_Female_Large.AD_ThirdPerson_PlayerPirate_Female_Large_C"));
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"53855178+Shat-sky@users.noreply.github.com"
] | 53855178+Shat-sky@users.noreply.github.com |
b7d3eb6cbe660e96af35f3fdc0b2c3e646d1f7dc | 48ebb9aa139b70ed9d8411168c9bd073741393f5 | /Classes/Native/I18N_West_I18N_West_CP100791554584814.h | 60b787f586644d71c972772be90e08f39816e07e | [] | no_license | JasonRy/0.9.1 | 36cae42b24faa025659252293d8c7f8bfa8ee529 | b72ec7b76d3e26eb055574712a5150b1123beaa5 | refs/heads/master | 2021-07-22T12:25:04.214322 | 2017-11-02T07:42:18 | 2017-11-02T07:42:18 | 109,232,088 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,168 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "I18N_I18N_Common_ByteEncoding1810358777.h"
// System.Char[]
struct CharU5BU5D_t1328083999;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// I18N.West.CP10079
struct CP10079_t1554584814 : public ByteEncoding_t1810358777
{
public:
public:
};
struct CP10079_t1554584814_StaticFields
{
public:
// System.Char[] I18N.West.CP10079::ToChars
CharU5BU5D_t1328083999* ___ToChars_42;
public:
inline static int32_t get_offset_of_ToChars_42() { return static_cast<int32_t>(offsetof(CP10079_t1554584814_StaticFields, ___ToChars_42)); }
inline CharU5BU5D_t1328083999* get_ToChars_42() const { return ___ToChars_42; }
inline CharU5BU5D_t1328083999** get_address_of_ToChars_42() { return &___ToChars_42; }
inline void set_ToChars_42(CharU5BU5D_t1328083999* value)
{
___ToChars_42 = value;
Il2CppCodeGenWriteBarrier(&___ToChars_42, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"renxiaoyi@me.com"
] | renxiaoyi@me.com |
96fc3a41d0db18d60476e3700b569771e4676b03 | 33fef7b5e70ad44ead9c4a756c6cc3699b3c6da5 | /modifyprofilehandler.cpp | 31ad0e56629657c59aa26c602eb78b9cf1f19223 | [] | no_license | MyComputableRomance/3DitiOSCom | dcb6c6fab4846e647783ff84a0a17f18c02e9d8a | b076ddabbe2449693888ad72fdc605e8c179cd3b | refs/heads/master | 2016-08-12T16:21:45.742507 | 2015-10-27T16:04:43 | 2015-10-27T16:04:43 | 44,088,960 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,100 | cpp | #include "modifyprofilehandler.h"
ModifyProfileHandler::ModifyProfileHandler(QObject *parent) : QObject(parent)
{
_changedEmail = "";
//_changedUsername = "";
connect(&_modifyProfileManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(modifiedReplyFinished(QNetworkReply*)));
}
ModifyProfileHandler::~ModifyProfileHandler() {}
void ModifyProfileHandler::execute()
{
QUrl url(QString(SERVER_FRIEND) + UserObjectId);
QJsonObject modifyJson;
//if(_changedUsername == "")
//{
modifyJson.insert("type", "modifyEmail");
modifyJson.insert("email", _changedEmail);
//}
/*else if(_changedEmail == "")
{
modifyJson.insert("type", "modifyUsername");
modifyJson.insert("username", _changedUsername);
}*/
QJsonDocument jsonDoc;
jsonDoc.setObject(modifyJson);
QByteArray postData = jsonDoc.toJson();
QNetworkRequest request(url);
_modifyProfileManager.put(request, postData);
}
void ModifyProfileHandler::modifiedReplyFinished(QNetworkReply *reply)
{
if(reply->error() == QNetworkReply::NoError)
{
QByteArray result = reply->readAll();
QJsonParseError jsonParse;
QJsonDocument jsonDoc = QJsonDocument::fromJson(result, &jsonParse);
if(jsonParse.error == QJsonParseError::NoError)
{
if(jsonDoc.isObject())
{
QJsonObject modifyResultObject = jsonDoc.object();
if(modifyResultObject.contains("result"))
{
QJsonValue resultCode = modifyResultObject.take("result");
//success OK failure ***Error
if(resultCode.isString())
{
if(resultCode.toString() == "OK")
_resultCode = true;
else
_resultCode = false;
}
}
}
}
}
reply->deleteLater();
emit modified();
}
/*QString ModifyProfileHandler::modifiedProfile() const
{
return _modifiedProfileInfo;
}*/
| [
"martin.t.jones@aol.com"
] | martin.t.jones@aol.com |
6ce4547e702ad13ad77834d3e053e7884875212e | 68c5c228cf9b15ee7892fa34988f292785e809af | /Test/Algorithms/algo/test_count.cpp | 99a72b357560a4e22895b4425feec26c2a414a12 | [
"MIT"
] | permissive | zsmj2017/MiniSTL | d117ad3ccba44f67074b2053f43e162fa6be1b97 | 49a4751fa4feddf55bc959ccee2ff7324e3c1df0 | refs/heads/master | 2022-11-12T00:14:25.751721 | 2022-11-01T04:24:32 | 2022-11-01T04:24:32 | 141,666,304 | 368 | 49 | MIT | 2022-11-01T04:10:16 | 2018-07-20T05:11:59 | C++ | UTF-8 | C++ | false | false | 809 | cpp | #include "Algorithms/algo/stl_algo.h"
#include "SequenceContainers/Vector/stl_vector.h"
#include <gtest/gtest.h>
using namespace ::MiniSTL;
class CountTest : public testing::Test {
protected:
void SetUp() override {
}
};
TEST_F(CountTest, count0) {
int numbers[10] = {1, 2, 4, 1, 2, 4, 1, 2, 4, 1};
int result = count(numbers, numbers + 10, 1);
ASSERT_TRUE(result == 4);
}
TEST_F(CountTest, count1) {
vector<int> numbers(100);
for (int i = 0; i < 100; i++)
numbers[i] = i % 3;
int elements = count(numbers.begin(), numbers.end(), 2);
ASSERT_TRUE(elements == 33);
}
TEST_F(CountTest, countif0) {
vector<int> numbers(100);
for (int i = 0; i < 100; i++)
numbers[i] = i % 3;
int elements = count_if(numbers.begin(), numbers.end(), odd<int>());
ASSERT_TRUE(elements == 33);
}
| [
"liuxiang@staff.weibo.com"
] | liuxiang@staff.weibo.com |
d63da2253848b619aabb9b0adb3d85805f893d83 | 601490f589afae6815d51cd831c930d330cdbb3d | /contest/abc/abc032/b.cpp | 569abcb1e3e6ebbec80805d3e88270ed70a47b17 | [] | no_license | hiramekun/CompetitiveProgrammingContests | cd26974d1e8f0b9b2dc3380dcccff00a8fb6833c | 1bcb2f840c9b44c438cc8c3d07c72fc5ff78f61a | refs/heads/master | 2022-01-02T06:29:36.759306 | 2021-12-29T00:44:59 | 2021-12-29T00:44:59 | 226,824,121 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,760 | cpp | /**
* Created by hiramekun at 20:54 on 2019-11-16.
*/
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vl = vector<ll>;
using vvl = vector<vl>;
using vb = vector<bool>;
using P = pair<ll, ll>;
template<typename T> using pq = priority_queue<T>;
template<typename T> using minpq = priority_queue<T, vector<T>, greater<T>>;
template<typename T, typename K> using ump = unordered_map<T, K>;
const ll dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
const ll mod = 1000000007;
const ll inf = ll(1e9);
const ll e5 = ll(1e5);
const ll ll_inf = ll(1e9) * ll(1e9);
#define rep(i, n) for(ll i = 0; i < (ll)(n); i++)
#define repr(i, n) for(ll i = ll(n - 1); i >= 0; i--)
#define each(i, mp) for(auto& i:mp)
#define eb emplace_back
#define F first
#define S second
#define all(obj) (obj).begin(), (obj).end()
template<class T>
ostream &operator<<(ostream &out, const vector<T> &list) {
ll n = list.size();
rep(i, n) out << list[i] << ' ';
return out;
}
template<class T>
istream &operator>>(istream &in, vector<T> &list) {
ll n = list.size();
rep(i, n) in >> list[i];
return in;
}
template<class T>
ostream &operator<<(ostream &out, const vector<vector<T>> &list) {
ll n = list.size();
rep(i, n) out << list[i] << '\n';
return out;
}
/* ------------- ANSWER ------------- */
/* ---------------------------------- */
void solve() {
string s;
ll k;
cin >> s >> k;
ll sn = s.size();
if (k>sn) cout << 0 << '\n';
else {
set<string> s1;
rep(i, sn - k + 1) {
s1.insert(s.substr(i, k));
}
cout << s1.size() << '\n';
}
}
int main() {
#ifdef MY_DEBUG
while (true) {
#endif
solve();
#ifdef MY_DEBUG
}
#endif
return 0;
}
| [
"thescript1210@gmail.com"
] | thescript1210@gmail.com |
eaaa3c8e1af8d7b7c272b0a583ac19ebb0b9f7c7 | 031f7354f569f118d73b5bf9ce0d4f860fb5eabf | /libkroll/ScriptController.cpp | e302616b7618b90efebe6f01b21eec66cdb250f8 | [
"Apache-2.0"
] | permissive | psycho-pas/kroll | 706e3a55bf390e3f447d619ad158c840ff176506 | 12fc8ead138984a84681b7d7a526d58f5b44e3bc | refs/heads/master | 2020-05-24T08:15:08.637812 | 2019-05-19T09:29:16 | 2019-05-19T09:29:16 | 187,138,484 | 0 | 0 | NOASSERTION | 2019-05-17T03:12:14 | 2019-05-17T03:12:14 | null | UTF-8 | C++ | false | false | 2,018 | cpp | /*
* Copyright (c) 2011 Appcelerator, Inc. 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 "ScriptController.h"
#include <string.h>
#include "Interpreter.h"
namespace kroll {
ScriptController::ScriptController()
{
}
void ScriptController::AddInterpreter(Interpreter* interpreter, const char* supportedScriptTypes[])
{
const char* type;
int i = 0;
while ((type = supportedScriptTypes[i++])) {
interpreters[type] = interpreter;
}
}
void ScriptController::RemoveInterpreter(Interpreter* interpreter)
{
InterpreterMapping::iterator i = interpreters.begin();
while (i != interpreters.end()) {
if (i->second == interpreter)
interpreters.erase(i++);
else
++i;
}
}
KValueRef ScriptController::EvaluateFile(const char* filepath, KObjectRef context)
{
const char* scriptType = strrchr(filepath, '.');
if (!scriptType)
throw ValueException::FromFormat("Invalid script path, missing extension: %s", filepath);
++scriptType;
Interpreter* interpreter = findInterpreterForType(scriptType);
return interpreter->EvaluateFile(filepath, context);
}
Interpreter* ScriptController::findInterpreterForType(const char* scriptType)
{
InterpreterMapping::iterator i = interpreters.find(scriptType);
if (i == interpreters.end())
throw ValueException::FromFormat("Cannot evalute file, invalid script type: %s", scriptType);
return i->second;
}
} // namespace kroll
| [
"jroesslein@appcelerator.com"
] | jroesslein@appcelerator.com |
54d6917d12d70ca66aede07897897d91a681861b | 119c1dd2b61764210064511d8ab5be252b8b7c8f | /450 DSA Questions/10 Stacks and Queues/5ImplementQueueFromScratch.cpp | 1216beaef2058f36697944c8443712b2efb07072 | [] | no_license | jasveen18/CP-krle-placement-lag-jayegi | 2557309a9dfc4feb01dbdc867a67f1ccc4f10868 | 8db92e5c3a7d08edfc34d8223af6c080aa3e4721 | refs/heads/main | 2023-07-29T09:39:36.270193 | 2021-09-03T15:19:22 | 2021-09-03T15:19:22 | 430,816,168 | 1 | 1 | null | 2021-11-22T18:10:13 | 2021-11-22T18:10:13 | null | UTF-8 | C++ | false | false | 777 | cpp | /******************************************
* AUTHOR : ARPIT *
* NICK : arpitfalcon *
* INSTITUTION : BIT MESRA *
******************************************/
// Problem Statement - Implement a queue from scratch
class CustomQueue {
private:
int capacity;
int front, rear, size;
vector<int> q;
public:
CustomQueue(int capacity) {
this->capacity = capacity;
q = vector<int> (capacity);
front = -1;
size = 0;
rear = -1;
}
void enqueue(int x) {
// If empty
if (rear == -1) {
front = 0;
}
q[++rear] = x;
size = size + 1;
}
int dequeue() {
if (size <= 0) return INT_MIN;
size = size - 1;
return q[front--];
}
int peek() {
return q[front];
}
bool isEmpty() {
return size == 0;
}
bool isFull() {
return size == capacity;
}
}; | [
"arpitfalcon1@gmail.com"
] | arpitfalcon1@gmail.com |
e9a99ad09fa03cb7789bcaeeae73098d43c1a705 | cc25fc6cf00dc91e7664e67ad0e1532615eabf17 | /src/lexer.h | 3acd3df19fec32ad51d7e080f13024ce3479a4b6 | [] | no_license | sosukesuzuki/calc-cpp | a79ca49708c08ed755e8462a38488c7c52aba5b9 | 1f25a5e4385c16d57931a5d07b27575efa729d8b | refs/heads/main | 2023-02-23T03:07:41.293375 | 2021-01-15T15:19:51 | 2021-01-15T15:19:51 | 326,259,382 | 0 | 0 | null | 2021-01-15T15:19:52 | 2021-01-02T19:49:29 | C++ | UTF-8 | C++ | false | false | 184 | h | #ifndef LEXER_H
#define LEXER_H
#include <vector>
std::vector<std::string> tokenize(std::string str);
bool is_number(std::string* token);
bool is_name(std::string* token);
#endif
| [
"aosukeke@gmail.com"
] | aosukeke@gmail.com |
3f62eeaa202a993b32e84cfb90a63281219c6d19 | f0749232d54f17e3c321b0b90daaeb23b9faec82 | /Online Judge Code/[Other] Online-Judge-Solutions-master_from github/ZOJ/3077 - Move to Baggage Office.cpp | 88f3c945d629247268e255d8bbb6c849824a10a9 | [] | no_license | tmuttaqueen/MyCodes | c9024a5b901e68e7c7466885eddbfcd31a5c9780 | 80ec40b26649029ad546ce8ce5bfec0b314b1f61 | refs/heads/master | 2020-04-18T22:20:51.845309 | 2019-05-16T18:11:02 | 2019-05-16T18:11:02 | 167,791,029 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 827 | cpp | #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct baggage{
int v,a,b;
baggage(){}
baggage(int _v, int _a, int _b){
v = _v; a = _a; b = _b;
}
bool operator < (baggage X)const{
return b<X.b;
}
}L[100];
int main(){
int T,s,n,dp[1001];
scanf("%d",&T);
while(T--){
scanf("%d %d",&s,&n);
for(int i = 0;i<n;++i)
scanf("%d %d %d",&L[i].v,&L[i].a,&L[i].b);
sort(L,L+n);
memset(dp,0,sizeof(dp));
int ans = 0;
for(int i = 0;i<n;++i) for(int j = s;j>=L[i].a;--j){
dp[j] = max(dp[j],L[i].v+dp[j-L[i].a+L[i].b]);
if(dp[j]>ans) ans = dp[j];
}
printf("%d\n",ans);
}
return 0;
}
| [
"1505002.tm@ugrad.cse.buet.ac.bd"
] | 1505002.tm@ugrad.cse.buet.ac.bd |
01d56048aa2677da5af1b29c661c835dba434104 | 40692316816b60ceb4a99b115e5f93aaedbae6bf | /September/14.09.2020/14.09.2020(Ravesli_test8).cpp | 5b6ba55e27088fa3a72a682e9832735a920f16d3 | [] | no_license | shanberochka/Ravesli | a69c4b328eeac6abfa28ed1894e287a44e85b3d1 | fe320f23e3121b0b94f6571d70af3a02ab462f8d | refs/heads/master | 2022-12-25T15:22:47.473630 | 2020-10-05T12:36:13 | 2020-10-05T12:36:13 | 297,061,771 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 68 | cpp | #include <iostream>
void ex31();
int main()
{
ex31();
}
| [
"noreply@github.com"
] | shanberochka.noreply@github.com |
bf80caa90caa217d10db042162d36db367a721a7 | 0ff8175618b7f682e25128b542f7d7ae0b55b45c | /OpenglBlend/OpenglBlend.cpp | 913b322aec17ab50dd1daf9e213e98f3bac3723f | [] | no_license | cgwang1580/LearnOpenGL | 02bb431d4137df9f774951958fed640cda137d94 | 617dfad3dc0eea5c2b2716535e74189362af4762 | refs/heads/master | 2020-05-23T14:50:50.259341 | 2020-04-03T06:35:03 | 2020-04-03T06:35:03 | 186,814,524 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,647 | cpp | #include "OpenglBlend.h"
int main() {
window = initGLFW();
if (NULL == window) {
cout << "initGLFW failed" << endl;
return -1;
}
#ifdef USE_SHADER_HELPER
Shader_Helper shaderHelper(vertexShaderPath, fragmentShaderPath);
#endif // USE_SHADER_HELPER
// setup cube VAO
glGenVertexArrays(1, &cubeVAO);
glGenBuffers(1, &cubeVBO);
glBindVertexArray(cubeVAO);
glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glBindVertexArray(0);
// setup plane VAO
glGenVertexArrays(1, &planeVAO);
glGenBuffers(1, &planeVBO);
glBindVertexArray(planeVAO);
glBindBuffer(GL_ARRAY_BUFFER, planeVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glBindVertexArray(0);
// set transparent plane VAO
glGenVertexArrays(1, &transparentVAO);
glGenBuffers(1, &transparentVBO);
glBindVertexArray(transparentVAO);
glBindBuffer(GL_ARRAY_BUFFER, transparentVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(transparentVertices), transparentVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glBindVertexArray(0);
// Load textures
GLuint cubeTexture = loadTexture((GLchar*)(imagePath.c_str()));
GLuint floorTexture = loadTexture((GLchar*)(imagePath2.c_str()));
GLuint transparentTexture = loadTexture((GLchar*)(imagePath3.c_str()), true);
glEnable(GL_DEPTH_TEST);
// get view port test
GLint dim[4];
glGetIntegerv(GL_VIEWPORT, dim);
#ifdef USE_SHADER_HELPER
shaderHelper.use();
shaderHelper.setInt("texture1", 0);
shaderHelper.setInt("texture2", 1);
#endif // USE_SHADER_HELPER
while (!glfwWindowShouldClose(window)) {
processInput(window);
currentTime = static_cast<GLfloat>(glfwGetTime());
takeTime = currentTime - lastTime;
//cameraSpeed = takeTime * 10000000000.0f * cameraSpeed;
//cout << "lastTime = " << lastTime << " currentTime = " << currentTime << " takeTime = " << takeTime << " cameraSpeed = " << cameraSpeed << endl;
doMovement();
// active texture
glActiveTexture(GL_TEXTURE0);
// bind Texture
glBindTexture(GL_TEXTURE_2D, texture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
// Create transformations
// make sure to initialize matrix to identity matrix first, important!!!
glm::mat4 transform = glm::mat4(1.0f);
transform = glm::rotate(transform, (float)glfwGetTime(), glm::vec3(0.5f, 1.0f, 0.0f));
glm::mat4 view = glm::mat4(1.0f);
view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);
glm::mat4 perspective = glm::mat4(1.0f);
perspective = glm::perspective(aspect, (float)WIN_WINDTH / WIN_HEIGHT, 0.1f, 100.0f);
// Get matrix's uniform location and set matrix
GLint transformLoc = glGetUniformLocation(shaderHelper.progreamId, "transform");
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(transform));
GLint viewLoc = glGetUniformLocation(shaderHelper.progreamId, "view");
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
GLint perspectiveLoc = glGetUniformLocation(shaderHelper.progreamId, "projection");
glUniformMatrix4fv(perspectiveLoc, 1, GL_FALSE, glm::value_ptr(perspective));
glBindVertexArray(VAO);
for (int i = 0; i < 10; ++i) {
glm::mat4 model = glm::mat4(1.0);
model = glm::translate(model, cubePositions[i]);
GLfloat angel = 20.0f * i;
if (i % 4 == 0) {
angel = (GLfloat)glfwGetTime();
}
model = glm::rotate(model, angel, glm::vec3(1.0f, 0.3f, 0.5f));
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(model));
glDrawArrays(GL_TRIANGLES, 0, 36);
}
glBindVertexArray(0);
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
lastTime = static_cast<float> (glfwGetTime());
}
glDeleteBuffers(1, &VBO);
glDeleteVertexArrays(1, &VAO);
//glDeleteBuffers(1, &EBO);
glfwTerminate();
return 0;
}
GLFWwindow* initGLFW() {
if (!glfwInit()) {
return NULL;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(WIN_WINDTH, WIN_HEIGHT, "HelloCamera", NULL, NULL);
if (NULL == window) {
cout << "glfwCreateWindow failed" << endl;
glfwTerminate();
return NULL;
}
glfwMakeContextCurrent(window);
// register callback function
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
/*if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
cout << "Failed to intialize GLAD" << endl;
return NULL;
}*/
int nrAttributes = 0;
glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &nrAttributes);
cout << "GL_MAX_VERTEX_ATTRIBS " << nrAttributes << endl;
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
glewExperimental = GL_TRUE;
glewInit();
return window;
}
void processInput(GLFWwindow *window) {
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// get input
if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) {
keys[GLFW_KEY_UP] = true;
}
if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) {
keys[GLFW_KEY_DOWN] = true;
}
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) {
keys[GLFW_KEY_LEFT] = true;
}
if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) {
keys[GLFW_KEY_RIGHT] = true;
}
//GLfloat cameraSpeed = 0.05f;
// get input
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
glfwSetWindowShouldClose(window, true);
}
/*if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) {
cameraPos += cameraSpeed * cameraFront;
}
if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) {
cameraPos -= cameraSpeed * cameraFront;
}
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) {
cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
}
if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) {
cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
}*/
}
void doMovement() {
if (keys[GLFW_KEY_UP])
cameraPos += cameraSpeed * cameraFront;
if (keys[GLFW_KEY_DOWN])
cameraPos -= cameraSpeed * cameraFront;
if (keys[GLFW_KEY_RIGHT])
cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
if (keys[GLFW_KEY_LEFT])
cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
for (int i = 0; i < 1024; ++i) {
keys[i] = false;
}
}
// This function loads a texture from file. Note: texture loading functions like these are usually
// managed by a 'Resource Manager' that manages all resources (like textures, models, audio).
// For learning purposes we'll just define it as a utility function.
GLuint loadTexture(GLchar* path, GLboolean alpha)
{
//Generate texture ID and load texture data
GLuint textureID;
glGenTextures(1, &textureID);
int width, height;
unsigned char* image = SOIL_load_image(path, &width, &height, 0, alpha ? SOIL_LOAD_RGBA : SOIL_LOAD_RGB);
// Assign texture to ID
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, alpha ? GL_RGBA : GL_RGB, width, height, 0, alpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
// Parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, alpha ? GL_CLAMP_TO_EDGE : GL_REPEAT); // Use GL_CLAMP_TO_EDGE to prevent semi-transparent borders. Due to interpolation it takes value from next repeat
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, alpha ? GL_CLAMP_TO_EDGE : GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
SOIL_free_image_data(image);
return textureID;
}
| [
"cgwang1580@gmail.com"
] | cgwang1580@gmail.com |
58b879acbee47a56642f24f67538149c193406f3 | b7689e759d7a8ffc3bf0baeef93bab054863238c | /二分查找.cpp | d247fd9686b2435d5bccf216e7d5638dda94807e | [] | no_license | FelixLiu1996/myCcodes | 8abb15c86049a250d67b4a78577e0c4787651cf5 | 4d0c0ef57c3939a9fc7b556efe9c1337bf00c3fb | refs/heads/master | 2020-07-29T18:46:48.706145 | 2019-09-21T04:08:11 | 2019-09-21T04:08:11 | 209,921,716 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 532 | cpp | #include<cstdio>
//A[]为严格递增序列,left为二分下界,right为二分上界,x为欲查找之数
int binarySearch(int A[], int left, int right, int x)
{
int mid;
while (left <= right)
{
mid = (right + left) / 2;
if(A[mid] == x) return mid;
else if (A[mid] > x)
{
right = mid - 1;
}
else {
left = mid + 1;
}
}
return -1;
}
int main(){
const int n = 10;
int A[n] = {1, 3, 4, 6, 7, 8, 10, 11, 12, 15};
printf ("%d %d", binarySearch(A, 0, n - 1, 6), binarySearch(A, 0, n - 1, 9));
return 0;
}
| [
"1321842068@qq.com"
] | 1321842068@qq.com |
43d076592fcb088d120b957a2d39baece6804a2c | 8feb7e19a9ab2ea535b1b6347bdbe48d619d94cb | /ConsoleApplication16_3/ConsoleApplication16_3/QueueTp.h | e973bcc5e79b7dc9bea8c7712313650dd4008a7c | [] | no_license | SmileHurry/cplusplus-primer-plus-6th- | 3426de7aed1de8a94d48c468e1a79fe95b6ed9b6 | 892c907a5c3b93631a219a28880525fe8ff10f12 | refs/heads/master | 2021-01-10T15:42:03.637199 | 2016-04-08T06:24:46 | 2016-04-08T06:24:46 | 55,745,488 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,065 | h | #ifndef QUEUETP_H_
#define QUEUETP_H_
template<typename T>
class QueueTp
{
protected:
struct Node
{
T item;
struct Node *next;
};
private:
const static int Q_size = 10;
Node *front;
Node *rear;
int items;
const int qsize;
QueueTp(const QueueTp &q) :qsize(0){}
QueueTp & operator=(const QueueTp &q){ return *this; }
public:
QueueTp(int qs = Q_size);
~QueueTp();
bool isempty() const;
bool isfull() const;
int queuecount() const;
bool enqueue(const T &item);
bool dequeue(T &item);
};
//---------------------------------------------------------------------//
//注意:以下所有的模板成员函数都不能放在独立的文件(比如:QueueTp.cpp)中。
//这是因为模板不是函数,他们不能单独编译。模板必须与特定的模块实例化请求一起使用。
//因此,最简单的方法是将所有模板信息放在一个头文件中,并在要使用这些模板的文件中包含该头文件!!!(P569)
template<typename T>
QueueTp<T>::QueueTp(int qs) :qsize(qs)
{
front = rear = nullptr;
items = 0;
}
template<typename T>
QueueTp<T>::~QueueTp()
{
Node *temp;
while (front != nullptr)
{
temp = front;
front = front->next;
delete temp;
}
rear = nullptr;
}
template<typename T>
bool QueueTp<T>::isempty() const
{
return items == 0;
}
template<typename T>
bool QueueTp<T>::isfull() const
{
return items == qsize;
}
template<typename T>
int QueueTp<T>::queuecount() const
{
return items;
}
template<typename T>
bool QueueTp<T>::enqueue(const T &item)
{
if (isfull())
return false;
Node *add = new Node;
add->item = item;
add->next = nullptr;
items++;
if (front == nullptr)
front = add;
else
rear->next = add;
rear = add;
return true;
}
template<typename T>
bool QueueTp<T>::dequeue(T &item)
{
if (front == nullptr)
return false;
item = front->item;
items--;
Node *temp = front;
front = front->next;
delete temp;
if (items == 0)
rear = nullptr;
return true;
}
#endif
| [
"395307009@qq.com"
] | 395307009@qq.com |
ed86a2f90eca6eea146fdc7cdeb26fa0cbb0a408 | e13f2093579cb011c50ca357ccbc08d732ceb151 | /mve/libs/sfm/bundler_common.h | f5354844c7e15f75c75f909357882c6c756a1f9c | [
"BSD-3-Clause"
] | permissive | dineshreddy91/CloudReconstruction | 4245f3cc4771881364350719556d5e7d9cb7fcbe | ef5c26301acd91cdb605bfebbb8f30810d4e4451 | refs/heads/master | 2020-03-15T22:15:31.773865 | 2018-05-07T06:53:13 | 2018-05-07T06:53:13 | 132,369,811 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,785 | h | /*
* Copyright (C) 2015, Simon Fuhrmann
* TU Darmstadt - Graphics, Capture and Massively Parallel Computing
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the LICENSE.txt file for details.
*/
#ifndef SFM_BUNDLER_COMMON_HEADER
#define SFM_BUNDLER_COMMON_HEADER
#include <string>
#include <unordered_map>
#include <vector>
#include "math/vector.h"
#include "util/aligned_memory.h"
#include "mve/image.h"
#include "sfm/camera_pose.h"
#include "sfm/correspondence.h"
#include "sfm/feature_set.h"
#include "sfm/sift.h"
#include "sfm/surf.h"
#include "sfm/defines.h"
SFM_NAMESPACE_BEGIN
SFM_BUNDLER_NAMESPACE_BEGIN
/* -------------------- Common Data Structures -------------------- */
/**
* Per-viewport information.
* Not all data is required for every step. It should be populated on demand
* and cleaned as early as possible to keep memory consumption in bounds.
*/
struct Viewport
{
Viewport (void);
/** Initial focal length estimate for the image. */
float focal_length;
/** Radial distortion parameter. */
float radial_distortion[2];
/** Camera pose for the viewport. */
CameraPose pose;
/** The actual image data for debugging purposes. Usually nullptr! */
mve::ByteImage::Ptr image;
/** Per-feature information. */
FeatureSet features;
/** Per-feature track ID, -1 if not part of a track. */
std::vector<int> track_ids;
/** Backup map from features to tracks that were removed due to errors. */
std::unordered_map<int, int> backup_tracks;
};
/** The list of all viewports considered for bundling. */
typedef std::vector<Viewport> ViewportList;
/* --------------- Data Structure for Feature Tracks -------------- */
/** References a 2D feature in a specific view. */
struct FeatureReference
{
FeatureReference (int view_id, int feature_id);
int view_id;
int feature_id;
};
/** The list of all feature references inside a track. */
typedef std::vector<FeatureReference> FeatureReferenceList;
/** Representation of a feature track. */
struct Track
{
bool is_valid (void) const;
void invalidate (void);
void remove_view (int view_id);
math::Vec3f pos;
math::Vec3uc color;
FeatureReferenceList features;
};
/** The list of all tracks. */
typedef std::vector<Track> TrackList;
/* Observation of a survey point in a specific view. */
struct SurveyObservation
{
SurveyObservation (int view_id, float x, float y);
int view_id;
math::Vec2f pos;
};
/** The list of all survey point observations inside a survey point. */
typedef std::vector<SurveyObservation> SurveyObservationList;
/** Representation of a survey point. */
struct SurveyPoint
{
math::Vec3f pos;
SurveyObservationList observations;
};
/** The list of all survey poins. */
typedef std::vector<SurveyPoint> SurveyPointList;
/* ------------- Data Structures for Feature Matching ------------- */
/** The matching result between two views. */
struct TwoViewMatching
{
bool operator< (TwoViewMatching const& rhs) const;
int view_1_id;
int view_2_id;
CorrespondenceIndices matches;
};
/** The matching result between several pairs of views. */
typedef std::vector<TwoViewMatching> PairwiseMatching;
/* ------------------ Input/Output for Prebundle ------------------ */
/**
* Saves the pre-bundle data to file, which records all viewport and
* matching data necessary for incremental structure-from-motion.
*/
void
save_prebundle_to_file (ViewportList const& viewports,
PairwiseMatching const& matching, std::string const& filename);
/**
* Loads the pre-bundle data from file, initializing viewports and matching.
*/
void
load_prebundle_from_file (std::string const& filename,
ViewportList* viewports, PairwiseMatching* matching);
/**
* Loads survey points and their observations from file.
*
* Survey file are ASCII files that start with the signature
* MVE_SURVEY followed by a newline, followed by the number of survey points
* and survey point observations.
* Each survey point is a 3D point followed by a newline. Each survey point
* observation is a line starting with the index of the survey point, followed
* by the view id an the 2D location within the image. The (x, y) coordinates
* have to be normalized such that the center of the image is (0, 0) and the
* larger image dimension is one. This means that all image coordinates are
* between (-0.5,-0.5) and (0.5, 0.5)
*
* MVE_SURVEY
* <num_points> <num_observations>
* <survey_point> // x y z
* ...
* <survey_point_observation> // survey_point_id view_id x y
* ...
*/
void
load_survey_from_file (std::string const& filename,
SurveyPointList* survey_points);
/* ---------------------- Feature undistortion -------------------- */
math::Vec2f
undistort_feature (math::Vec2f const& f, double const k1, double const k2,
float const focal_length);
/* ------------------------ Implementation ------------------------ */
inline
FeatureReference::FeatureReference (int view_id, int feature_id)
: view_id(view_id)
, feature_id(feature_id)
{
}
inline
SurveyObservation::SurveyObservation (int view_id, float x, float y)
: view_id(view_id)
, pos(x, y)
{
}
inline bool
TwoViewMatching::operator< (TwoViewMatching const& rhs) const
{
return this->view_1_id == rhs.view_1_id
? this->view_2_id < rhs.view_2_id
: this->view_1_id < rhs.view_1_id;
}
inline
Viewport::Viewport (void)
: focal_length(0.0f)
{
std::fill(this->radial_distortion, this->radial_distortion + 2, 0.0f);
}
inline bool
Track::is_valid (void) const
{
return !std::isnan(this->pos[0]);
}
SFM_BUNDLER_NAMESPACE_END
SFM_NAMESPACE_END
#endif /* SFM_BUNDLER_COMMON_HEADER */
| [
"dinesh.andromeda@gmail.com"
] | dinesh.andromeda@gmail.com |
f922a8ac241f7b94d045b3beb6db440015b8a1bb | 23a3f7fb0684de95b89ab4e6cdff98dad8237338 | /TTHNtupleAnalyzer/plugins/event_interpretation.cc | 342f88fc02bbb2eafcba86b5f5c9d84b31adf741 | [] | no_license | camclean/tthbb13 | 1ff3c1f5e68bd3ca85cfe0efc3bf9f7c45d03200 | 7d738c44f6596e153837248354c6f514ff06d651 | refs/heads/master | 2020-12-30T23:08:39.712119 | 2015-01-14T16:11:44 | 2015-01-14T16:11:44 | 29,531,749 | 0 | 0 | null | 2015-01-20T13:45:15 | 2015-01-20T13:45:15 | null | UTF-8 | C++ | false | false | 2,044 | cc |
//
// event_interpretation.cpp
// MEStudiesJP
//
// Created by Joosep Pata on 13/12/14.
// Copyright (c) 2014 Joosep Pata. All rights reserved.
//
#include <stdio.h>
#include <TTH/TTHNtupleAnalyzer/interface/event_interpretation.hh>
//these are simple 'sentinel values' for uninitialized variables
//for clarity, it would be best to use these instead of manually writing -99 etc.
//this way, undefined variables are always unique and one can write functions to recognize them
#define DEF_VAL_FLOAT -9999.0f
#define DEF_VAL_DOUBLE -9999.0d
#define DEF_VAL_INT -9999
#define FLOAT_EPS 0.0000001f
#define DOUBLE_EPS 0.0000001d
//checks if a branch variable is undefined
inline bool is_undef(int x) { return x==DEF_VAL_INT; };
inline bool is_undef(float x) { return fabs(x-DEF_VAL_FLOAT) < FLOAT_EPS; };
inline bool is_undef(double x) { return fabs(x-DEF_VAL_DOUBLE) < DOUBLE_EPS; };
const TLorentzVector vec_from_ptetaphim(double pt, double eta, double phi, double m) {
TLorentzVector _p4;
if (!is_undef(pt) && !is_undef(eta) && !is_undef(phi) && !is_undef(m))
_p4.SetPtEtaPhiM(pt, eta, phi, m);
return _p4;
}
Particle::Particle(double pt, double eta, double phi, double m, int _id, int _idx, const std::vector<Particle*> _parents, const std::vector<Particle*> _children) :
p4(vec_from_ptetaphim(pt, eta, phi, m)),
id(_id),
idx(_idx),
parents(_parents),
children(_children)
{
}
Particle::Particle(double pt, double eta, double phi, double m, int _id, int _idx) :
p4(vec_from_ptetaphim(pt, eta, phi, m)),
id(_id),
idx(_idx)
{
}
Particle::Particle(double pt, double eta, double phi, double m, int _id) :
p4(vec_from_ptetaphim(pt, eta, phi, m)),
id(_id),
idx(-1)
{
}
Event::Event(plist _particles, plist _jets, plist _gen_jets, plist _leptons, plist _gen_leptons, plist _top_decays, plist _higgs_decays) :
particles(_particles),
jets(_jets),
gen_jets(_gen_jets),
leptons(_leptons),
gen_leptons(_gen_leptons),
top_decays(_top_decays),
higgs_decays(_higgs_decays)
{
}
Event::~Event() {
for (auto* v : particles) {
delete v;
}
}
| [
"joosep.pata@gmail.com"
] | joosep.pata@gmail.com |
e0588b3220a5007d7006f28ef93bba4ae847c1f9 | 715ebb5e326d1451da3cc14b2925fbf729a2911c | /FinalCode/FinalCode.ino | e6649ea8073535d0d568da72a9ba9e905b47024a | [] | no_license | lemonbabu/Inteligent-power-management-system | 735f563eda8577db0f279809d22ae431da8f99cb | 474e03258462bb33565f16512ec76a8157578228 | refs/heads/master | 2020-12-14T12:58:56.752882 | 2020-01-18T15:11:46 | 2020-01-18T15:11:46 | 234,752,612 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,592 | ino |
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#include<SoftwareSerial.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
int n = 0;
String data;
const int light1 = 16, light2 = 5, fan = 4;
float light1Time, light2Time, fanTime;
//Time
const long utcOffsetInSeconds = 3600;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds);
// Set these to run example.
#define FIREBASE_HOST "intelligent-power-management.firebaseio.com"
#define FIREBASE_AUTH "ibAf2DwCd93xvalQqtrwDGP4b9lE6fD6laXcqJUh"
#define WIFI_SSID "X-OR"
#define WIFI_PASSWORD "xor.duet"
void setup() {
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
Serial.print("connected: ");
Serial.println(WiFi.localIP());
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
timeClient.begin();
pinMode(light1, OUTPUT);
pinMode(light2, OUTPUT);
pinMode(fan, OUTPUT);
pinMode(13, OUTPUT);
pinMode(15, INPUT);
}
//Main loop
void loop() {
timeClient.update();
Serial.print(daysOfTheWeek[timeClient.getDay()]);
Serial.print(", ");
if(timeClient.getHours()+5 >= 24)
Serial.print(timeClient.getHours()+5 - 24);
else
Serial.print(timeClient.getHours()+5);
Serial.print(":");
Serial.print(timeClient.getMinutes());
Serial.print(":");
Serial.println(timeClient.getSeconds());
// put your main code here, to run repeatedly:
data = Firebase.getString("Users/Lemon/mode");
//Auto mode
if (data == "auto"){
Serial.println("Auto mode is on.");
}
//Manual Mode
else {
Serial.println("Manual mode is on.");
data = Firebase.getString("Users/Lemon/devices/light1/light");
Serial.println(data);
if(data == "True"){
digitalWrite(light1, HIGH);
}
else{
digitalWrite(light1, LOW);
}
data = Firebase.getString("Users/Lemon/devices/light2/light");
Serial.println(data);
if(data == "True"){
digitalWrite(light2, HIGH);
}
else{
digitalWrite(light2, LOW);
}
data = Firebase.getString("Users/Lemon/devices/fan1/fan");
Serial.println(data);
if(data == "True"){
digitalWrite(fan, HIGH);
}
else{
digitalWrite(fan, LOW);
}
}
delay(1000);
}
void sensor(){
}
| [
"noreply@github.com"
] | lemonbabu.noreply@github.com |
5025d8227a17badea8fdf32a04d257f8e0c62204 | b84c209f273fd3e627181c287f98d5a7c0bc89ab | /LIFsim/source/SpikingTempotron.cpp | 4f8fd3a544b17951e903f026e99e58e94ae99bc3 | [] | no_license | ranr01/Rubin2017Balanced | 2676492aaf6fcf970e3d84cfd8dc50f97c488c68 | e3725170abd3c16309b189ebdf4a48bdd1835e0f | refs/heads/master | 2021-08-29T17:35:39.277671 | 2017-12-14T13:38:22 | 2017-12-14T13:38:22 | 114,165,860 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,023 | cpp | //#include <iostream>
#include <deque>
#include <numeric>
#include <stdexcept>
#include "SpikingTempotron.h"
#include "Spike2.h"
#include "Tempotron2.h"
#include "NR.h"
//#include "InputLayer2.h"
using namespace std;
void SpikingTempotron::activate() {
//removed from this code since no learning is needed
}
void SpikingTempotron::activate_noTeacher() {
static long double lnD, lnD_s, t_max, V_cur, V_next;
static std::deque< Spike2 >::const_iterator spikesEnd;
static int dtb;
KminusTh f(this);
crossings_.clear();
#ifdef DEBUG
int stage;
#endif
spikesEnd = spikes_->end();
currentSpike_ = spikes_->begin();
nextSpike_ = currentSpike_;
++nextSpike_;
timeBlock_ = 0;
expTimeBlock_taum_ = std::exp((long double) (-spikes_->timeBlockSize / K_->tau));
expTimeBlock_taus_ = std::exp((long double) (-spikes_->timeBlockSize / K_->tau_s));
TB_BeginTime_ = 0.0;
reset_D_ = 0.0;
D = 0.0;
D_s = 0.0;
try {
while (nextSpike_ != spikesEnd) {
if (currentSpike_->timeBlock > timeBlock_) {
D *= std::pow(expTimeBlock_taum_, currentSpike_->timeBlock - timeBlock_);
reset_D_ *= std::pow(expTimeBlock_taum_, currentSpike_->timeBlock - timeBlock_);
D_s *= std::pow(expTimeBlock_taus_, currentSpike_->timeBlock - timeBlock_);
timeBlock_ = currentSpike_->timeBlock;
TB_BeginTime_ = timeBlock_ * spikes_->timeBlockSize;
}
D += w_[ currentSpike_->affarent ] * currentSpike_->tau_exponent;
D_s += w_[ currentSpike_->affarent ] * currentSpike_->tau_s_exponent;
if ((D > 0.0) && (D_s > 0.0)) {
lnD = std::log(D);
lnD_s = std::log(D_s);
t_max = K_->t_max_fac * (lnD_s - lnD + K_->lntt);
if (t_max > currentSpike_->time) {
dtb = nextSpike_->timeBlock - currentSpike_->timeBlock;
if (t_max <= nextSpike_->time + dtb * spikes_->timeBlockSize) {
V_max_ = std::exp(K_->v_max_fac * (K_->tau * lnD - K_->tau_s * lnD_s));
if (V_max_ > threshold_) {
#ifdef DEBUG
stage = 1;
#endif
crossings_.push_back(TB_BeginTime_ + NR::Math::find_x(currentSpike_->time, t_max, f));
reset_V(crossings_.back());
}
} else {
V_next = K_->Vo * (D / nextSpike_->tau_exponent * std::pow(expTimeBlock_taum_, dtb) -
D_s / nextSpike_->tau_s_exponent * std::pow(expTimeBlock_taus_, dtb));
if (V_next > threshold_) {
#ifdef DEBUG
stage = 2;
#endif
crossings_.push_back(TB_BeginTime_ + NR::Math::find_x(currentSpike_->time, nextSpike_->time + dtb * spikes_->timeBlockSize, f));
reset_V(crossings_.back());
}
}
}
}
++currentSpike_;
++nextSpike_;
}
if (currentSpike_->timeBlock > timeBlock_) {
D *= std::pow(expTimeBlock_taum_, currentSpike_->timeBlock - timeBlock_);
reset_D_ *= std::pow(expTimeBlock_taum_, currentSpike_->timeBlock - timeBlock_);
D_s *= std::pow(expTimeBlock_taus_, currentSpike_->timeBlock - timeBlock_);
timeBlock_ = currentSpike_->timeBlock;
TB_BeginTime_ = timeBlock_ * spikes_->timeBlockSize;
}
D += w_[ currentSpike_->affarent ] * currentSpike_->tau_exponent;
D_s += w_[ currentSpike_->affarent ] * currentSpike_->tau_s_exponent;
if ((D > 0.0) && (D_s > 0.0)) {
lnD = std::log(D);
lnD_s = std::log(D_s);
t_max = K_->t_max_fac * (lnD_s - lnD + K_->lntt);
if (t_max > currentSpike_->time) {
V_max_ = std::exp(K_->v_max_fac * (K_->tau * lnD - K_->tau_s * lnD_s));
if (V_max_ > threshold_) {
#ifdef DEBUG
stage = 7;
#endif
crossings_.push_back(TB_BeginTime_ + NR::Math::find_x(currentSpike_->time, t_max, f));
reset_V_last_spike(crossings_.back());
}
}
}
} catch (std::runtime_error & e) {
cout << " Error in activate_noTeacher()\n";
#ifdef DEBUG
cout << "stage=" << stage;
#endif
cout << " S" << currentSpike_ - spikes_->begin() << " " << D << " " << D_s << "\n"
<< e.what() << "\n"
<< " t_max=" << t_max << " V_next=" << V_next << " V_max_=" << V_max_ << " thershold_=" << threshold_ << "\n";
cout << "curruntSpike: " << *currentSpike_ << '\n'
<< "nextSpike: " << *nextSpike_ << "\n"
<< "End=" << (nextSpike_ == spikesEnd) << endl;
throw;
}
++currentSpike_;
}
int SpikingTempotron::learn() {
//Removed from this code since no learning is needed
return 0;
}
bool SpikingTempotron::td_err(int count) {
static long double V;
if (count) {
V = (D_td_[count] / spikes_->tds[count]->tau_exponent - D_s_td_[count] / spikes_->tds[count]->tau_s_exponent);
V -= (D_td_[count - 1] / spikes_->tds[count - 1]->tau_exponent - D_s_td_[count - 1] / spikes_->tds[count - 1]->tau_s_exponent)
* spikes_->tds[count - 1]->tau_exponent / spikes_->tds[count]->tau_exponent;
return ((V * K_->Vo) < threshold_);
} else
return ((K_->Vo * (D_td_[count] / spikes_->tds[count]->tau_exponent - D_s_td_[count] / spikes_->tds[count]->tau_s_exponent)) < threshold_);
}
void SpikingTempotron::reset_V(double t) {
static long double lnD, lnD_s, t_max, V_next, dD;
static int dtb;
KminusTh f(this);
#ifdef DEBUG
static int spike_count = 0;
#endif
t -= TB_BeginTime_;
dD = (long double)(fraction_reset*threshold_ / K_->Vo) * std::exp((long double) (t / K_->tau));
D -= dD;
reset_D_ -= dD;
if ((D > 0.0) && (D_s > 0.0)) {
lnD = std::log(D);
lnD_s = std::log(D_s);
t_max = K_->t_max_fac * (lnD_s - lnD + K_->lntt);
if (t_max > t) {
dtb = nextSpike_->timeBlock - timeBlock_;
if (t_max <= nextSpike_->time + dtb * spikes_->timeBlockSize) {
V_max_ = std::exp(K_->v_max_fac * (K_->tau * lnD - K_->tau_s * lnD_s));
if (V_max_ > threshold_) {
#ifdef DEBUG
++spike_count;
long double V_t = K_->Vo * ( D * std::exp((long double)(-t/K_->tau)) - D_s * std::exp((long double)(-t/K_->tau_s)));
cout<<"Multiple Spikes (t_max): t="<<t<<" V(t)="<<V_t<<" t_max="<<t_max<<" V_max="<<V_max_<<" spike_count="<<spike_count<<endl;
#endif
crossings_.push_back(TB_BeginTime_ + NR::Math::find_x(t, t_max, f));
reset_V(crossings_.back());
}
} else {
V_next = K_->Vo * (D / nextSpike_->tau_exponent * std::pow(expTimeBlock_taum_, dtb) -
D_s / nextSpike_->tau_s_exponent * std::pow(expTimeBlock_taus_, dtb));
if (V_next > threshold_) {
#ifdef DEBUG
++spike_count;
long double V_t = K_->Vo * ( D * std::exp((long double)(-t/K_->tau)) - D_s * std::exp((long double)(-t/K_->tau_s)));
cout<<"Multiple Spikes (t_next): t="<<t<<" V(t)="<<V_t<<" t_next="<<nextSpike_->time + dtb * spikes_->timeBlockSize
<<" V_next="<<V_next<<" spike_count="<<spike_count<<endl;
#endif
crossings_.push_back(TB_BeginTime_ + NR::Math::find_x(t, nextSpike_->time + dtb * spikes_->timeBlockSize, f));
reset_V(crossings_.back());
}
}
}
}
#ifdef DEBUG
spike_count=0;
#endif
}
void SpikingTempotron::reset_V_last_spike(double t) {
static long double lnD, lnD_s, t_max, dD;
KminusTh f(this);
t -= TB_BeginTime_;
dD = (fraction_reset*threshold_ / K_->Vo) * std::exp((long double) (t / K_->tau));
D -= dD;
reset_D_ -= dD;
if ((D > 0.0) && (D_s > 0.0)) {
lnD = std::log(D);
lnD_s = std::log(D_s);
t_max = K_->t_max_fac * (lnD_s - lnD + K_->lntt);
if (t_max > t) {
V_max_ = std::exp(K_->v_max_fac * (K_->tau * lnD - K_->tau_s * lnD_s));
if (V_max_ > threshold_) {
crossings_.push_back(TB_BeginTime_ + NR::Math::find_x(t, t_max, f));
reset_V_last_spike(crossings_.back());
}
}
}
}
void SpikingTempotron::teacher_reset_V(long double Vtd) {
static long double dD;
D_td_[td_count_] = D - reset_D_;
D_s_td_[td_count_] = D_s;
V_td_[td_count_] = Vtd;
dD = (Vtd / K_->Vo) * this->tdSpike_->tau_exponent;
D -= dD;
reset_D_ -= dD;
}
| [
"rr2980@columbia.edu"
] | rr2980@columbia.edu |
7ae38fc1f7dee984c5a26326572a0620a10b0cbf | dfe1f796a54143e5eb8661f3328ad29dbfa072d6 | /psx/_dump_/25/_dump_c_src_/diabpsx/psxsrc/primpool.cpp | b5ba00654692d5dd2d75282ade51e19cdebc3c33 | [
"Unlicense"
] | permissive | diasurgical/scalpel | 0f73ad9be0750ce08eb747edc27aeff7931800cd | 8c631dff3236a70e6952b1f564d0dca8d2f4730f | refs/heads/master | 2021-06-10T18:07:03.533074 | 2020-04-16T04:08:35 | 2020-04-16T04:08:35 | 138,939,330 | 15 | 7 | Unlicense | 2019-08-27T08:45:36 | 2018-06-27T22:30:04 | C | UTF-8 | C++ | false | false | 3,088 | cpp | // C:\diabpsx\PSXSRC\PRIMPOOL.CPP
#include "types.h"
// address: 0x8007BDB4
// line start: 142
// line end: 179
unsigned char PRIM_Open__FiiiP10SCREEN_ENVUl(int Prims, int OtSize, int Depth, struct SCREEN_ENV *Scr, unsigned long MemType) {
{
{
{
{
// register: 16
register int f;
}
}
}
}
}
// address: 0x8007BED0
// line start: 186
// line end: 204
unsigned char InitPrimBuffer__FP11PRIM_BUFFERii(struct PRIM_BUFFER *Pr, int Prims, int OtSize) {
}
// address: 0x8007BFAC
// line start: 215
// line end: 237
void PRIM_Clip__FP4RECTi(struct RECT *R, int Depth) {
// register: 16
// size: 0xC
register struct DR_MODE *DrArea;
// address: 0xFFFFFFE8
// size: 0x8
auto struct RECT RealRect;
}
// address: 0x8007C0D4
// line start: 247
// line end: 248
unsigned char PRIM_GetCurrentScreen__Fv() {
}
// address: 0x8007C0E0
// line start: 256
// line end: 265
void PRIM_FullScreen__Fi(int Depth) {
// address: 0xFFFFFFF0
// size: 0x8
auto struct RECT R;
}
// address: 0x8007C11C
// line start: 278
// line end: 341
void PRIM_Flush__Fv() {
// register: 16
// size: 0x1C
register struct PRIM_BUFFER *Pb;
}
// address: 0x8007C324
// line start: 365
// line end: 366
unsigned long *PRIM_GetCurrentOtList__Fv() {
}
// address: 0x8007C330
// line start: 374
// line end: 376
void ClearPbOnDrawSync(struct PRIM_BUFFER *Pb) {
}
// address: 0x8007C36C
// line start: 380
// line end: 381
unsigned char ClearedYet__Fv() {
}
// address: 0x8007C378
// line start: 389
// line end: 393
void PrimDrawSycnCallBack() {
}
// address: 0x8007C398
// line start: 403
// line end: 404
void SendDispEnv__Fv() {
}
// address: 0x8007C3BC
// size: 0x18
// line start: 453
// line end: 457
struct POLY_F4 *PRIM_GetNextPolyF4__Fv() {
// register: 2
// size: 0x18
register struct POLY_F4 *RetPage;
}
// address: 0x8007C3D4
// size: 0x28
// line start: 461
// line end: 465
struct POLY_FT4 *PRIM_GetNextPolyFt4__Fv() {
// register: 2
// size: 0x28
register struct POLY_FT4 *RetPage;
}
// address: 0x8007C3EC
// size: 0x34
// line start: 469
// line end: 473
struct POLY_GT4 *PRIM_GetNextPolyGt4__Fv() {
// register: 2
// size: 0x34
register struct POLY_GT4 *RetPage;
}
// address: 0x8007C404
// size: 0x24
// line start: 478
// line end: 482
struct POLY_G4 *PRIM_GetNextPolyG4__Fv() {
// register: 2
// size: 0x24
register struct POLY_G4 *RetPage;
}
// address: 0x8007C41C
// size: 0x14
// line start: 486
// line end: 490
struct POLY_F3 *PRIM_GetNextPolyF3__Fv() {
// register: 2
// size: 0x14
register struct POLY_F3 *RetPage;
}
// address: 0x8007C434
// size: 0xC
// line start: 503
// line end: 507
struct DR_MODE *PRIM_GetNextDrArea__Fv() {
// register: 2
// size: 0xC
register struct DR_MODE *RetPage;
}
// address: 0x8007C44C
// line start: 511
// line end: 540
bool ClipRect__FRC4RECTR4RECT(struct RECT *ClipRect, struct RECT *RectToClip) {
}
// address: 0x8007C560
// line start: 546
// line end: 557
bool IsColiding__FRC4RECTT0(struct RECT *ClipRect, struct RECT *NewRect) {
}
| [
"rnd0x00@gmail.com"
] | rnd0x00@gmail.com |
ff8403971a5402f6919713d49d6e0faa877ad9ef | ed25a200fca8ccc7ab1f5641ea5bf2da9c093345 | /src/forthy2/forms/splice.cpp | 1983f0537a9be009cc2e74f6f26db3340370a55c | [
"MIT"
] | permissive | stjordanis/forthy2 | aad43694768db3670037513db52463c962baf506 | 36464f548cf092bc03f580df87f66f1e71cf4dee | refs/heads/master | 2022-03-26T11:50:33.162342 | 2019-12-24T16:00:53 | 2019-12-24T16:00:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 461 | cpp | #include "forthy2/cx.hpp"
#include "forthy2/forms/splice.hpp"
namespace forthy2 {
SpliceForm::SpliceForm(const Pos &pos): Form(pos) {}
Node<Op> &SpliceForm::compile(Cx &cx, Forms &in, Node<Op> &out) {
throw ESys(pos, "Missing splice");
}
Form &SpliceForm::quote(Cx &cx, Pos pos) { return cx.quote_form.get(pos, *this); }
void SpliceForm::dealloc(Cx &cx) { cx.splice_form.put(*this); }
void SpliceForm::write(ostream &out) { out << '%'; }
}
| [
"andreas.gone.wild@gmail.com"
] | andreas.gone.wild@gmail.com |
b5b90d0197e95c9e8727a9f023ff814e3102ace6 | 7011a092ce4d787c7b0bf68ef901bcc02a56e4aa | /list.h | b8e28700aac0ebcf08c238334be855ba5089de3f | [] | no_license | duule/LMS | 9063389233827737a07b8ddb86a87cc8cf3b4e4d | dd9a9a1fa3027bc4303dc4b319edfa3cfcf670cc | refs/heads/master | 2021-06-04T02:08:35.556317 | 2016-09-02T19:27:52 | 2016-09-02T19:27:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 548 | h | #ifndef LIST_H
#define LIST_H
#include <iostream>
#include "readerinfo.h"
class List
{
class Node{
public:
Node* next;
Node* front;
ReaderInfo* info;
Node(ReaderInfo* info, Node* front, Node* next){
this->info = info;
this->front = front;
this->next = next;
}
};
Node* Head;
Node* Tail;
public:
List();
void append(ReaderInfo* info);
void remove(std::string id);
ReaderInfo* get(std::string id);
void each();
};
#endif // LIST_H
| [
"1326435210@qq.com"
] | 1326435210@qq.com |
a4deb3e8e2c9b497dbc45ff41eb8409c82e2a7e8 | 5d0550a3a1eb1611f9cf5b9410cccc9bd30afdcc | /TcpServer/MessageParser.cpp | 00a25e7dc89d7a7d08e99007efae6ec95472d29f | [] | no_license | guxingjian/CCProject | 0aa740e41392b5e22c8f34ddf858ee51f22e4ad3 | 355500473743cdb3f3be3e46db01b2bffa4cd45e | refs/heads/master | 2021-01-20T19:59:40.559814 | 2016-06-03T15:03:50 | 2016-06-03T15:03:50 | 60,353,129 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,379 | cpp | #include "MessageParser.h"
#include <iostream>
using namespace std;
MessageParser::MessageParser(int socket_fd)
{
this->m_nFd = socket_fd;
this->m_structSM.messageType = 0;
parse();
}
MessageParser::~MessageParser()
{
}
void MessageParser::parse()
{
cout << "start parse" << endl;
unsigned char tempBuffer[8] = {};
memset(tempBuffer, 0, sizeof(tempBuffer));
int nReadByte = read(this->m_nFd, tempBuffer, sizeof(tempBuffer));
if(nReadByte < 0)
{
cout << "read error!" << endl;
return ;
}
this->m_structSM.messageType = *((unsigned int*)tempBuffer);
this->m_structSM.messageLength = *((unsigned int*)(tempBuffer + (sizeof(unsigned int))));
unsigned int nTotalLength = this->m_structSM.messageLength - 8;
cout << "recive head data, messageType: " << this->m_structSM.messageType << "messageLength: " << this->m_structSM.messageLength << endl;
if(1 == m_structSM.messageType ||
2 == m_structSM.messageType ||
3 == m_structSM.messageType) // 登陆, 退出, 文字消息
{
char* bodyBuffer = new char[nTotalLength + 1];
memset(bodyBuffer, 0, nTotalLength + 1);
unsigned int nTotalReadLen = 0;
while(nTotalReadLen < nTotalLength)
{
nReadByte = read(this->m_nFd, bodyBuffer + nTotalReadLen, nTotalLength - nTotalReadLen);
if(-1 == nReadByte)
break;
nTotalReadLen += (unsigned int)nReadByte;
}
m_structSM.messageBody = bodyBuffer;
cout << "recive body data" << endl;
}
else if(4 == m_structSM.messageType) // 声音消息
{
unsigned char* bodyBuffer = new unsigned char[nTotalLength];
memset(bodyBuffer, 0, nTotalLength);
unsigned int nTotalReadLen = 0;
while(nTotalReadLen < nTotalLength)
{
nReadByte = read(this->m_nFd, bodyBuffer + nTotalReadLen, nTotalLength - nTotalReadLen);
if(-1 == nReadByte)
break;
nTotalReadLen += (unsigned int)nReadByte;
}
m_structSM.messageBody = bodyBuffer;
cout << "recive body data" << endl;
}
else if(5 == m_structSM.messageType)
{
}
else if(6 == m_structSM.messageType)
{
}
}
| [
"heqingzhao1990@sina.com"
] | heqingzhao1990@sina.com |
12c36215474eeced16bf853562ea3a137404e776 | a3345e2d62f9382046d465c951482529706baed2 | /Untitled1.cpp | 6bfa67a868f5d056debb2982248730387b5d62b3 | [] | no_license | tuyen1998/CTDLGT | ecdae162f9e85610de56eb8dbed5ce17129dca20 | f9dee42d4306bbd69c8e11f1fa5fd58d5b487256 | refs/heads/master | 2020-03-29T08:21:07.506783 | 2018-09-21T03:43:36 | 2018-09-21T03:43:36 | 149,706,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 569 | cpp | #include <stdio.h>
#include <math.h>
int main()
{
int n,nn,i;
printf("Nhap n:");
scanf("%d",&n);
nn=abs(n);
printf("\nCac uoc la: 1 -1 ");
if (nn%2==0)
for (i=2;i<=(int)sqrt(nn);i++)
if (nn%i==0)
if (i*i!=nn) printf(" %d %d %d %d ",i,-1*i,nn/i,-nn/i);
else printf(" %d %d ",i,-1*i);
if (nn%2!=0)
for (i=3;i<=(int)sqrt(nn);i=i+2)
if (nn%i==0)
if (i*i!=nn) printf(" %d %d %d %d ",i,-1*i,nn/i,-nn/i);
else printf(" %d %d ",i,-1*i);
printf(" %d %d ",nn,-1*nn);
return 0;
}
| [
"35531872+tuyen1998@users.noreply.github.com"
] | 35531872+tuyen1998@users.noreply.github.com |
5cd5e5ae764283fde4b30fee8ba9785d84d45e40 | ecd4b1f46eba598d241ac3597ed87e6104dc332d | /main.cpp | 5238397229422bd3644fa45412c00f9cad86204d | [] | no_license | GromovIgor/la2 | 7a5ab8042d6ded2a5d25b0d426d0981ed45e3ef6 | b331479784a08c72609a7b0249d60916c02508f2 | refs/heads/master | 2021-01-01T19:56:58.134734 | 2014-11-24T05:21:52 | 2014-11-24T05:21:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 196 | cpp | #include <QtGui>
#include <QApplication>
#include "graphic.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Graphic window;
window.show();
return app.exec();
}
| [
"skilled.development@gmail.com"
] | skilled.development@gmail.com |
5588d8295447f5042efbe6f9b0e78373614a587b | 727c167cebbc2388045aeea054695a5b0d6eabf9 | /MyCommen/GdiPlus/gdiplus20071007/include/GdipFont.hpp | 337249e3657d7fc7e880d21d373c297638eee5f8 | [] | no_license | endlesslove137/Delphi | 6ab86398b12d45548392d2cad3bb8b9208f5898f | 886cf8b4f2a6a3dc207926f89d9e68d0acfcf690 | refs/heads/master | 2020-04-19T23:34:16.689349 | 2019-01-31T09:39:51 | 2019-01-31T09:39:51 | 168,499,620 | 1 | 2 | null | null | null | null | GB18030 | C++ | false | false | 3,784 | hpp | /**************************************************************************\
*
* Module Name:
*
* GdipFont.hpp
*
* 2007年,湖北省公安县统计局 毛泽发 于大连
*
\**************************************************************************/
#ifndef GdipFontHPP
#define GdipFontHPP
inline
float __fastcall TGpFont::GetSize(void)
{
CheckStatus(GdipGetFontSize(Native, &Result.rFLOAT));
return Result.rFLOAT;
}
inline
TFontStyles __fastcall TGpFont::GetStyle(void)
{
CheckStatus(GdipGetFontStyle(Native, &Result.rINT));
return *(TFontStyles*)&Result.rINT;
}
inline
TUnit __fastcall TGpFont::GetUnit(void)
{
CheckStatus(GdipGetFontUnit(Native, (GdiplusSys::Unit*)&Result.rINT));
return (TUnit)Result.rINT;
}
inline
WideString __fastcall TGpFont::GetName()
{
GdipGetFamily(Native, &Result.rNATIVE);
WCHAR str[LF_FACESIZE];
CheckStatus(GdipGetFamilyName(Result.rNATIVE, str, 0));
return WideString(str);
}
inline
__fastcall TGpFont::TGpFont(HDC DC)
{
CheckStatus(GdipCreateFontFromDC(DC, &Native));
}
inline
__fastcall TGpFont::TGpFont(HDC DC, LOGFONTA* logfont)
{
if (logfont)
CheckStatus(GdipCreateFontFromLogfontA(DC, logfont, &Native));
else
CheckStatus(GdipCreateFontFromDC(DC, &Native));
}
inline
__fastcall TGpFont::TGpFont(HDC DC, LOGFONTW* logfont)
{
if (logfont)
CheckStatus(GdipCreateFontFromLogfontW(DC, logfont, &Native));
else
CheckStatus(GdipCreateFontFromDC(DC, &Native));
}
inline
__fastcall TGpFont::TGpFont(HDC DC, HFONT font)
{
LOGFONTA lf;
if (font && GetObjectA(font, sizeof(LOGFONTA), &lf))
CheckStatus(GdipCreateFontFromLogfontA(DC, &lf, &Native));
else
CheckStatus(GdipCreateFontFromDC(DC, &Native));
}
inline
__fastcall TGpFont::TGpFont(TGpFontFamily* family, float emSize, TFontStyles style, TUnit unit)
{
CheckStatus(GdipCreateFont(ObjectNative(family), emSize,
SETTOBYTE(style), (GdiplusSys::Unit)(int)unit, &Native));
}
inline
__fastcall TGpFont::TGpFont(WideString familyName, float emSize,
TFontStyles style, TUnit unit, TGpFontCollection* fontCollection)
{
GpFontFamily *nativeFamily;
TStatus Status = GdipCreateFontFamilyFromName(familyName.c_bstr(),
fontCollection? fontCollection->Native : NULL, &nativeFamily);
bool IsFree = Status == Ok;
if (Status != Ok)
nativeFamily = TGpFontFamily::GenericSansSerif()->Native;
Status = GdipCreateFont(nativeFamily, emSize, SETTOBYTE(style),
(GdiplusSys::Unit)(int)unit, &Native);
if (Status != Ok)
{
nativeFamily = TGpFontFamily::GenericSansSerif()->Native;
Status = GdipCreateFont(nativeFamily, emSize, SETTOBYTE(style),
(GdiplusSys::Unit)(int)unit, &Native);
}
if (IsFree) GdipDeleteFontFamily(nativeFamily);
else CheckStatus(Status);
}
inline
__fastcall TGpFont::~TGpFont(void)
{
GdipDeleteFont(Native);
}
inline
LOGFONTA __fastcall TGpFont::GetLogFontA(TGpGraphics* g)
{
LOGFONTA la;
CheckStatus(GdipGetLogFontA(Native, g? g->Native : NULL, &la));
return la;
}
inline
LOGFONTW __fastcall TGpFont::GetLogFontW(TGpGraphics* g)
{
LOGFONTW lw;
CheckStatus(GdipGetLogFontW(Native, g? g->Native : NULL, &lw));
return lw;
}
inline
TGpFont* __fastcall TGpFont::Clone(void)
{
return new TGpFont(Native, (TCloneAPI)GdipCloneFont);
}
inline
bool __fastcall TGpFont::IsAvailable(void)
{
return Native;
}
inline
float __fastcall TGpFont::GetHeight(TGpGraphics* graphics)
{
CheckStatus(GdipGetFontHeight(Native, ObjectNative(graphics), &Result.rFLOAT));
return Result.rFLOAT;
}
inline
float __fastcall TGpFont::GetHeight(float dpi)
{
CheckStatus(GdipGetFontHeightGivenDPI(Native, dpi, &Result.rFLOAT));
return Result.rFLOAT;
}
inline
void __fastcall TGpFont::GetFamily(TGpFontFamily* family)
{
if (!family) CheckStatus(InvalidParameter);
CheckStatus(GdipGetFamily(Native, &family->Native));
}
#endif
| [
"endlesslove137@icloud.com"
] | endlesslove137@icloud.com |
a09cf6ab0941a13d59bbe38d21d2196ebf7b55b3 | 619023beac5024be874417cbbb4c878519b78777 | /iolib/He/he.cpuf.cpp | 95e98602fa6ac52865b0b35a25c6d124af68d03e | [
"Apache-2.0",
"MIT",
"MS-PL",
"Libpng",
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | SerVB/pph-native | 73feea2036d7d5597b651f1c004bc4a811212bf4 | 22a6ff265158c57413c4e74443b6c2fd1538ff29 | refs/heads/master | 2023-08-29T15:26:11.981956 | 2021-11-04T15:14:04 | 2021-11-04T15:14:04 | 420,064,860 | 2 | 0 | null | null | null | null | MacCentralEurope | C++ | false | false | 68,877 | cpp | /*
* This file is a part of Pocket Heroes Game project
* http://www.pocketheroes.net
* https://code.google.com/p/pocketheroes/
*
* Copyright 2004-2010 by Robert Tarasov and Anton Stuk (iO UPG)
*
* 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 "he.std.h"
#include "he.cpuf.h"
iCPUFeatures gCPUFeatures;
/* Symbolic constants for feature flags in CPUID standard feature flags */
#define CPUID_STD_FPU 0x00000001
#define CPUID_STD_VME 0x00000002
#define CPUID_STD_DEBUGEXT 0x00000004
#define CPUID_STD_4MPAGE 0x00000008
#define CPUID_STD_TSC 0x00000010
#define CPUID_STD_MSR 0x00000020
#define CPUID_STD_PAE 0x00000040
#define CPUID_STD_MCHKXCP 0x00000080
#define CPUID_STD_CMPXCHG8B 0x00000100
#define CPUID_STD_APIC 0x00000200
#define CPUID_STD_SYSENTER 0x00000800
#define CPUID_STD_MTRR 0x00001000
#define CPUID_STD_GPE 0x00002000
#define CPUID_STD_MCHKARCH 0x00004000
#define CPUID_STD_CMOV 0x00008000
#define CPUID_STD_PAT 0x00010000
#define CPUID_STD_PSE36 0x00020000
#define CPUID_STD_MMX 0x00800000
#define CPUID_STD_FXSAVE 0x01000000
#define CPUID_STD_SSE 0x02000000
#define CPUID_STD_SSE2 0x04000000
/* Symbolic constants for feature flags in CPUID extended feature flags */
#define CPUID_EXT_3DNOW 0x80000000
#define CPUID_EXT_AMD_3DNOWEXT 0x40000000
#define CPUID_EXT_AMD_MMXEXT 0x00400000
/* Symbolic constants for application specific feature flags */
#define FEATURE_CPUID 0x00000001
#define FEATURE_STD_FEATURES 0x00000002
#define FEATURE_EXT_FEATURES 0x00000004
#define FEATURE_TSC 0x00000010
#define FEATURE_MMX 0x00000020
#define FEATURE_CMOV 0x00000040
#define FEATURE_3DNOW 0x00000080
#define FEATURE_3DNOWEXT 0x00000100
#define FEATURE_MMXEXT 0x00000200
#define FEATURE_SSEFP 0x00000400
#define FEATURE_K6_MTRR 0x00000800
#define FEATURE_P6_MTRR 0x00001000
#define FEATURE_SSE2 0x00002000
/* get_feature_flags extracts all features the application wants to know
about from CPUID information and returns a bit string of application
specific feature bits. The following design criteria apply:
1. Processor capabilities should be directly derived from CPUID feature bits
wherever possible, instead of being derived from vendor strings and
processor signatures. However, some features are not indicated by CPUID
feature flags (whether basic or extended) and do require looking at
vendor strings and processor signatures. Applications may also choose to
implement pseudo capabilities, for example indicating performance
levels.
2. The basic feature flags returned by CPUID function #1 are compatible
across all x86 processor vendors with very few exceptions and therefore
common feature checks for things like MMX or TSC support do not require
a vendor check before evaluating the basic feature flag information.
If unsure about a particular feature, review the processor vendor's
literature.
3. 3DNow! is an open standard. Therefore 3DNow! capabilities are indicated
by bit 31 in the extended feature flags regardless of processor vendor.
4. Applications should always treat the floating-point part of SSE and
the MMX part of SSE as separate capabilities because SSE FP requires
OS support that might not be available, while SSE MMX works with all
operating systems.
*/
uint32 get_feature_flags(void)
{
uint32 result = 0;
uint32 signature = 0;
char vendor[13] = "UnknownVendr"; /* Needs to be exactly 12 chars */
/* Define known vendor strings here */
char vendorAMD[13] = "AuthenticAMD"; /* Needs to be exactly 12 chars */
/*;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Step 1: Check if processor has CPUID support. Processor faults
;; with an illegal instruction exception if the instruction is not
;; supported. This step catches the exception and immediately returns
;; with feature string bits with all 0s, if the exception occurs.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;*/
__try
{
__asm xor eax, eax
__asm xor ebx, ebx
__asm xor ecx, ecx
__asm xor edx, edx
__asm cpuid
}
__except (/*EXCEPTION_EXECUTE_HANDLER*/0)
{
return (0);
}
result |= FEATURE_CPUID;
__asm
{
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//;; Step 2: Check if CPUID supports function 1 (signature/std features)
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
xor eax, eax //; CPUID function #0
cpuid //; largest std func/vendor string
mov dword ptr [vendor], ebx //; save
mov dword ptr [vendor+4], edx //; vendor
mov dword ptr [vendor+8], ecx //; string
test eax, eax //; largest standard function==0?
jz $no_standard_features //; yes, no standard features func
or [result], FEATURE_STD_FEATURES //; does have standard features
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//;; Step 3: Get standard feature flags and signature
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov eax, 1 //; CPUID function #1
cpuid //; get signature/std feature flgs
mov [signature], eax //; save processor signature
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//;; Step 4: Extract desired features from standard feature flags
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//;; Check for time stamp counter support
mov ecx, CPUID_STD_TSC //; bit 4 indicates TSC support
and ecx, edx //; supports TSC ? CPUID_STD_TSC:0
neg ecx //; supports TSC ? CY : NC
sbb ecx, ecx //; supports TSC ? 0xffffffff:0
and ecx, FEATURE_TSC //; supports TSC ? FEATURE_TSC:0
or [result], ecx //; merge into feature flags
//;; Check for MMX support
mov ecx, CPUID_STD_MMX //; bit 23 indicates MMX support
and ecx, edx //; supports MMX ? CPUID_STD_MMX:0
neg ecx //; supports MMX ? CY : NC
sbb ecx, ecx //; supports MMX ? 0xffffffff:0
and ecx, FEATURE_MMX //; supports MMX ? FEATURE_MMX:0
or [result], ecx //; merge into feature flags
//;; Check for CMOV support
mov ecx, CPUID_STD_CMOV //; bit 15 indicates CMOV support
and ecx, edx //; supports CMOV?CPUID_STD_CMOV:0
neg ecx //; supports CMOV ? CY : NC
sbb ecx, ecx //; supports CMOV ? 0xffffffff:0
and ecx, FEATURE_CMOV //; supports CMOV ? FEATURE_CMOV:0
or [result], ecx //; merge into feature flags
//;; Check support for P6-style MTRRs
mov ecx, CPUID_STD_MTRR //; bit 12 indicates MTRR support
and ecx, edx //; supports MTRR?CPUID_STD_MTRR:0
neg ecx //; supports MTRR ? CY : NC
sbb ecx, ecx //; supports MTRR ? 0xffffffff:0
and ecx, FEATURE_P6_MTRR //; supports MTRR ? FEATURE_MTRR:0
or [result], ecx //; merge into feature flags
//;; Check for initial SSE support. There can still be partial SSE
//;; support. Step 9 will check for partial support.
mov ecx, CPUID_STD_SSE //; bit 25 indicates SSE support
and ecx, edx //; supports SSE ? CPUID_STD_SSE:0
neg ecx //; supports SSE ? CY : NC
sbb ecx, ecx //; supports SSE ? 0xffffffff:0
and ecx, (FEATURE_MMXEXT+FEATURE_SSEFP) //; supports SSE ?
//; FEATURE_MMXEXT+FEATURE_SSEFP:0
or [result], ecx //; merge into feature flags
//;; Check for SSE2 support
mov ecx, CPUID_STD_SSE2 //; bit 26 indicates SSE2 support
and ecx, edx //; supports SSE2 ? CPUID_STD_SSE2 : 0
neg ecx //; supports SSE2 ? CY : NC
sbb ecx, ecx //; supports SSE2 ? 0xffffffff:0
and ecx, (FEATURE_SSE2) //; supports SSE2 ? FEATURE_SSE2 : 0
or [result], ecx //; merge into feature flags
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//;; Step 5: Check for CPUID extended functions
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov eax, 0x80000000 //; extended function 0x80000000
cpuid //; largest extended function
cmp eax, 0x80000000 //; no function > 0x80000000 ?
jbe $no_extended_features //; yes, no extended feature flags
or [result], FEATURE_EXT_FEATURES //; does have ext. feature flags
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//;; Step 6: Get extended feature flags
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov eax, 0x80000001 //; CPUID ext. function 0x80000001
cpuid //; EDX = extended feature flags
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//;; Step 7: Extract vendor independent features from extended flags
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//;; Check for 3DNow! support (vendor independent)
mov ecx, CPUID_EXT_3DNOW //; bit 31 indicates 3DNow! supprt
and ecx, edx //; supp 3DNow! ?CPUID_EXT_3DNOW:0
neg ecx //; supports 3DNow! ? CY : NC
sbb ecx, ecx //; supports 3DNow! ? 0xffffffff:0
and ecx, FEATURE_3DNOW //; support 3DNow!?FEATURE_3DNOW:0
or [result], ecx //; merge into feature flags
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//;; Step 8: Determine CPU vendor
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
lea esi, vendorAMD //; AMD's vendor string
lea edi, vendor //; this CPU's vendor string
mov ecx, 12 //; strings are 12 characters
cld //; compare lowest to highest
repe cmpsb //; current vendor str == AMD's ?
jnz $not_AMD //; no, CPU vendor is not AMD
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//;; Step 9: Check AMD specific extended features
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov ecx, CPUID_EXT_AMD_3DNOWEXT //; bit 30 indicates 3DNow! ext.
and ecx, edx //; 3DNow! ext?
neg ecx //; 3DNow! ext ? CY : NC
sbb ecx, ecx //; 3DNow! ext ? 0xffffffff : 0
and ecx, FEATURE_3DNOWEXT //; 3DNow! ext?FEATURE_3DNOWEXT:0
or [result], ecx //; merge into feature flags
test [result], FEATURE_MMXEXT //; determined SSE MMX support?
jnz $has_mmxext //; yes, don't need to check again
//;; Check support for AMD's multimedia instruction set additions
mov ecx, CPUID_EXT_AMD_MMXEXT //; bit 22 indicates MMX extension
and ecx, edx //; MMX ext?CPUID_EXT_AMD_MMXEXT:0
neg ecx //; MMX ext? CY : NC
sbb ecx, ecx //; MMX ext? 0xffffffff : 0
and ecx, FEATURE_MMXEXT //; MMX ext ? FEATURE_MMXEXT:0
or [result], ecx //; merge into feature flags
$has_mmxext:
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//;; Step 10: Check AMD-specific features not reported by CPUID
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
//;; Check support for AMD-K6 processor-style MTRRs
mov eax, [signature] //; get processor signature
and eax, 0xFFF //; extract family/model/stepping
cmp eax, 0x588 //; CPU < AMD-K6-2/CXT ? CY : NC
sbb edx, edx //; CPU < AMD-K6-2/CXT ? 0xffffffff:0
not edx //; CPU < AMD-K6-2/CXT ? 0:0xffffffff
cmp eax, 0x600 //; CPU < AMD Athlon ? CY : NC
sbb ecx, ecx //; CPU < AMD-K6 ? 0xffffffff:0
and ecx, edx //; (CPU>=AMD-K6-2/CXT)&&
//; (CPU<AMD Athlon) ? 0xffffffff:0
and ecx, FEATURE_K6_MTRR //; (CPU>=AMD-K6-2/CXT)&&
//; (CPU<AMD Athlon) ? FEATURE_K6_MTRR:0
or [result], ecx //; merge into feature flags
jmp $all_done //; desired features determined
$not_AMD:
/* Extract features specific to non AMD CPUs */
$no_extended_features:
$no_standard_features:
$all_done:
}
/* The FP part of SSE introduces a new architectural state and therefore
requires support from the operating system. So even if CPUID indicates
support for SSE FP, the application might not be able to use it. If
CPUID indicates support for SSE FP, check here whether it is also
supported by the OS, and turn off the SSE FP feature bit if there
is no OS support for SSE FP.
Operating systems that do not support SSE FP return an illegal
instruction exception if execution of an SSE FP instruction is performed.
Here, a sample SSE FP instruction is executed, and is checked for an
exception using the (non-standard) __try/__except mechanism
of Microsoft Visual C.
*/
if (result & FEATURE_SSEFP)
{
__try
{
__asm _emit 0x0f
__asm _emit 0x56
__asm _emit 0xC0 //;; orps xmm0, xmm0
return (result);
}
__except (/*EXCEPTION_EXECUTE_HANDLER*/0)
{
result &= ~FEATURE_SSEFP;
// If we can not support SSE, then we can not support SSE2.
result &= ~FEATURE_SSE2;
}
}
return (result);
}
iCPUFeatures DetectCPUFeatures(void)
{
uint32 CPU;
iCPUFeatures Features;
Features.Reset();
CPU = get_feature_flags ();
if (CPU & FEATURE_MMX)
Features.x86_MMX = true;
if (CPU & FEATURE_CMOV)
Features.x86_CMOV = true;
if (CPU & FEATURE_3DNOW)
Features.x86_3DNow = true;
// Is FEATURE_3DNOWEXT the same as 3DNow!2 ?
if (CPU & FEATURE_3DNOWEXT)
Features.x86_3DNowExt = true;
// SSE comes in two parts, an extension to MMX (or Integer SSE) and Floating
// Point SSE (actually, the instructions that work on the 128-bit registers)
// Before we say that "SSE is available" we check for both.
// See Note #4 at the beginning of this file, within AMD's comments
// Also, we'd rather refer to MMX, SSE, and SSE2 instead of "MMX, SSE/Int,
// SSE/FPU, SSE2/Int, SSE2/FPU". It's cleaner that way, and only cuts off
// support in a few instances (ie, someone running Windows 95).
if ((CPU & FEATURE_SSEFP) && (CPU & FEATURE_MMXEXT))
Features.x86_SSE = true;
if (CPU & FEATURE_SSE2)
Features.x86_SSE2 = true;
return (Features);
}
void InitCPUFeatures (void)
{
gCPUFeatures = DetectCPUFeatures ();
}
// --------------------------------------------------------
//
// Constructor Functions - CPUInfo Class
//
// --------------------------------------------------------
CPUInfo::CPUInfo ()
{
memset(this,0,sizeof(CPUInfo));
// Check to see if this processor supports CPUID.
if (DoesCPUSupportCPUID ()) {
// Retrieve the CPU details.
RetrieveCPUIdentity ();
RetrieveCPUFeatures ();
if (!RetrieveCPUClockSpeed ()) RetrieveClassicalCPUClockSpeed ();
// Attempt to retrieve cache information.
if (!RetrieveCPUCacheDetails ()) RetrieveClassicalCPUCacheDetails ();
// Retrieve the extended CPU details.
if (!RetrieveExtendedCPUIdentity ()) RetrieveClassicalCPUIdentity ();
RetrieveExtendedCPUFeatures ();
// Now attempt to retrieve the serial number (if possible).
RetrieveProcessorSerialNumber ();
}
}
CPUInfo::~CPUInfo ()
{}
// --------------------------------------------------------
//
// Public Functions - CPUInfo Class
//
// --------------------------------------------------------
iCharT* CPUInfo::GetVendorString ()
{
// Return the vendor string.
return ChipID.Vendor;
}
iCharT* CPUInfo::GetVendorID ()
{
// Return the vendor ID.
switch (ChipManufacturer) {
case Intel:
return _T("Intel Corporation");
case AMD:
return _T("Advanced Micro Devices");
case NSC:
return _T("National Semiconductor");
case Cyrix:
return _T("Cyrix Corp., VIA Inc.");
case NexGen:
return _T("NexGen Inc., Advanced Micro Devices");
case IDT:
return _T("IDT\\Centaur, Via Inc.");
case UMC:
return _T("United Microelectronics Corp.");
case Rise:
return _T("Rise");
case Transmeta:
return _T("Transmeta");
default:
return _T("Unknown Manufacturer");
}
}
iCharT* CPUInfo::GetTypeID ()
{
// Return the type ID of the CPU.
iCharT* szTypeID = new iCharT[32];
_itot(ChipID.Type, szTypeID, 10);
return szTypeID;
}
iCharT* CPUInfo::GetFamilyID ()
{
// Return the family of the CPU present.
iCharT* szFamilyID = new iCharT[32];
_itot(ChipID.Family, szFamilyID, 10);
return szFamilyID;
}
iCharT* CPUInfo::GetModelID ()
{
// Return the model of CPU present.
iCharT* szModelID = new iCharT[32];
_itot(ChipID.Model, szModelID, 10);
return szModelID;
}
iCharT* CPUInfo::GetSteppingCode ()
{
// Return the stepping code of the CPU present.
iCharT* szSteppingCode = new iCharT[32];
_itot(ChipID.Revision, szSteppingCode, 10);
return szSteppingCode;
}
iCharT* CPUInfo::GetExtendedProcessorName ()
{
// Return the stepping code of the CPU present.
return ChipID.ProcessorName;
}
iCharT* CPUInfo::GetProcessorSerialNumber ()
{
// Return the serial number of the processor in hexadecimal: xxxx-xxxx-xxxx-xxxx-xxxx-xxxx.
return ChipID.SerialNumber;
}
int CPUInfo::GetLogicalProcessorsPerPhysical ()
{
// Return the logical processors per physical.
return Features.ExtendedFeatures.LogicalProcessorsPerPhysical;
}
int CPUInfo::GetProcessorClockFrequency ()
{
// Return the processor clock frequency.
if (Speed != NULL) return Speed->CPUSpeedInMHz;
// Display the error condition.
else return -1;
}
int CPUInfo::GetProcessorAPICID ()
{
// Return the APIC ID.
return Features.ExtendedFeatures.APIC_ID;
}
int CPUInfo::GetProcessorCacheXSize (DWORD dwCacheID)
{
// Return the chosen cache size.
switch (dwCacheID) {
case L1CACHE_FEATURE:
return Features.L1CacheSize;
case L2CACHE_FEATURE:
return Features.L2CacheSize;
case L3CACHE_FEATURE:
return Features.L3CacheSize;
}
// The user did something strange just return and error.
return -1;
}
bool CPUInfo::DoesCPUSupportFeature (DWORD dwFeature)
{
bool bHasFeature = false;
// Check for MMX instructions.
if (((dwFeature & MMX_FEATURE) != 0) && Features.HasMMX) bHasFeature = true;
// Check for MMX+ instructions.
if (((dwFeature & MMX_PLUS_FEATURE) != 0) && Features.ExtendedFeatures.HasMMXPlus) bHasFeature = true;
// Check for SSE FP instructions.
if (((dwFeature & SSE_FEATURE) != 0) && Features.HasSSE) bHasFeature = true;
// Check for SSE FP instructions.
if (((dwFeature & SSE_FP_FEATURE) != 0) && Features.HasSSEFP) bHasFeature = true;
// Check for SSE MMX instructions.
if (((dwFeature & SSE_MMX_FEATURE) != 0) && Features.ExtendedFeatures.HasSSEMMX) bHasFeature = true;
// Check for SSE2 instructions.
if (((dwFeature & SSE2_FEATURE) != 0) && Features.HasSSE2) bHasFeature = true;
// Check for 3DNow! instructions.
if (((dwFeature & AMD_3DNOW_FEATURE) != 0) && Features.ExtendedFeatures.Has3DNow) bHasFeature = true;
// Check for 3DNow+ instructions.
if (((dwFeature & AMD_3DNOW_PLUS_FEATURE) != 0) && Features.ExtendedFeatures.Has3DNowPlus) bHasFeature = true;
// Check for IA64 instructions.
if (((dwFeature & IA64_FEATURE) != 0) && Features.HasIA64) bHasFeature = true;
// Check for MP capable.
if (((dwFeature & MP_CAPABLE) != 0) && Features.ExtendedFeatures.SupportsMP) bHasFeature = true;
// Check for a serial number for the processor.
if (((dwFeature & SERIALNUMBER_FEATURE) != 0) && Features.HasSerial) bHasFeature = true;
// Check for a local APIC in the processor.
if (((dwFeature & APIC_FEATURE) != 0) && Features.HasAPIC) bHasFeature = true;
// Check for CMOV instructions.
if (((dwFeature & CMOV_FEATURE) != 0) && Features.HasCMOV) bHasFeature = true;
// Check for MTRR instructions.
if (((dwFeature & MTRR_FEATURE) != 0) && Features.HasMTRR) bHasFeature = true;
// Check for L1 cache size.
if (((dwFeature & L1CACHE_FEATURE) != 0) && (Features.L1CacheSize != -1)) bHasFeature = true;
// Check for L2 cache size.
if (((dwFeature & L2CACHE_FEATURE) != 0) && (Features.L2CacheSize != -1)) bHasFeature = true;
// Check for L3 cache size.
if (((dwFeature & L3CACHE_FEATURE) != 0) && (Features.L3CacheSize != -1)) bHasFeature = true;
// Check for ACPI capability.
if (((dwFeature & ACPI_FEATURE) != 0) && Features.HasACPI) bHasFeature = true;
// Check for thermal monitor support.
if (((dwFeature & THERMALMONITOR_FEATURE) != 0) && Features.HasThermal) bHasFeature = true;
// Check for temperature sensing diode support.
if (((dwFeature & TEMPSENSEDIODE_FEATURE) != 0) && Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode) bHasFeature = true;
// Check for frequency ID support.
if (((dwFeature & FREQUENCYID_FEATURE) != 0) && Features.ExtendedFeatures.PowerManagement.HasFrequencyID) bHasFeature = true;
// Check for voltage ID support.
if (((dwFeature & VOLTAGEID_FREQUENCY) != 0) && Features.ExtendedFeatures.PowerManagement.HasVoltageID) bHasFeature = true;
return bHasFeature;
}
// --------------------------------------------------------
//
// Private Functions - CPUInfo Class
//
// --------------------------------------------------------
bool __cdecl CPUInfo::DoesCPUSupportCPUID ()
{
int CPUIDPresent = 0;
#ifdef _WIN32
// Use SEH to determine CPUID presence
__try {
_asm {
#ifdef CPUID_AWARE_COMPILER
; we must push/pop the registers <<CPUID>> writes to, as the
; optimiser doesn't know about <<CPUID>>, and so doesn't expect
; these registers to change.
push eax
push ebx
push ecx
push edx
#endif
; <<CPUID>>
mov eax, 0
CPUID_INSTRUCTION
#ifdef CPUID_AWARE_COMPILER
pop edx
pop ecx
pop ebx
pop eax
#endif
}
}
// A generic catch-all just to be sure...
__except (1) {
// Stop the class from trying to use CPUID again!
CPUIDPresent = false;
return false;
}
#else
// The "right" way, which doesn't work under certain Windows versions
__try {
_asm {
pushfd ; save EFLAGS to stack.
pop eax ; store EFLAGS in eax.
mov edx, eax ; save in ebx for testing later.
xor eax, 0200000h ; switch bit 21.
push eax ; copy "changed" value to stack.
popfd ; save "changed" eax to EFLAGS.
pushfd
pop eax
xor eax, edx ; See if bit changeable.
jnz short cpuid_present ; if so, mark
mov eax, -1 ; CPUID not present - disable its usage
jmp no_features
cpuid_present:
mov eax, 0 ; CPUID capable CPU - enable its usage.
no_features:
mov CPUIDPresent, eax ; Save the value in eax to a variable.
}
}
// A generic catch-all just to be sure...
__except (1) {
// Stop the class from trying to use CPUID again!
CPUIDPresent = false;
return false;
}
#endif
// Return true to indicate support or false to indicate lack.
return (CPUIDPresent == 0) ? true : false;
}
bool __cdecl CPUInfo::RetrieveCPUFeatures ()
{
int CPUFeatures = 0;
int CPUAdvanced = 0;
// Use assembly to detect CPUID information...
__try {
_asm {
#ifdef CPUID_AWARE_COMPILER
; we must push/pop the registers <<CPUID>> writes to, as the
; optimiser doesn't know about <<CPUID>>, and so doesn't expect
; these registers to change.
push eax
push ebx
push ecx
push edx
#endif
; <<CPUID>>
; eax = 1 --> eax: CPU ID - bits 31..16 - unused, bits 15..12 - type, bits 11..8 - family, bits 7..4 - model, bits 3..0 - mask revision
; ebx: 31..24 - default APIC ID, 23..16 - logical processsor ID, 15..8 - CFLUSH chunk size , 7..0 - brand ID
; edx: CPU feature flags
mov eax,1
CPUID_INSTRUCTION
mov CPUFeatures, edx
mov CPUAdvanced, ebx
#ifdef CPUID_AWARE_COMPILER
pop edx
pop ecx
pop ebx
pop eax
#endif
}
}
// A generic catch-all just to be sure...
__except (1) {
return false;
}
// Retrieve the features of CPU present.
Features.HasFPU = ((CPUFeatures & 0x00000001) != 0); // FPU Present --> Bit 0
Features.HasTSC = ((CPUFeatures & 0x00000010) != 0); // TSC Present --> Bit 4
Features.HasAPIC = ((CPUFeatures & 0x00000200) != 0); // APIC Present --> Bit 9
Features.HasMTRR = ((CPUFeatures & 0x00001000) != 0); // MTRR Present --> Bit 12
Features.HasCMOV = ((CPUFeatures & 0x00008000) != 0); // CMOV Present --> Bit 15
Features.HasSerial = ((CPUFeatures & 0x00040000) != 0); // Serial Present --> Bit 18
Features.HasACPI = ((CPUFeatures & 0x00400000) != 0); // ACPI Capable --> Bit 22
Features.HasMMX = ((CPUFeatures & 0x00800000) != 0); // MMX Present --> Bit 23
Features.HasSSE = ((CPUFeatures & 0x02000000) != 0); // SSE Present --> Bit 25
Features.HasSSE2 = ((CPUFeatures & 0x04000000) != 0); // SSE2 Present --> Bit 26
Features.HasThermal = ((CPUFeatures & 0x20000000) != 0); // Thermal Monitor Present --> Bit 29
Features.HasIA64 = ((CPUFeatures & 0x40000000) != 0); // IA64 Present --> Bit 30
// Retrieve extended SSE capabilities if SSE is available.
if (Features.HasSSE) {
// Attempt to __try some SSE FP instructions.
__try {
// Perform: orps xmm0, xmm0
_asm {
_emit 0x0f
_emit 0x56
_emit 0xc0
}
// SSE FP capable processor.
Features.HasSSEFP = true;
}
// A generic catch-all just to be sure...
__except (1) {
// bad instruction - processor or OS cannot handle SSE FP.
Features.HasSSEFP = false;
}
} else {
// Set the advanced SSE capabilities to not available.
Features.HasSSEFP = false;
}
// Retrieve Intel specific extended features.
if (ChipManufacturer == Intel) {
Features.ExtendedFeatures.SupportsHyperthreading = ((CPUFeatures & 0x10000000) != 0); // Intel specific: Hyperthreading --> Bit 28
Features.ExtendedFeatures.LogicalProcessorsPerPhysical = (Features.ExtendedFeatures.SupportsHyperthreading) ? ((CPUAdvanced & 0x00FF0000) >> 16) : 1;
if ((Features.ExtendedFeatures.SupportsHyperthreading) && (Features.HasAPIC)){
// Retrieve APIC information if there is one present.
Features.ExtendedFeatures.APIC_ID = ((CPUAdvanced & 0xFF000000) >> 24);
}
}
return true;
}
bool __cdecl CPUInfo::RetrieveCPUIdentity ()
{
int CPUVendor[3];
int CPUSignature;
// Use assembly to detect CPUID information...
__try {
_asm {
#ifdef CPUID_AWARE_COMPILER
; we must push/pop the registers <<CPUID>> writes to, as the
; optimiser doesn't know about <<CPUID>>, and so doesn't expect
; these registers to change.
push eax
push ebx
push ecx
push edx
#endif
; <<CPUID>>
; eax = 0 --> eax: maximum value of CPUID instruction.
; ebx: part 1 of 3; CPU signature.
; edx: part 2 of 3; CPU signature.
; ecx: part 3 of 3; CPU signature.
mov eax, 0
CPUID_INSTRUCTION
mov CPUVendor[0 * TYPE int], ebx
mov CPUVendor[1 * TYPE int], edx
mov CPUVendor[2 * TYPE int], ecx
; <<CPUID>>
; eax = 1 --> eax: CPU ID - bits 31..16 - unused, bits 15..12 - type, bits 11..8 - family, bits 7..4 - model, bits 3..0 - mask revision
; ebx: 31..24 - default APIC ID, 23..16 - logical processsor ID, 15..8 - CFLUSH chunk size , 7..0 - brand ID
; edx: CPU feature flags
mov eax,1
CPUID_INSTRUCTION
mov CPUSignature, eax
#ifdef CPUID_AWARE_COMPILER
pop edx
pop ecx
pop ebx
pop eax
#endif
}
}
// A generic catch-all just to be sure...
__except (1) {
return false;
}
iCharA tmpVendor[VENDOR_STRING_LENGTH];
// Process the returned information.
memcpy (tmpVendor, &(CPUVendor[0]), sizeof (int));
memcpy (&(tmpVendor[4]), &(CPUVendor[1]), sizeof (int));
memcpy (&(tmpVendor[8]), &(CPUVendor[2]), sizeof (int));
tmpVendor[12] = '\0';
ChipID.Vendor[0] = '\0';
#ifdef _UNICODE
sint32 len = strlen(tmpVendor);
MultiByteToWideChar(CP_ACP, 0, tmpVendor, len, ChipID.Vendor, len);
#else
strcpy( ChipID.Vendor, tmpVendor);
#endif
// Attempt to retrieve the manufacturer from the vendor string.
if (_tcscmp(ChipID.Vendor, _T("GenuineIntel")) == 0) ChipManufacturer = Intel; // Intel Corp.
else if (_tcscmp(ChipID.Vendor, _T("UMC UMC UMC ")) == 0) ChipManufacturer = UMC; // United Microelectronics Corp.
else if (_tcscmp(ChipID.Vendor, _T("AuthenticAMD")) == 0) ChipManufacturer = AMD; // Advanced Micro Devices
else if (_tcscmp(ChipID.Vendor, _T("AMD ISBETTER")) == 0) ChipManufacturer = AMD; // Advanced Micro Devices (1994)
else if (_tcscmp(ChipID.Vendor, _T("CyrixInstead")) == 0) ChipManufacturer = Cyrix; // Cyrix Corp., VIA Inc.
else if (_tcscmp(ChipID.Vendor, _T("NexGenDriven")) == 0) ChipManufacturer = NexGen; // NexGen Inc. (now AMD)
else if (_tcscmp(ChipID.Vendor, _T("CentaurHauls")) == 0) ChipManufacturer = IDT; // IDT/Centaur (now VIA)
else if (_tcscmp(ChipID.Vendor, _T("RiseRiseRise")) == 0) ChipManufacturer = Rise; // Rise
else if (_tcscmp(ChipID.Vendor, _T("GenuineTMx86")) == 0) ChipManufacturer = Transmeta; // Transmeta
else if (_tcscmp(ChipID.Vendor, _T("TransmetaCPU")) == 0) ChipManufacturer = Transmeta; // Transmeta
else if (_tcscmp(ChipID.Vendor, _T("Geode By NSC")) == 0) ChipManufacturer = NSC; // National Semiconductor
else ChipManufacturer = UnknownManufacturer; // Unknown manufacturer
// Retrieve the family of CPU present.
ChipID.ExtendedFamily = ((CPUSignature & 0x0FF00000) >> 20); // Bits 27..20 Used
ChipID.ExtendedModel = ((CPUSignature & 0x000F0000) >> 16); // Bits 19..16 Used
ChipID.Type = ((CPUSignature & 0x0000F000) >> 12); // Bits 15..12 Used
ChipID.Family = ((CPUSignature & 0x00000F00) >> 8); // Bits 11..8 Used
ChipID.Model = ((CPUSignature & 0x000000F0) >> 4); // Bits 7..4 Used
ChipID.Revision = ((CPUSignature & 0x0000000F) >> 0); // Bits 3..0 Used
return true;
}
bool __cdecl CPUInfo::RetrieveCPUCacheDetails ()
{
int L1Cache[4] = { 0, 0, 0, 0 };
int L2Cache[4] = { 0, 0, 0, 0 };
// Check to see if what we are about to do is supported...
if (RetrieveCPUExtendedLevelSupport (0x80000005)) {
// Use assembly to retrieve the L1 cache information ...
__try {
_asm {
#ifdef CPUID_AWARE_COMPILER
; we must push/pop the registers <<CPUID>> writes to, as the
; optimiser doesn't know about <<CPUID>>, and so doesn't expect
; these registers to change.
push eax
push ebx
push ecx
push edx
#endif
; <<CPUID>>
; eax = 0x80000005 --> eax: L1 cache information - Part 1 of 4.
; ebx: L1 cache information - Part 2 of 4.
; edx: L1 cache information - Part 3 of 4.
; ecx: L1 cache information - Part 4 of 4.
mov eax, 0x80000005
CPUID_INSTRUCTION
mov L1Cache[0 * TYPE int], eax
mov L1Cache[1 * TYPE int], ebx
mov L1Cache[2 * TYPE int], ecx
mov L1Cache[3 * TYPE int], edx
#ifdef CPUID_AWARE_COMPILER
pop edx
pop ecx
pop ebx
pop eax
#endif
}
}
// A generic catch-all just to be sure...
__except (1) {
return false;
}
// Save the L1 data cache size (in KB) from ecx: bits 31..24 as well as data cache size from edx: bits 31..24.
Features.L1CacheSize = ((L1Cache[2] & 0xFF000000) >> 24);
Features.L1CacheSize += ((L1Cache[3] & 0xFF000000) >> 24);
} else {
// Store -1 to indicate the cache could not be queried.
Features.L1CacheSize = -1;
}
// Check to see if what we are about to do is supported...
if (RetrieveCPUExtendedLevelSupport (0x80000006)) {
// Use assembly to retrieve the L2 cache information ...
__try {
_asm {
#ifdef CPUID_AWARE_COMPILER
; we must push/pop the registers <<CPUID>> writes to, as the
; optimiser doesn't know about <<CPUID>>, and so doesn't expect
; these registers to change.
push eax
push ebx
push ecx
push edx
#endif
; <<CPUID>>
; eax = 0x80000006 --> eax: L2 cache information - Part 1 of 4.
; ebx: L2 cache information - Part 2 of 4.
; edx: L2 cache information - Part 3 of 4.
; ecx: L2 cache information - Part 4 of 4.
mov eax, 0x80000006
CPUID_INSTRUCTION
mov L2Cache[0 * TYPE int], eax
mov L2Cache[1 * TYPE int], ebx
mov L2Cache[2 * TYPE int], ecx
mov L2Cache[3 * TYPE int], edx
#ifdef CPUID_AWARE_COMPILER
pop edx
pop ecx
pop ebx
pop eax
#endif
}
}
// A generic catch-all just to be sure...
__except (1) {
return false;
}
// Save the L2 unified cache size (in KB) from ecx: bits 31..16.
Features.L2CacheSize = ((L2Cache[2] & 0xFFFF0000) >> 16);
} else {
// Store -1 to indicate the cache could not be queried.
Features.L2CacheSize = -1;
}
// Define L3 as being not present as we cannot test for it.
Features.L3CacheSize = -1;
// Return failure if we cannot detect either cache with this method.
return ((Features.L1CacheSize == -1) && (Features.L2CacheSize == -1)) ? false : true;
}
bool __cdecl CPUInfo::RetrieveClassicalCPUCacheDetails ()
{
int TLBCode = -1, TLBData = -1, L1Code = -1, L1Data = -1, L1Trace = -1, L2Unified = -1, L3Unified = -1;
int TLBCacheData[4] = { 0, 0, 0, 0 };
int TLBPassCounter = 0;
int TLBCacheUnit = 0;
do {
// Use assembly to retrieve the L2 cache information ...
__try {
_asm {
#ifdef CPUID_AWARE_COMPILER
; we must push/pop the registers <<CPUID>> writes to, as the
; optimiser doesn't know about <<CPUID>>, and so doesn't expect
; these registers to change.
push eax
push ebx
push ecx
push edx
#endif
; <<CPUID>>
; eax = 2 --> eax: TLB and cache information - Part 1 of 4.
; ebx: TLB and cache information - Part 2 of 4.
; ecx: TLB and cache information - Part 3 of 4.
; edx: TLB and cache information - Part 4 of 4.
mov eax, 2
CPUID_INSTRUCTION
mov TLBCacheData[0 * TYPE int], eax
mov TLBCacheData[1 * TYPE int], ebx
mov TLBCacheData[2 * TYPE int], ecx
mov TLBCacheData[3 * TYPE int], edx
#ifdef CPUID_AWARE_COMPILER
pop edx
pop ecx
pop ebx
pop eax
#endif
}
}
// A generic catch-all just to be sure...
__except (1) {
return false;
}
int bob = ((TLBCacheData[0] & 0x00FF0000) >> 16);
// Process the returned TLB and cache information.
for (int nCounter = 0; nCounter < TLBCACHE_INFO_UNITS; nCounter ++) {
// First of all - decide which unit we are dealing with.
switch (nCounter) {
// eax: bits 8..15 : bits 16..23 : bits 24..31
case 0: TLBCacheUnit = ((TLBCacheData[0] & 0x0000FF00) >> 8); break;
case 1: TLBCacheUnit = ((TLBCacheData[0] & 0x00FF0000) >> 16); break;
case 2: TLBCacheUnit = ((TLBCacheData[0] & 0xFF000000) >> 24); break;
// ebx: bits 0..7 : bits 8..15 : bits 16..23 : bits 24..31
case 3: TLBCacheUnit = ((TLBCacheData[1] & 0x000000FF) >> 0); break;
case 4: TLBCacheUnit = ((TLBCacheData[1] & 0x0000FF00) >> 8); break;
case 5: TLBCacheUnit = ((TLBCacheData[1] & 0x00FF0000) >> 16); break;
case 6: TLBCacheUnit = ((TLBCacheData[1] & 0xFF000000) >> 24); break;
// ecx: bits 0..7 : bits 8..15 : bits 16..23 : bits 24..31
case 7: TLBCacheUnit = ((TLBCacheData[2] & 0x000000FF) >> 0); break;
case 8: TLBCacheUnit = ((TLBCacheData[2] & 0x0000FF00) >> 8); break;
case 9: TLBCacheUnit = ((TLBCacheData[2] & 0x00FF0000) >> 16); break;
case 10: TLBCacheUnit = ((TLBCacheData[2] & 0xFF000000) >> 24); break;
// edx: bits 0..7 : bits 8..15 : bits 16..23 : bits 24..31
case 11: TLBCacheUnit = ((TLBCacheData[3] & 0x000000FF) >> 0); break;
case 12: TLBCacheUnit = ((TLBCacheData[3] & 0x0000FF00) >> 8); break;
case 13: TLBCacheUnit = ((TLBCacheData[3] & 0x00FF0000) >> 16); break;
case 14: TLBCacheUnit = ((TLBCacheData[3] & 0xFF000000) >> 24); break;
// Default case - an error has occured.
default: return false;
}
// Now process the resulting unit to see what it means....
switch (TLBCacheUnit) {
case 0x00: break;
case 0x01: STORE_TLBCACHE_INFO (TLBCode, 4); break;
case 0x02: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
case 0x03: STORE_TLBCACHE_INFO (TLBData, 4); break;
case 0x04: STORE_TLBCACHE_INFO (TLBData, 4096); break;
case 0x06: STORE_TLBCACHE_INFO (L1Code, 8); break;
case 0x08: STORE_TLBCACHE_INFO (L1Code, 16); break;
case 0x0a: STORE_TLBCACHE_INFO (L1Data, 8); break;
case 0x0c: STORE_TLBCACHE_INFO (L1Data, 16); break;
case 0x10: STORE_TLBCACHE_INFO (L1Data, 16); break; // <-- FIXME: IA-64 Only
case 0x15: STORE_TLBCACHE_INFO (L1Code, 16); break; // <-- FIXME: IA-64 Only
case 0x1a: STORE_TLBCACHE_INFO (L2Unified, 96); break; // <-- FIXME: IA-64 Only
case 0x22: STORE_TLBCACHE_INFO (L3Unified, 512); break;
case 0x23: STORE_TLBCACHE_INFO (L3Unified, 1024); break;
case 0x25: STORE_TLBCACHE_INFO (L3Unified, 2048); break;
case 0x29: STORE_TLBCACHE_INFO (L3Unified, 4096); break;
case 0x39: STORE_TLBCACHE_INFO (L2Unified, 128); break;
case 0x3c: STORE_TLBCACHE_INFO (L2Unified, 256); break;
case 0x40: STORE_TLBCACHE_INFO (L2Unified, 0); break; // <-- FIXME: No integrated L2 cache (P6 core) or L3 cache (P4 core).
case 0x41: STORE_TLBCACHE_INFO (L2Unified, 128); break;
case 0x42: STORE_TLBCACHE_INFO (L2Unified, 256); break;
case 0x43: STORE_TLBCACHE_INFO (L2Unified, 512); break;
case 0x44: STORE_TLBCACHE_INFO (L2Unified, 1024); break;
case 0x45: STORE_TLBCACHE_INFO (L2Unified, 2048); break;
case 0x50: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
case 0x51: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
case 0x52: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
case 0x5b: STORE_TLBCACHE_INFO (TLBData, 4096); break;
case 0x5c: STORE_TLBCACHE_INFO (TLBData, 4096); break;
case 0x5d: STORE_TLBCACHE_INFO (TLBData, 4096); break;
case 0x66: STORE_TLBCACHE_INFO (L1Data, 8); break;
case 0x67: STORE_TLBCACHE_INFO (L1Data, 16); break;
case 0x68: STORE_TLBCACHE_INFO (L1Data, 32); break;
case 0x70: STORE_TLBCACHE_INFO (L1Trace, 12); break;
case 0x71: STORE_TLBCACHE_INFO (L1Trace, 16); break;
case 0x72: STORE_TLBCACHE_INFO (L1Trace, 32); break;
case 0x77: STORE_TLBCACHE_INFO (L1Code, 16); break; // <-- FIXME: IA-64 Only
case 0x79: STORE_TLBCACHE_INFO (L2Unified, 128); break;
case 0x7a: STORE_TLBCACHE_INFO (L2Unified, 256); break;
case 0x7b: STORE_TLBCACHE_INFO (L2Unified, 512); break;
case 0x7c: STORE_TLBCACHE_INFO (L2Unified, 1024); break;
case 0x7e: STORE_TLBCACHE_INFO (L2Unified, 256); break;
case 0x81: STORE_TLBCACHE_INFO (L2Unified, 128); break;
case 0x82: STORE_TLBCACHE_INFO (L2Unified, 256); break;
case 0x83: STORE_TLBCACHE_INFO (L2Unified, 512); break;
case 0x84: STORE_TLBCACHE_INFO (L2Unified, 1024); break;
case 0x85: STORE_TLBCACHE_INFO (L2Unified, 2048); break;
case 0x88: STORE_TLBCACHE_INFO (L3Unified, 2048); break; // <-- FIXME: IA-64 Only
case 0x89: STORE_TLBCACHE_INFO (L3Unified, 4096); break; // <-- FIXME: IA-64 Only
case 0x8a: STORE_TLBCACHE_INFO (L3Unified, 8192); break; // <-- FIXME: IA-64 Only
case 0x8d: STORE_TLBCACHE_INFO (L3Unified, 3096); break; // <-- FIXME: IA-64 Only
case 0x90: STORE_TLBCACHE_INFO (TLBCode, 262144); break; // <-- FIXME: IA-64 Only
case 0x96: STORE_TLBCACHE_INFO (TLBCode, 262144); break; // <-- FIXME: IA-64 Only
case 0x9b: STORE_TLBCACHE_INFO (TLBCode, 262144); break; // <-- FIXME: IA-64 Only
// Default case - an error has occured.
default: return false;
}
}
// Increment the TLB pass counter.
TLBPassCounter ++;
} while ((TLBCacheData[0] & 0x000000FF) > TLBPassCounter);
// Ok - we now have the maximum TLB, L1, L2, and L3 sizes...
if ((L1Code == -1) && (L1Data == -1) && (L1Trace == -1)) Features.L1CacheSize = -1;
else if ((L1Code == -1) && (L1Data == -1) && (L1Trace != -1)) Features.L1CacheSize = L1Trace;
else if ((L1Code != -1) && (L1Data == -1)) Features.L1CacheSize = L1Code;
else if ((L1Code == -1) && (L1Data != -1)) Features.L1CacheSize = L1Data;
else if ((L1Code != -1) && (L1Data != -1)) Features.L1CacheSize = L1Code + L1Data;
else Features.L1CacheSize = -1;
// Ok - we now have the maximum TLB, L1, L2, and L3 sizes...
if (L2Unified == -1) Features.L2CacheSize = -1;
else Features.L2CacheSize = L2Unified;
// Ok - we now have the maximum TLB, L1, L2, and L3 sizes...
if (L3Unified == -1) Features.L3CacheSize = -1;
else Features.L3CacheSize = L3Unified;
return true;
}
bool __cdecl CPUInfo::RetrieveCPUClockSpeed ()
{
// First of all we check to see if the RDTSC (0x0F, 0x31) instruction is supported.
if (!Features.HasTSC) return false;
// Get the clock speed.
Speed = new CPUSpeed ();
if (Speed == NULL) return false;
return true;
}
bool __cdecl CPUInfo::RetrieveClassicalCPUClockSpeed ()
{
LARGE_INTEGER liStart, liEnd, liCountsPerSecond;
double dFrequency, dDifference;
// Attempt to get a starting tick count.
QueryPerformanceCounter (&liStart);
__try {
_asm {
mov eax, 0x80000000
mov ebx, CLASSICAL_CPU_FREQ_LOOP
Timer_Loop:
bsf ecx,eax
dec ebx
jnz Timer_Loop
}
}
// A generic catch-all just to be sure...
__except (1) {
return false;
}
// Attempt to get a starting tick count.
QueryPerformanceCounter (&liEnd);
// Get the difference... NB: This is in seconds....
QueryPerformanceFrequency (&liCountsPerSecond);
dDifference = (((double) liEnd.QuadPart - (double) liStart.QuadPart) / (double) liCountsPerSecond.QuadPart);
// Calculate the clock speed.
if (ChipID.Family == 3) {
// 80386 processors.... Loop time is 115 cycles!
dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 115) / dDifference) / 1048576);
} else if (ChipID.Family == 4) {
// 80486 processors.... Loop time is 47 cycles!
dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 47) / dDifference) / 1048576);
} else if (ChipID.Family == 5) {
// Pentium processors.... Loop time is 43 cycles!
dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 43) / dDifference) / 1048576);
}
// Save the clock speed.
Features.CPUSpeed = (int) dFrequency;
return true;
}
bool __cdecl CPUInfo::RetrieveCPUExtendedLevelSupport (int CPULevelToCheck)
{
int MaxCPUExtendedLevel = 0;
// The extended CPUID is supported by various vendors starting with the following CPU models:
//
// Manufacturer & Chip Name | Family Model Revision
//
// AMD K6, K6-2 | 5 6 x
// Cyrix GXm, Cyrix III "Joshua" | 5 4 x
// IDT C6-2 | 5 8 x
// VIA Cyrix III | 6 5 x
// Transmeta Crusoe | 5 x x
// Intel Pentium 4 | f x x
//
// We check to see if a supported processor is present...
if (ChipManufacturer == AMD) {
if (ChipID.Family < 5) return false;
if ((ChipID.Family == 5) && (ChipID.Model < 6)) return false;
} else if (ChipManufacturer == Cyrix) {
if (ChipID.Family < 5) return false;
if ((ChipID.Family == 5) && (ChipID.Model < 4)) return false;
if ((ChipID.Family == 6) && (ChipID.Model < 5)) return false;
} else if (ChipManufacturer == IDT) {
if (ChipID.Family < 5) return false;
if ((ChipID.Family == 5) && (ChipID.Model < 8)) return false;
} else if (ChipManufacturer == Transmeta) {
if (ChipID.Family < 5) return false;
} else if (ChipManufacturer == Intel) {
if (ChipID.Family < 0xf) return false;
}
// Use assembly to detect CPUID information...
__try {
_asm {
#ifdef CPUID_AWARE_COMPILER
; we must push/pop the registers <<CPUID>> writes to, as the
; optimiser doesn't know about <<CPUID>>, and so doesn't expect
; these registers to change.
push eax
push ebx
push ecx
push edx
#endif
; <<CPUID>>
; eax = 0x80000000 --> eax: maximum supported extended level
mov eax,0x80000000
CPUID_INSTRUCTION
mov MaxCPUExtendedLevel, eax
#ifdef CPUID_AWARE_COMPILER
pop edx
pop ecx
pop ebx
pop eax
#endif
}
}
// A generic catch-all just to be sure...
__except (1) {
return false;
}
// Now we have to check the level wanted vs level returned...
int nLevelWanted = (CPULevelToCheck & 0x7FFFFFFF);
int nLevelReturn = (MaxCPUExtendedLevel & 0x7FFFFFFF);
// Check to see if the level provided is supported...
if (nLevelWanted > nLevelReturn) return false;
return true;
}
bool __cdecl CPUInfo::RetrieveExtendedCPUFeatures ()
{
int CPUExtendedFeatures = 0;
// Check that we are not using an Intel processor as it does not support this.
if (ChipManufacturer == Intel) return false;
// Check to see if what we are about to do is supported...
if (!RetrieveCPUExtendedLevelSupport (0x80000001)) return false;
// Use assembly to detect CPUID information...
__try {
_asm {
#ifdef CPUID_AWARE_COMPILER
; we must push/pop the registers <<CPUID>> writes to, as the
; optimiser doesn't know about <<CPUID>>, and so doesn't expect
; these registers to change.
push eax
push ebx
push ecx
push edx
#endif
; <<CPUID>>
; eax = 0x80000001 --> eax: CPU ID - bits 31..16 - unused, bits 15..12 - type, bits 11..8 - family, bits 7..4 - model, bits 3..0 - mask revision
; ebx: 31..24 - default APIC ID, 23..16 - logical processsor ID, 15..8 - CFLUSH chunk size , 7..0 - brand ID
; edx: CPU feature flags
mov eax,0x80000001
CPUID_INSTRUCTION
mov CPUExtendedFeatures, edx
#ifdef CPUID_AWARE_COMPILER
pop edx
pop ecx
pop ebx
pop eax
#endif
}
}
// A generic catch-all just to be sure...
__except (1) {
return false;
}
// Retrieve the extended features of CPU present.
Features.ExtendedFeatures.Has3DNow = ((CPUExtendedFeatures & 0x80000000) != 0); // 3DNow Present --> Bit 31.
Features.ExtendedFeatures.Has3DNowPlus = ((CPUExtendedFeatures & 0x40000000) != 0); // 3DNow+ Present -- > Bit 30.
Features.ExtendedFeatures.HasSSEMMX = ((CPUExtendedFeatures & 0x00400000) != 0); // SSE MMX Present --> Bit 22.
Features.ExtendedFeatures.SupportsMP = ((CPUExtendedFeatures & 0x00080000) != 0); // MP Capable -- > Bit 19.
// Retrieve AMD specific extended features.
if (ChipManufacturer == AMD) {
Features.ExtendedFeatures.HasMMXPlus = ((CPUExtendedFeatures & 0x00400000) != 0); // AMD specific: MMX-SSE --> Bit 22
}
// Retrieve Cyrix specific extended features.
if (ChipManufacturer == Cyrix) {
Features.ExtendedFeatures.HasMMXPlus = ((CPUExtendedFeatures & 0x01000000) != 0); // Cyrix specific: Extended MMX --> Bit 24
}
return true;
}
bool __cdecl CPUInfo::RetrieveProcessorSerialNumber ()
{
int SerialNumber[3];
// Check to see if the processor supports the processor serial number.
if (!Features.HasSerial) return false;
// Use assembly to detect CPUID information...
__try {
_asm {
#ifdef CPUID_AWARE_COMPILER
; we must push/pop the registers <<CPUID>> writes to, as the
; optimiser doesn't know about <<CPUID>>, and so doesn't expect
; these registers to change.
push eax
push ebx
push ecx
push edx
#endif
; <<CPUID>>
; eax = 3 --> ebx: top 32 bits are the processor signature bits --> NB: Transmeta only ?!?
; ecx: middle 32 bits are the processor signature bits
; edx: bottom 32 bits are the processor signature bits
mov eax, 3
CPUID_INSTRUCTION
mov SerialNumber[0 * TYPE int], ebx
mov SerialNumber[1 * TYPE int], ecx
mov SerialNumber[2 * TYPE int], edx
#ifdef CPUID_AWARE_COMPILER
pop edx
pop ecx
pop ebx
pop eax
#endif
}
}
// A generic catch-all just to be sure...
__except (1) {
return false;
}
// Process the returned information.
_stprintf(ChipID.SerialNumber, _T("%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x"),
((SerialNumber[0] & 0xff000000) >> 24),
((SerialNumber[0] & 0x00ff0000) >> 16),
((SerialNumber[0] & 0x0000ff00) >> 8),
((SerialNumber[0] & 0x000000ff) >> 0),
((SerialNumber[1] & 0xff000000) >> 24),
((SerialNumber[1] & 0x00ff0000) >> 16),
((SerialNumber[1] & 0x0000ff00) >> 8),
((SerialNumber[1] & 0x000000ff) >> 0),
((SerialNumber[2] & 0xff000000) >> 24),
((SerialNumber[2] & 0x00ff0000) >> 16),
((SerialNumber[2] & 0x0000ff00) >> 8),
((SerialNumber[2] & 0x000000ff) >> 0));
return true;
}
bool __cdecl CPUInfo::RetrieveCPUPowerManagement ()
{
int CPUPowerManagement = 0;
// Check to see if what we are about to do is supported...
if (!RetrieveCPUExtendedLevelSupport (0x80000007)) {
Features.ExtendedFeatures.PowerManagement.HasFrequencyID = false;
Features.ExtendedFeatures.PowerManagement.HasVoltageID = false;
Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode = false;
return false;
}
// Use assembly to detect CPUID information...
__try {
_asm {
#ifdef CPUID_AWARE_COMPILER
; we must push/pop the registers <<CPUID>> writes to, as the
; optimiser doesn't know about <<CPUID>>, and so doesn't expect
; these registers to change.
push eax
push ebx
push ecx
push edx
#endif
; <<CPUID>>
; eax = 0x80000007 --> edx: get processor power management
mov eax,0x80000007
CPUID_INSTRUCTION
mov CPUPowerManagement, edx
#ifdef CPUID_AWARE_COMPILER
pop edx
pop ecx
pop ebx
pop eax
#endif
}
}
// A generic catch-all just to be sure...
__except (1) {
return false;
}
// Check for the power management capabilities of the CPU.
Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode = ((CPUPowerManagement & 0x00000001) != 0);
Features.ExtendedFeatures.PowerManagement.HasFrequencyID = ((CPUPowerManagement & 0x00000002) != 0);
Features.ExtendedFeatures.PowerManagement.HasVoltageID = ((CPUPowerManagement & 0x00000004) != 0);
return true;
}
bool __cdecl CPUInfo::RetrieveExtendedCPUIdentity ()
{
int ProcessorNameStartPos = 0;
int CPUExtendedIdentity[12];
// Check to see if what we are about to do is supported...
if (!RetrieveCPUExtendedLevelSupport (0x80000002)) return false;
if (!RetrieveCPUExtendedLevelSupport (0x80000003)) return false;
if (!RetrieveCPUExtendedLevelSupport (0x80000004)) return false;
// Use assembly to detect CPUID information...
__try {
_asm {
#ifdef CPUID_AWARE_COMPILER
; we must push/pop the registers <<CPUID>> writes to, as the
; optimiser doesn't know about <<CPUID>>, and so doesn't expect
; these registers to change.
push eax
push ebx
push ecx
push edx
#endif
; <<CPUID>>
; eax = 0x80000002 --> eax, ebx, ecx, edx: get processor name string (part 1)
mov eax,0x80000002
CPUID_INSTRUCTION
mov CPUExtendedIdentity[0 * TYPE int], eax
mov CPUExtendedIdentity[1 * TYPE int], ebx
mov CPUExtendedIdentity[2 * TYPE int], ecx
mov CPUExtendedIdentity[3 * TYPE int], edx
; <<CPUID>>
; eax = 0x80000003 --> eax, ebx, ecx, edx: get processor name string (part 2)
mov eax,0x80000003
CPUID_INSTRUCTION
mov CPUExtendedIdentity[4 * TYPE int], eax
mov CPUExtendedIdentity[5 * TYPE int], ebx
mov CPUExtendedIdentity[6 * TYPE int], ecx
mov CPUExtendedIdentity[7 * TYPE int], edx
; <<CPUID>>
; eax = 0x80000004 --> eax, ebx, ecx, edx: get processor name string (part 3)
mov eax,0x80000004
CPUID_INSTRUCTION
mov CPUExtendedIdentity[8 * TYPE int], eax
mov CPUExtendedIdentity[9 * TYPE int], ebx
mov CPUExtendedIdentity[10 * TYPE int], ecx
mov CPUExtendedIdentity[11 * TYPE int], edx
#ifdef CPUID_AWARE_COMPILER
pop edx
pop ecx
pop ebx
pop eax
#endif
}
}
// A generic catch-all just to be sure...
__except (1) {
return false;
}
iCharA pname[CHIPNAME_STRING_LENGTH];
// Process the returned information.
memcpy (pname, &(CPUExtendedIdentity[0]), sizeof (int));
memcpy (&(pname[4]), &(CPUExtendedIdentity[1]), sizeof (int));
memcpy (&(pname[8]), &(CPUExtendedIdentity[2]), sizeof (int));
memcpy (&(pname[12]), &(CPUExtendedIdentity[3]), sizeof (int));
memcpy (&(pname[16]), &(CPUExtendedIdentity[4]), sizeof (int));
memcpy (&(pname[20]), &(CPUExtendedIdentity[5]), sizeof (int));
memcpy (&(pname[24]), &(CPUExtendedIdentity[6]), sizeof (int));
memcpy (&(pname[28]), &(CPUExtendedIdentity[7]), sizeof (int));
memcpy (&(pname[32]), &(CPUExtendedIdentity[8]), sizeof (int));
memcpy (&(pname[36]), &(CPUExtendedIdentity[9]), sizeof (int));
memcpy (&(pname[40]), &(CPUExtendedIdentity[10]), sizeof (int));
memcpy (&(pname[44]), &(CPUExtendedIdentity[11]), sizeof (int));
pname[48] = '\0';
#ifdef _UNICODE
sint32 len = strlen(pname);
MultiByteToWideChar(CP_ACP, 0, pname, len, ChipID.ProcessorName, len);
#else
strcpy( ChipID.ProcessorName, pname);
#endif
// Because some manufacturers (<cough>Intel</cough>) have leading white space - we have to post-process the name.
if (ChipManufacturer == Intel) {
for (int nCounter = 0; nCounter < CHIPNAME_STRING_LENGTH; nCounter ++) {
// There will either be NULL (\0) or spaces ( ) as the leading characters.
if ((ChipID.ProcessorName[nCounter] != '\0') && (ChipID.ProcessorName[nCounter] != ' ')) {
// We have found the starting position of the name.
ProcessorNameStartPos = nCounter;
// Terminate the loop.
break;
}
}
// Check to see if there is any white space at the start.
if (ProcessorNameStartPos == 0) return true;
// Now move the name forward so that there is no white space.
memmove (ChipID.ProcessorName, &(ChipID.ProcessorName[ProcessorNameStartPos]), (CHIPNAME_STRING_LENGTH - ProcessorNameStartPos));
}
return true;
}
bool _cdecl CPUInfo::RetrieveClassicalCPUIdentity ()
{
// Start by decided which manufacturer we are using....
switch (ChipManufacturer) {
case Intel:
// Check the family / model / revision to determine the CPU ID.
switch (ChipID.Family) {
case 3:
_stprintf(ChipID.ProcessorName, _T("Newer i80386 family"));
break;
case 4:
switch (ChipID.Model) {
case 0: STORE_CLASSICAL_NAME (_T("i80486DX-25/33")); break;
case 1: STORE_CLASSICAL_NAME (_T("i80486DX-50")); break;
case 2: STORE_CLASSICAL_NAME (_T("i80486SX")); break;
case 3: STORE_CLASSICAL_NAME (_T("i80486DX2")); break;
case 4: STORE_CLASSICAL_NAME (_T("i80486SL")); break;
case 5: STORE_CLASSICAL_NAME (_T("i80486SX2")); break;
case 7: STORE_CLASSICAL_NAME (_T("i80486DX2 WriteBack")); break;
case 8: STORE_CLASSICAL_NAME (_T("i80486DX4")); break;
case 9: STORE_CLASSICAL_NAME (_T("i80486DX4 WriteBack")); break;
default: STORE_CLASSICAL_NAME (_T("Unknown 80486 family")); return false;
}
break;
case 5:
switch (ChipID.Model) {
case 0: STORE_CLASSICAL_NAME (_T("P5 A-Step")); break;
case 1: STORE_CLASSICAL_NAME (_T("P5")); break;
case 2: STORE_CLASSICAL_NAME (_T("P54C")); break;
case 3: STORE_CLASSICAL_NAME (_T("P24T OverDrive")); break;
case 4: STORE_CLASSICAL_NAME (_T("P55C")); break;
case 7: STORE_CLASSICAL_NAME (_T("P54C")); break;
case 8: STORE_CLASSICAL_NAME (_T("P55C (0.25¶m)")); break;
default: STORE_CLASSICAL_NAME (_T("Unknown PentiumÓ family")); return false;
}
break;
case 6:
switch (ChipID.Model) {
case 0: STORE_CLASSICAL_NAME (_T("P6 A-Step")); break;
case 1: STORE_CLASSICAL_NAME (_T("P6")); break;
case 3: STORE_CLASSICAL_NAME (_T("PentiumÓ II (0.28 ¶m)")); break;
case 5: STORE_CLASSICAL_NAME (_T("PentiumÓ II (0.25 ¶m)")); break;
case 6: STORE_CLASSICAL_NAME (_T("PentiumÓ II With On-Die L2 Cache")); break;
case 7: STORE_CLASSICAL_NAME (_T("PentiumÓ III (0.25 ¶m)")); break;
case 8: STORE_CLASSICAL_NAME (_T("PentiumÓ III (0.18 ¶m) With 256 KB On-Die L2 Cache ")); break;
case 0xa: STORE_CLASSICAL_NAME (_T("PentiumÓ III (0.18 ¶m) With 1 Or 2 MB On-Die L2 Cache ")); break;
case 0xb: STORE_CLASSICAL_NAME (_T("PentiumÓ III (0.13 ¶m) With 256 Or 512 KB On-Die L2 Cache ")); break;
default: STORE_CLASSICAL_NAME (_T("Unknown P6 family")); return false;
}
break;
case 7:
STORE_CLASSICAL_NAME (_T("Intel Merced (IA-64)"));
break;
case 0xf:
// Check the extended family bits...
switch (ChipID.ExtendedFamily) {
case 0:
switch (ChipID.Model) {
case 0: STORE_CLASSICAL_NAME (_T("PentiumÓ IV (0.18 ¶m)")); break;
case 1: STORE_CLASSICAL_NAME (_T("PentiumÓ IV (0.18 ¶m)")); break;
case 2: STORE_CLASSICAL_NAME (_T("PentiumÓ IV (0.13 ¶m)")); break;
default: STORE_CLASSICAL_NAME (_T("Unknown Pentium 4 family")); return false;
}
break;
case 1:
STORE_CLASSICAL_NAME (_T("Intel McKinley (IA-64)"));
break;
}
break;
default:
STORE_CLASSICAL_NAME (_T("Unknown Intel family"));
return false;
}
break;
case AMD:
// Check the family / model / revision to determine the CPU ID.
switch (ChipID.Family) {
case 4:
switch (ChipID.Model) {
case 3: STORE_CLASSICAL_NAME (_T("80486DX2")); break;
case 7: STORE_CLASSICAL_NAME (_T("80486DX2 WriteBack")); break;
case 8: STORE_CLASSICAL_NAME (_T("80486DX4")); break;
case 9: STORE_CLASSICAL_NAME (_T("80486DX4 WriteBack")); break;
case 0xe: STORE_CLASSICAL_NAME (_T("5x86")); break;
case 0xf: STORE_CLASSICAL_NAME (_T("5x86WB")); break;
default: STORE_CLASSICAL_NAME (_T("Unknown 80486 family")); return false;
}
break;
case 5:
switch (ChipID.Model) {
case 0: STORE_CLASSICAL_NAME (_T("SSA5 (PR75, PR90, PR100)")); break;
case 1: STORE_CLASSICAL_NAME (_T("5k86 (PR120, PR133)")); break;
case 2: STORE_CLASSICAL_NAME (_T("5k86 (PR166)")); break;
case 3: STORE_CLASSICAL_NAME (_T("5k86 (PR200)")); break;
case 6: STORE_CLASSICAL_NAME (_T("K6 (0.30 ¶m)")); break;
case 7: STORE_CLASSICAL_NAME (_T("K6 (0.25 ¶m)")); break;
case 8: STORE_CLASSICAL_NAME (_T("K6-2")); break;
case 9: STORE_CLASSICAL_NAME (_T("K6-III")); break;
case 0xd: STORE_CLASSICAL_NAME (_T("K6-2+ or K6-III+ (0.18 ¶m)")); break;
default: STORE_CLASSICAL_NAME (_T("Unknown 80586 family")); return false;
}
break;
case 6:
switch (ChipID.Model) {
case 1: STORE_CLASSICAL_NAME (_T("AthlonŔ (0.25 ¶m)")); break;
case 2: STORE_CLASSICAL_NAME (_T("AthlonŔ (0.18 ¶m)")); break;
case 3: STORE_CLASSICAL_NAME (_T("DuronŔ (SF core)")); break;
case 4: STORE_CLASSICAL_NAME (_T("AthlonŔ (Thunderbird core)")); break;
case 6: STORE_CLASSICAL_NAME (_T("AthlonŔ (Palomino core)")); break;
case 7: STORE_CLASSICAL_NAME (_T("DuronŔ (Morgan core)")); break;
case 8:
if (Features.ExtendedFeatures.SupportsMP)
STORE_CLASSICAL_NAME (_T("AthlonŔ MP (Thoroughbred core)"));
else STORE_CLASSICAL_NAME (_T("AthlonŔ XP (Thoroughbred core)"));
break;
default: STORE_CLASSICAL_NAME (_T("Unknown K7 family")); return false;
}
break;
default:
STORE_CLASSICAL_NAME (_T("Unknown AMD family"));
return false;
}
break;
case Transmeta:
switch (ChipID.Family) {
case 5:
switch (ChipID.Model) {
case 4: STORE_CLASSICAL_NAME (_T("Crusoe TM3x00 and TM5x00")); break;
default: STORE_CLASSICAL_NAME (_T("Unknown Crusoe family")); return false;
}
break;
default:
STORE_CLASSICAL_NAME (_T("Unknown Transmeta family"));
return false;
}
break;
case Rise:
switch (ChipID.Family) {
case 5:
switch (ChipID.Model) {
case 0: STORE_CLASSICAL_NAME (_T("mP6 (0.25 ¶m)")); break;
case 2: STORE_CLASSICAL_NAME (_T("mP6 (0.18 ¶m)")); break;
default: STORE_CLASSICAL_NAME (_T("Unknown Rise family")); return false;
}
break;
default:
STORE_CLASSICAL_NAME (_T("Unknown Rise family"));
return false;
}
break;
case UMC:
switch (ChipID.Family) {
case 4:
switch (ChipID.Model) {
case 1: STORE_CLASSICAL_NAME (_T("U5D")); break;
case 2: STORE_CLASSICAL_NAME (_T("U5S")); break;
default: STORE_CLASSICAL_NAME (_T("Unknown UMC family")); return false;
}
break;
default:
STORE_CLASSICAL_NAME (_T("Unknown UMC family"));
return false;
}
break;
case IDT:
switch (ChipID.Family) {
case 5:
switch (ChipID.Model) {
case 4: STORE_CLASSICAL_NAME (_T("C6")); break;
case 8: STORE_CLASSICAL_NAME (_T("C2")); break;
case 9: STORE_CLASSICAL_NAME (_T("C3")); break;
default: STORE_CLASSICAL_NAME (_T("Unknown IDT\\Centaur family")); return false;
}
break;
case 6:
switch (ChipID.Model) {
case 6: STORE_CLASSICAL_NAME (_T("VIA Cyrix III - Samuel")); break;
default: STORE_CLASSICAL_NAME (_T("Unknown IDT\\Centaur family")); return false;
}
break;
default:
STORE_CLASSICAL_NAME (_T("Unknown IDT\\Centaur family"));
return false;
}
break;
case Cyrix:
switch (ChipID.Family) {
case 4:
switch (ChipID.Model) {
case 4: STORE_CLASSICAL_NAME (_T("MediaGX GX, GXm")); break;
case 9: STORE_CLASSICAL_NAME (_T("5x86")); break;
default: STORE_CLASSICAL_NAME (_T("Unknown Cx5x86 family")); return false;
}
break;
case 5:
switch (ChipID.Model) {
case 2: STORE_CLASSICAL_NAME (_T("Cx6x86")); break;
case 4: STORE_CLASSICAL_NAME (_T("MediaGX GXm")); break;
default: STORE_CLASSICAL_NAME (_T("Unknown Cx6x86 family")); return false;
}
break;
case 6:
switch (ChipID.Model) {
case 0: STORE_CLASSICAL_NAME (_T("6x86MX")); break;
case 5: STORE_CLASSICAL_NAME (_T("Cyrix M2 Core")); break;
case 6: STORE_CLASSICAL_NAME (_T("WinChip C5A Core")); break;
case 7: STORE_CLASSICAL_NAME (_T("WinChip C5B\\C5C Core")); break;
case 8: STORE_CLASSICAL_NAME (_T("WinChip C5C-T Core")); break;
default: STORE_CLASSICAL_NAME (_T("Unknown 6x86MX\\Cyrix III family")); return false;
}
break;
default:
STORE_CLASSICAL_NAME (_T("Unknown Cyrix family"));
return false;
}
break;
case NexGen:
switch (ChipID.Family) {
case 5:
switch (ChipID.Model) {
case 0: STORE_CLASSICAL_NAME (_T("Nx586 or Nx586FPU")); break;
default: STORE_CLASSICAL_NAME (_T("Unknown NexGen family")); return false;
}
break;
default:
STORE_CLASSICAL_NAME (_T("Unknown NexGen family"));
return false;
}
break;
case NSC:
STORE_CLASSICAL_NAME (_T("Cx486SLC \\ DLC \\ Cx486S A-Step"));
break;
default:
// We cannot identify the processor.
STORE_CLASSICAL_NAME (_T("Unknown family"));
return false;
}
return true;
}
// --------------------------------------------------------
//
// Constructor Functions - CPUSpeed Class
//
// --------------------------------------------------------
CPUSpeed::CPUSpeed ()
{
unsigned int uiRepetitions = 1;
unsigned int uiMSecPerRepetition = 50;
__int64 i64Total = 0, i64Overhead = 0;
for (unsigned int nCounter = 0; nCounter < uiRepetitions; nCounter ++) {
i64Total += GetCyclesDifference (CPUSpeed::Delay, uiMSecPerRepetition);
i64Overhead += GetCyclesDifference (CPUSpeed::DelayOverhead, uiMSecPerRepetition);
}
// Calculate the MHz speed.
i64Total -= i64Overhead;
i64Total /= uiRepetitions;
i64Total /= uiMSecPerRepetition;
i64Total /= 1000;
// Save the CPU speed.
CPUSpeedInMHz = (int) i64Total;
}
CPUSpeed::~CPUSpeed ()
{
}
__int64 __cdecl CPUSpeed::GetCyclesDifference (DELAY_FUNC DelayFunction, unsigned int uiParameter)
{
unsigned int edx1, eax1;
unsigned int edx2, eax2;
// Calculate the frequency of the CPU instructions.
__try {
_asm {
push uiParameter ; push parameter param
mov ebx, DelayFunction ; store func in ebx
RDTSC_INSTRUCTION
mov esi, eax ; esi = eax
mov edi, edx ; edi = edx
call ebx ; call the delay functions
RDTSC_INSTRUCTION
pop ebx
mov edx2, edx ; edx2 = edx
mov eax2, eax ; eax2 = eax
mov edx1, edi ; edx2 = edi
mov eax1, esi ; eax2 = esi
}
}
// A generic catch-all just to be sure...
__except (1) {
return -1;
}
return (CPUSPEED_I32TO64 (edx2, eax2) - CPUSPEED_I32TO64 (edx1, eax1));
}
void CPUSpeed::Delay (unsigned int uiMS)
{
LARGE_INTEGER Frequency, StartCounter, EndCounter;
__int64 x;
// Get the frequency of the high performance counter.
if (!QueryPerformanceFrequency (&Frequency)) return;
x = Frequency.QuadPart / 1000 * uiMS;
// Get the starting position of the counter.
QueryPerformanceCounter (&StartCounter);
do {
// Get the ending position of the counter.
QueryPerformanceCounter (&EndCounter);
} while (EndCounter.QuadPart - StartCounter.QuadPart < x);
}
void CPUSpeed::DelayOverhead (unsigned int uiMS)
{
LARGE_INTEGER Frequency, StartCounter, EndCounter;
__int64 x;
// Get the frequency of the high performance counter.
if (!QueryPerformanceFrequency (&Frequency)) return;
x = Frequency.QuadPart / 1000 * uiMS;
// Get the starting position of the counter.
QueryPerformanceCounter (&StartCounter);
do {
// Get the ending position of the counter.
QueryPerformanceCounter (&EndCounter);
} while (EndCounter.QuadPart - StartCounter.QuadPart == x);
} | [
"sigman@ioupg.com"
] | sigman@ioupg.com |
ddb611d0d8ab884b7d80bdfd6e21e919badd88f9 | b52052ec76ee61d5510203812949029551125cf5 | /UE4/SpaceWarOnline/SpaceTribes-master/SpaceWarOnline/Source/SpaceWarOnline/Public/MyPlanetControlled.h | 4da9b073bd7962f2ad2f168e1770bbad6f5f0f9f | [
"MIT"
] | permissive | Invectys/Games | af9e1bf0c784e6ccf79a8ea2e31ea3f927e781d1 | 89aa7a0cbcdf4b4dd500b3768daeac355969ee38 | refs/heads/main | 2023-01-07T21:20:29.852206 | 2020-11-04T07:41:55 | 2020-11-04T07:41:55 | 309,297,856 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 308 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "MyPlanetDefault.h"
#include "MyPlanetControlled.generated.h"
/**
*
*/
UCLASS()
class SPACEWARONLINE_API AMyPlanetControlled : public AMyPlanetDefault
{
GENERATED_BODY()
};
| [
"34795455+Invectys@users.noreply.github.com"
] | 34795455+Invectys@users.noreply.github.com |
416f69e32351ee65aa61e8a9ae9d9a3b06f1762b | 11cb9f0c93bef94d9fc14b1fc02a285ecc27f19e | /lap5/bai5.cpp | f07073f5b8adc777975eda78b2d8212c3bc849c9 | [] | no_license | vietlinh9712/T2004E_C | 088af761baf1b3bc7aa9c18ed9f7b31f65751a6d | 1548284360befadaefe6c5dd191d44e8aae21591 | refs/heads/master | 2022-09-06T06:21:00.839960 | 2020-06-02T13:03:29 | 2020-06-02T13:03:29 | 262,034,401 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | cpp | #include <stdio.h>
int main()
{
int n, fibo, num1 = 0, num2 = 1;
printf("Nhap n: ");
scanf("%d", &n);
if (n == 0)
{
printf("So fibonanci thu 1 la : 0");
}else
{
for (int i = 1; i != n ; i++)
{
fibo = num1 + num2;
num2 = num1;
num1 = fibo;
}
printf("So fibonaci thu %d la: %d", n, fibo);
}
return 0;
}
| [
"64905071+vietlinh9712@users.noreply.github.com"
] | 64905071+vietlinh9712@users.noreply.github.com |
235bf57c0f34b61fba8f4a86a90a26f2b512df1d | 8f37e02e657ea05ed050c26ba7ca7158b1b8f501 | /src/Resources/TileType.cpp | c717d1ae4c2e77096909ce191e5cf15da5b0d5fd | [] | no_license | Asmageddon/r1 | 8178a49fd4626c11ed1c694b5a26a98a0e199372 | 9d0b2b5b3b9dc505e44b82312e3fe93d12fb0a1d | refs/heads/master | 2020-05-14T22:48:43.463521 | 2013-01-21T19:28:37 | 2013-01-21T19:28:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,290 | cpp | #include "TileType.hpp"
#include "../Data.hpp"
#include "ResourceManager.hpp"
#include "../TileSprite.hpp"
TILE_CLASS TileType::get_tile_class(const std::string& type) {
if (type == "wall")
return TILE_WALL;
if (type == "floor")
return TILE_FLOOR;
if (type == "void")
return TILE_VOID;
return TILE_UNKNOWN;
}
TileType::TileType(ResourceManager *resman, Data data) : Resource(data) , Displayable(data) {
this->resman = resman;
type = get_tile_class(data[""]["type"]);
//If it's not set in the data file, set it basing on type
if (!data["appearance"].HasField("blocks_sight")) {
if (type == TILE_WALL)
blocks_sight = true;
else
blocks_sight = false;
}
density = data["properties"]["density"].as_float();
durability = data["properties"]["durability"].as_float();
resilience = data["properties"]["resilience"].as_float();
//TODO: Add borders for different kinds of neighbouring tiles
border_tileset = data["appearance"]["border"];
if (border_tileset == "")
border_sprite = NULL;
else {
border_sprite = new TileSprite;
(*border_sprite) = resman->GetSprite(border_tileset, 0);
}
sprite = resman->GetSprite(tileset, image);
}
| [
"Asmageddon@gmail.com"
] | Asmageddon@gmail.com |
22bb056a386b90ac6a3d95a8cfee84851d6111c3 | 8aae4e3ee7943f9293085fd57b4867e06ab836b2 | /ProgrammingLanguage/Tools/SmallTools/random.cpp | a09326613617c8aca9dec75b8e3773431d4127a2 | [] | no_license | eboladev/Study | 42213e73384788671deacd8d37004a571c95b7bb | 388f3629e7651e41d2569be92d4f65c4c94cd512 | refs/heads/master | 2020-12-25T22:47:03.624272 | 2014-10-24T12:10:13 | 2014-10-24T12:10:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 264 | cpp | #include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int MAX = 50;
ofstream fout("random.txt");
int main()
{
srand(time(NULL));
for (int i = 0; i < MAX; ++i)
fout << rand() << ' ';
fout << endl;
return 0;
}
| [
"jack.xsuperman@gmail.com"
] | jack.xsuperman@gmail.com |
705756edfd917ffc41718520d10808b96450c06b | 3fa4da4ec11dff76882d85de4cdbff5bd9dff9fa | /[new 4.4]3D_ESSUE/Tool/Default/MainForm.cpp | a5f0a218b3e16d1e28a146019f3d53a68684f5d8 | [] | no_license | buseog/Direct3D_Solo | 4561259cb8b7d46d0e1e209c5b17a73fa28e0b84 | cb7610976edaa7cc413a32ae60b2382e2ac89d45 | refs/heads/master | 2021-06-20T09:30:21.969667 | 2017-05-11T18:32:47 | 2017-05-11T18:32:47 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,017 | cpp | // MainForm.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "Tool.h"
#include "MainForm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// CMainForm
IMPLEMENT_DYNCREATE(CMainForm, CFormView)
CMainForm::CMainForm()
: CFormView(CMainForm::IDD)
, m_iToolType(0)
{
}
CMainForm::~CMainForm()
{
}
void CMainForm::DoDataExchange(CDataExchange* pDX)
{
CFormView::DoDataExchange(pDX);
DDX_Control(pDX, IDC_TAB1, m_TabControl);
}
BEGIN_MESSAGE_MAP(CMainForm, CFormView)
ON_NOTIFY(TCN_SELCHANGE, IDC_TAB1, &CMainForm::OnChangeTab)
END_MESSAGE_MAP()
// CMainForm 진단입니다.
#ifdef _DEBUG
void CMainForm::AssertValid() const
{
CFormView::AssertValid();
}
#ifndef _WIN32_WCE
void CMainForm::Dump(CDumpContext& dc) const
{
CFormView::Dump(dc);
}
#endif
#endif //_DEBUG
// CMainForm 메시지 처리기입니다.
void CMainForm::OnChangeTab(NMHDR *pNMHDR, LRESULT *pResult)
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
*pResult = 0;
UpdateData(TRUE);
m_iToolType = m_TabControl.GetCurSel();
switch(m_iToolType)
{
case 0:
m_MapTool.ShowWindow(SW_SHOW);
m_NaviTool.ShowWindow(SW_HIDE);
break;
case 1:
m_MapTool.ShowWindow(SW_HIDE);
m_NaviTool.ShowWindow(SW_SHOW);
break;
}
UpdateData(FALSE);
}
void CMainForm::OnInitialUpdate()
{
CFormView::OnInitialUpdate();
// TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다.
m_TabControl.DeleteAllItems();
m_TabControl.InsertItem(0, L"Map");
m_TabControl.InsertItem(1, L"Navi Mesh");
CRect rc;
m_TabControl.GetClientRect(&rc);
m_MapTool.Create(IDD_MAPTOOL, &m_TabControl );
m_MapTool.SetWindowPos(NULL, 0, 25, rc.Width() - 5, rc.Height() - 5, SWP_SHOWWINDOW);
m_MapTool.ShowWindow(SW_SHOW);
m_NaviTool.Create(IDD_NAVITOOL, &m_TabControl );
m_NaviTool.SetWindowPos(NULL, 0, 25, rc.Width() - 5, rc.Height() - 5, SWP_SHOWWINDOW);
m_NaviTool.ShowWindow(SW_HIDE);
Invalidate(FALSE);
}
| [
"buseog1991@naver.com"
] | buseog1991@naver.com |
51dbaec450ef5c84d46e4e4295b84c6ca657f171 | eb8af3acac129e0c151ef82ceccc74c03dd644b1 | /sketch_jun08a/sketch_jun08a.ino | ff39cf499561e98bf594ef8b774c165cebf49089 | [] | no_license | rumalex/arduino-sketchs | 2f54791a44eaa47cd1be98e970df8fc7b115bf29 | 83cfd9ca9a022fd3c4e0b7e5b98d26a310dd71a3 | refs/heads/master | 2021-01-01T05:28:55.622942 | 2017-05-05T04:09:33 | 2017-05-05T04:09:33 | 59,225,672 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,287 | ino |
#include <EEPROM.h>
#include <Wire.h>
#include <DS1307.h>
#include "RTClib.h"
#define RELE_1 8 //объявляем работу 1 реле на пине 7
#define RELE_2 9 //объявляем работу 2 реле на пине 8
int FullMinutesTimerOn = EEPROM.read(0);
int FullMinutesTimerOff = EEPROM.read(2);
int rtc[7];
byte rr[7];
};
// loop counter
int count = 0;
void setup () {
pinMode(RELE_1, OUTPUT); //инициируем реле только на выход
pinMode(RELE_2, OUTPUT); //инициируем реле только на выход
digitalWrite(RELE_1, HIGH); // запускаем реле выключенными
digitalWrite(RELE_2, HIGH); // запускаем реле выключенными
RTC.get(rtc,true);
};
void loop () {
int hourOn=EEPROM.read(110); //EEPROM.read(110)
int hourOff= EEPROM.read(112);; //EEPROM.read(112)
int minOn= EEPROM.read(111);; //EEPROM.read(111)
int minOff= EEPROM.read(113);; //EEPROM.read(113)
int minVent= EEPROM.read(114); //время работы вентилятора
int Hour = rtc[2]; //присваиваем часы
int Minute = rtc[1]; //присваиваем минуты
int Second = rtc[0]; // присваиваем секунды
int FullMinutes = Hour * 60 + Minute; //приводим значение текущего времени к минутам
int FullMinutesTimerOn= hourOn*60+minOn; //приводим значение ВКЛЮЧЕНИЯ таймера к минутам
int FullMinutesTimerOff= hourOff*60+minOff; //приводим значение ВЫКЛЮЧЕНИЯ таймера к минутам
int sutki=0; // по умолчанию, таймер работает в одних сутках
if (hourOff-hourOn < 0) sutki=1; //если время выключения на следующие сутки, то включаем триггер сутки=1
else sutki=0;
if (sutki==1 && (FullMinutes >= FullMinutesTimerOn || FullMinutes <= FullMinutesTimerOff) )
{
digitalWrite(RELE_1, LOW);
// если сутки перескакивают, то проверяем время оператором ИЛИ
}
else if (sutki==1)
{
digitalWrite(RELE_1, HIGH);
}
if (sutki == 0 && (FullMinutes >= FullMinutesTimerOn && FullMinutes <= FullMinutesTimerOff ))
{
digitalWrite(RELE_1, LOW);
} // если сутки НЕ перескакивают, то проверяем время оператором И
else if (sutki == 0)
{
digitalWrite(RELE_1, HIGH);
}
if ((Minute >= 0 && Minute <= minVent) && (Hour >= 9 && Hour <= 21))
{
digitalWrite(RELE_2, LOW);
}
if (Minute >= 0 && Minute > minVent)
{
digitalWrite(RELE_2, HIGH);
}
RTC.get(rtc,true);
if (rejim==0)
{
lcd.setCursor(0, 2);
lcd.print ("ojidayu komandi");
}
if (rejim==1)
{
setTimerOn();
}
if (rejim==2)
{
setTimerOff();
}
if (rejim==3)
{
setTime();
}
if (rejim==4)
{
setVent();
}
if (digitalRead (button5) == HIGH)
{
rejim++;
if (rejim>4) rejim=0;
lcd.clear();
//}
}
}
void setTimerOn()
{
int hourOn= EEPROM.read(110);
int minOn= EEPROM.read(111);
lcd.setCursor(0, 2);
lcd.print("nastroika VKL");
if (digitalRead(button3)==HIGH) //нажимая верхнюю кнопку меняем часы
{
hourOn++;
if (hourOn >=24) hourOn=0;
}
if (!digitalRead(button4)) //нажимая нижнюю кнопку меняем минуты
{
minOn++;
if (minOn >=60)
{
minOn=0;
hourOn++;
if (hourOn >=24) hourOn=0;
}
}
strokatimera();
if (digitalRead(button2) == HIGH)
{
EEPROM.write(110, hourOn);
EEPROM.write(111, minOn);
lcd.clear();
}
}
void setTimerOff()
{
int hourOff= EEPROM.read(112);
int minOff= EEPROM.read(113);
lcd.setCursor(0, 2);
lcd.print("nastroika VIKL");
if (digitalRead(button3)==HIGH) //нажимая верхнюю кнопку меняем часы
{
hourOff++;
if (hourOff >=24) hourOff=0;
}
if (!digitalRead(button4)) //нажимая нижнюю кнопку меняем минуты
{
minOff++;
if (minOff >=60)
{
minOff=0;
hourOff++;
if (hourOff >=24) hourOff=0;
}
}
strokatimera();
if (digitalRead(button2) == HIGH)
{
EEPROM.write(112, hourOff);
EEPROM.write(113, minOff);
lcd.clear();
}
}
void setTime()
{
int Hour = rtc[2]; //присваиваем часы
int Minute = rtc[1];
//lcd.clear();
lcd.setCursor(0, 2);
lcd.print ("nastroika time");
RTC.get(rtc,true);
//lcd.setCursor(0, 3); // вывод в последней строчке времени работы таймера
// lcd.print(Hour);
// lcd.print(":");
// lcd.print(Minute);
if (!digitalRead(button4)) //нажимая нижнюю кнопку меняем минуты
{
Minute++;
if (Minute >=60)
{
Minute=0;
Hour++;
if (Hour >=24) Hour=0;
}
}
if (digitalRead(button2) == HIGH)
{
RTC.set(DS1307_MIN,Minute);
RTC.set(DS1307_HR,Hour);
lcd.clear();
}
}
| [
"rumalex@gmail.com"
] | rumalex@gmail.com |
7abce9fe96d221e503d4a0b87e24ae259ab0d986 | 6150dcbb20ce934c54c32ebd42a62d565aebd4e8 | /src/mylib.cpp | bc5794b48c7788490b99cd45cc3ff8b70759c701 | [] | no_license | rmartens/mylib | baf94627c98c2dc56b9d95d680ed8fb02edb3c05 | 3b2085a2c3ca601f981e94c516cb635f48f9cdea | refs/heads/master | 2023-04-08T06:21:10.329819 | 2021-04-23T15:15:26 | 2021-04-23T15:15:26 | 359,596,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 61 | cpp | #include "mylib.h"
int foo()
{
// test
return 42;
}
| [
"rmartens@gmail.com"
] | rmartens@gmail.com |
3ada1cf34d2c9ad83b4a7b61d5783b1d43d399a4 | cf8ddfc720bf6451c4ef4fa01684327431db1919 | /SDK/ARKSurvivalEvolved_Piranha_Character_BP_BreakNet_functions.cpp | 35c8f75ba24d37fbc7ea66d8a1c38d4cde6eb9b1 | [
"MIT"
] | permissive | git-Charlie/ARK-SDK | 75337684b11e7b9f668da1f15e8054052a3b600f | c38ca9925309516b2093ad8c3a70ed9489e1d573 | refs/heads/master | 2023-06-20T06:30:33.550123 | 2021-07-11T13:41:45 | 2021-07-11T13:41:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,643 | cpp | // ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Piranha_Character_BP_BreakNet_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function Piranha_Character_BP_BreakNet.Piranha_Character_BP_BreakNet_C.UserConstructionScript
// ()
void APiranha_Character_BP_BreakNet_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function Piranha_Character_BP_BreakNet.Piranha_Character_BP_BreakNet_C.UserConstructionScript");
APiranha_Character_BP_BreakNet_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Piranha_Character_BP_BreakNet.Piranha_Character_BP_BreakNet_C.ExecuteUbergraph_Piranha_Character_BP_BreakNet
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void APiranha_Character_BP_BreakNet_C::ExecuteUbergraph_Piranha_Character_BP_BreakNet(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function Piranha_Character_BP_BreakNet.Piranha_Character_BP_BreakNet_C.ExecuteUbergraph_Piranha_Character_BP_BreakNet");
APiranha_Character_BP_BreakNet_C_ExecuteUbergraph_Piranha_Character_BP_BreakNet_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
94dc88adacb207bf0d982f493b90e3532283013c | f7e9b7730a605fe9a5c3b981b0c03ff9a541dc3b | /playerData.inc | 61871438252731524f28c42167af0399a51c6210 | [
"Unlicense"
] | permissive | RevolutionSoftware/Juego | 9bdcc0508e1e0d2cc33024d2a8cfa5fc0b1f4481 | 31c1706e41713e9bcf631f369b89ce1f94bef0d5 | refs/heads/master | 2021-01-19T11:05:50.163401 | 2017-06-29T22:10:01 | 2017-06-29T22:10:01 | 95,699,198 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,911 | inc | ;base stats
characterStats:
franciStats:
.dw 55 ;hp
.dw 10 ;mp
.dw 12 ;str
.dw 12 ;udef
.dw 12 ;ldef
.dw 8 ;agi
.dw 4 ;int
.db 8 ;end
.db 1 ;sinc
.db 0 ;head
.db 0 ;chest
.db 0 ;hands
.db 0 ;feet
.db 0 ;feet slot
.db 0 ;arm left
.db 0 ;arm left slot
.db 0 ;arm right
.db 0 ;arm right slot
.db 0 ;accessory 1
.db 0 ;accessory 2
.db 1 ;level
CHAR_STATS_SIZE = $-characterStats
anselmoStats:
.dw 55 ;hp
.dw 10 ;mp
.dw 12 ;str
.dw 12 ;udef
.dw 12 ;ldef
.dw 8 ;agi
.dw 4 ;int
.db 5 ;end
.db 1 ;sinc
.db 0 ;head
.db 0 ;chest
.db 0 ;hands
.db 0 ;feet
.db 0 ;feet slot
.db 0 ;arm left
.db 0 ;arm left slot
.db 0 ;arm right
.db 0 ;arm right slot
.db 0 ;accessory 1
.db 0 ;accessory 2
.db 0 ;level
nadyaStats:
.dw 55 ;hp
.dw 10 ;mp
.dw 12 ;str
.dw 12 ;udef
.dw 12 ;ldef
.dw 8 ;agi
.dw 4 ;int
.db 5 ;end
.db 1 ;sinc
.db 0 ;head
.db 0 ;chest
.db 0 ;hands
.db 0 ;feet
.db 0 ;feet slot
.db 0 ;arm left
.db 0 ;arm left slot
.db 0 ;arm right
.db 0 ;arm right slot
.db 0 ;accessory 1
.db 0 ;accessory 2
.db 0 ;level
porterStats:
.dw 55 ;hp
.dw 10 ;mp
.dw 12 ;str
.dw 12 ;udef
.dw 12 ;ldef
.dw 8 ;agi
.dw 4 ;int
.db 5 ;end
.db 1 ;sinc
.db 0 ;head
.db 0 ;chest
.db 0 ;hands
.db 0 ;feet
.db 0 ;feet slot
.db 0 ;arm left
.db 0 ;arm left slot
.db 0 ;arm right
.db 0 ;arm right slot
.db 0 ;accessory 1
.db 0 ;accessory 2
.db 0 ;level
pucStats:
.dw 55 ;hp
.dw 10 ;mp
.dw 12 ;str
.dw 12 ;udef
.dw 12 ;ldef
.dw 8 ;agi
.dw 4 ;int
.db 5 ;end
.db 1 ;sinc
.db 0 ;head
.db 0 ;chest
.db 0 ;hands
.db 0 ;feet
.db 0 ;feet slot
.db 0 ;arm left
.db 0 ;arm left slot
.db 0 ;arm right
.db 0 ;arm right slot
.db 0 ;accessory 1
.db 0 ;accessory 2
.db 0 ;level
characterSprites:
anselmo_sprite: #include "npcs/anselmo.bmp"
nadya_sprite: #include "npcs/nadya.bmp"
porter_sprite: #include "npcs/porter.bmp"
puc_sprite: #include "npcs/puc.bmp"
| [
"pokemaster103@gmail.com"
] | pokemaster103@gmail.com |
eda9cca8a4c0cb36bb557a7d3f3fbb19458952da | 4420739a7cb2a2652e97b03600c20c38d0b33168 | /source/EventTestObject.h | 213e6850d7a167bdaecb83d1df8cc0cbaf6357b6 | [] | no_license | MrFloip/Legacy-of-Gold | 3648e664c20bbd470d80b461d009f6fedaadc79e | 1c6db067f9d597bd86473b4c789ffa92d9a0a9c4 | refs/heads/master | 2021-01-17T05:24:15.243939 | 2012-11-19T00:23:36 | 2012-11-19T00:23:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 305 | h | #ifndef _EVENT_TEST_OBJECT_H_
#define _EVENT_TEST_OBJECT_H_
#include "event_manager.hpp"
struct Message
{
int iMsg;
};
class EventTestObject: public EventManager
{
private:
Message message;
public:
EventTestObject();
void printUid();
void sendMessage(int value);
void catchMessage();
};
#endif | [
"Filip.lindeby@gmail.com"
] | Filip.lindeby@gmail.com |
eaa3286cc428ba4f47772f8cc3590ef76622500f | d6569cd6269513c56eab978764c8142abdfc7826 | /snippets/cpp/include/Interface.h | 0e55046cad3b5398eec5d9e8820f7deba79305cc | [] | no_license | mboussaa/Haxe_Samples | 500ec7b2637e005f36f39105a73b643ffadf08fe | 6ba949a702785829fde345341f9d87233a596320 | refs/heads/master | 2021-01-10T18:45:37.327945 | 2014-10-14T10:04:39 | 2014-10-14T10:04:39 | 24,419,063 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,619 | h | #ifndef INCLUDED_Interface
#define INCLUDED_Interface
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS0(Interface)
class HXCPP_CLASS_ATTRIBUTES Interface_obj : public hx::Interface{
public:
typedef hx::Interface super;
typedef Interface_obj OBJ_;
HX_DO_INTERFACE_RTTI;
static void __boot();
virtual ::String lookAndSay( ::String s)=0;
Dynamic lookAndSay_dyn();
virtual bool isValidEmail( ::String email)=0;
Dynamic isValidEmail_dyn();
virtual int FibIter( int limit)=0;
Dynamic FibIter_dyn();
virtual Void findOpenLockers( int n)=0;
Dynamic findOpenLockers_dyn();
};
#define DELEGATE_Interface \
virtual ::String lookAndSay( ::String s) { return mDelegate->lookAndSay(s);} \
virtual Dynamic lookAndSay_dyn() { return mDelegate->lookAndSay_dyn();} \
virtual bool isValidEmail( ::String email) { return mDelegate->isValidEmail(email);} \
virtual Dynamic isValidEmail_dyn() { return mDelegate->isValidEmail_dyn();} \
virtual int FibIter( int limit) { return mDelegate->FibIter(limit);} \
virtual Dynamic FibIter_dyn() { return mDelegate->FibIter_dyn();} \
virtual Void findOpenLockers( int n) { return mDelegate->findOpenLockers(n);} \
virtual Dynamic findOpenLockers_dyn() { return mDelegate->findOpenLockers_dyn();} \
template<typename IMPL>
class Interface_delegate_ : public Interface_obj
{
protected:
IMPL *mDelegate;
public:
Interface_delegate_(IMPL *inDelegate) : mDelegate(inDelegate) {}
hx::Object *__GetRealObject() { return mDelegate; }
void __Visit(HX_VISIT_PARAMS) { HX_VISIT_OBJECT(mDelegate); }
DELEGATE_Interface
};
#endif /* INCLUDED_Interface */
| [
"mohamedboussaa3@gmail.com"
] | mohamedboussaa3@gmail.com |
63dbf9c42433a4049847f5e4112ea517f5f23239 | 2c9532ae2c36f3986b9f0c66b23cb287b8e57f34 | /prime factors of a number.cpp | f0233d4a3e437cb960462cfc1487a311d73e5601 | [] | no_license | sn0wFlake420/-contribution- | 1a1a499652e6cc44f238bc5288842d565f1f3c1a | b658d92d0496f9a29b090120f7e687c0dbf53953 | refs/heads/main | 2023-08-10T07:26:03.441942 | 2021-09-17T12:59:42 | 2021-09-17T12:59:42 | 407,540,166 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 637 | cpp | #include <stdio.h>
#include <conio.h>
main()
{
int i, j, n, p;
printf("Enter a number\n");
scanf("%d", &n);
printf("Prime Factors of %d are\n", n);
for(i=2; i<=n; i++)
{
if(n % i==0)
{
p = 1;
for(j=2; j<=i/2; j++)
{
if(i%j==0)
{
p = 0;
break;
}
}
if(p==1)
{
printf("%d, ", i);
}
}
}
getch();
}
| [
"noreply@github.com"
] | sn0wFlake420.noreply@github.com |
940be3af1e8bcb82176f17e3fb4e08bf9c18be8d | 6cd88e053e5e15daad54c6ba56fec17173d9d324 | /scintilla/lexlib/WordList.h | 71ebaead5489c5a9d30ec3b4433d0cef233b5abf | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-scintilla",
"BSD-2-Clause"
] | permissive | safino9/notepad2 | 8b2e0a14fa4bd4c97dcb4fa8bfc7f7d60041f7d7 | ea41ff9c3cae65e617a5c0b5b590829328f0c570 | refs/heads/master | 2023-03-01T19:52:49.372621 | 2021-02-16T08:50:12 | 2021-02-16T08:50:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,277 | h | // Scintilla source code edit control
/** @file WordList.h
** Hold a list of words.
**/
// Copyright 1998-2010 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#pragma once
namespace Scintilla {
/**
*/
class WordList final {
// Each word contains at least one character - a empty word acts as sentinel at the end.
char **words;
char *list;
int len;
// words in [start, end) starts with same character.
struct Range {
int start;
int end;
};
Range ranges[128]; // only ASCII, most word starts with character in '_a-zA-Z'
public:
explicit WordList() noexcept;
~WordList();
operator bool() const noexcept;
bool operator!=(const WordList &other) const noexcept;
bool operator==(const WordList &other) const noexcept {
return !(*this != other);
}
int Length() const noexcept;
void Clear() noexcept;
bool Set(const char *s, bool toLower);
bool InList(const char *s) const noexcept;
bool InListPrefixed(const char *s, char marker) const noexcept;
bool InListAbbreviated(const char *s, char marker) const noexcept;
bool InListAbridged(const char *s, char marker) const noexcept;
const char *WordAt(int n) const noexcept;
};
}
| [
"zufuliu@gmail.com"
] | zufuliu@gmail.com |
a67da16af38715a1580ec0c496adbd03e91074ea | 55b3b942183b50565ea5f557a8de6a5fc9c09741 | /live_events/CompetitveProgrammingPractice/CSES/IntroductoryProblems/GrayCode/GrayCode.cpp | 0b9610dcc60a1e9b80183446c3a50cbe349c0316 | [] | no_license | weakunix/python_git | e29b3fdaed58f1951718cc412db0007a4183dad9 | a2bfa0365d66e607a952f1b86b734cea0fba020f | refs/heads/master | 2023-09-01T07:13:45.134448 | 2023-08-21T18:03:47 | 2023-08-21T18:03:47 | 190,823,760 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 730 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <algorithm>
#include <cassert>
using namespace std;
typedef long long ll;
typedef pair<int, int> simps;
typedef pair<int, simps> threesome;
#define sec second.first
#define third second.second
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
int n;
vector<string> prv = {"0", "1"};
int main() {
int n;
cin >> n;
for (int i = 1; i < n; i++) {
vector<string> cur;
for (int j = 0; j < (1 << i); j++) cur.push_back("0" + prv[j]);
for (int j = (1 << i) - 1; j >= 0; j--) cur.push_back("1" + prv[j]);
swap(prv, cur);
}
for (string& s : prv) cout << s << "\n";
return 0;
}
| [
"mrmooooyt@gmail.com"
] | mrmooooyt@gmail.com |
959290a7831c625c6e8d527104a8ebaf6359bdb5 | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/pdfium/xfa/fxfa/parser/cxfa_output.h | 3577bb4cbf012d36f30c8e77224997bc9b9fca22 | [
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 579 | h | // Copyright 2017 The PDFium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#ifndef XFA_FXFA_PARSER_CXFA_OUTPUT_H_
#define XFA_FXFA_PARSER_CXFA_OUTPUT_H_
#include "xfa/fxfa/parser/cxfa_node.h"
class CXFA_Output final : public CXFA_Node {
public:
CONSTRUCT_VIA_MAKE_GARBAGE_COLLECTED;
~CXFA_Output() override;
private:
CXFA_Output(CXFA_Document* doc, XFA_PacketType packet);
};
#endif // XFA_FXFA_PARSER_CXFA_OUTPUT_H_
| [
"jengelh@inai.de"
] | jengelh@inai.de |
3949acd2f3f3ffc3ab15779cc861050fb32fbfa6 | 551671f92763cbbf3f59c8dbf710e976b73e06df | /Unreal/FileSystem/UnArchivePak.cpp | d0179d5078d6cf6ee9c190d48ee5fd0fc77d115e | [
"BSD-3-Clause"
] | permissive | Hankant/UEViewer | 5f5ae5a42008ef6b6758e11462d095d3b675927e | 594506ac509f991a46728bce4c087ca1280b8a11 | refs/heads/master | 2023-02-06T07:05:52.267724 | 2020-12-15T20:52:09 | 2020-12-15T20:52:09 | 324,972,350 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,648 | cpp | #include "Core.h"
#include "UnCore.h"
#include "GameFileSystem.h"
#include "FileSystemUtils.h"
#include "UnArchivePak.h"
#if UNREAL4
#define PAK_FILE_MAGIC 0x5A6F12E1
// Number of pak file handles kept open when files no longer used (cache of open pak file handles).
// We're limiting number of simultaneously open pak files to this value in a case game has number
// of pak files exceeding C library limitations (2048 files in msvcrt.dll).
#define MAX_OPEN_PAKS 32
FArchive& operator<<(FArchive& Ar, FPakInfo& P)
{
// New FPakInfo fields.
Ar << P.EncryptionKeyGuid; // PakFile_Version_EncryptionKeyGuid
Ar << P.bEncryptedIndex; // PakFile_Version_IndexEncryption
// Old FPakInfo fields.
Ar << P.Magic;
if (P.Magic != PAK_FILE_MAGIC)
{
// Stop immediately when magic is wrong
return Ar;
}
Ar << P.Version << P.IndexOffset << P.IndexSize;
Ar.Serialize(ARRAY_ARG(P.IndexHash));
#if SOD2
if (GForceGame == GAME_StateOfDecay2)
P.Version &= 0xffff;
#endif
if (P.Version == PakFile_Version_FrozenIndex)
{
uint8 bIndexIsFrozen;
Ar << bIndexIsFrozen;
assert(!bIndexIsFrozen); // used just for 4.25, so don't do any support unless it's really needed
}
if (P.Version >= PakFile_Version_FNameBasedCompressionMethod)
{
// For UE4.23, there are 5 compression methods, but we're ignoring last one.
for (int i = 0; i < 4; i++)
{
char name[32+1];
Ar.Serialize(name, 32);
name[32] = 0;
P.CompressionMethods[i] = StringToCompressionMethod(name);
}
}
// Reset new fields to their default states when seralizing older pak format.
if (P.Version < PakFile_Version_IndexEncryption)
{
P.bEncryptedIndex = false;
}
if (P.Version < PakFile_Version_EncryptionKeyGuid)
{
P.EncryptionKeyGuid = { 0, 0, 0, 0 };
}
return Ar;
}
void FPakEntry::Serialize(FArchive& Ar)
{
guard(FPakEntry<<);
// FPakEntry is duplicated before each stored file, without a filename. So,
// remember the serialized size of this structure to avoid recomputation later.
int64 StartOffset = Ar.Tell64();
#if GEARS4
if (GForceGame == GAME_Gears4)
{
Ar << Pos << (int32&)Size << (int32&)UncompressedSize << (byte&)CompressionMethod;
if (PakVer < PakFile_Version_NoTimestamps)
{
int64 timestamp;
Ar << timestamp;
}
if (PakVer >= PakFile_Version_CompressionEncryption)
{
if (CompressionMethod != 0)
Ar << CompressionBlocks;
Ar << CompressionBlockSize;
if (CompressionMethod == 4)
CompressionMethod = COMPRESS_LZ4;
}
goto end;
}
#endif // GEARS4
Ar << Pos << Size << UncompressedSize;
if (PakVer < PakFile_Version_FNameBasedCompressionMethod)
{
Ar << CompressionMethod;
}
else if (PakVer == PakFile_Version_FNameBasedCompressionMethod && PakSubver == 0)
{
// UE4.22
uint8 CompressionMethodIndex;
Ar << CompressionMethodIndex;
CompressionMethod = CompressionMethodIndex;
}
else
{
// UE4.23+
uint32 CompressionMethodIndex;
Ar << CompressionMethodIndex;
CompressionMethod = CompressionMethodIndex;
}
if (PakVer < PakFile_Version_NoTimestamps)
{
int64 timestamp;
Ar << timestamp;
}
uint8 Hash[20];
Ar.Serialize(ARRAY_ARG(Hash));
if (PakVer >= PakFile_Version_CompressionEncryption)
{
if (CompressionMethod != 0)
Ar << CompressionBlocks;
Ar << bEncrypted << CompressionBlockSize;
}
if (CompressionMethod == COMPRESS_Custom)
{
CompressionMethod = COMPRESS_FIND;
}
#if TEKKEN7
if (GForceGame == GAME_Tekken7)
bEncrypted = false; // Tekken 7 has 'bEncrypted' flag set, but actually there's no encryption
#endif
#if SOD2
if (GForceGame == GAME_StateOfDecay2 && CompressionMethod > 16)
CompressionMethod = COMPRESS_LZ4;
#endif
if (PakVer >= PakFile_Version_RelativeChunkOffsets)
{
// Convert relative compressed offsets to absolute
for (int i = 0; i < CompressionBlocks.Num(); i++)
{
FPakCompressedBlock& B = CompressionBlocks[i];
B.CompressedStart += Pos;
B.CompressedEnd += Pos;
}
}
end:
StructSize = Ar.Tell64() - StartOffset;
unguard;
}
void FPakEntry::DecodeFrom(const uint8* Data)
{
guard(FPakEntry::DecodeFrom);
// UE4 reference: FPakFile::DecodePakEntry()
uint32 Bitfield = *(uint32*)Data;
Data += sizeof(uint32);
CompressionMethod = (Bitfield >> 23) & 0x3f;
// Offset follows - either 32 or 64 bit value
if (Bitfield & 0x80000000)
{
Pos = *(uint32*)Data;
Data += sizeof(uint32);
}
else
{
Pos = *(uint64*)Data;
Data += sizeof(uint64);
}
// The same for UncompressedSize
if (Bitfield & 0x40000000)
{
UncompressedSize = *(uint32*)Data;
Data += sizeof(uint32);
}
else
{
UncompressedSize = *(uint64*)Data;
Data += sizeof(uint64);
}
// Size field
if (CompressionMethod)
{
if (Bitfield & 0x20000000)
{
Size = *(uint32*)Data;
Data += sizeof(uint32);
}
else
{
Size = *(uint64*)Data;
Data += sizeof(uint64);
}
}
else
{
Size = UncompressedSize;
}
// bEncrypted
bEncrypted = (Bitfield >> 22) & 1;
// Compressed block count
int BlockCount = (Bitfield >> 6) & 0xffff;
// Compute StructSize: each file still have FPakEntry data prepended, and it should be skipped.
StructSize = sizeof(int64) * 3 + sizeof(int32) * 2 + 1 + 20;
// Take into account CompressionBlocks
if (CompressionMethod)
{
StructSize += sizeof(int32) + BlockCount * 2 * sizeof(int64);
}
// Compression information
CompressionBlocks.AddUninitialized(BlockCount);
CompressionBlockSize = 0;
if (BlockCount)
{
// CompressionBlockSize
if (UncompressedSize < 65536)
CompressionBlockSize = UncompressedSize;
else
CompressionBlockSize = (Bitfield & 0x3f) << 11;
// CompressionBlocks
if (BlockCount == 1)
{
FPakCompressedBlock& Block = CompressionBlocks[0];
Block.CompressedStart = Pos + StructSize;
Block.CompressedEnd = Block.CompressedStart + Size;
}
else
{
int64 CurrentOffset = Pos + StructSize;
int64 Alignment = bEncrypted ? FPakFile::EncryptionAlign : 1;
for (int BlockIndex = 0; BlockIndex < BlockCount; BlockIndex++)
{
uint32 CurrentBlockSize = *(uint32*)Data;
Data += sizeof(uint32);
FPakCompressedBlock& Block = CompressionBlocks[BlockIndex];
Block.CompressedStart = CurrentOffset;
Block.CompressedEnd = Block.CompressedStart + CurrentBlockSize;
CurrentOffset += Align(CurrentBlockSize, Alignment);
}
}
}
unguard;
}
FPakFile::~FPakFile()
{
// Can't call virtual 'Close' from destructor, so use fully qualified name
FPakFile::Close();
}
void FPakFile::Close()
{
if (UncompressedBuffer)
{
appFree(UncompressedBuffer);
UncompressedBuffer = NULL;
}
if (IsFileOpen)
{
Parent->FileClosed();
IsFileOpen = false;
}
}
void FPakFile::Serialize(void *data, int size)
{
PROFILE_IF(size >= 1024);
guard(FPakFile::Serialize);
if (ArStopper > 0 && ArPos + size > ArStopper)
appError("Serializing behind stopper (%X+%X > %X)", ArPos, size, ArStopper);
// (Re-)open pak file if needed
if (!IsFileOpen)
{
Parent->FileOpened();
IsFileOpen = true;
}
FArchive* Reader = Parent->Reader;
if (Info->CompressionMethod)
{
guard(SerializeCompressed);
while (size > 0)
{
if ((UncompressedBuffer == NULL) || (ArPos < UncompressedBufferPos) || (ArPos >= UncompressedBufferPos + Info->CompressionBlockSize))
{
// buffer is not ready
if (UncompressedBuffer == NULL)
{
UncompressedBuffer = (byte*)appMallocNoInit((int)Info->CompressionBlockSize); // size of uncompressed block
}
// prepare buffer
int BlockIndex = ArPos / Info->CompressionBlockSize;
UncompressedBufferPos = Info->CompressionBlockSize * BlockIndex;
const FPakCompressedBlock& Block = Info->CompressionBlocks[BlockIndex];
int CompressedBlockSize = (int)(Block.CompressedEnd - Block.CompressedStart);
int UncompressedBlockSize = min((int)Info->CompressionBlockSize, (int)Info->UncompressedSize - UncompressedBufferPos); // don't pass file end
byte* CompressedData;
if (!Info->bEncrypted)
{
CompressedData = (byte*)appMallocNoInit(CompressedBlockSize);
Reader->Seek64(Block.CompressedStart);
Reader->Serialize(CompressedData, CompressedBlockSize);
}
else
{
int EncryptedSize = Align(CompressedBlockSize, EncryptionAlign);
CompressedData = (byte*)appMallocNoInit(EncryptedSize);
Reader->Seek64(Block.CompressedStart);
Reader->Serialize(CompressedData, EncryptedSize);
FileRequiresAesKey();
appDecryptAES(CompressedData, EncryptedSize);
}
appDecompress(CompressedData, CompressedBlockSize, UncompressedBuffer, UncompressedBlockSize, Info->CompressionMethod);
appFree(CompressedData);
}
// data is in buffer, copy it
int BytesToCopy = UncompressedBufferPos + Info->CompressionBlockSize - ArPos; // number of bytes until end of the buffer
if (BytesToCopy > size) BytesToCopy = size;
assert(BytesToCopy > 0);
// copy uncompressed data
int OffsetInBuffer = ArPos - UncompressedBufferPos;
memcpy(data, UncompressedBuffer + OffsetInBuffer, BytesToCopy);
// advance pointers
ArPos += BytesToCopy;
size -= BytesToCopy;
data = OffsetPointer(data, BytesToCopy);
}
unguard;
}
else if (Info->bEncrypted)
{
guard(SerializeEncrypted);
// Uncompressed encrypted data. Reuse compression fields to handle decryption efficiently
if (UncompressedBuffer == NULL)
{
UncompressedBuffer = (byte*)appMallocNoInit(EncryptedBufferSize);
UncompressedBufferPos = 0x40000000; // some invalid value
}
while (size > 0)
{
if ((ArPos < UncompressedBufferPos) || (ArPos >= UncompressedBufferPos + EncryptedBufferSize))
{
// Should fetch block and decrypt it.
// Note: AES is block encryption, so we should always align read requests for correct decryption.
UncompressedBufferPos = ArPos & ~(EncryptionAlign - 1);
Reader->Seek64(Info->Pos + Info->StructSize + UncompressedBufferPos);
int RemainingSize = Info->Size - UncompressedBufferPos;
if (RemainingSize > EncryptedBufferSize)
RemainingSize = EncryptedBufferSize;
RemainingSize = Align(RemainingSize, EncryptionAlign); // align for AES, pak contains aligned data
Reader->Serialize(UncompressedBuffer, RemainingSize);
FileRequiresAesKey();
appDecryptAES(UncompressedBuffer, RemainingSize);
}
// Now copy decrypted data from UncompressedBuffer (code is very similar to those used in decompression above)
int BytesToCopy = UncompressedBufferPos + EncryptedBufferSize - ArPos; // number of bytes until end of the buffer
if (BytesToCopy > size) BytesToCopy = size;
assert(BytesToCopy > 0);
// copy uncompressed data
int OffsetInBuffer = ArPos - UncompressedBufferPos;
memcpy(data, UncompressedBuffer + OffsetInBuffer, BytesToCopy);
// advance pointers
ArPos += BytesToCopy;
size -= BytesToCopy;
data = OffsetPointer(data, BytesToCopy);
}
unguard;
}
else
{
guard(SerializeUncompressed);
// Pure data
// seek every time in a case if the same 'Reader' was used by different FPakFile
// (this is a lightweight operation for buffered FArchive)
Reader->Seek64(Info->Pos + Info->StructSize + ArPos);
Reader->Serialize(data, size);
ArPos += size;
unguard;
}
unguardf("file=%s", *Info->FileInfo->GetRelativeName());
}
bool FPakVFS::AttachReader(FArchive* reader, FString& error)
{
int mainVer = 0, subVer = 0;
guard(FPakVFS::ReadDirectory);
PROFILE_LABEL(*Filename);
// Pak file may have different header sizes, try them all
static const int OffsetsToTry[] = { FPakInfo::Size, FPakInfo::Size8, FPakInfo::Size8a, FPakInfo::Size9 };
FPakInfo info;
for (int32 Offset : OffsetsToTry)
{
// Read pak header
int64 HeaderOffset = reader->GetFileSize64() - Offset;
if (HeaderOffset <= 0)
{
// The file is too small
return false;
}
reader->Seek64(HeaderOffset);
*reader << info;
if (info.Magic == PAK_FILE_MAGIC) // no endian checking here
{
if (Offset == FPakInfo::Size8a && info.Version == 8)
{
subVer = 1;
}
break;
}
}
if (info.Magic != PAK_FILE_MAGIC)
{
// We didn't find a pak header
return false;
}
if (info.Version > PakFile_Version_Latest)
{
appPrintf("WARNING: Pak file \"%s\" has unsupported version %d\n", *Filename, info.Version);
}
mainVer = info.Version;
if (info.bEncryptedIndex)
{
if (!FileRequiresAesKey(false))
{
char buf[1024];
appSprintf(ARRAY_ARG(buf), "WARNING: Pak \"%s\" has encrypted index. Skipping.", *Filename);
error = buf;
return false;
}
}
// Read pak index
// Set PakVer
reader->ArLicenseeVer = MakePakVer(mainVer, subVer);
reader->Seek64(info.IndexOffset);
bool result = false;
if (info.Version < PakFile_Version_PathHashIndex)
{
result = LoadPakIndexLegacy(reader, info, error);
}
else
{
result = LoadPakIndex(reader, info, error);
}
if (result)
{
// Print statistics
appPrintf("Pak %s: %d files", *Filename, FileInfos.Num());
if (NumEncryptedFiles)
appPrintf(" (%d encrypted)", NumEncryptedFiles);
if (strcmp(*MountPoint, "/") != 0)
appPrintf(", mount point: \"%s\"", *MountPoint);
appPrintf(", version %d\n", info.Version);
}
// Close the file handle
if (Reader)
{
Reader->Close();
}
return result;
unguardf("PakVer=%d.%d", mainVer, subVer);
}
// FPakVFS objects which has Reader open, but no active files (MRU)
static TStaticArray<FPakVFS*, MAX_OPEN_PAKS> VFSWithOpenReaders;
FArchive* FPakVFS::CreateReader(int index)
{
guard(FPakVFS::CreateReader);
const FPakEntry& info = FileInfos[index];
FileOpened();
return new FPakFile(&info, this);
unguard;
}
void FPakVFS::FileOpened()
{
guard(FPakVFS::FileOpened);
if (NumOpenFiles++ == 0)
{
// This is the very first open handle in pak.
// This pak could be in VFSWithOpenReaders list, in this case just reuse it without opening.
int FoundIndex = VFSWithOpenReaders.FindItem(this);
if (FoundIndex >= 0)
{
// This pak should be already opened
assert(VFSWithOpenReaders[FoundIndex]->Reader->IsOpen());
VFSWithOpenReaders.RemoveAt(FoundIndex);
}
else
{
if (!Reader->IsOpen())
Reader->Open();
}
}
unguard;
}
void FPakVFS::FileClosed()
{
guard(FPakVFS::FileClosed);
assert(NumOpenFiles > 0);
if (--NumOpenFiles == 0)
{
// Put this pak file into VFSWithOpenReaders.
// Check for MRU list overflow, drop the olders pak file.
if (VFSWithOpenReaders.Num() == MAX_OPEN_PAKS)
{
VFSWithOpenReaders[MAX_OPEN_PAKS-1]->Reader->Close();
VFSWithOpenReaders.RemoveAt(MAX_OPEN_PAKS-1);
}
VFSWithOpenReaders.Insert(this, 0);
}
unguard;
}
static bool ValidateString(FArchive& Ar)
{
// We're operating with index data, which is definitely less than 2Gb of size, so use Tell instead of Tell64.
int SavePos = Ar.Tell();
// Try to validate the decrypted data. The first thing going here is MountPoint which is FString.
int32 StringLen;
Ar << StringLen;
bool bFail = false;
if (StringLen > 512 || StringLen < -512)
{
bFail = true;
}
if (!bFail)
{
// Seek to terminating zero character
if (StringLen < 0)
{
Ar.Seek(Ar.Tell() - (StringLen - 1) * 2);
uint16 c;
Ar << c;
bFail = (c != 0);
}
else
{
Ar.Seek(Ar.Tell() + StringLen - 1);
char c;
Ar << c;
bFail = (c != 0);
}
}
Ar.Seek(SavePos);
return !bFail;
}
bool FPakVFS::LoadPakIndexLegacy(FArchive* reader, const FPakInfo& info, FString& error)
{
guard(FPakVFS::LoadPakIndexLegacy);
// Always read index to memory block for faster serialization
TArray<byte> InfoBlock;
InfoBlock.SetNumUninitialized(info.IndexSize);
reader->Serialize(InfoBlock.GetData(), info.IndexSize);
FMemReader InfoReader(InfoBlock.GetData(), info.IndexSize);
InfoReader.SetupFrom(*reader);
// Manage pak files with encrypted index
if (info.bEncryptedIndex)
{
guard(CheckEncryptedIndex);
appDecryptAES(InfoBlock.GetData(), InfoBlock.Num());
// Try to validate the decrypted data. The first thing going here is MountPoint which is FString.
if (!ValidateString(InfoReader))
{
char buf[1024];
appSprintf(ARRAY_ARG(buf), "WARNING: The provided encryption key doesn't work with \"%s\". Skipping.", *Filename);
error = buf;
return false;
}
// Data is ok, seek to data start.
InfoReader.Seek(0);
unguard;
}
// this file looks correct, store 'reader'
Reader = reader;
// Read pak index
TRY {
// Read MountPoint with catching error, to override error message.
InfoReader << MountPoint;
} CATCH {
if (info.bEncryptedIndex)
{
// Display nice error message
appErrorNoLog("Error during loading of encrypted pak file index. Probably the provided AES key is not correct.");
}
else
{
THROW_AGAIN;
}
}
// Read number of files
int32 count;
InfoReader << count;
if (!count)
{
// appPrintf("Empty pak file \"%s\"\n", *Filename);
return true;
}
// Process MountPoint
ValidateMountPoint(MountPoint, Filename);
// Read file information
FileInfos.AddZeroed(count);
Reserve(count);
for (int i = 0; i < count; i++)
{
guard(ReadInfo);
FPakEntry& E = FileInfos[i];
// serialize name, combine with MountPoint
FStaticString<MAX_PACKAGE_PATH> Filename;
InfoReader << Filename;
FStaticString<MAX_PACKAGE_PATH> CombinedPath;
CombinedPath = MountPoint;
CombinedPath += Filename;
// compact file name
CompactFilePath(CombinedPath);
// serialize other fields
E.Serialize(InfoReader);
if (E.bEncrypted)
{
// appPrintf("Encrypted file: %s\n", *Filename);
NumEncryptedFiles++;
}
if (info.Version >= PakFile_Version_FNameBasedCompressionMethod)
{
int32 CompressionMethodIndex = E.CompressionMethod;
assert(CompressionMethodIndex >= 0 && CompressionMethodIndex <= 4);
E.CompressionMethod = CompressionMethodIndex > 0 ? info.CompressionMethods[CompressionMethodIndex-1] : 0;
}
else if (E.CompressionMethod == COMPRESS_Custom)
{
// Custom compression method for UE4.20-UE4.21, use detection code.
E.CompressionMethod = COMPRESS_FIND;
}
// Register the file
CRegisterFileInfo reg;
reg.Filename = *CombinedPath;
reg.Size = E.UncompressedSize;
reg.IndexInArchive = i;
E.FileInfo = RegisterFile(reg);
unguardf("Index=%d/%d", i, count);
}
#if 0
if (count >= MIN_PAK_SIZE_FOR_HASHING)
{
// Hash everything
for (FPakEntry& E : FileInfos)
{
AddFileToHash(&E);
}
}
#endif
return true;
unguard;
}
bool FPakVFS::LoadPakIndex(FArchive* reader, const FPakInfo& info, FString& error)
{
guard(FPakVFS::LoadPakIndex);
// Read full index into InfoBlock and setup InfoReader
TArray<byte> InfoBlock;
InfoBlock.SetNumUninitialized(info.IndexSize);
reader->Serialize(InfoBlock.GetData(), info.IndexSize);
FMemReader InfoReader(InfoBlock.GetData(), info.IndexSize);
InfoReader.SetupFrom(*reader);
// Manage pak files with encrypted index
if (info.bEncryptedIndex)
{
guard(CheckEncryptedIndex);
appDecryptAES(InfoBlock.GetData(), InfoBlock.Num());
// Try to validate the decrypted data. The first thing going here is MountPoint which is FString.
if (!ValidateString(InfoReader))
{
char buf[1024];
appSprintf(ARRAY_ARG(buf), "WARNING: The provided encryption key doesn't work with \"%s\". Skipping.", *Filename);
error = buf;
return false;
}
// Data is ok, seek to data start.
InfoReader.Seek(0);
unguard;
}
// this file looks correct, store 'reader'
Reader = reader;
// Read pak index
TRY {
// Read MountPoint with catching error, to override error message.
InfoReader << MountPoint;
} CATCH {
if (info.bEncryptedIndex)
{
// Display nice error message
appErrorNoLog("Error during loading of encrypted pak file index. Probably the provided AES key is not correct.");
}
else
{
THROW_AGAIN;
}
}
// Read number of files
int32 count;
InfoReader << count;
if (!count)
{
// appPrintf("Empty pak file \"%s\"\n", *Filename);
return true;
}
Reserve(count);
// Process MountPoint
ValidateMountPoint(MountPoint, Filename);
uint64 PathHashSeed;
InfoReader << PathHashSeed;
// Read directory information
bool bReaderHasPathHashIndex;
int64 PathHashIndexOffset = -1;
int64 PathHashIndexSize = 0;
InfoReader << bReaderHasPathHashIndex;
if (bReaderHasPathHashIndex)
{
InfoReader << PathHashIndexOffset << PathHashIndexSize;
// Skip PathHashIndexHash
InfoReader.Seek(InfoReader.Tell() + 20);
}
bool bReaderHasFullDirectoryIndex = false;
int64 FullDirectoryIndexOffset = -1;
int64 FullDirectoryIndexSize = 0;
InfoReader << bReaderHasFullDirectoryIndex;
if (bReaderHasFullDirectoryIndex)
{
InfoReader << FullDirectoryIndexOffset << FullDirectoryIndexSize;
// Skip FullDirectoryIndexHash
InfoReader.Seek(InfoReader.Tell() + 20);
}
if (!bReaderHasFullDirectoryIndex)
{
// todo: read PathHashIndex: PathHashIndexOffset + PathHashIndexSize
// todo: structure: TMap<uint64, FPakEntryLocation> (i.e. not array), FPakEntryLocation = int32
// todo: seems it maps hash to file index.
char buf[1024];
appSprintf(ARRAY_ARG(buf), "WARNING: Pak file \"%s\" doesn't have a full index. Skipping.", *Filename);
error = buf;
return false;
}
TArray<uint8> EncodedPakEntries;
InfoReader << EncodedPakEntries;
// Read 'Files' array. This one holds decoded file entries, without file names.
TArray<FPakEntry> Files;
InfoReader << Files;
// Read the full index via the same InfoReader object
assert(bReaderHasFullDirectoryIndex);
guard(ReadFullDirectory);
reader->Seek64(FullDirectoryIndexOffset);
InfoBlock.Empty(); // avoid reallocation with memcpy
InfoBlock.SetNumUninitialized(FullDirectoryIndexSize);
reader->Serialize(InfoBlock.GetData(), FullDirectoryIndexSize);
InfoReader = FMemReader(InfoBlock.GetData(), InfoBlock.Num());
InfoReader.SetupFrom(*reader);
if (info.bEncryptedIndex)
{
// Read encrypted data and decrypt
appDecryptAES(InfoBlock.GetData(), InfoBlock.Num());
}
unguard;
// Now InfoReader points to the full index data, either with use of 'reader' or 'InfoReaderProxy'.
// Build "legacy" FileInfos array from new data format
FileInfos.AddZeroed(count);
guard(BuildFullDirectory);
int FileIndex = 0;
/*
// We're unwrapping this complex structure serializer for faster performance (much less allocations)
using FPakEntryLocation = int32;
typedef TMap<FString, FPakEntryLocation> FPakDirectory;
// Each directory has files, it maps clean filename to index
TMap<FString, FPakDirectory> DirectoryIndex;
InfoReader << DirectoryIndex;
*/
int32 DirectoryCount;
InfoReader << DirectoryCount;
for (int DirectoryIndex = 0; DirectoryIndex < DirectoryCount; DirectoryIndex++)
{
guard(Directory);
// Read DirectoryIndex::Key
FStaticString<MAX_PACKAGE_PATH> DirectoryName;
InfoReader << DirectoryName;
// Build folder name. MountPoint ends with '/', directory name too.
FStaticString<MAX_PACKAGE_PATH> DirectoryPath;
DirectoryPath = MountPoint;
DirectoryPath += DirectoryName;
CompactFilePath(DirectoryPath);
if (DirectoryPath[DirectoryPath.Len()-1] == '/')
DirectoryPath.RemoveAt(DirectoryPath.Len()-1, 1);
// Read size of FPakDirectory (DirectoryIndex::Value)
int32 NumFilesInDirectory;
InfoReader << NumFilesInDirectory;
int FolderIndex = -1;
if (NumFilesInDirectory)
{
FolderIndex = RegisterGameFolder(*DirectoryPath);
}
for (int DirectoryFileIndex = 0; DirectoryFileIndex < NumFilesInDirectory; DirectoryFileIndex++)
{
guard(File);
// Read FPakDirectory entry Key
FStaticString<MAX_PACKAGE_PATH> DirectoryFileName;
InfoReader << DirectoryFileName;
// Read FPakDirectory entry Value
int32 PakEntryLocation;
InfoReader << PakEntryLocation;
FPakEntry& E = FileInfos[FileIndex];
// PakEntryLocation is positive (offset in 'EncodedPakEntries') or negative (index in 'Files')
// References in UE4:
// FPakFile::DecodePakEntry <- FPakFile::GetPakEntry (decode or pick from 'Files') <- FPakFile::Find (name to index/location)
if (PakEntryLocation < 0)
{
// Index in 'Files' array
E.CopyFrom(Files[-(PakEntryLocation + 1)]);
}
else
{
// Pointer in 'EncodedPakEntries'
E.DecodeFrom(&EncodedPakEntries[PakEntryLocation]);
}
if (E.bEncrypted)
{
// appPrintf("Encrypted file: %s\n", *Filename);
NumEncryptedFiles++;
}
// Convert compression method
int32 CompressionMethodIndex = E.CompressionMethod;
assert(CompressionMethodIndex >= 0 && CompressionMethodIndex <= 4);
E.CompressionMethod = CompressionMethodIndex > 0 ? info.CompressionMethods[CompressionMethodIndex-1] : 0;
// Register the file
CRegisterFileInfo reg;
reg.Filename = *DirectoryFileName;
reg.FolderIndex = FolderIndex;
reg.Size = E.UncompressedSize;
reg.IndexInArchive = FileIndex;
E.FileInfo = RegisterFile(reg);
FileIndex++;
unguard;
}
unguard;
}
if (FileIndex != FileInfos.Num())
{
appError("Wrong pak file directory?");
}
unguard;
#if 0
if (count >= MIN_PAK_SIZE_FOR_HASHING)
{
// Hash everything
for (FPakEntry& E : FileInfos)
{
AddFileToHash(&E);
}
}
#endif
return true;
unguard;
}
#if 0
const FPakEntry* FPakVFS::FindFile(const char* name)
{
if (LastInfo && !stricmp(LastInfo->Name, name))
return LastInfo;
FastNameComparer cmp(name);
if (HashTable)
{
// Have a hash table, use it
uint16 hash = GetHashForFileName(name);
for (FPakEntry* info = HashTable[hash]; info; info = info->HashNext)
{
if (cmp(info->Name))
{
LastInfo = info;
return info;
}
}
return NULL;
}
// Linear search without a hash table
for (int i = 0; i < FileInfos.Num(); i++)
{
FPakEntry* info = &FileInfos[i];
if (!stricmp(info->Name, name))
{
LastInfo = info;
return info;
}
}
return NULL;
}
#endif
#endif // UNREAL4
| [
"git@gildor.org"
] | git@gildor.org |
67020f5ebd0c8f9bffa230e0cd6f3b9272528205 | 3559f65cdaa8535ebb2e53653a6cd6234c55cf10 | /StructureProject/Testers/LinearTester.hpp | a32fc73aecdb327da11192ff6dafd051be850582 | [] | no_license | rphi8796/StructureProject | d433ccaceb7e680b0d7453834abab75b8b1fcabc | 33c0c06ccd71beb5c18c55e37e0970fe114e1572 | refs/heads/master | 2020-04-19T05:27:25.037698 | 2019-05-04T17:16:21 | 2019-05-04T17:16:21 | 167,988,248 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 686 | hpp | //
// LinkedListTester.hpp
// StructureProject
//
// Created by Phillips, Ryan on 2/13/19.
// Copyright © 2019 CTEC. All rights reserved.
//
#ifndef LinearTester_hpp
#define LinearTester_hpp
#include "../Controller/FileController.hpp"
#include "../Controller/Tools/Timer.hpp"
#include "../Model/Linear/LinkedList.hpp"
#include "../Model/Linear/Stack.hpp"
#include "../Model/Linear/Queue.hpp"
#include "../Model/Linear/Array.hpp"
#include "../Model/Linear/CircularList.hpp"
#include <iostream>
using namespace std;
class LinearTester
{
public:
void testVsSTL();
void testVsStack();
void testVsQueue();
void testVsDouble();
};
#endif /* LinkedListTester_hpp */
| [
"jlkfop@gmail.com"
] | jlkfop@gmail.com |
dd3979df672203d317508579c181f80916167d03 | 1cf139d2eb6ae9e82bcf2fb5bb30d2c3e689bb6f | /node_modules/msnodesqlv8/src/ReadNextResultOperation.h | 0cdcd858b389d1eef6f76d86a54b9e198267da61 | [
"MIT",
"Apache-2.0"
] | permissive | narendra9268/attendance | 759aa96891e1d394667a267cbbef2865d473b0ae | 3fc619b7561e73da5ab35e593100fe2a92ea4565 | refs/heads/master | 2020-03-28T22:29:12.875655 | 2018-09-18T06:04:22 | 2018-09-18T06:04:22 | 149,236,385 | 0 | 1 | MIT | 2018-12-09T16:47:47 | 2018-09-18T06:00:18 | JavaScript | UTF-8 | C++ | false | false | 1,510 | h | //---------------------------------------------------------------------------------------------------------------------------------
// File: OdbcOperation.h
// Contents: ODBC Operation objects called on background thread
//
// Copyright Microsoft Corporation and contributors
//
// 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 <OdbcOperation.h>
namespace mssql
{
using namespace std;
using namespace v8;
class OdbcConnection;
class ReadNextResultOperation : public OdbcOperation
{
public:
ReadNextResultOperation(shared_ptr<OdbcConnection> connection, size_t queryId, Handle<Object> callback)
: OdbcOperation(connection, callback), preRowCount(-1), postRowCount(-1)
{
_statementId = queryId;
}
bool TryInvokeOdbc() override;
Local<Value> CreateCompletionArg() override;
SQLLEN preRowCount;
SQLLEN postRowCount;
};
}
| [
"narendra.soni@cloudester.com"
] | narendra.soni@cloudester.com |
d37db9c0c42631feb9805d5c61556c023c1ef56c | 7b88f02d8824db9da785d3dad6e31a0f123e02bc | /9.7/Time.h | 3df8cd25ba0cfd9c0a1a314322b8bf3204f6251b | [] | no_license | guoyuting666/Guo_Yuting | 4e2811f1565b7f0f5669b5531ea2b6d51daf8802 | dcd89e64afc42c81d81f5a4b97c4e32770ab20e0 | refs/heads/master | 2020-04-28T03:18:29.055277 | 2019-06-02T03:16:20 | 2019-06-02T03:16:20 | 174,931,711 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 386 | h | #ifndef TIME_H
#define TIME_H
class Time
{
public:
Time( int = 0, int = 0, int = 0 );
void setTime( int, int, int );
void setHour( int );
void setMinute( int );
void setSecond( int );
int getHour();
int getMinute();
int getSecond();
void tick();
void printUniversal();
void printStandard();
private:
int hour;
int minute;
int second;
};
#endif
| [
"769140403@qq.com"
] | 769140403@qq.com |
c3c545e880ce9924637686f975b080e5aad8f497 | 53180a2f2279f932c590b0768c2e9e69919cc929 | /Vehicle.h | 36b8bb75aa8b9aeb3e2e1d654ce472cda7faf49d | [] | no_license | ClarkMulvey/SDLProject | 72791059bf8166793b453d10bfdcd6b23870c94f | ec7532640bdb4c7c2198c1ba4637dc7b1d96582d | refs/heads/main | 2023-02-02T06:59:04.968483 | 2020-12-14T06:42:43 | 2020-12-14T06:42:43 | 317,441,733 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,170 | h | #include <iostream>
#include <cassert>
#ifndef VEHICLE_H
#define VEHICLE_H
class Vehicle
{
protected:
double speed;
double fuel;
double maxFuel;
double accelerateBurnRate;
public:
Vehicle();
Vehicle(double speed, double fuel, double maxFuel, double accelerateBurnRate);
void GetStatus();
void Refuel(double fuel);
void Accelerate(double mph);
// To help with writing test cases
const double GetSpeed();
const double GetFuel();
const double GetMaxFuel();
};
// default constructor
Vehicle::Vehicle()
{
this->speed = 0;
this->fuel = 0;
this->maxFuel = 0;
this->accelerateBurnRate = 0;
}
// non-default constructor
Vehicle::Vehicle(double speed, double fuel, double maxFuel, double accelerateBurnRate)
{
this->speed = speed;
this->fuel = fuel;
this->maxFuel = maxFuel;
this->accelerateBurnRate = accelerateBurnRate;
}
// GETTERS
const double Vehicle::GetSpeed()
{
return this->speed;
}
const double Vehicle::GetFuel()
{
return this->fuel;
}
const double Vehicle::GetMaxFuel()
{
return this->maxFuel;
}
// Print out the current state of the Vehicle
void Vehicle::GetStatus()
{
std::cout << "The current state of the vehicle: \n";
std::cout << "Speed (mph): " << this->speed << std::endl;
std::cout << "Fuel (gallons): " << this->fuel << std::endl << std::endl;
}
// Refuel a specified number of gallons
// You can't overfill the tank
void Vehicle::Refuel(double fuelIntake)
{
assert(fuelIntake >= 0);
if ((this->fuel + fuelIntake) >= this->maxFuel)
{
this->fuel = this->maxFuel;
}
else
{
this->fuel += fuelIntake;
}
}
// Accelerate a specified number of mph
// Each additional mph should decrease fuel by accelerateBurnRate gallons
// Signal if there isn't enough fuel to perform the operation
void Vehicle::Accelerate(double mphIncrease)
{
assert(mphIncrease >= 0);
double fuelSpent = mphIncrease * accelerateBurnRate;
// Vehicle has enough fuel
if ((this->fuel - fuelSpent) >= 0)
{
this->fuel -= fuelSpent;
this->speed += mphIncrease;
}
// Vehicle does not have enough fuel
else
{
std::cout << "The vehicle does not have enough fuel for that maneuver.\n\n";
}
}
#endif //VEHICLE_H | [
"clarkgmulvey3@gmail.com"
] | clarkgmulvey3@gmail.com |
962775d6c54302dfc2e95e9f3491a6cd869fd1c2 | 77815edd2b5e5e27c2ebd8d7f00e135b0e41a6c5 | /memmon/gdiswitcher.h | 86930b6d9354d78a33ac1292d7f5caa6e14ca268 | [
"MIT"
] | permissive | fengsiri/memtools | 787571f907b0b092d1144e8f85e5b6e88c858d67 | ef5dd39fcb99865d0c6164fa7d863f1013a7fd39 | refs/heads/master | 2021-06-08T10:01:40.351855 | 2016-09-25T19:42:19 | 2016-09-25T19:42:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | h | #ifndef GDISWITCHER_H
#define GDISWITCHER_H
// Copyright (c) 2009 Charles Bailey
#include <windows.h>
#include "mminfo.h"
namespace GDI
{
class Switcher
{
public:
Switcher(HDC hdc, HGDIOBJ hobj)
: _hdc(hdc)
, _hobj(::SelectObject(_hdc, hobj))
{
if (_hobj == NULL)
throw MemMon::ConstructorFailure<Switcher>();
}
~Switcher()
{
::SelectObject(_hdc, _hobj);
}
private:
HDC _hdc;
HGDIOBJ _hobj;
};
}
#endif//GDISWITCHER_H
| [
"charles@hashpling.org"
] | charles@hashpling.org |
4f8106d12c81f003ca383e8b923bc7f35b905960 | b33a9177edaaf6bf185ef20bf87d36eada719d4f | /qtxmlpatterns/src/xmlpatterns/data/qschemanumeric_p.h | e1b1258b98294c06f60610bbcbce0258d9aa19ee | [
"LGPL-2.0-or-later",
"LGPL-3.0-only",
"GPL-3.0-only",
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"GFDL-1.3-only",
"Qt-LGPL-exception-1.1",
"LGPL-2.1-only",
"LicenseRef-scancode-digia-qt-preview",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-generic-exception"
] | permissive | wgnet/wds_qt | ab8c093b8c6eead9adf4057d843e00f04915d987 | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | refs/heads/master | 2021-04-02T11:07:10.181067 | 2020-06-02T10:29:03 | 2020-06-02T10:34:19 | 248,267,925 | 1 | 0 | Apache-2.0 | 2020-04-30T12:16:53 | 2020-03-18T15:20:38 | null | UTF-8 | C++ | false | false | 8,377 | h | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtXmlPatterns module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
#ifndef Patternist_Numeric_H
#define Patternist_Numeric_H
#include <private/qitem_p.h>
#include <private/qprimitives_p.h>
QT_BEGIN_NAMESPACE
/**
* @file
* @short Contains class Numeric. This file was originally called qnumeric_p.h,
* but various build systems cannot handle that that name happens to be
* identical to another one, the one in QtCore.
*/
namespace QPatternist
{
/**
* @short Base class for all numeric values.
*
* @section creation Creating Instances
*
* @todo
* - Depending on what type of val
* - Numeric::createFromString
* - Various classes has ::Zero(), ::PosINF(), ::NaN(), NegINF()
* - Never use constructor, use createFromNative, or createFromString.
*
* @see <a href="http://www.w3.org/TR/xquery-operators/#numeric-functions">XQuery 1.0
* and XPath 2.0 Functions and Operators, 6 Functions and Operators on Numerics</a>
* @see <a href="http://www.w3.org/TR/xquery-operators/#func-overloading">XQuery 1.0
* and XPath 2.0 Functions and Operators, 1.2 Function Overloading</a>
* @author Frans Englich <frans.englich@nokia.com>
* @ingroup Patternist_xdm
* @todo discuss data hierarchy the non existatnt number data type
*/
class Numeric : public AtomicValue
{
public:
typedef QExplicitlySharedDataPointer<Numeric> Ptr;
/**
* Creates a Numeric sub-class that is appropriate for @p number.
*
* @note usages of e/E is not handled; Double::fromLexical should
* be used in that case. There is no function similar to fromLexical that also
* takes double values into account(because that distinction is done in the scanner).
*
* Currently used in the parser to create appropriate expressions.
*/
static AtomicValue::Ptr fromLexical(const QString &number);
/**
* @returns the particular number's value as a native representation of
* the type xs:double. This can be considered that the value is cast to
* xs:double.
*/
virtual xsDouble toDouble() const = 0;
/**
* @returns the particular number's value as a native representation of
* the type xs:integer. This can be considered that the value is cast to
* xs:integer.
*/
virtual xsInteger toInteger() const = 0;
/**
* @returns the number as an unsigned integer. If the value is not
* unsigned, the code asserts and behavior is undefined.
*/
virtual qulonglong toUnsignedInteger() const = 0;
/**
* @returns the particular number's value as a native representation of
* the type xs:float. This can be considered that the value is cast to
* xs:float.
*/
virtual xsFloat toFloat() const = 0;
/**
* @returns the particular number's value as a native representation of
* the type xs:decimal. This can be considered that the value is cast to
* xs:decimal.
*/
virtual xsFloat toDecimal() const = 0;
/**
* Performs the algorithm specified for the function fn:round on this Numeric,
* and whose result is returned.
*
* @see <a href="http://www.w3.org/TR/xpath-functions/#func-round">XQuery 1.0
* and XPath 2.0 Functions and Operators, 6.4.4 fn:round</a>
*/
virtual Numeric::Ptr round() const = 0;
/**
* Performs rounding as defined for the fn:round-half-to-even on this Numeric,
* and whose result is returned.
*
* @see <a href="http://www.w3.org/TR/xpath-functions/#func-round-half-to-even">XQuery 1.0
* and XPath 2.0 Functions and Operators, 6.4.5 fn:round-half-to-even</a>
*/
virtual Numeric::Ptr roundHalfToEven(const xsInteger scale) const = 0;
/**
* Performs the algorithm specified for the function fn:floor on this Numeric,
* and whose result is returned.
*
* @see <a href="http://www.w3.org/TR/xpath-functions/#func-floor">XQuery 1.0
* and XPath 2.0 Functions and Operators, 6.4.3 fn:floor</a>
*/
virtual Numeric::Ptr floor() const = 0;
/**
* Performs the algorithm specified for the function fn:ceiling on this Numeric,
* and whose result is returned.
*
* @see <a href="http://www.w3.org/TR/xpath-functions/#func-ceiling">XQuery 1.0
* and XPath 2.0 Functions and Operators, 6.4.2 fn:ceiling</a>
*/
virtual Numeric::Ptr ceiling() const = 0;
/**
* Performs the algorithm specified for the function fn:abs on this Numeric,
* and whose result is returned.
*
* @see <a href="http://www.w3.org/TR/xpath-functions/#func-ceiling">XQuery 1.0
* and XPath 2.0 Functions and Operators, 6.4.1 fn:abs</a>
*/
virtual Numeric::Ptr abs() const = 0;
/**
* Determines whether this Numeric is not-a-number, @c NaN. For numeric types
* that cannot represent @c NaN, this function should return @c false.
*
* @returns @c true if this Numeric is @c NaN
*/
virtual bool isNaN() const = 0;
/**
* Determines whether this Numeric is an infinite number. Signedness
* is irrelevant, -INF as well as INF is considered infinity.
*
* For numeric types that cannot represent infinity, such as xs:integer
* , this function should return @c false.
*
* @returns @c true if this Numeric is an infinite number
*/
virtual bool isInf() const = 0;
/**
* Unary minus.
*/
virtual Item toNegated() const = 0;
/**
* @short Returns @c true if this value is signed. If @c false is
* returned, the value is unsigned.
*
* For float and decimal values, @c xs:double, @c xs:float and @c
* xs:decimal, the code asserts and behavior is undefined.
*/
virtual bool isSigned() const = 0;
protected:
/**
* @short Implements @c fn:round() for types implemented with floating
* point.
*
* MS Windows and at least IRIX does not have C99's nearbyint() function(see the man
* page), so we reinvent it.
*/
static xsDouble roundFloat(const xsDouble val);
};
}
QT_END_NAMESPACE
#endif
| [
"p_pavlov@wargaming.net"
] | p_pavlov@wargaming.net |
55657a82044a24cc718996ef7ce00c2c1720871b | 89d8b82e7d41f1438c3d791d409147f441b35cf2 | /_drafts/CCFastTMXLayer.cpp | 803bc1637cde642d1434f6767497147d86945f4f | [
"MIT"
] | permissive | helloztq/helloztq.github.io | 277e59f0260c131ecbb8bc43e62fa2b73e66bd23 | 436f419d32955a513f0e4c6c6ebdb8472d3079e5 | refs/heads/master | 2021-01-19T01:58:18.942759 | 2018-03-21T08:28:33 | 2018-03-21T08:28:33 | 84,399,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,055 | cpp | /****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2011 HKASoftware
http://www.cocos2d-x.org
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.
****************************************************************************/
/*
Original rewrite of TMXLayer was based on HKTMXTiledMap by HKASoftware http://hkasoftware.com
Further info: http://www.cocos2d-iphone.org/forums/topic/hktmxtiledmap/
It was rewritten again, and only a small part of the original HK ideas/code remains in this implementation
*/
#include "CCFastTMXLayer.h"
#include "CCTMXXMLParser.h"
#include "CCFastTMXTiledMap.h"
#include "2d/CCSprite.h"
#include "renderer/CCTextureCache.h"
#include "renderer/CCGLProgramCache.h"
#include "renderer/CCGLProgram.h"
#include "base/CCDirector.h"
#include "base/CCConfiguration.h"
#include "renderer/CCRenderer.h"
#include "deprecated/CCString.h"
#include "renderer/CCGLProgramStateCache.h"
#include "renderer/CCVertexIndexBuffer.h"
#include "platform/CCFileUtils.h"
#include <algorithm>
#include "base/ZipUtils.h"
NS_CC_BEGIN
namespace experimental {
const int TMXLayer::FAST_TMX_ORIENTATION_ORTHO = 0;
const int TMXLayer::FAST_TMX_ORIENTATION_HEX = 1;
const int TMXLayer::FAST_TMX_ORIENTATION_ISO = 2;
const int TMXLayer::FAST_TMX_ORIENTATION_STAG = 3;
#define INDICES_TMP_FILE_NAME "_indices.tmp"
#define TOTALQUADS_TMP_FILE_NAME "_totalQuads.tmp"
#if USE_INDICES_FILEBUFFER
GLushort* TMXLayer::_indicesBuffer = NULL;
#endif
//16384
#define MAX_QUAD_SIZE 4096
// FastTMXLayer - init & alloc & dealloc
TMXLayer * TMXLayer::create(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
{
TMXLayer *ret = new (std::nothrow) TMXLayer();
if (ret->initWithTilesetInfo(tilesetInfo, layerInfo, mapInfo))
{
ret->autorelease();
return ret;
}
return nullptr;
}
bool TMXLayer::initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
{
if( tilesetInfo )
{
_texture = Director::getInstance()->getTextureCache()->addImage(tilesetInfo->_sourceImage);
_texture->retain();
}
// layerInfo
_layerName = layerInfo->_name;
CCLOG("LayerName: %s, sourceImage: %s", _layerName.c_str(), tilesetInfo->_sourceImage.c_str());
_layerSize = layerInfo->_layerSize;
_tiles = layerInfo->_tiles;
_quadsDirty = true;
setOpacity( layerInfo->_opacity );
setProperties(layerInfo->getProperties());
// tilesetInfo
_tileSet = tilesetInfo;
CC_SAFE_RETAIN(_tileSet);
// mapInfo
_mapTileSize = mapInfo->getTileSize();
_layerOrientation = mapInfo->getOrientation();
// offset (after layer orientation is set);
Vec2 offset = this->calculateLayerOffset(layerInfo->_offset);
this->setPosition(CC_POINT_PIXELS_TO_POINTS(offset));
if (_layerOrientation == FAST_TMX_ORIENTATION_STAG)
{
this->setContentSize(CC_SIZE_PIXELS_TO_POINTS(Size((_layerSize.width + 0.5) * _mapTileSize.width, ((_layerSize.height + 1) / 2) * _mapTileSize.height )));
} else {
this->setContentSize(CC_SIZE_PIXELS_TO_POINTS(Size(_layerSize.width * _mapTileSize.width, _layerSize.height * _mapTileSize.height)));
}
this->tileToNodeTransform();
// shader, and other stuff
setGLProgram(GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
_useAutomaticVertexZ = false;
_vertexZvalue = 0;
return true;
}
TMXLayer::TMXLayer()
: _layerName("")
, _layerSize(Size::ZERO)
, _mapTileSize(Size::ZERO)
, _tiles(nullptr)
, _tileSet(nullptr)
, _layerOrientation(FAST_TMX_ORIENTATION_ORTHO)
,_texture(nullptr)
, _vertexZvalue(0)
, _useAutomaticVertexZ(false)
, _quadsDirty(true)
, _dirty(true)
, _vertexBuffer(nullptr)
, _vData(nullptr)
, _indexBuffer(nullptr)
#if USE_TOTALQUADS_FILE_BUFFER
,_totalQuadsFILE(nullptr)
#endif
#if USE_INDICES_FILEBUFFER
,_indicesFILE(nullptr)
#endif
,_indiceCount(0)
{
}
TMXLayer::~TMXLayer()
{
CC_SAFE_RELEASE(_tileSet);
CC_SAFE_RELEASE(_texture);
CC_SAFE_DELETE_ARRAY(_tiles);
CC_SAFE_RELEASE(_vData);
CC_SAFE_RELEASE(_vertexBuffer);
CC_SAFE_RELEASE(_indexBuffer);
#if USE_INDICES_FILEBUFFER
CC_SAFE_FREE(_indicesBuffer);
if (_indicesFILE)
{
fclose(_indicesFILE);
_indicesFILE = nullptr;
}
#endif
#if USE_TOTALQUADS_FILE_BUFFER
if (_totalQuadsFILE)
{
fclose(_totalQuadsFILE);
_totalQuadsFILE = nullptr;
}
#endif
}
void TMXLayer::draw(Renderer *renderer, const Mat4& transform, uint32_t flags)
{
if (!_visible)
{
return;
}
updateTotalQuads();
if( flags != 0 || _dirty || _quadsDirty )
{
Size s = Director::getInstance()->getWinSize();
auto rect = Rect(0, 0, s.width, s.height);
Mat4 inv = transform;
inv.inverse();
rect = RectApplyTransform(rect, inv);
updateTiles(rect);
updateIndexBuffer();
updatePrimitives();
_dirty = false;
}
if(_renderCommands.size() < static_cast<size_t>(_primitives.size()))
{
_renderCommands.resize(_primitives.size());
}
int index = 0;
for(const auto& iter : _primitives)
{
if(iter.second->getCount() > 0)
{
auto& cmd = _renderCommands[index++];
cmd.init(iter.first, _texture->getName(), getGLProgramState(), BlendFunc::ALPHA_PREMULTIPLIED, iter.second, _modelViewTransform, flags);
renderer->addCommand(&cmd);
}
}
}
void TMXLayer::onDraw(Primitive *primitive)
{
GL::bindTexture2D(_texture->getName());
getGLProgramState()->apply(_modelViewTransform);
GL::bindVAO(0);
primitive->draw();
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1, primitive->getCount() * 4);
}
void TMXLayer::updateTiles(const Rect& culledRect)
{
Rect visibleTiles = culledRect;
Size mapTileSize = CC_SIZE_PIXELS_TO_POINTS(_mapTileSize);
Size tileSize = CC_SIZE_PIXELS_TO_POINTS(_tileSet->_tileSize);
Mat4 nodeToTileTransform = _tileToNodeTransform.getInversed();
//transform to tile
visibleTiles = RectApplyTransform(visibleTiles, nodeToTileTransform);
// tile coordinate is upside-down, so we need to make the tile coordinate use top-left for the start point.
visibleTiles.origin.y += 1;
// if x=0.7, width=9.5, we need to draw number 0~10 of tiles, and so is height.
visibleTiles.size.width = ceil(visibleTiles.origin.x + visibleTiles.size.width) - floor(visibleTiles.origin.x);
visibleTiles.size.height = ceil(visibleTiles.origin.y + visibleTiles.size.height) - floor(visibleTiles.origin.y);
visibleTiles.origin.x = floor(visibleTiles.origin.x);
visibleTiles.origin.y = floor(visibleTiles.origin.y);
// for the bigger tiles.
int tilesOverX = 0;
int tilesOverY = 0;
// for diagonal oriention tiles
float tileSizeMax = std::max(tileSize.width, tileSize.height);
if (_layerOrientation == FAST_TMX_ORIENTATION_ORTHO)
{
tilesOverX = ceil(tileSizeMax / mapTileSize.width) - 1;
tilesOverY = ceil(tileSizeMax / mapTileSize.height) - 1;
if (tilesOverX < 0) tilesOverX = 0;
if (tilesOverY < 0) tilesOverY = 0;
}
else if(_layerOrientation == FAST_TMX_ORIENTATION_ISO)
{
Rect overTileRect(0, 0, tileSizeMax - mapTileSize.width, tileSizeMax - mapTileSize.height);
if (overTileRect.size.width < 0) overTileRect.size.width = 0;
if (overTileRect.size.height < 0) overTileRect.size.height = 0;
overTileRect = RectApplyTransform(overTileRect, nodeToTileTransform);
tilesOverX = ceil(overTileRect.origin.x + overTileRect.size.width) - floor(overTileRect.origin.x);
tilesOverY = ceil(overTileRect.origin.y + overTileRect.size.height) - floor(overTileRect.origin.y);
}
else if (_layerOrientation == FAST_TMX_ORIENTATION_STAG)
{
tilesOverX = ceil(tileSizeMax / mapTileSize.width) + 1;
tilesOverY = ceil(tileSizeMax / mapTileSize.height) + 1;
if (tilesOverX < 0) tilesOverX = 0;
if (tilesOverY < 0) tilesOverY = 0;
}
else
{
//do nothing, do not support
//CCASSERT(0, "TMX invalid value");
}
_indicesVertexZNumber.clear();
for(const auto& iter : _indicesVertexZOffsets)
{
_indicesVertexZNumber[iter.first] = iter.second;
}
int yBegin = std::max(0.f,visibleTiles.origin.y - tilesOverY);
int yEnd = std::min(_layerSize.height,visibleTiles.origin.y + visibleTiles.size.height + tilesOverY);
int xBegin = std::max(0.f,visibleTiles.origin.x - tilesOverX);
int xEnd = std::min(_layerSize.width,visibleTiles.origin.x + visibleTiles.size.width + tilesOverX);
_newQuadIndex = 0;
for (int y = yBegin; y < yEnd; ++y)
{
for (int x = xBegin; x < xEnd; ++x)
{
int tileIndex = getTileIndexByPos(x, y);
if(_tiles[tileIndex] == 0) continue;
int vertexZ = getVertexZForPos(Vec2(x,y));
auto iter = _indicesVertexZNumber.find(vertexZ);
int offset = iter->second;
iter->second++;
int quadIndex = _tileToQuadIndex[tileIndex];
CC_ASSERT(-1 != quadIndex);
#if USE_TOTALQUADS_FILE_BUFFER
fseek(_totalQuadsFILE, quadIndex * sizeof(V3F_C4B_T2F_Quad), SEEK_SET);
fread(&_totalQuadsBuffer[_newQuadIndex], sizeof(V3F_C4B_T2F_Quad), 1, _totalQuadsFILE);
#else
memcpy(&_totalQuadsBuffer[_newQuadIndex], &_totalQuads[quadIndex], sizeof(V3F_C4B_T2F_Quad));
#endif
// _indices[6 * offset + 0] = _newQuadIndex * 4 + 0;
// _indices[6 * offset + 1] = _newQuadIndex * 4 + 1;
// _indices[6 * offset + 2] = _newQuadIndex * 4 + 2;
// _indices[6 * offset + 3] = _newQuadIndex * 4 + 3;
// _indices[6 * offset + 4] = _newQuadIndex * 4 + 2;
// _indices[6 * offset + 5] = _newQuadIndex * 4 + 1;
setIndies(offset, _newQuadIndex);
++_newQuadIndex;
} // for x
} // for y
for(const auto& iter : _indicesVertexZOffsets)
{
_indicesVertexZNumber[iter.first] -= iter.second;
if(_indicesVertexZNumber[iter.first] == 0)
{
_indicesVertexZNumber.erase(iter.first);
}
}
}
void TMXLayer::updateVertexBuffer()
{
GL::bindVAO(0);
if(nullptr == _vData)
{
// _vertexBuffer = VertexBuffer::create(sizeof(V3F_C4B_T2F), (int)_tmpTotalQuads[0].size() * 4);
_vertexBuffer = VertexBuffer::create(sizeof(V3F_C4B_T2F), (int)_totalQuadsBuffer.size() * 4);
_vData = VertexData::create();
_vData->setStream(_vertexBuffer, VertexStreamAttribute(0, GLProgram::VERTEX_ATTRIB_POSITION, GL_FLOAT, 3));
_vData->setStream(_vertexBuffer, VertexStreamAttribute(offsetof(V3F_C4B_T2F, colors), GLProgram::VERTEX_ATTRIB_COLOR, GL_UNSIGNED_BYTE, 4, true));
_vData->setStream(_vertexBuffer, VertexStreamAttribute(offsetof(V3F_C4B_T2F, texCoords), GLProgram::VERTEX_ATTRIB_TEX_COORD, GL_FLOAT, 2));
CC_SAFE_RETAIN(_vData);
CC_SAFE_RETAIN(_vertexBuffer);
}
if(_vertexBuffer)
{
// _vertexBuffer->updateVertices((void*)&_totalQuads[0], (int)_totalQuads.size() * 4, 0);
_vertexBuffer->updateVertices((void*)&_totalQuadsBuffer[0], (int)_totalQuadsBuffer.size() * 4, 0);
}
}
void TMXLayer::updateIndexBuffer()
{
if(nullptr == _indexBuffer)
{
_indexBuffer = IndexBuffer::create(IndexBuffer::IndexType::INDEX_TYPE_SHORT_16, _indiceCount);
CC_SAFE_RETAIN(_indexBuffer);
}
updateVertexBuffer();
#if USE_INDICES_FILEBUFFER
fseek(_indicesFILE, 0, SEEK_SET);
fread(_indicesBuffer, sizeof(GLushort), _indiceCount, _indicesFILE);
_indexBuffer->updateIndices(_indicesBuffer, _indiceCount, 0);
#else
_indexBuffer->updateIndices(&_indices[0], (int)_indices.size(), 0);
#endif
}
// FastTMXLayer - setup Tiles
void TMXLayer::setupTiles()
{
// Optimization: quick hack that sets the image size on the tileset
_tileSet->_imageSize = _texture->getContentSizeInPixels();
// By default all the tiles are aliased
// pros: easier to render
// cons: difficult to scale / rotate / etc.
_texture->setAliasTexParameters();
//CFByteOrder o = CFByteOrderGetCurrent();
// Parse cocos2d properties
this->parseInternalProperties();
Size screenSize = Director::getInstance()->getWinSize();
switch (_layerOrientation)
{
case FAST_TMX_ORIENTATION_ORTHO:
_screenGridSize.width = ceil(screenSize.width / _mapTileSize.width) + 1;
_screenGridSize.height = ceil(screenSize.height / _mapTileSize.height) + 1;
// tiles could be bigger than the grid, add additional rows if needed
_screenGridSize.height += _tileSet->_tileSize.height / _mapTileSize.height;
break;
case FAST_TMX_ORIENTATION_ISO:
_screenGridSize.width = ceil(screenSize.width / _mapTileSize.width) + 2;
_screenGridSize.height = ceil(screenSize.height / (_mapTileSize.height/2)) + 4;
break;
case FAST_TMX_ORIENTATION_STAG:
{
_screenGridSize.width = ceil(screenSize.width / _mapTileSize.width) + 1;
_screenGridSize.height = ceil(screenSize.height / _mapTileSize.height) + 1;
}
break;
case FAST_TMX_ORIENTATION_HEX:
default:
CCLOGERROR("FastTMX does not support type %d", _layerOrientation);
break;
}
_screenTileCount = _screenGridSize.width * _screenGridSize.height;
initTotalQuads();
}
Mat4 TMXLayer::tileToNodeTransform()
{
float w = _mapTileSize.width / CC_CONTENT_SCALE_FACTOR();
float h = _mapTileSize.height / CC_CONTENT_SCALE_FACTOR();
float offY = (_layerSize.height - 1) * h;
switch(_layerOrientation)
{
case FAST_TMX_ORIENTATION_ORTHO:
{
_tileToNodeTransform = Mat4
(
w, 0.0f, 0.0f, 0.0f,
0.0f, -h, 0.0f, offY,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0, 0.0f, 1.0f
);
return _tileToNodeTransform;
}
case FAST_TMX_ORIENTATION_ISO:
{
float offX = (_layerSize.width - 1) * w / 2;
_tileToNodeTransform = Mat4
(
w/2, -w/2, 0.0f, offX,
-h/2, -h/2, 0.0f, offY,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
);
return _tileToNodeTransform;
}
case FAST_TMX_ORIENTATION_HEX:
{
_tileToNodeTransform = Mat4
(
h * sqrtf(0.75), 0, 0, 0,
-h/2, -h, 0, offY,
0, 0, 1, 0,
0, 0, 0, 1
);
return _tileToNodeTransform;
}
case FAST_TMX_ORIENTATION_STAG:
{
_tileToNodeTransform = Mat4
(
w, 0, 0.0f, 0,
0, -h / 2, 0.0f, offY / 2,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0, 0.0f, 1.0f
);
//_tileToNodeTransform_STAG = _tileToNodeTransform;
_tileToNodeTransform_STAG = Mat4
(
w, 0, 0.0f, w / 2,
0, -h / 2, 0.0f, offY / 2,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0, 0.0f, 1.0f
);
return _tileToNodeTransform;
}
default:
{
_tileToNodeTransform = Mat4::IDENTITY;
return _tileToNodeTransform;
}
}
}
void TMXLayer::updatePrimitives()
{
for(const auto& iter : _indicesVertexZNumber)
{
int start = _indicesVertexZOffsets.at(iter.first);
auto primitiveIter= _primitives.find(iter.first);
if(primitiveIter == _primitives.end())
{
auto primitive = Primitive::create(_vData, _indexBuffer, GL_TRIANGLES);
primitive->setCount(iter.second * 6);
primitive->setStart(start * 6);
_primitives.insert(iter.first, primitive);
}
else
{
primitiveIter->second->setCount(iter.second * 6);
primitiveIter->second->setStart(start * 6);
}
}
}
void TMXLayer::setIndies(int &offset, int &guadIndex)
{
// CCLOG("========= offset: %d", offset);
#if USE_INDICES_FILEBUFFER
fseek(_indicesFILE, sizeof(GLushort) * (6 * offset), SEEK_SET);
GLushort guadIndex_1 = guadIndex * 4 + 0;
GLushort guadIndex_2 = guadIndex * 4 + 1;
GLushort guadIndex_3 = guadIndex * 4 + 2;
GLushort guadIndex_4 = guadIndex * 4 + 3;
GLushort guadIndex_5 = guadIndex * 4 + 2;
GLushort guadIndex_6 = guadIndex * 4 + 1;
fwrite(&guadIndex_1, sizeof(GLushort), 1, _indicesFILE);
fwrite(&guadIndex_2, sizeof(GLushort), 1, _indicesFILE);
fwrite(&guadIndex_3, sizeof(GLushort), 1, _indicesFILE);
fwrite(&guadIndex_4, sizeof(GLushort), 1, _indicesFILE);
fwrite(&guadIndex_5, sizeof(GLushort), 1, _indicesFILE);
fwrite(&guadIndex_6, sizeof(GLushort), 1, _indicesFILE);
#else
_indices[6 * offset + 0] = guadIndex * 4 + 0;
_indices[6 * offset + 1] = guadIndex * 4 + 1;
_indices[6 * offset + 2] = guadIndex * 4 + 2;
_indices[6 * offset + 3] = guadIndex * 4 + 3;
_indices[6 * offset + 4] = guadIndex * 4 + 2;
_indices[6 * offset + 5] = guadIndex * 4 + 1;
#endif
}
static FILE *create_tmp_file(const std::string &path)
{
std::string p = FileUtils::getInstance()->getWritablePath() + path;
FILE *file = fopen(p.c_str(), "wb");
fclose(file);
file = fopen(p.c_str(), "rb+");
return file;
}
void TMXLayer::initTotalQuads()
{
Size tileSize = CC_SIZE_PIXELS_TO_POINTS(_tileSet->_tileSize);
Size texSize = _tileSet->_imageSize;
_tileToQuadIndex.clear();
_totalQuadsBuffer.resize(MAX_QUAD_SIZE);
_indiceCount = 6 * MAX_QUAD_SIZE;
// int(_layerSize.width * _layerSize.height);
_tileToQuadIndex.resize(int(_layerSize.width * _layerSize.height),-1);
_indicesVertexZOffsets.clear();
#if USE_INDICES_FILEBUFFER
_indicesFILE = create_tmp_file(getLayerName() + INDICES_TMP_FILE_NAME);
if (!_indicesBuffer)
{
_indicesBuffer = (GLushort *)malloc(sizeof(GLushort) * _indiceCount);
}
memset(_indicesBuffer, 0, sizeof(GLushort) * _indiceCount);
fwrite(_indicesBuffer, sizeof(GLushort) * _indiceCount, 1, _indicesFILE);
#else
_indices.resize(_indiceCount);
#endif
#if USE_TOTALQUADS_FILE_BUFFER
_totalQuadsFILE = create_tmp_file(getLayerName() + TOTALQUADS_TMP_FILE_NAME);
V3F_C4B_T2F_Quad quad;
// std::string path = "json/mapconfig/" + getLayerName() + TOTALQUADS_TMP_FILE_NAME + ".gz";
// unsigned char *deflated = nullptr;
//
// ssize_t inflatedLen = cocos2d::ZipUtils::inflateGZipFile(FileUtils::getInstance()->fullPathForFilename(path).c_str(), &deflated);
//
// fwrite(deflated, inflatedLen, 1, _totalQuadsFILE);
#else
_totalQuads.resize(int(_layerSize.width * _layerSize.height));
#endif
int quadIndex = 0;
for(int y = 0; y < _layerSize.height; ++y)
{
for(int x =0; x < _layerSize.width; ++x)
{
int tileIndex = getTileIndexByPos(x, y);
int tileGID = _tiles[tileIndex];
if(tileGID == 0) continue;
_tileToQuadIndex[tileIndex] = quadIndex;
#if !USE_TOTALQUADS_FILE_BUFFER
auto& quad = _totalQuads[quadIndex];
#endif
Vec3 nodePos(float(x), float(y), 0);
if (_layerOrientation == FAST_TMX_ORIENTATION_STAG && (y & 1))
{
_tileToNodeTransform_STAG.transformPoint(&nodePos);
} else {
_tileToNodeTransform.transformPoint(&nodePos);
}
float left, right, top, bottom, z;
z = getVertexZForPos(Vec2(x, y));
auto iter = _indicesVertexZOffsets.find(z);
if(iter == _indicesVertexZOffsets.end())
{
_indicesVertexZOffsets[z] = 1;
}
else
{
iter->second++;
}
// vertices
if (tileGID & kTMXTileDiagonalFlag)
{
left = nodePos.x;
right = nodePos.x + tileSize.height;
bottom = nodePos.y + tileSize.width;
top = nodePos.y;
}
else
{
left = nodePos.x;
right = nodePos.x + tileSize.width;
bottom = nodePos.y + tileSize.height;
top = nodePos.y;
}
if(tileGID & kTMXTileVerticalFlag)
std::swap(top, bottom);
if(tileGID & kTMXTileHorizontalFlag)
std::swap(left, right);
if(tileGID & kTMXTileDiagonalFlag)
{
// XXX: not working correcly
quad.bl.vertices.x = left;
quad.bl.vertices.y = bottom;
quad.bl.vertices.z = z;
quad.br.vertices.x = left;
quad.br.vertices.y = top;
quad.br.vertices.z = z;
quad.tl.vertices.x = right;
quad.tl.vertices.y = bottom;
quad.tl.vertices.z = z;
quad.tr.vertices.x = right;
quad.tr.vertices.y = top;
quad.tr.vertices.z = z;
}
else
{
quad.bl.vertices.x = left;
quad.bl.vertices.y = bottom;
quad.bl.vertices.z = z;
quad.br.vertices.x = right;
quad.br.vertices.y = bottom;
quad.br.vertices.z = z;
quad.tl.vertices.x = left;
quad.tl.vertices.y = top;
quad.tl.vertices.z = z;
quad.tr.vertices.x = right;
quad.tr.vertices.y = top;
quad.tr.vertices.z = z;
}
// texcoords
Rect tileTexture = _tileSet->getRectForGID(tileGID);
left = (tileTexture.origin.x / texSize.width);
right = left + (tileTexture.size.width / texSize.width);
bottom = (tileTexture.origin.y / texSize.height);
top = bottom + (tileTexture.size.height / texSize.height);
quad.bl.texCoords.u = left;
quad.bl.texCoords.v = bottom;
quad.br.texCoords.u = right;
quad.br.texCoords.v = bottom;
quad.tl.texCoords.u = left;
quad.tl.texCoords.v = top;
quad.tr.texCoords.u = right;
quad.tr.texCoords.v = top;
quad.bl.colors = Color4B::WHITE;
quad.br.colors = Color4B::WHITE;
quad.tl.colors = Color4B::WHITE;
quad.tr.colors = Color4B::WHITE;
#if USE_TOTALQUADS_FILE_BUFFER
fwrite(&quad, sizeof(quad), 1, _totalQuadsFILE);
#endif
++quadIndex;
}
}
}
void TMXLayer::updateTotalQuads()
{
if(_quadsDirty)
{
int offset = 0;
for(auto iter = _indicesVertexZOffsets.begin(); iter != _indicesVertexZOffsets.end(); ++iter)
{
std::swap(offset, iter->second);
offset += iter->second;
}
updateVertexBuffer();
_quadsDirty = false;
}
}
// removing / getting tiles
Sprite* TMXLayer::getTileAt(const Vec2& tileCoordinate)
{
CCASSERT( tileCoordinate.x < _layerSize.width && tileCoordinate.y < _layerSize.height && tileCoordinate.x >=0 && tileCoordinate.y >=0, "TMXLayer: invalid position");
CCASSERT( _tiles, "TMXLayer: the tiles map has been released");
Sprite *tile = nullptr;
int gid = this->getTileGIDAt(tileCoordinate);
// if GID == 0, then no tile is present
if( gid ) {
int index = tileCoordinate.x + tileCoordinate.y * _layerSize.width;
auto it = _spriteContainer.find(index);
if (it != _spriteContainer.end())
{
tile = it->second.first;
}
else
{
// tile not created yet. create it
Rect rect = _tileSet->getRectForGID(gid);
rect = CC_RECT_PIXELS_TO_POINTS(rect);
tile = Sprite::createWithTexture(_texture, rect);
Vec2 p = this->getPositionAt(tileCoordinate);
tile->setAnchorPoint(Vec2::ZERO);
tile->setPosition(p);
tile->setPositionZ((float)getVertexZForPos(tileCoordinate));
tile->setOpacity(this->getOpacity());
tile->setTag(index);
this->addChild(tile, index);
_spriteContainer.insert(std::pair<int, std::pair<Sprite*, int> >(index, std::pair<Sprite*, int>(tile, gid)));
// tile is converted to sprite.
setFlaggedTileGIDByIndex(index, 0);
}
}
return tile;
}
int TMXLayer::getTileGIDAt(const Vec2& tileCoordinate, TMXTileFlags* flags/* = nullptr*/)
{
CCASSERT(tileCoordinate.x < _layerSize.width && tileCoordinate.y < _layerSize.height && tileCoordinate.x >=0 && tileCoordinate.y >=0, "TMXLayer: invalid position");
CCASSERT(_tiles, "TMXLayer: the tiles map has been released");
int idx = static_cast<int>((tileCoordinate.x + tileCoordinate.y * _layerSize.width));
// Bits on the far end of the 32-bit global tile ID are used for tile flags
int tile = _tiles[idx];
auto it = _spriteContainer.find(idx);
// converted to sprite.
if (tile == 0 && it != _spriteContainer.end())
{
tile = it->second.second;
}
// issue1264, flipped tiles can be changed dynamically
if (flags)
{
*flags = (TMXTileFlags)(tile & kTMXFlipedAll);
}
return (tile & kTMXFlippedMask);
}
Vec2 TMXLayer::getPositionAt(const Vec2& pos)
{
return PointApplyTransform(pos, _tileToNodeTransform);
}
int TMXLayer::getVertexZForPos(const Vec2& pos)
{
int ret = 0;
int maxVal = 0;
if (_useAutomaticVertexZ)
{
switch (_layerOrientation)
{
case FAST_TMX_ORIENTATION_ISO:
maxVal = static_cast<int>(_layerSize.width + _layerSize.height);
ret = static_cast<int>(-(maxVal - (pos.x + pos.y)));
break;
case FAST_TMX_ORIENTATION_ORTHO:
ret = static_cast<int>(-(_layerSize.height-pos.y));
break;
case FAST_TMX_ORIENTATION_STAG:
maxVal = static_cast<int>(_layerSize.width + _layerSize.height);
ret = static_cast<int>(-(maxVal - (pos.x + pos.y)));
case FAST_TMX_ORIENTATION_HEX:
CCASSERT(0, "TMX Hexa vertexZ not supported");
break;
default:
CCASSERT(0, "TMX invalid value");
break;
}
}
else
{
ret = _vertexZvalue;
}
return ret;
}
void TMXLayer::removeTileAt(const Vec2& tileCoordinate)
{
CCASSERT( tileCoordinate.x < _layerSize.width && tileCoordinate.y < _layerSize.height && tileCoordinate.x >=0 && tileCoordinate.y >=0, "TMXLayer: invalid position");
int gid = this->getTileGIDAt(tileCoordinate);
if( gid ) {
int z = tileCoordinate.x + tileCoordinate.y * _layerSize.width;
// remove tile from GID map
setFlaggedTileGIDByIndex(z, 0);
// remove it from sprites
auto it = _spriteContainer.find(z);
if (it != _spriteContainer.end())
{
this->removeChild(it->second.first);
}
}
}
void TMXLayer::setFlaggedTileGIDByIndex(int index, int gid)
{
if(gid == _tiles[index]) return;
_tiles[index] = gid;
_quadsDirty = true;
_dirty = true;
}
void TMXLayer::removeChild(Node* node, bool cleanup)
{
int tag = node->getTag();
auto it = _spriteContainer.find(tag);
if (it != _spriteContainer.end() && it->second.first == node)
{
_spriteContainer.erase(it);
}
Node::removeChild(node, cleanup);
}
// TMXLayer - Properties
Value TMXLayer::getProperty(const std::string& propertyName) const
{
if (_properties.find(propertyName) != _properties.end())
return _properties.at(propertyName);
return Value();
}
void TMXLayer::parseInternalProperties()
{
auto vertexz = getProperty("cc_vertexz");
if (vertexz.isNull()) return;
std::string vertexZStr = vertexz.asString();
// If "automatic" is on, then parse the "cc_alpha_func" too
if (vertexZStr == "automatic")
{
_useAutomaticVertexZ = true;
auto alphaFuncVal = getProperty("cc_alpha_func");
float alphaFuncValue = alphaFuncVal.asFloat();
setGLProgram(GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST));
GLint alphaValueLocation = glGetUniformLocation(getGLProgram()->getProgram(), GLProgram::UNIFORM_NAME_ALPHA_TEST_VALUE);
// NOTE: alpha test shader is hard-coded to use the equivalent of a glAlphaFunc(GL_GREATER) comparison
// use shader program to set uniform
getGLProgram()->use();
getGLProgram()->setUniformLocationWith1f(alphaValueLocation, alphaFuncValue);
CHECK_GL_ERROR_DEBUG();
}
else
{
_vertexZvalue = vertexz.asInt();
}
}
//CCTMXLayer2 - obtaining positions, offset
Vec2 TMXLayer::calculateLayerOffset(const Vec2& pos)
{
Vec2 ret;
switch (_layerOrientation)
{
case FAST_TMX_ORIENTATION_ORTHO:
ret.set( pos.x * _mapTileSize.width, -pos.y *_mapTileSize.height);
break;
case FAST_TMX_ORIENTATION_ISO:
ret.set((_mapTileSize.width /2) * (pos.x - pos.y),
(_mapTileSize.height /2 ) * (-pos.x - pos.y));
break;
case FAST_TMX_ORIENTATION_STAG:
{
float diffX = 0;
if ((int)std::abs(pos.y) % 2 == 1)
{
diffX = _mapTileSize.width / 2;
}
ret = Vec2(pos.x * _mapTileSize.width + diffX, (-pos.y) * _mapTileSize.height/2);
}
break;
case FAST_TMX_ORIENTATION_HEX:
default:
CCASSERT(pos.isZero(), "offset for this map not implemented yet");
break;
}
return ret;
}
// TMXLayer - adding / remove tiles
void TMXLayer::setTileGID(int gid, const Vec2& tileCoordinate)
{
setTileGID(gid, tileCoordinate, (TMXTileFlags)0);
}
void TMXLayer::setTileGID(int gid, const Vec2& tileCoordinate, TMXTileFlags flags)
{
CCASSERT(tileCoordinate.x < _layerSize.width && tileCoordinate.y < _layerSize.height && tileCoordinate.x >=0 && tileCoordinate.y >=0, "TMXLayer: invalid position");
CCASSERT(_tiles, "TMXLayer: the tiles map has been released");
CCASSERT(gid == 0 || gid >= _tileSet->_firstGid, "TMXLayer: invalid gid" );
TMXTileFlags currentFlags;
int currentGID = getTileGIDAt(tileCoordinate, ¤tFlags);
if (currentGID == gid && currentFlags == flags) return;
int gidAndFlags = gid | flags;
// setting gid=0 is equal to remove the tile
if (gid == 0)
{
removeTileAt(tileCoordinate);
}
// empty tile. create a new one
else if (currentGID == 0)
{
int z = tileCoordinate.x + tileCoordinate.y * _layerSize.width;
setFlaggedTileGIDByIndex(z, gidAndFlags);
}
// modifying an existing tile with a non-empty tile
else
{
int z = tileCoordinate.x + tileCoordinate.y * _layerSize.width;
auto it = _spriteContainer.find(z);
if (it != _spriteContainer.end())
{
Sprite *sprite = it->second.first;
Rect rect = _tileSet->getRectForGID(gid);
rect = CC_RECT_PIXELS_TO_POINTS(rect);
sprite->setTextureRect(rect, false, rect.size);
this->reorderChild(sprite, z);
if (flags)
{
setupTileSprite(sprite, sprite->getPosition(), gidAndFlags);
}
it->second.second = gidAndFlags;
}
else
{
setFlaggedTileGIDByIndex(z, gidAndFlags);
}
}
}
void TMXLayer::setupTileSprite(Sprite* sprite, Vec2 pos, int gid)
{
sprite->setPosition(getPositionAt(pos));
sprite->setPositionZ((float)getVertexZForPos(pos));
sprite->setAnchorPoint(Vec2::ZERO);
sprite->setOpacity(this->getOpacity());
//issue 1264, flip can be undone as well
sprite->setFlippedX(false);
sprite->setFlippedY(false);
sprite->setRotation(0.0f);
// Rotation in tiled is achieved using 3 flipped states, flipping across the horizontal, vertical, and diagonal axes of the tiles.
if (gid & kTMXTileDiagonalFlag)
{
// put the anchor in the middle for ease of rotation.
sprite->setAnchorPoint(Vec2(0.5f,0.5f));
sprite->setPosition(getPositionAt(pos).x + sprite->getContentSize().height/2,
getPositionAt(pos).y + sprite->getContentSize().width/2 );
int flag = gid & (kTMXTileHorizontalFlag | kTMXTileVerticalFlag );
// handle the 4 diagonally flipped states.
if (flag == kTMXTileHorizontalFlag)
{
sprite->setRotation(90.0f);
}
else if (flag == kTMXTileVerticalFlag)
{
sprite->setRotation(270.0f);
}
else if (flag == (kTMXTileVerticalFlag | kTMXTileHorizontalFlag) )
{
sprite->setRotation(90.0f);
sprite->setFlippedX(true);
}
else
{
sprite->setRotation(270.0f);
sprite->setFlippedX(true);
}
}
else
{
if (gid & kTMXTileHorizontalFlag)
{
sprite->setFlippedX(true);
}
if (gid & kTMXTileVerticalFlag)
{
sprite->setFlippedY(true);
}
}
}
std::string TMXLayer::getDescription() const
{
return StringUtils::format("<FastTMXLayer | tag = %d, size = %d,%d>", _tag, (int)_mapTileSize.width, (int)_mapTileSize.height);
}
} //end of namespace experimental
NS_CC_END
| [
"499464653@qq.com"
] | 499464653@qq.com |
21dde776e394a6c314b4f640da560bf78f332d79 | 72e6f1563bc0636c7530667bff631e1ea535f80d | /models/FileConfig.h | f401d22d2a59dff43ef1c81c887a034fd662bd94 | [] | no_license | remote-backup-project/remote-backup | b52cc5c6c1753b94830680af921eedfff79470aa | 648ddafbe135a7ea19e2453a1c9cdb2d29cbd283 | refs/heads/master | 2023-02-24T12:17:38.469436 | 2021-01-26T18:50:44 | 2021-01-26T18:50:44 | 305,156,967 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,513 | h | #ifndef REMOTE_BACKUP_FILECONFIG_H
#define REMOTE_BACKUP_FILECONFIG_H
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <filesystem>
#include "Serializable.h"
#include "../utils/StringUtils.h"
#include "../converters/Deserializer.h"
#include "../converters/Serializer.h"
namespace fs = std::filesystem;
class FileConfig : Serializable{
std::string inputDirPath;
std::string outputDirPath;
std::string username;
std::string hostname;
std::string port;
std::string macInterface;
void createServerConfigFile();
void createClientConfigFile();
public:
FileConfig();
FileConfig(std::string inputDirPath, std::string outputDirPath, std::string username, std::string hostname, std::string port);
FileConfig(std::string inputDirPath, std::string outputDirPath, std::string username, std::string hostname, std::string port, std::string macInterface);
std::string getInputDirPath();
std::string getOutputDirPath();
std::string getUsername();
std::string getHostname();
std::string getPort();
std::string getMacInterface();
void writeAsString(boost::property_tree::ptree& pt) override;
void readAsString(boost::property_tree::ptree& pt) override;
void readServerFile();
void readClientFile();
std::string to_string() override;
};
extern FileConfig fileConfig;
#endif //REMOTE_BACKUP_FILECONFIG_H | [
"s270206@studenti.polito.it"
] | s270206@studenti.polito.it |
f63b3d75d24d408ad7c43fe480238eb3cebaf20b | 01f8171fdaf0177123866b9c8706d603e2f3c2e8 | /ui/controls/enum_control.cpp | 881a7b585cfee79a2c7ac0defef46c30604da1b3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | ppearson/ImaginePartial | 5176fb31927e09c43ece207dd3ae021274e4bd93 | 9871b052f2edeb023e2845578ad69c25c5baf7d2 | refs/heads/master | 2020-05-21T14:08:50.162787 | 2020-01-22T08:12:23 | 2020-01-22T08:12:23 | 46,647,365 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,441 | cpp | /*
Imagine
Copyright 2011-2012 Peter Pearson.
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 "enum_control.h"
namespace Imagine
{
EnumControl::EnumControl(const std::string& name, unsigned char* pairedValue, const char** options, const std::string& label) : Control(name, label)
{
m_comboBox = new QComboBox();
m_comboBox->setMinimumSize(100, 22);
m_comboBox->setMaximumHeight(26);
m_widget = m_comboBox;
m_pairedValue = pairedValue;
if (options)
{
unsigned int i = 0;
while (options[i])
{
m_comboBox->addItem(options[i++]);
}
}
m_comboBox->setCurrentIndex(*m_pairedValue);
m_pConnectionProxy->registerComboIndexChangedInt(m_comboBox);
}
EnumControl::~EnumControl()
{
}
bool EnumControl::valueChanged()
{
*m_pairedValue = (unsigned char)m_comboBox->currentIndex();
return true;
}
void EnumControl::refreshFromValue()
{
m_comboBox->setCurrentIndex((int)*m_pairedValue);
}
} // namespace Imagine
| [
"peter.pearson@gmail.com"
] | peter.pearson@gmail.com |
00f26186e1eb051a57e34397e929811cd6c9bef4 | 3c305dfca2e726c4959f980a8c287cd5bdd7fc05 | /Remove_Duplicates_From_Sorted_List.cpp | 534fde2e011eb581c700f9f230e7c6eada87e39e | [] | no_license | huy312100/leetcode-solutions | 2f17105fb40dea2a512ef5e59c855c1320a4ad5b | b4abae73e5351ce1c0d1a2bdfd29d9fd56a9dee1 | refs/heads/master | 2021-12-02T22:36:05.238588 | 2013-01-13T13:37:20 | 2013-01-13T13:37:20 | 422,103,718 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,011 | cpp | /*
Remove Duplicates from Sorted List
Given a sorted linked list, delete all
duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
int count = 0;
ListNode *cur = head;
ListNode *last = NULL;
while (cur) {
if (count == 0) {
last = cur;
cur = cur->next;
count = 1;
} else if (count == 1 && last->val == cur->val) {
//delete cur
last->next = cur->next;
cur = cur->next;
} else { //count == 1 && last->val != cur->val
last = cur;
cur = cur->next;
}
}
return head;
}
};
| [
"kofreestyler@gmail.com"
] | kofreestyler@gmail.com |
52d9d9c8c7cffac0b3b3051af516a72756923256 | cf5aa4c1d9bb93f0fb26b48522fc105f602aff7d | /EDay23.cpp | 61d16f79a7d0a42d7fb5666a676b77727aba587d | [] | no_license | LiiuKingming/cpp_learn | 5bbe138ee861f85caecaa7ba776e9ae624d9132d | 1dd238f99ebe1c8d6bef429c91a0f77faea05645 | refs/heads/master | 2020-09-04T03:36:32.273193 | 2020-06-20T05:09:54 | 2020-06-20T05:09:54 | 219,648,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,357 | cpp | //
// Created by 28943 on 2019/12/3.
//
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
//微信红包
/*方法一 做出来的*/
class Gift1 {
public:
int getValue(vector<int> gifts, int n) {
// write code here
sort(gifts.begin(), gifts.end());
int count = 0;
for(int i = 0; i < gifts.size(); i++){
if(gifts[n / 2] == gifts[i]){
count++;
}
}
if(count > n / 2){
return gifts[n / 2];
}
return 0;
}
};
/*思路二:map统计*///没想到
class Gift {
public:
int getValue(vector<int> gifts, int n) {
map<int,int> count;
int middle = gifts.size() / 2;
//直接用map排序
for(const auto& e : gifts){
++count[e];
}
for(const auto& e : count){
if(e.second >= middle)
return e.first;
}
return 0;
}
};
//字符串编辑距离 更改 删除 增加字符 各为一步
int minDistance(string word1, string word2) {
// word与空串之间的编辑距离为word的长度
if (word1.empty() || word2.empty()) {
return max(word1.size(), word2.size());
}
int len1 = word1.size();
int len2 = word2.size();
// F(i,j)初始化
vector<vector<int>> f(1 + len1, vector<int>(1 + len2, 0));
for (int i = 0; i <= len1; ++i) {
f[i][0] = i;
}
for (int i = 0; i <= len2; ++i) {
f[0][i] = i;
}
for (int i = 1; i <= len1; ++i) {
for (int j = 1; j <= len2; ++j) {
// F(i,j) = min { F(i-1,j)+1, F(i,j-1) +1, F(i-1,j-1) + (w1[i]==w2[j]?0:1) }
// 判断word1的第i个字符是否与word2的第j个字符相等
if (word1[i - 1] == word2[j - 1]) {
f[i][j] = 1 + min(f[i][j - 1], f[i - 1][j]);
// 字符相等,F(i-1,j-1)编辑距离不变
f[i][j] = min(f[i][j], f[i - 1][j - 1]);
} else {
f[i][j] = 1 + min(f[i][j - 1], f[i - 1][j]);
// 字符不相等,F(i-1,j-1)编辑距离 + 1
f[i][j] = min(f[i][j], 1 + f[i - 1][j - 1]);
}
}
}
return f[len1][len2];
}
int main(){
string a,b;
while(cin>>a>>b)
cout<<minDistance(a, b)<<endl;
return 0;
}
| [
"289437926@qq.com"
] | 289437926@qq.com |
f6b0c6494c6e8c0155d93d50596f242da9feedad | 68b3aabc0433e5b401320f177945522fdfbbb078 | /SourceCode/TestOne/TestOne/TestOne.cpp | c603366bbe205860fd89cb0fad0cd03984938883 | [] | no_license | whalecanfly/Hello-World | 36eded2f9edd659fd74bdd3387f92900dd48249d | c6f2b7b5036cedfadc829f058d4a3a8536c428c8 | refs/heads/master | 2021-01-21T20:43:16.177300 | 2017-08-13T06:50:12 | 2017-08-13T06:50:12 | 94,677,014 | 0 | 0 | null | 2017-06-18T09:35:49 | 2017-06-18T09:16:35 | null | GB18030 | C++ | false | false | 346 | cpp | // TestOne.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdio.h>
#include<iostream>
#include <fstream>
int _tmain(int argc, _TCHAR* argv[])
{
std::cout<<"Hello, world!"<<std::showpoint;
printf("Hello, world!\n");
std::ofstream file("file.txt");
file << "Hello, world!" << std::endl;
return 0;
}
| [
"whalecanfly@163.com"
] | whalecanfly@163.com |
6dbdb37893d1c76323cb93e0cd8bd2cde66f7363 | 0c94f92f67ed1642098fbc1c0b79d9472d28e722 | /P05/full_credit/data.cpp | 4890ccac1e2375d83d7f5f6696efb58d6bbff8da | [
"MIT"
] | permissive | Code-Saurav/cse1325-1 | bd9b3805290f27064134a13f966c1d458cb16e74 | 2dcd3f027cff2db2213d6f43f8f495784535d88a | refs/heads/master | 2023-01-31T07:30:09.499243 | 2020-12-19T15:22:39 | 2020-12-19T15:22:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 166 | cpp | /*
This file stores all needed data for the classes.
needed for the derived, main or base classes
*/
#include <iostream>
typedef bool Signal;
typedef int Pin;
| [
"humagain.prabesh@outlook.com"
] | humagain.prabesh@outlook.com |
bcb5fe83e8eb841f916656aee1c7a17b6ff91134 | 3722725e1916503cf5173d6a21a6cad0c7c22bf0 | /unidadeII/cpts.cpp | d2ff64d06361ecc6a08a1f047fbc48023120b267 | [] | no_license | matheuspetrovich/matheuspetrovich.github.io | 626a7a99126b406bb7e90c16d6f621a5873288c2 | 0df70ede8386894b8b14b20c1093101a2a4fd128 | refs/heads/master | 2021-01-17T13:20:55.975880 | 2017-01-13T01:16:22 | 2017-01-13T01:16:22 | 52,447,921 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,805 | cpp | #include <fstream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <numeric>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include "opencv2/opencv.hpp"
#define STEP 4
using namespace std;
using namespace cv;
int top_slider = 10;
int top_slider_max = 200;
char TrackbarName[50];
Mat image, border;
void on_trackbar_canny(int, void*){
}
int main(int argc, char** argv){
vector<int> yrange;
vector<int> xrange;
int width, height;
int x, y, raio = 4, jitter = 4;
Mat points, roi;
float passo;
Vec3b val;
image= imread(argv[1],CV_LOAD_IMAGE_COLOR);
width=image.size().width;
height=image.size().height;
xrange.resize(height/STEP);
yrange.resize(width/STEP);
iota(xrange.begin(), xrange.end(), 0);
iota(yrange.begin(), yrange.end(), 0);
for(uint i=0; i<xrange.size(); i++)
xrange[i]= xrange[i]*STEP+STEP/2;
for(uint i=0; i<yrange.size(); i++)
yrange[i]= yrange[i]*STEP+STEP/2;
points = Mat(height, width, CV_8UC3, Scalar(255,255,255));
random_shuffle(xrange.begin(), xrange.end());
for(auto i : xrange){
random_shuffle(yrange.begin(),yrange.end());
for(auto j : yrange){
x = i+rand()%(2*jitter)-jitter+1;
y = j+rand()%(2*jitter)-jitter+1;
passo = (rand()%2)/10.0 +1.0;
val[0] = min((int)(image.at<Vec3b>(x,y)[0]*passo),255);
val[1] = min((int)(image.at<Vec3b>(x,y)[1]*passo),255);
val[2] = min((int)(image.at<Vec3b>(x,y)[2]*passo),255);
circle(points,
cv::Point(y,x),
raio,
cv::Scalar(val[0],val[1],val[2]),
-1);
}
}//*/
jitter = 3;
Mat tmp = image.clone();
Mat out(373, 664, CV_8UC3, Scalar(255,255,255));
char novo[] = {'0','B','.','p','n','g','\0'};
for(int i=1; i<160 ;i+=20){
Canny(image, border, i, 3*i);
resize(border,out,Size(664,373));
novo[1] = 'B';
imwrite(novo,out);
tmp = Scalar(255,255,255); //limpa tmp para receber a prox iteração
for(int l=3; l<height-3 ;l++)
for(int c=3; c<width-3 ;c++){
if(border.at<uchar>(l,c) == 255){
raio = 1+rand()%3;
passo = (rand()%2)/10.0 +1.0;
x = l+rand()%(2*jitter)-jitter+1;
y = c+rand()%(2*jitter)-jitter+1;
val[0] = min((int)(image.at<Vec3b>(x,y)[0]*passo),255);
val[1] = min((int)(image.at<Vec3b>(x,y)[1]*passo),255);
val[2] = min((int)(image.at<Vec3b>(x,y)[2]*passo),255);
circle(points,
cv::Point(y,x),
raio,
cv::Scalar(val[0],val[1],val[2]),
-1);
circle(tmp,
cv::Point(y,x),
raio,
cv::Scalar(val[0],val[1],val[2]),
-1);
}
}
resize(tmp,out,Size(664,373));
novo[1] = 'A';
imwrite(novo,out);
novo[0]++;
}
imshow("cannyborders.png", points);
waitKey();
imwrite("cannyborders.png", points);
return 0;
}
| [
"matheus.petrovich@gmail.com"
] | matheus.petrovich@gmail.com |
535770b654e625510364a505cdac8d38bd48a429 | 4bc21b62a346c48cbe29b898b7fe331d6dedc023 | /src/qt/addresstablemodel.cpp | aab343f0c5daeec1eb8d8bc5f5b2bda494f189c4 | [
"MIT"
] | permissive | dachcoin/dach | 0bc1f57a2be087c81a847b8114d8d38cb211d39b | 57c2b4af4005e8deba7932e81bd6ccdfbfe7f6bf | refs/heads/master | 2020-04-12T22:36:32.451311 | 2019-01-30T05:54:04 | 2019-01-30T05:54:04 | 162,793,444 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,189 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "addresstablemodel.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "base58.h"
#include "wallet.h"
#include "askpassphrasedialog.h"
#include <QDebug>
#include <QFont>
const QString AddressTableModel::Send = "S";
const QString AddressTableModel::Receive = "R";
const QString AddressTableModel::Zerocoin = "X";
struct AddressTableEntry {
enum Type {
Sending,
Receiving,
Zerocoin,
Hidden /* QSortFilterProxyModel will filter these out */
};
Type type;
QString label;
QString address;
QString pubcoin;
AddressTableEntry() {}
AddressTableEntry(Type type, const QString &pubcoin): type(type), pubcoin(pubcoin) {}
AddressTableEntry(Type type, const QString& label, const QString& address) : type(type), label(label), address(address) {}
};
struct AddressTableEntryLessThan {
bool operator()(const AddressTableEntry& a, const AddressTableEntry& b) const
{
return a.address < b.address;
}
bool operator()(const AddressTableEntry& a, const QString& b) const
{
return a.address < b;
}
bool operator()(const QString& a, const AddressTableEntry& b) const
{
return a < b.address;
}
};
/* Determine address type from address purpose */
static AddressTableEntry::Type translateTransactionType(const QString& strPurpose, bool isMine)
{
AddressTableEntry::Type addressType = AddressTableEntry::Hidden;
// "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all.
if (strPurpose == "send")
addressType = AddressTableEntry::Sending;
else if (strPurpose == "receive")
addressType = AddressTableEntry::Receiving;
else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess
addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending);
return addressType;
}
// Private implementation
class AddressTablePriv
{
public:
CWallet* wallet;
QList<AddressTableEntry> cachedAddressTable;
AddressTableModel* parent;
AddressTablePriv(CWallet* wallet, AddressTableModel* parent) : wallet(wallet), parent(parent) {}
void refreshAddressTable()
{
cachedAddressTable.clear();
{
LOCK(wallet->cs_wallet);
BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, wallet->mapAddressBook) {
const CBitcoinAddress& address = item.first;
bool fMine = IsMine(*wallet, address.Get());
AddressTableEntry::Type addressType = translateTransactionType(
QString::fromStdString(item.second.purpose), fMine);
const std::string& strName = item.second.name;
cachedAddressTable.append(AddressTableEntry(addressType,
QString::fromStdString(strName),
QString::fromStdString(address.ToString())));
}
}
// qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order
// Even though the map is already sorted this re-sorting step is needed because the originating map
// is sorted by binary address, not by base58() address.
qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan());
}
void updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status)
{
// Find address / label in model
QList<AddressTableEntry>::iterator lower = qLowerBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
QList<AddressTableEntry>::iterator upper = qUpperBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
int lowerIndex = (lower - cachedAddressTable.begin());
int upperIndex = (upper - cachedAddressTable.begin());
bool inModel = (lower != upper);
AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine);
switch (status) {
case CT_NEW:
if (inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_NEW, but entry is already in model";
break;
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address));
parent->endInsertRows();
break;
case CT_UPDATED:
if (!inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_UPDATED, but entry is not in model";
break;
}
lower->type = newEntryType;
lower->label = label;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
if (!inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_DELETED, but entry is not in model";
break;
}
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex - 1);
cachedAddressTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
void updateEntry(const QString &pubCoin, const QString &isUsed, int status)
{
// Find address / label in model
QList<AddressTableEntry>::iterator lower = qLowerBound(
cachedAddressTable.begin(), cachedAddressTable.end(), pubCoin, AddressTableEntryLessThan());
QList<AddressTableEntry>::iterator upper = qUpperBound(
cachedAddressTable.begin(), cachedAddressTable.end(), pubCoin, AddressTableEntryLessThan());
int lowerIndex = (lower - cachedAddressTable.begin());
bool inModel = (lower != upper);
AddressTableEntry::Type newEntryType = AddressTableEntry::Zerocoin;
switch(status)
{
case CT_NEW:
if(inModel)
{
qWarning() << "AddressTablePriv_ZC::updateEntry : Warning: Got CT_NEW, but entry is already in model";
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, isUsed, pubCoin));
parent->endInsertRows();
break;
case CT_UPDATED:
if(!inModel)
{
qWarning() << "AddressTablePriv_ZC::updateEntry : Warning: Got CT_UPDATED, but entry is not in model";
break;
}
lower->type = newEntryType;
lower->label = isUsed;
parent->emitDataChanged(lowerIndex);
break;
}
}
int size()
{
return cachedAddressTable.size();
}
AddressTableEntry* index(int idx)
{
if (idx >= 0 && idx < cachedAddressTable.size()) {
return &cachedAddressTable[idx];
} else {
return 0;
}
}
};
AddressTableModel::AddressTableModel(CWallet* wallet, WalletModel* parent) : QAbstractTableModel(parent), walletModel(parent), wallet(wallet), priv(0)
{
columns << tr("Label") << tr("Address");
priv = new AddressTablePriv(wallet, this);
priv->refreshAddressTable();
}
AddressTableModel::~AddressTableModel()
{
delete priv;
}
int AddressTableModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int AddressTableModel::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant AddressTableModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
if (role == Qt::DisplayRole || role == Qt::EditRole) {
switch (index.column()) {
case Label:
if (rec->label.isEmpty() && role == Qt::DisplayRole) {
return tr("(no label)");
} else {
return rec->label;
}
case Address:
return rec->address;
}
} else if (role == Qt::FontRole) {
QFont font;
if (index.column() == Address) {
font = GUIUtil::bitcoinAddressFont();
}
return font;
} else if (role == TypeRole) {
switch (rec->type) {
case AddressTableEntry::Sending:
return Send;
case AddressTableEntry::Receiving:
return Receive;
default:
break;
}
}
return QVariant();
}
bool AddressTableModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (!index.isValid())
return false;
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive");
editStatus = OK;
if (role == Qt::EditRole) {
LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */
CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get();
if (index.column() == Label) {
// Do nothing, if old label == new label
if (rec->label == value.toString()) {
editStatus = NO_CHANGES;
return false;
}
wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose);
} else if (index.column() == Address) {
CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get();
// Refuse to set invalid address, set error status and return false
if (boost::get<CNoDestination>(&newAddress)) {
editStatus = INVALID_ADDRESS;
return false;
}
// Do nothing, if old address == new address
else if (newAddress == curAddress) {
editStatus = NO_CHANGES;
return false;
}
// Check for duplicate addresses to prevent accidental deletion of addresses, if you try
// to paste an existing address over another address (with a different label)
else if (wallet->mapAddressBook.count(newAddress)) {
editStatus = DUPLICATE_ADDRESS;
return false;
}
// Double-check that we're not overwriting a receiving address
else if (rec->type == AddressTableEntry::Sending) {
// Remove old entry
wallet->DelAddressBook(curAddress);
// Add new entry with new address
wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose);
}
}
return true;
}
return false;
}
QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal) {
if (role == Qt::DisplayRole && section < columns.size()) {
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags AddressTableModel::flags(const QModelIndex& index) const
{
if (!index.isValid())
return 0;
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
// Can edit address and label for sending addresses,
// and only label for receiving addresses.
if (rec->type == AddressTableEntry::Sending ||
(rec->type == AddressTableEntry::Receiving && index.column() == Label)) {
retval |= Qt::ItemIsEditable;
}
return retval;
}
QModelIndex AddressTableModel::index(int row, int column, const QModelIndex& parent) const
{
Q_UNUSED(parent);
AddressTableEntry* data = priv->index(row);
if (data) {
return createIndex(row, column, priv->index(row));
} else {
return QModelIndex();
}
}
void AddressTableModel::updateEntry(const QString& address,
const QString& label,
bool isMine,
const QString& purpose,
int status)
{
// Update address book model from Dach core
priv->updateEntry(address, label, isMine, purpose, status);
}
void AddressTableModel::updateEntry(const QString &pubCoin, const QString &isUsed, int status)
{
// Update stealth address book model from Bitcoin core
priv->updateEntry(pubCoin, isUsed, status);
}
QString AddressTableModel::addRow(const QString& type, const QString& label, const QString& address)
{
std::string strLabel = label.toStdString();
std::string strAddress = address.toStdString();
editStatus = OK;
if (type == Send) {
if (!walletModel->validateAddress(address)) {
editStatus = INVALID_ADDRESS;
return QString();
}
// Check for duplicate addresses
{
LOCK(wallet->cs_wallet);
if (wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) {
editStatus = DUPLICATE_ADDRESS;
return QString();
}
}
} else if (type == Receive) {
// Generate a new address to associate with given label
CPubKey newKey;
if (!wallet->GetKeyFromPool(newKey)) {
WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Unlock_Full, true));
if (!ctx.isValid()) {
// Unlock wallet failed or was cancelled
editStatus = WALLET_UNLOCK_FAILURE;
return QString();
}
if (!wallet->GetKeyFromPool(newKey)) {
editStatus = KEY_GENERATION_FAILURE;
return QString();
}
}
strAddress = CBitcoinAddress(newKey.GetID()).ToString();
} else {
return QString();
}
// Add entry
{
LOCK(wallet->cs_wallet);
wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel,
(type == Send ? "send" : "receive"));
}
return QString::fromStdString(strAddress);
}
bool AddressTableModel::removeRows(int row, int count, const QModelIndex& parent)
{
Q_UNUSED(parent);
AddressTableEntry* rec = priv->index(row);
if (count != 1 || !rec || rec->type == AddressTableEntry::Receiving) {
// Can only remove one row at a time, and cannot remove rows not in model.
// Also refuse to remove receiving addresses.
return false;
}
{
LOCK(wallet->cs_wallet);
wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get());
}
return true;
}
/* Look up label for address in address book, if not found return empty string.
*/
QString AddressTableModel::labelForAddress(const QString& address) const
{
{
LOCK(wallet->cs_wallet);
CBitcoinAddress address_parsed(address.toStdString());
std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get());
if (mi != wallet->mapAddressBook.end()) {
return QString::fromStdString(mi->second.name);
}
}
return QString();
}
int AddressTableModel::lookupAddress(const QString& address) const
{
QModelIndexList lst = match(index(0, Address, QModelIndex()),
Qt::EditRole, address, 1, Qt::MatchExactly);
if (lst.isEmpty()) {
return -1;
} else {
return lst.at(0).row();
}
}
void AddressTableModel::emitDataChanged(int idx)
{
emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length() - 1, QModelIndex()));
}
| [
"media@dachcoin.live"
] | media@dachcoin.live |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.