hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b9e4a22695e1df8e058c2f1e71372a4a02e1657a | 1,809 | cc | C++ | tile/codegen/rewrite_locs.cc | TolyaTalamanov/plaidml | 275a79cd640def34c1b7bc7053397f5989ef55c2 | [
"Apache-2.0"
] | 1 | 2019-09-11T11:18:50.000Z | 2019-09-11T11:18:50.000Z | tile/codegen/rewrite_locs.cc | HubBucket-Team/plaidml | 762d5fff6467b43a15623f927502892ce8df91a4 | [
"Apache-2.0"
] | null | null | null | tile/codegen/rewrite_locs.cc | HubBucket-Team/plaidml | 762d5fff6467b43a15623f927502892ce8df91a4 | [
"Apache-2.0"
] | 1 | 2019-09-11T11:18:52.000Z | 2019-09-11T11:18:52.000Z | // Copyright 2018, Intel Corp.
#include "tile/codegen/rewrite_locs.h"
#include <algorithm>
#include <iterator>
#include <queue>
namespace vertexai {
namespace tile {
namespace codegen {
namespace {
struct Rewrite {
std::vector<stripe::Device> prefix;
std::vector<stripe::Device> target;
};
void RewriteLocation(stripe::Location* loc, const std::vector<Rewrite>& rewrites) {
for (auto& rewrite : rewrites) {
auto loc_it = loc->devs.begin();
auto rew_it = rewrite.prefix.begin();
for (; loc_it != loc->devs.end() && *loc_it == *rew_it; ++loc_it, ++rew_it) {
}
if (rew_it == rewrite.prefix.end()) {
std::vector<stripe::Device> target = rewrite.target;
std::copy(loc_it, loc->devs.end(), std::back_inserter(target));
std::swap(loc->devs, target);
break;
}
}
}
} // namespace
void RewriteLocationsPass::Apply(CompilerState* state) const {
std::vector<Rewrite> rewrites;
for (const auto& rewrite : options_.rewrites()) {
rewrites.emplace_back(Rewrite{stripe::FromProto(rewrite.prefix()), stripe::FromProto(rewrite.target())});
}
std::queue<stripe::Block*> todo;
todo.push(state->entry());
while (todo.size()) {
stripe::Block* block = todo.front();
todo.pop();
RewriteLocation(&block->location, rewrites);
for (auto& ref : block->refs) {
RewriteLocation(&ref.mut().location, rewrites);
}
for (auto& stmt : block->stmts) {
stripe::Block* inner = dynamic_cast<stripe::Block*>(stmt.get());
if (inner) {
todo.push(inner);
}
}
}
}
namespace {
[[gnu::unused]] char reg = []() -> char {
CompilePassFactory<RewriteLocationsPass, proto::RewriteLocationsPass>::Register();
return 0;
}();
} // namespace
} // namespace codegen
} // namespace tile
} // namespace vertexai
| 24.780822 | 109 | 0.642344 | TolyaTalamanov |
b9e86fddafa3ddc8ecfebd6c1bc4b3a69df8aa9e | 1,888 | cpp | C++ | bitcoinPoSTdisplay/libraries/ArduinoJson/extras/tests/JsonArray/remove.cpp | adrienlacombe-ledger/bitcoinPoS | 2a4701c445c7eeec88c8abc2bd7940916899e79c | [
"MIT"
] | 81 | 2022-01-22T17:35:01.000Z | 2022-03-08T09:59:02.000Z | bitcoinPoSTdisplay/libraries/ArduinoJson/extras/tests/JsonArray/remove.cpp | adrienlacombe-ledger/bitcoinPoS | 2a4701c445c7eeec88c8abc2bd7940916899e79c | [
"MIT"
] | 6 | 2022-01-25T20:23:08.000Z | 2022-03-07T23:50:32.000Z | bitcoinPoSTdisplay/libraries/ArduinoJson/extras/tests/JsonArray/remove.cpp | adrienlacombe-ledger/bitcoinPoS | 2a4701c445c7eeec88c8abc2bd7940916899e79c | [
"MIT"
] | 14 | 2022-01-22T18:16:11.000Z | 2022-03-07T21:32:41.000Z | // ArduinoJson - https://arduinojson.org
// Copyright © 2014-2022, Benoit BLANCHON
// MIT License
#include <ArduinoJson.h>
#include <catch.hpp>
TEST_CASE("JsonArray::remove()") {
DynamicJsonDocument doc(4096);
JsonArray array = doc.to<JsonArray>();
array.add(1);
array.add(2);
array.add(3);
SECTION("remove first by index") {
array.remove(0);
REQUIRE(2 == array.size());
REQUIRE(array[0] == 2);
REQUIRE(array[1] == 3);
}
SECTION("remove middle by index") {
array.remove(1);
REQUIRE(2 == array.size());
REQUIRE(array[0] == 1);
REQUIRE(array[1] == 3);
}
SECTION("remove last by index") {
array.remove(2);
REQUIRE(2 == array.size());
REQUIRE(array[0] == 1);
REQUIRE(array[1] == 2);
}
SECTION("remove first by iterator") {
JsonArray::iterator it = array.begin();
array.remove(it);
REQUIRE(2 == array.size());
REQUIRE(array[0] == 2);
REQUIRE(array[1] == 3);
}
SECTION("remove middle by iterator") {
JsonArray::iterator it = array.begin();
++it;
array.remove(it);
REQUIRE(2 == array.size());
REQUIRE(array[0] == 1);
REQUIRE(array[1] == 3);
}
SECTION("remove last bty iterator") {
JsonArray::iterator it = array.begin();
++it;
++it;
array.remove(it);
REQUIRE(2 == array.size());
REQUIRE(array[0] == 1);
REQUIRE(array[1] == 2);
}
SECTION("In a loop") {
for (JsonArray::iterator it = array.begin(); it != array.end(); ++it) {
if (*it == 2)
array.remove(it);
}
REQUIRE(2 == array.size());
REQUIRE(array[0] == 1);
REQUIRE(array[1] == 3);
}
SECTION("remove by index on unbound reference") {
JsonArray unboundArray;
unboundArray.remove(20);
}
SECTION("remove by iterator on unbound reference") {
JsonArray unboundArray;
unboundArray.remove(unboundArray.begin());
}
}
| 20.977778 | 75 | 0.585275 | adrienlacombe-ledger |
b9e8a95ae026e5d6c76448564f1e9a7eaf29fc25 | 7,862 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/wifi/p2p/nsd/CWifiP2pServiceResponse.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/wifi/p2p/nsd/CWifiP2pServiceResponse.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/wifi/p2p/nsd/CWifiP2pServiceResponse.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// 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 "elastos/droid/wifi/p2p/nsd/CWifiP2pServiceResponse.h"
#include "elastos/droid/wifi/p2p/nsd/CWifiP2pDnsSdServiceResponse.h"
#include "elastos/droid/wifi/p2p/nsd/CWifiP2pUpnpServiceResponse.h"
#include "elastos/droid/wifi/p2p/CWifiP2pDevice.h"
#include <elastos/core/StringUtils.h>
#include "elastos/droid/ext/frameworkext.h"
#include <elastos/utility/etl/List.h>
using Elastos::Utility::Etl::List;
using Elastos::Core::StringUtils;
using Elastos::IO::IByteArrayInputStream;
using Elastos::IO::CByteArrayInputStream;
using Elastos::IO::IDataInputStream;
using Elastos::IO::CDataInputStream;
using Elastos::IO::IDataInput;
namespace Elastos {
namespace Droid {
namespace Wifi {
namespace P2p {
namespace Nsd {
CAR_OBJECT_IMPL(CWifiP2pServiceResponse)
ECode CWifiP2pServiceResponse::GetServiceType(
/* [out] */ Int32* serviceType)
{
return WifiP2pServiceResponse::GetServiceType(serviceType);
}
ECode CWifiP2pServiceResponse::GetStatus(
/* [out] */ Int32* status)
{
return WifiP2pServiceResponse::GetStatus(status);
}
ECode CWifiP2pServiceResponse::GetTransactionId(
/* [out] */ Int32* transactionId)
{
return WifiP2pServiceResponse::GetTransactionId(transactionId);
}
ECode CWifiP2pServiceResponse::GetRawData(
/* [out, callee] */ ArrayOf<Byte>** rawData)
{
return WifiP2pServiceResponse::GetRawData(rawData);
}
ECode CWifiP2pServiceResponse::GetSrcDevice(
/* [out] */ IWifiP2pDevice** srcDevice)
{
return WifiP2pServiceResponse::GetSrcDevice(srcDevice);
}
ECode CWifiP2pServiceResponse::SetSrcDevice(
/* [in] */ IWifiP2pDevice* dev)
{
return WifiP2pServiceResponse::SetSrcDevice(dev);
}
ECode CWifiP2pServiceResponse::ToString(
/* [out] */ String* string)
{
return WifiP2pServiceResponse::ToString(string);
}
ECode CWifiP2pServiceResponse::Equals(
/* [in] */ IInterface* obj,
/* [out] */ Boolean* isEqual)
{
return WifiP2pServiceResponse::Equals(obj, isEqual);
}
ECode CWifiP2pServiceResponse::GetHashCode(
/* [out] */ Int32* hashCode)
{
return WifiP2pServiceResponse::GetHashCode(hashCode);
}
ECode CWifiP2pServiceResponse::ReadFromParcel(
/* [in] */ IParcel* source)
{
return WifiP2pServiceResponse::ReadFromParcel(source);
}
ECode CWifiP2pServiceResponse::WriteToParcel(
/* [in] */ IParcel* dest)
{
return WifiP2pServiceResponse::WriteToParcel(dest);
}
ECode CWifiP2pServiceResponse::NewInstance(
/* [in] */ const String& supplicantEvent,
/* [out, callee] */ ArrayOf<IWifiP2pServiceResponse*>** list)
{
VALIDATE_NOT_NULL(list);
*list = NULL;
List<AutoPtr<IWifiP2pServiceResponse> > respList;
AutoPtr<ArrayOf<String> > args;
StringUtils::Split(supplicantEvent, String(" "), (ArrayOf<String>**)&args);
if ((args == NULL) || (args->GetLength() != 4)) {
return NOERROR;
}
AutoPtr<IWifiP2pDevice> dev;
FAIL_RETURN(CWifiP2pDevice::New((IWifiP2pDevice**)&dev));
String srcAddr;
srcAddr = (*args)[1];
FAIL_RETURN(dev->SetDeviceAddress(srcAddr));
//String updateIndicator = args[2];//not used.
AutoPtr<ArrayOf<Byte> > bin;
FAIL_RETURN(WifiP2pServiceResponse::HexStr2Bin((*args)[3], (ArrayOf<Byte>**)&bin));
if (bin == NULL) {
return NOERROR;
}
AutoPtr<IByteArrayInputStream> ins;
FAIL_RETURN(CByteArrayInputStream::New(bin, (IByteArrayInputStream**)&ins));
AutoPtr<IDataInputStream> dis;
assert(0);
// TODO
// FAIL_RETURN(CDataInputStream::New(ins, (IDataInputStream**)&dis));
AutoPtr<IDataInput> idi = IDataInput::Probe(dis);
if (idi == NULL) return E_NO_INTERFACE;
Int32 i, type, status;
Int64 temp, length;
List<AutoPtr<IWifiP2pServiceResponse> >::Iterator it;
AutoPtr<ArrayOf<IWifiP2pServiceResponse*> > ret;
Int32 temp1, temp2, transId;
// try {
Int32 number;
while (TRUE) {
assert(0);
// TODO
// FAIL_GOTO(dis->Available(&number), L_ERR_EXIT);
if (number <= 0) break;
/*
* Service discovery header is as follows.
* ______________________________________________________________
* | Length(2byte) | Type(1byte) | TransId(1byte)}|
* ______________________________________________________________
* | status(1byte) | vendor specific(variable) |
*/
// The length equals to 3 plus the number of octets in the vendor
// specific content field. And this is little endian.
FAIL_GOTO(idi->ReadUnsignedByte(&temp1), L_ERR_EXIT);
FAIL_GOTO(idi->ReadUnsignedByte(&temp2), L_ERR_EXIT);
length = (temp1 + (temp2 << 8)) - 3;
if (length < 0) {
return NOERROR;
}
FAIL_GOTO(idi->ReadUnsignedByte(&type), L_ERR_EXIT);
FAIL_GOTO(idi->ReadUnsignedByte(&transId), L_ERR_EXIT);
FAIL_GOTO(idi->ReadUnsignedByte(&status), L_ERR_EXIT);
if (length == 0) {
if (status == IWifiP2pServiceResponseStatus::SUCCESS) {
AutoPtr<IWifiP2pServiceResponse> resp;
FAIL_GOTO(CWifiP2pServiceResponse::New(
type, status, (Int32)transId, dev, NULL, (IWifiP2pServiceResponse**)&resp), L_ERR_EXIT);
respList.PushBack(resp);
}
continue;
}
if (length > MAX_BUF_SIZE) {
assert(0);
// TODO
// FAIL_GOTO(dis->Skip(length, &temp), L_ERR_EXIT);
continue;
}
AutoPtr<ArrayOf<Byte> > data = ArrayOf<Byte>::Alloc(length);
if (data == NULL) goto L_ERR_EXIT;
FAIL_GOTO(idi->ReadFully((ArrayOf<Byte>*)data), L_ERR_EXIT);
AutoPtr<IWifiP2pServiceResponse> resp;
if (type == IWifiP2pServiceInfo::SERVICE_TYPE_BONJOUR) {
FAIL_GOTO(CWifiP2pDnsSdServiceResponse::New(
status, (Int32)transId, dev, data, (IWifiP2pServiceResponse**)&resp), L_ERR_EXIT);
}
else if (type == IWifiP2pServiceInfo::SERVICE_TYPE_UPNP) {
FAIL_GOTO(CWifiP2pUpnpServiceResponse::New(
status, (Int32)transId, dev, data, (IWifiP2pServiceResponse**)&resp), L_ERR_EXIT);
}
else {
AutoPtr<CWifiP2pServiceResponse> rsp;
FAIL_GOTO(CWifiP2pServiceResponse::New(
type, status, (Int32)transId, dev, data, (IWifiP2pServiceResponse**)&resp), L_ERR_EXIT);
}
if (resp != NULL) {
FAIL_GOTO(resp->GetStatus(&status), L_ERR_EXIT);
if (status == IWifiP2pServiceResponseStatus::SUCCESS) {
respList.PushBack(resp);
}
}
}
L_ERR_EXIT:
ret = ArrayOf<IWifiP2pServiceResponse*>::Alloc(respList.GetSize());
if (ret == NULL) goto L_ERR_EXIT;
i = 0;
for (it = respList.Begin(); it != respList.End(); ++it) {
AutoPtr<IWifiP2pServiceResponse> resp = *it;
ret->Set(i++, resp);
}
*list = ret;
REFCOUNT_ADD(*list);
return NOERROR;
}
} // namespace Nsd
} // namespace P2p
} // namespace Wifi
} // namespace Droid
} // namespace Elastos
| 32.089796 | 108 | 0.648436 | jingcao80 |
b9e94ed79ea8e9220e2f2cba68b0f7f827fa3549 | 845 | cc | C++ | Cplusplus/Bootcamp/03_MoreBasics/Casting.cc | Kreijeck/learning | eaffee08e61f2a34e01eb8f9f04519aac633f48c | [
"MIT"
] | null | null | null | Cplusplus/Bootcamp/03_MoreBasics/Casting.cc | Kreijeck/learning | eaffee08e61f2a34e01eb8f9f04519aac633f48c | [
"MIT"
] | null | null | null | Cplusplus/Bootcamp/03_MoreBasics/Casting.cc | Kreijeck/learning | eaffee08e61f2a34e01eb8f9f04519aac633f48c | [
"MIT"
] | null | null | null | #include <iomanip>
#include <iostream>
// 1a. C++: static_cast<> - converts object from type to another
// 1b. C: (newDtype)(varName)
int main()
{
double number = 3.14;
std::cout << std::setprecision(20) << number << std::endl;
int num2 = number;
std::cout << num2 << std::endl;
//C-Casting
// groß nach klein verliert genauigkeit
float number3 = (float)(number);
std::cout << number3 << std::endl;
// klein nach Groß. alles prima!
float number4 = (double)(number3);
std::cout << number3 << std::endl;
//C++-Casting
// groß nach klein verliert genauigkeit
float number5 = static_cast<float>(number);
std::cout << number5 << std::endl;
// klein nach Groß. alles prima!
float number6 = static_cast<double>(number3);
std::cout << number6 << std::endl;
return 0;
}
| 24.142857 | 64 | 0.611834 | Kreijeck |
b9ee69e0cd6eeff2e6812602a3dd9520d0f9251b | 1,365 | hpp | C++ | test/ElapseTimer.hpp | GerHobbelt/libtiff | 5b615d29bc86fb8ff9641dc26cc9ed8cc730bcce | [
"libtiff"
] | null | null | null | test/ElapseTimer.hpp | GerHobbelt/libtiff | 5b615d29bc86fb8ff9641dc26cc9ed8cc730bcce | [
"libtiff"
] | null | null | null | test/ElapseTimer.hpp | GerHobbelt/libtiff | 5b615d29bc86fb8ff9641dc26cc9ed8cc730bcce | [
"libtiff"
] | null | null | null | // Elapse Timer
/** @file ElapseTimer.h
** Interface to ElapseTimer facilities.
** Implemented ElapseTimer.cpp Code stolen from Scintilla Platform.h and PlatWX.cxx
**/
// Copyright 1998-2009 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef ELAPSETIMER_H
#define ELAPSETIMER_H
#include <windows.h> //for LARGE_INTEGER, and QueryPerformanceFrequency() etc.
#include <time.h> //for clock()
#include <tchar.h> //for Tatl strings
/**
* ElapsedTime class definition
*/
class ElapseTimer {
friend class Tatl;
long bigBit;
long littleBit;
public:
ElapseTimer();
double Duration(bool reset=false);
};
/**
* Trace Analysis Tool class definition
*/
class Tatl {
private:
#define TATLSRCFILESTRLEN 300
#define TATLMESSAGESTRLEN 1024
typedef struct {
TCHAR srcFile[TATLSRCFILESTRLEN];
int srcLine;
TCHAR message[TATLMESSAGESTRLEN];
double elapsedTime;
} TatlArray_t;
#define TATLARRAYSIZE 100
short nArrayEntries;
TatlArray_t tatlArray[TATLARRAYSIZE];
ElapseTimer tatlTimer;
public:
Tatl();
void TatlReset();
void TatlSetMark(const TCHAR* srcFile, int srcLine, const TCHAR* message);
void Tatl::TatlPrintAnalysis(TCHAR* strReturn, int nStrMax);
}; //-- class Tatl --
//-- Global Trace Analysis object --
extern Tatl tatlAnalysis;
#endif //ELAPSETIMER_H | 22.75 | 94 | 0.756044 | GerHobbelt |
b9f0203c850126067cadb83bfd52a4dc74919861 | 24,190 | cpp | C++ | modules/attention_segmentation/src/algo.cpp | v4r-tuwien/v4r | ff3fbd6d2b298b83268ba4737868bab258262a40 | [
"BSD-1-Clause",
"BSD-2-Clause"
] | 2 | 2021-02-22T11:36:33.000Z | 2021-07-20T11:31:08.000Z | modules/attention_segmentation/src/algo.cpp | v4r-tuwien/v4r | ff3fbd6d2b298b83268ba4737868bab258262a40 | [
"BSD-1-Clause",
"BSD-2-Clause"
] | null | null | null | modules/attention_segmentation/src/algo.cpp | v4r-tuwien/v4r | ff3fbd6d2b298b83268ba4737868bab258262a40 | [
"BSD-1-Clause",
"BSD-2-Clause"
] | 3 | 2018-10-19T10:39:23.000Z | 2021-04-07T13:39:03.000Z | /****************************************************************************
**
** Copyright (C) 2017 TU Wien, ACIN, Vision 4 Robotics (V4R) group
** Contact: v4r.acin.tuwien.ac.at
**
** This file is part of V4R
**
** V4R is distributed under dual licenses - GPLv3 or closed source.
**
** GNU General Public License Usage
** V4R 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.
**
** V4R 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.
**
** Please review the following information to ensure the GNU General Public
** License requirements will be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
**
** Commercial License Usage
** If GPL is not suitable for your project, you must purchase a commercial
** license to use V4R. Licensees holding valid commercial V4R 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 TU Wien, ACIN, V4R.
** For licensing terms and conditions please contact office<at>acin.tuwien.ac.at.
**
**
** The copyright holder additionally grants the author(s) of the file the right
** to use, copy, modify, merge, publish, distribute, sublicense, and/or
** sell copies of their contributions without any restrictions.
**
****************************************************************************/
#include "v4r/attention_segmentation/algo.h"
#include "v4r/attention_segmentation/AttentionModuleErrors.h"
#include <Eigen/Dense>
namespace v4r {
void filterGaussian(cv::Mat &input, cv::Mat &output, cv::Mat &mask) {
float kernel[5] = {1.0, 4.0, 6.0, 4.0, 1.0};
cv::Mat temp = cv::Mat_<float>::zeros(input.rows, input.cols);
for (int i = 0; i < input.rows; ++i) {
for (int j = 0; j < input.cols; j = j + 2) {
if (mask.at<float>(i, j) > 0) {
float value = 0;
float kernel_sum = 0;
for (int k = 0; k < 5; ++k) {
int jj = j + (k - 2);
if ((jj >= 0) && (jj < input.cols)) {
if (mask.at<float>(i, jj) > 0) {
value += kernel[k] * input.at<float>(i, jj);
kernel_sum += kernel[k];
}
}
}
if (kernel_sum > 0) {
temp.at<float>(i, j) = value / kernel_sum;
}
}
}
}
cv::Mat temp2 = cv::Mat_<float>::zeros(temp.rows, temp.cols);
for (int i = 0; i < temp.rows; i = i + 2) {
for (int j = 0; j < temp.cols; j = j + 2) {
if (mask.at<float>(i, j) > 0) {
float value = 0;
float kernel_sum = 0;
for (int k = 0; k < 5; ++k) {
int ii = i + (k - 2);
if ((ii >= 0) && (ii < temp.rows)) {
if (mask.at<float>(ii, j) > 0) {
value += kernel[k] * temp.at<float>(ii, j);
kernel_sum += kernel[k];
}
}
}
if (kernel_sum > 0) {
temp2.at<float>(i, j) = value / kernel_sum;
}
}
}
}
int new_width = input.cols / 2;
int new_height = input.rows / 2;
cv::Mat mask_output = cv::Mat_<float>::zeros(new_height, new_width);
output = cv::Mat_<float>::zeros(new_height, new_width);
for (int i = 0; i < new_height; ++i) {
for (int j = 0; j < new_width; ++j) {
if (mask.at<float>(2 * i, 2 * j) > 0) {
mask_output.at<float>(i, j) = 1.0;
output.at<float>(i, j) = temp2.at<float>(2 * i, 2 * j);
}
}
}
mask_output.copyTo(mask);
}
void buildDepthPyramid(cv::Mat &image, std::vector<cv::Mat> &pyramid, cv::Mat &mask, unsigned int levelNumber) {
pyramid.resize(levelNumber + 1);
image.copyTo(pyramid.at(0));
cv::Mat oldMask;
mask.copyTo(oldMask);
for (unsigned int i = 1; i <= levelNumber; ++i) {
cv::Mat tempImage;
filterGaussian(pyramid.at(i - 1), tempImage, oldMask);
tempImage.copyTo(pyramid.at(i));
}
}
int createPointCloudPyramid(std::vector<cv::Mat> &pyramidX, std::vector<cv::Mat> &pyramidY,
std::vector<cv::Mat> &pyramidZ, std::vector<cv::Mat> &pyramidIndices,
std::vector<pcl::PointCloud<pcl::PointXYZRGB>::Ptr> &pyramidCloud) {
assert(pyramidX.size() == pyramidY.size());
assert(pyramidX.size() == pyramidZ.size());
assert(pyramidX.size() == pyramidIndices.size());
if (pyramidX.size() != pyramidY.size() && pyramidX.size() != pyramidZ.size() &&
pyramidX.size() != pyramidIndices.size())
return AM_DIFFERENTSIZES;
unsigned int num_levels = pyramidX.size();
pyramidCloud.resize(num_levels);
for (unsigned int idx = 0; idx < num_levels; ++idx) {
assert(pyramidX.at(idx).rows == pyramidY.at(idx).rows);
assert(pyramidX.at(idx).cols == pyramidY.at(idx).cols);
assert(pyramidX.at(idx).rows == pyramidZ.at(idx).rows);
assert(pyramidX.at(idx).cols == pyramidZ.at(idx).cols);
assert(pyramidX.at(idx).rows == pyramidIndices.at(idx).rows);
assert(pyramidX.at(idx).cols == pyramidIndices.at(idx).cols);
pyramidCloud.at(idx) = pcl::PointCloud<pcl::PointXYZRGB>::Ptr(new pcl::PointCloud<pcl::PointXYZRGB>());
unsigned int cur_height = pyramidX.at(idx).rows;
unsigned int cur_width = pyramidX.at(idx).cols;
pyramidCloud.at(idx)->points.resize(cur_height * cur_width);
pyramidCloud.at(idx)->width = cur_width;
pyramidCloud.at(idx)->height = cur_height;
for (unsigned int i = 0; i < cur_height; ++i) {
for (unsigned int j = 0; j < cur_width; ++j) {
pcl::PointXYZRGB p_cur;
p_cur.x = pyramidX.at(idx).at<float>(i, j);
p_cur.y = pyramidY.at(idx).at<float>(i, j);
p_cur.z = pyramidZ.at(idx).at<float>(i, j);
int p_idx = i * cur_width + j;
pyramidCloud.at(idx)->points.at(p_idx) = p_cur;
}
}
}
return AM_OK;
}
void createNormalPyramid(std::vector<cv::Mat> &pyramidNx, std::vector<cv::Mat> &pyramidNy,
std::vector<cv::Mat> &pyramidNz, std::vector<cv::Mat> &pyramidIndices,
std::vector<pcl::PointCloud<pcl::Normal>::Ptr> &pyramidNormal) {
assert(pyramidNx.size() == pyramidNy.size());
assert(pyramidNx.size() == pyramidNz.size());
assert(pyramidIndices.size() == pyramidNz.size());
unsigned int num_levels = pyramidNx.size();
pyramidNormal.resize(num_levels);
for (unsigned int idx = 0; idx < num_levels; ++idx) {
assert(pyramidNx.at(idx).rows == pyramidNy.at(idx).rows);
assert(pyramidNx.at(idx).cols == pyramidNy.at(idx).cols);
assert(pyramidNx.at(idx).rows == pyramidNz.at(idx).rows);
assert(pyramidNx.at(idx).cols == pyramidNz.at(idx).cols);
assert(pyramidNx.at(idx).rows == pyramidIndices.at(idx).rows);
assert(pyramidNx.at(idx).cols == pyramidIndices.at(idx).cols);
pyramidNormal.at(idx) = pcl::PointCloud<pcl::Normal>::Ptr(new pcl::PointCloud<pcl::Normal>());
unsigned int cur_height = pyramidNx.at(idx).rows;
unsigned int cur_width = pyramidNx.at(idx).cols;
pyramidNormal.at(idx)->points.clear();
for (unsigned int i = 0; i < cur_height; ++i) {
for (unsigned int j = 0; j < cur_width; ++j) {
if (pyramidIndices.at(idx).at<float>(i, j) > 0) {
pcl::Normal p_cur;
p_cur.normal[0] = pyramidNx.at(idx).at<float>(i, j);
p_cur.normal[1] = pyramidNy.at(idx).at<float>(i, j);
p_cur.normal[2] = pyramidNz.at(idx).at<float>(i, j);
pyramidNormal.at(idx)->points.push_back(p_cur);
}
}
}
pyramidNormal.at(idx)->width = pyramidNormal.at(idx)->points.size();
pyramidNormal.at(idx)->height = 1;
}
}
void createIndicesPyramid(std::vector<cv::Mat> &pyramidIndices,
std::vector<pcl::PointIndices::Ptr> &pyramidIndiceSets) {
unsigned int num_levels = pyramidIndices.size();
pyramidIndiceSets.resize(num_levels);
for (unsigned int idx = 0; idx < num_levels; ++idx) {
pyramidIndiceSets.at(idx) = pcl::PointIndices::Ptr(new pcl::PointIndices());
unsigned int cur_height = pyramidIndices.at(idx).rows;
unsigned int cur_width = pyramidIndices.at(idx).cols;
pyramidIndiceSets.at(idx)->indices.clear();
for (unsigned int i = 0; i < cur_height; ++i) {
for (unsigned int j = 0; j < cur_width; ++j) {
if (pyramidIndices.at(idx).at<float>(i, j) > 0) {
int p_idx = i * cur_width + j;
pyramidIndiceSets.at(idx)->indices.push_back(p_idx);
}
}
}
}
}
void upscaleImage(cv::Mat &input, cv::Mat &output, unsigned int width, unsigned int height) {
assert(width >= (unsigned int)(2 * input.cols));
assert(height >= (unsigned int)(2 * input.rows));
output = cv::Mat_<float>::zeros(height, width);
for (unsigned int i = 0; i < (unsigned int)input.rows; ++i) {
for (unsigned int j = 0; j < (unsigned int)input.cols; ++j) {
output.at<float>(2 * i, 2 * j) = input.at<float>(i, j);
}
}
for (unsigned int i = 0; i < (unsigned int)output.rows; i = i + 2) {
for (unsigned int j = 1; j < (unsigned int)output.cols - 1; j = j + 2) {
output.at<float>(i, j) = (output.at<float>(i, j - 1) + output.at<float>(i, j + 1)) / 2.0;
}
}
for (unsigned int i = 1; i < (unsigned int)output.rows - 1; i = i + 2) {
for (unsigned int j = 0; j < (unsigned int)output.cols; j = j + 2) {
output.at<float>(i, j) = (output.at<float>(i - 1, j) + output.at<float>(i + 1, j)) / 2.0;
}
}
for (unsigned int i = 1; i < (unsigned int)output.rows - 1; i = i + 2) {
for (unsigned int j = 1; j < (unsigned int)output.cols - 1; j = j + 2) {
output.at<float>(i, j) = (output.at<float>(i - 1, j - 1) + output.at<float>(i - 1, j + 1) +
output.at<float>(i + 1, j - 1) + output.at<float>(i + 1, j + 1)) /
4.0;
}
}
}
void downscaleImage(cv::Mat &input, cv::Mat &output, unsigned int width, unsigned int height) {
assert(2 * width <= (unsigned int)(input.cols));
assert(2 * height <= (unsigned int)(input.rows));
output = cv::Mat_<float>::zeros(height, width);
for (unsigned int i = 0; i < (unsigned int)output.rows; ++i) {
for (unsigned int j = 0; j < (unsigned int)output.cols; ++j) {
output.at<float>(i, j) = input.at<float>(2 * i, 2 * j);
}
}
}
void scaleImage(std::vector<cv::Mat> &inputPyramid, cv::Mat &input, cv::Mat &output, int inLevel, int outLevel) {
assert(input.cols == inputPyramid.at(inLevel).cols);
assert(input.rows == inputPyramid.at(inLevel).rows);
if (inLevel < outLevel) {
input.copyTo(output);
for (int l = inLevel + 1; l <= outLevel; ++l) {
cv::Mat temp;
downscaleImage(output, temp, inputPyramid.at(l).cols, inputPyramid.at(l).rows);
temp.copyTo(output);
}
} else if (inLevel > outLevel) {
input.copyTo(output);
for (int l = inLevel - 1; l >= outLevel; --l) {
cv::Mat temp;
upscaleImage(output, temp, inputPyramid.at(l).cols, inputPyramid.at(l).rows);
temp.copyTo(output);
}
} else {
input.copyTo(output);
}
}
bool inPoly(std::vector<cv::Point> &poly, cv::Point p) {
cv::Point newPoint;
cv::Point oldPoint;
cv::Point p1, p2;
bool inside = false;
if (poly.size() < 3) {
return (false);
}
oldPoint = poly.at(poly.size() - 1);
for (unsigned int i = 0; i < poly.size(); i++) {
newPoint = poly.at(i);
if (newPoint.y > oldPoint.y) {
p1 = oldPoint;
p2 = newPoint;
} else {
p1 = newPoint;
p2 = oldPoint;
}
if ((newPoint.y < p.y) == (p.y <= oldPoint.y) /* edge "open" at one end */
&& ((long)p.x - (long)p1.x) * (long)(p2.y - p1.y) < ((long)p2.x - (long)p1.x) * (long)(p.y - p1.y)) {
inside = !inside;
}
oldPoint = newPoint;
}
return (inside);
}
void buildPolygonMap(cv::Mat &polygonMap, std::vector<std::vector<cv::Point>> &polygons) {
for (int i = 0; i < polygonMap.rows; ++i) {
for (int j = 0; j < polygonMap.cols; ++j) {
unsigned int k = 0;
while ((polygonMap.at<uchar>(i, j) == 0) && (k < polygons.size())) {
if (inPoly(polygons.at(k), cv::Point(j, i)))
polygonMap.at<uchar>(i, j) = k + 1;
k += 1;
}
}
}
}
void buildCountourMap(cv::Mat &polygonMap, std::vector<std::vector<cv::Point>> &polygons, cv::Scalar color) {
for (unsigned int i = 0; i < polygons.size(); ++i) {
for (unsigned int j = 0; j < polygons.at(i).size(); ++j) {
cv::line(polygonMap, polygons.at(i).at(j), polygons.at(i).at((j + 1) % polygons.at(i).size()), color, 2);
}
}
}
float normPDF(float x, float mean, float stddev) {
float val = exp(-(x - mean) * (x - mean) / (2 * stddev * stddev));
val /= sqrt(2 * 3.14) * stddev;
return val;
}
float normPDF(std::vector<float> x, std::vector<float> mean, cv::Mat stddev) {
int dim = mean.size();
EIGEN_ALIGN16 Eigen::MatrixXf _stddev = Eigen::MatrixXf::Zero(dim, dim);
EIGEN_ALIGN16 Eigen::VectorXf _x = Eigen::VectorXf::Zero(dim);
for (int i = 0; i < dim; ++i) {
_x[i] = x.at(i) - mean.at(i);
for (int j = 0; j < dim; ++j) {
_stddev(i, j) = stddev.at<float>(i, j);
}
}
float value = (_x.transpose()) * _stddev * _x;
value /= -2;
value = exp(value);
float det = _stddev.determinant();
value /= sqrt(pow(2 * 3.14, dim) * det);
return (value);
}
void addNoise(cv::Mat &image, cv::Mat &nImage, cv::RNG &rng, float min, float max) {
nImage = cv::Mat_<float>::zeros(image.rows, image.cols);
for (int i = 0; i < image.rows; ++i) {
for (int j = 0; j < image.cols; ++j) {
float val = image.at<float>(i, j) + rng.uniform(min, max);
nImage.at<float>(i, j) = (val < 0 ? 0 : (val > 1 ? 1 : val));
}
}
}
void normPDF(cv::Mat &mat, float mean, float stddev, cv::Mat &res) {
res = cv::Mat_<float>::zeros(mat.rows, mat.cols);
res = mat - mean;
res = res.mul(res);
float b = -1.0f / (2 * stddev * stddev);
res = res * b;
cv::exp(res, res);
float a = 1.0f / (stddev * sqrt(2 * M_PI));
res = res * a;
}
void normalizeDist(std::vector<float> &dist) {
float total_sum = 0;
for (unsigned int i = 0; i < dist.size(); ++i) {
total_sum += dist.at(i);
}
for (unsigned int i = 0; i < dist.size(); ++i) {
dist.at(i) /= total_sum;
}
}
float getMean(std::vector<float> dist, float total_num) {
float mean = 0;
for (unsigned int i = 0; i < dist.size(); ++i) {
mean += (dist.at(i) / total_num) * i;
}
return mean;
}
float getStd(std::vector<float> dist, float mean, float total_num) {
float stdDev = 0;
for (unsigned int i = 0; i < dist.size(); ++i) {
stdDev += (i - mean) * (i - mean) * (dist.at(i) / total_num);
}
stdDev = sqrt(stdDev);
return stdDev;
}
long commulativeFunctionArgValue(float x, std::vector<float> &A) {
long min = 0;
long max = A.size() - 1;
while (max != min + 1) {
long mid = (min + max) / 2;
if (x <= A.at(mid)) {
max = mid;
} else {
min = mid;
}
}
if (A.at(min) >= x)
return (min);
else
return (max);
}
void createContoursFromMasks(std::vector<cv::Mat> &masks, std::vector<std::vector<cv::Point>> &contours) {
contours.clear();
contours.resize(masks.size());
for (unsigned int i = 0; i < masks.size(); ++i) {
std::vector<std::vector<cv::Point>> temp;
cv::Mat temp_image;
masks.at(i).copyTo(temp_image);
cv::findContours(temp_image, temp, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
if (temp.size()) {
long totalPointsNum = 0;
for (unsigned int j = 0; j < temp.size(); ++j) {
totalPointsNum += temp.at(j).size();
}
contours.at(i).resize(totalPointsNum);
totalPointsNum = 0;
for (unsigned int j = 0; j < temp.size(); ++j) {
for (unsigned int k = 0; k < temp.at(j).size(); ++k) {
contours.at(i).at(totalPointsNum) = temp.at(j).at(k);
totalPointsNum += 1;
}
}
}
}
}
uchar Num01Transitions(cv::Mat s, int j, int i) {
uchar p2 = s.at<uchar>(j - 1, i);
uchar p3 = s.at<uchar>(j - 1, i + 1);
uchar p4 = s.at<uchar>(j, i + 1);
uchar p5 = s.at<uchar>(j + 1, i + 1);
uchar p6 = s.at<uchar>(j + 1, i);
uchar p7 = s.at<uchar>(j + 1, i - 1);
uchar p8 = s.at<uchar>(j, i - 1);
uchar p9 = s.at<uchar>(j - 1, i - 1);
uchar Nt = 0;
if ((p3 - p2) == 1)
Nt++;
if ((p4 - p3) == 1)
Nt++;
if ((p5 - p4) == 1)
Nt++;
if ((p6 - p5) == 1)
Nt++;
if ((p7 - p6) == 1)
Nt++;
if ((p8 - p7) == 1)
Nt++;
if ((p9 - p8) == 1)
Nt++;
if ((p2 - p9) == 1)
Nt++;
return Nt;
}
void MConnectivity(cv::Mat &s, uchar *element) {
for (int i = 1; i < s.rows - 1; ++i) {
for (int j = 1; j < s.cols - 1; ++j) {
if (s.at<uchar>(i, j) > 0) {
bool remove = true;
for (int p = 0; p < 8; ++p) {
int new_x = j + dx8[p];
int new_y = i + dy8[p];
uchar value = s.at<uchar>(new_y, new_x);
if (element[p] < 2) {
if (value != element[p]) {
remove = false;
}
}
}
if (remove) {
s.at<uchar>(i, j) = 0;
}
}
}
}
}
V4R_EXPORTS void Skeleton(cv::Mat a, cv::Mat &s) {
int width = a.cols;
int height = a.rows;
a.copyTo(s);
cv::Scalar prevsum(0);
while (true) {
cv::Mat m = cv::Mat_<uchar>::ones(height, width);
for (int j = 1; j < height - 1; ++j) {
for (int i = 1; i < width - 1; ++i) {
if (s.at<uchar>(j, i) == 1) {
uchar p2 = s.at<uchar>(j - 1, i);
uchar p3 = s.at<uchar>(j - 1, i + 1);
uchar p4 = s.at<uchar>(j, i + 1);
uchar p5 = s.at<uchar>(j + 1, i + 1);
uchar p6 = s.at<uchar>(j + 1, i);
uchar p7 = s.at<uchar>(j + 1, i - 1);
uchar p8 = s.at<uchar>(j, i - 1);
uchar p9 = s.at<uchar>(j - 1, i - 1);
uchar condA = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9;
uchar condB = Num01Transitions(s, j, i);
uchar condC = p2 * p4 * p6;
uchar condD = p4 * p6 * p8;
if ((condA >= 2) && (condA <= 6) && (condB == 1) && (condC == 0) && (condD == 0))
m.at<uchar>(j, i) = 0;
}
}
}
for (int j = 1; j < height - 1; ++j) {
for (int i = 1; i < width - 1; ++i) {
s.at<uchar>(j, i) = s.at<uchar>(j, i) * m.at<uchar>(j, i);
}
}
m = cv::Mat_<uchar>::ones(height, width);
for (int j = 1; j < height - 1; ++j) {
for (int i = 1; i < width - 1; ++i) {
if (s.at<uchar>(j, i) == 1) {
uchar p2 = s.at<uchar>(j - 1, i);
uchar p3 = s.at<uchar>(j - 1, i + 1);
uchar p4 = s.at<uchar>(j, i + 1);
uchar p5 = s.at<uchar>(j + 1, i + 1);
uchar p6 = s.at<uchar>(j + 1, i);
uchar p7 = s.at<uchar>(j + 1, i - 1);
uchar p8 = s.at<uchar>(j, i - 1);
uchar p9 = s.at<uchar>(j - 1, i - 1);
uchar condA = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9;
uchar condB = Num01Transitions(s, j, i);
uchar condC = p2 * p4 * p8;
uchar condD = p2 * p6 * p8;
if ((condA >= 2) && (condA <= 6) && (condB == 1) && (condC == 0) && (condD == 0))
m.at<uchar>(j, i) = 0;
}
}
}
for (int j = 1; j < height - 1; ++j) {
for (int i = 1; i < width - 1; ++i) {
s.at<uchar>(j, i) = s.at<uchar>(j, i) * m.at<uchar>(j, i);
}
}
cv::Scalar newsum = cv::sum(s);
if (newsum(0) == prevsum(0))
break;
prevsum = newsum;
}
prevsum = cv::sum(s);
uchar e1[8] = {2, 1, 2, 1, 2, 0, 0, 0};
uchar e2[8] = {2, 1, 2, 0, 0, 0, 2, 1};
uchar e3[8] = {0, 0, 2, 1, 2, 1, 2, 0};
uchar e4[8] = {2, 0, 0, 0, 2, 1, 2, 1};
while (true) {
MConnectivity(s, e1);
MConnectivity(s, e2);
MConnectivity(s, e3);
MConnectivity(s, e4);
cv::Scalar newsum = cv::sum(s);
if (newsum(0) == prevsum(0))
break;
prevsum = newsum;
}
}
float calculateDistance(cv::Point center, cv::Point point) {
float distance = sqrt((center.x - point.x) * (center.x - point.x) + (center.y - point.y) * (center.y - point.y));
return (distance);
}
float calculateDistance(cv::Point center, cv::Point point, float sigma) {
float distance = (center.x - point.x) * (center.x - point.x) + (center.y - point.y) * (center.y - point.y);
distance = exp(-distance / (2 * sigma * sigma));
return (distance);
}
void calculateObjectCenter(cv::Mat mask, cv::Point ¢er) {
assert(mask.type() == CV_8UC1);
float x_cen = 0;
float y_cen = 0;
cv::Scalar area = cv::sum(mask);
for (int i = 0; i < mask.rows; ++i) {
for (int j = 0; j < mask.cols; ++j) {
uchar value = mask.at<uchar>(i, j);
if (value > 0) {
x_cen = x_cen + ((float)j) / area(0);
y_cen = y_cen + ((float)i) / area(0);
}
}
}
if (mask.at<uchar>(y_cen, x_cen) == 0) {
// search for closes 4-neighbour point
std::list<cv::Point> points;
points.push_back(cv::Point(x_cen, y_cen));
cv::Mat used = cv::Mat_<uchar>::zeros(mask.rows, mask.cols);
used.at<uchar>(y_cen, x_cen) = 1;
while (points.size()) {
cv::Point p = points.front();
points.pop_front();
if (mask.at<uchar>(p.y, p.x) > 0) {
x_cen = p.x;
y_cen = p.y;
break;
}
for (int i = 0; i < 8; ++i) {
int new_x = p.x + dx8[i];
int new_y = p.y + dy8[i];
if ((new_x < 0) || (new_y < 0) || (new_x >= used.cols) || (new_y >= used.rows))
continue;
if (used.at<uchar>(new_y, new_x) <= 0) {
points.push_back(cv::Point(new_x, new_y));
used.at<uchar>(new_y, new_x) = 1;
}
}
}
}
center.x = x_cen;
center.y = y_cen;
}
void calculateObjectCenter(std::vector<cv::Point> contour, cv::Mat mask, cv::Point ¢er) {
float x_cen = 0;
float y_cen = 0;
for (unsigned int i = 0; i < contour.size(); ++i) {
x_cen = x_cen + ((float)contour.at(i).x) / contour.size();
y_cen = y_cen + ((float)contour.at(i).y) / contour.size();
}
if (mask.at<uchar>(y_cen, x_cen) == 0) {
// search for closes 4-neighbour point
std::list<cv::Point> points;
points.push_back(cv::Point(x_cen, y_cen));
cv::Mat used = cv::Mat_<uchar>::zeros(mask.rows, mask.cols);
used.at<uchar>(y_cen, x_cen) = 1;
while (points.size()) {
cv::Point p = points.front();
points.pop_front();
if (mask.at<uchar>(p.y, p.x) > 0) {
x_cen = p.x;
y_cen = p.y;
break;
}
for (int i = 0; i < 8; ++i) {
int new_x = p.x + dx8[i];
int new_y = p.y + dy8[i];
if ((new_x < 0) || (new_y < 0) || (new_x >= used.cols) || (new_y >= used.rows))
continue;
if (used.at<uchar>(new_y, new_x) <= 0) {
points.push_back(cv::Point(new_x, new_y));
used.at<uchar>(new_y, new_x) = 1;
}
}
}
}
center.x = x_cen;
center.y = y_cen;
}
void get2DNeighbors(const cv::Mat &patches, cv::Mat &neighbors, int patchesNumber) {
neighbors = cv::Mat_<bool>(patchesNumber, patchesNumber);
neighbors.setTo(false);
int dr[4] = {-1, 0, -1};
int dc[4] = {0, -1, -1};
for (int r = 1; r < patches.rows - 1; r++) {
for (int c = 1; c < patches.cols - 1; c++) {
// if the patch exist
if (patches.at<int>(r, c) != -1) {
int patchIdx = patches.at<int>(r, c);
//@ep: why we did not use 1,-1 shift???
for (int i = 0; i < 3; ++i) //@ep: TODO 3->4
{
int nr = r + dr[i];
int nc = c + dc[i];
int currentPatchIdx = patches.at<int>(nr, nc);
if (currentPatchIdx == -1)
continue;
if (patchIdx != currentPatchIdx) {
neighbors.at<bool>(currentPatchIdx, patchIdx) = true;
neighbors.at<bool>(patchIdx, currentPatchIdx) = true;
}
}
}
}
}
}
} // namespace v4r
| 30.504414 | 115 | 0.545763 | v4r-tuwien |
b9f3aa80314c729c793ef69ca75a4d180c3fc236 | 6,284 | cpp | C++ | iOS/G3MApp/G3MApp/G3MCameraDemoScene.cpp | restjohn/g3m | 608657fd6f0e2898bd963d15136ff085b499e97e | [
"BSD-2-Clause"
] | 1 | 2016-08-23T10:29:44.000Z | 2016-08-23T10:29:44.000Z | iOS/G3MApp/G3MApp/G3MCameraDemoScene.cpp | restjohn/g3m | 608657fd6f0e2898bd963d15136ff085b499e97e | [
"BSD-2-Clause"
] | null | null | null | iOS/G3MApp/G3MApp/G3MCameraDemoScene.cpp | restjohn/g3m | 608657fd6f0e2898bd963d15136ff085b499e97e | [
"BSD-2-Clause"
] | null | null | null | //
// G3MCameraDemoScene.cpp
// G3MApp
//
// Created by Diego Gomez Deck on 11/18/13.
// Copyright (c) 2013 Igo Software SL. All rights reserved.
//
#include "G3MCameraDemoScene.hpp"
#include <G3MiOSSDK/ILogger.hpp>
#include <G3MiOSSDK/Angle.hpp>
#include <G3MiOSSDK/TimeInterval.hpp>
#include <G3MiOSSDK/ShapesRenderer.hpp>
#include <G3MiOSSDK/SGShape.hpp>
#include <G3MiOSSDK/MapBoxLayer.hpp>
#include <G3MiOSSDK/LayerSet.hpp>
//#include <G3MiOSSDK/PlanetRenderer.hpp>
#include "G3MDemoModel.hpp"
class G3MCameraDemoSceneShapeLoadListener : public ShapeLoadListener {
protected:
G3MCameraDemoScene* _scene;
G3MCameraDemoSceneShapeLoadListener(G3MCameraDemoScene* scene) :
_scene(scene)
{
}
};
class TheSphynxShapeLoadListener : public G3MCameraDemoSceneShapeLoadListener {
public:
TheSphynxShapeLoadListener(G3MCameraDemoScene* scene) :
G3MCameraDemoSceneShapeLoadListener(scene)
{
}
void onBeforeAddShape(SGShape* shape) {
shape->setPitch(Angle::fromDegrees(90));
}
void onAfterAddShape(SGShape* shape) {
_scene->setTheSphynxShape(shape);
}
};
class TheEiffelTowerShapeLoadListener : public G3MCameraDemoSceneShapeLoadListener {
public:
TheEiffelTowerShapeLoadListener(G3MCameraDemoScene* scene) :
G3MCameraDemoSceneShapeLoadListener(scene)
{
}
void onBeforeAddShape(SGShape* shape) {
shape->setScale(0.02);
}
void onAfterAddShape(SGShape* shape) {
_scene->setTheEiffelTowerShape(shape);
}
};
class ArcDeTriompheShapeLoadListener : public G3MCameraDemoSceneShapeLoadListener {
public:
ArcDeTriompheShapeLoadListener(G3MCameraDemoScene* scene) :
G3MCameraDemoSceneShapeLoadListener(scene)
{
}
void onBeforeAddShape(SGShape* shape) {
shape->setScale(0.5);
shape->setPitch(Angle::fromDegrees(90));
}
void onAfterAddShape(SGShape* shape) {
_scene->setArcDeTriompheShape(shape);
}
};
void G3MCameraDemoScene::rawActivate(const G3MContext* context) {
G3MDemoModel* model = getModel();
ShapesRenderer* shapesRenderer = model->getShapesRenderer();
// PlanetRenderer* planetRenderer = model->getPlanetRenderer();
// planetRenderer->setVerticalExaggeration(0);
MapBoxLayer* layer = new MapBoxLayer("examples.map-m0t0lrpu",
TimeInterval::fromDays(30),
true,
2);
model->getLayerSet()->addLayer(layer);
shapesRenderer->loadBSONSceneJS(URL("file:///sphinx.bson"),
"file:///",
false, // isTransparent
new Geodetic3D(Angle::fromDegreesMinutesSeconds(29, 58, 30.99),
Angle::fromDegreesMinutesSeconds(31, 8, 15.84),
0),
RELATIVE_TO_GROUND,
new TheSphynxShapeLoadListener(this));
shapesRenderer->loadBSONSceneJS(URL("file:///eifeltower.bson"),
"file:///eifel/",
true, // isTransparent
new Geodetic3D(Angle::fromDegreesMinutesSeconds(48, 51, 29.06),
Angle::fromDegreesMinutesSeconds(2, 17, 40.48),
0), //
RELATIVE_TO_GROUND,
new TheEiffelTowerShapeLoadListener(this));
shapesRenderer->loadBSONSceneJS(URL("file:///arcdeTriomphe.bson"),
"file:///arc/",
false,
new Geodetic3D(Angle::fromDegreesMinutesSeconds(48, 52, 25.58),
Angle::fromDegreesMinutesSeconds(2, 17, 42.12),
0),
RELATIVE_TO_GROUND,
new ArcDeTriompheShapeLoadListener(this));
}
void G3MCameraDemoScene::rawSelectOption(const std::string& option,
int optionIndex) {
if (option == "The Sphynx") {
if (_theSphynxShape != NULL) {
const double fromDistance = 6000;
const double toDistance = 2000;
const Angle fromAzimuth = Angle::fromDegrees(-90);
const Angle toAzimuth = Angle::fromDegrees(45);
const Angle fromAltitude = Angle::fromDegrees(90);
const Angle toAltitude = Angle::fromDegrees(30);
_theSphynxShape->orbitCamera(TimeInterval::fromSeconds(20),
fromDistance, toDistance,
fromAzimuth, toAzimuth,
fromAltitude, toAltitude);
}
}
else if (option == "The Eiffel Tower") {
if (_theEiffelTowerShape != NULL) {
const double fromDistance = 10000;
const double toDistance = 1000;
const Angle fromAzimuth = Angle::fromDegrees(-90);
const Angle toAzimuth = Angle::fromDegrees(270);
const Angle fromAltitude = Angle::fromDegrees(90);
const Angle toAltitude = Angle::fromDegrees(15);
_theEiffelTowerShape->orbitCamera(TimeInterval::fromSeconds(20),
fromDistance, toDistance,
fromAzimuth, toAzimuth,
fromAltitude, toAltitude);
}
}
else if (option == "Arc de Triomphe") {
if (_arcDeTriompheShape != NULL) {
const double fromDistance = 10000;
const double toDistance = 1000;
const Angle fromAzimuth = Angle::fromDegrees(-90);
const Angle toAzimuth = Angle::fromDegrees(270);
const Angle fromAltitude = Angle::fromDegrees(90);
const Angle toAltitude = Angle::fromDegrees(15);
_arcDeTriompheShape->orbitCamera(TimeInterval::fromSeconds(20),
fromDistance, toDistance,
fromAzimuth, toAzimuth,
fromAltitude, toAltitude);
}
}
else {
ILogger::instance()->logError("option \"%s\" not supported", option.c_str());
}
}
| 34.911111 | 97 | 0.580204 | restjohn |
b9f4361c00fd88d61e84092afce6d01d8ea21d5e | 36,075 | cpp | C++ | Userland/Libraries/LibUnicode/CodeGenerators/GenerateUnicodeData.cpp | Blocky-studio/serenity | 8337e6cb52076e7f3e2cb5f9a5fd270141e8bbfe | [
"BSD-2-Clause"
] | 2 | 2021-06-25T13:20:28.000Z | 2021-08-19T11:00:54.000Z | Userland/Libraries/LibUnicode/CodeGenerators/GenerateUnicodeData.cpp | Blocky-studio/serenity | 8337e6cb52076e7f3e2cb5f9a5fd270141e8bbfe | [
"BSD-2-Clause"
] | null | null | null | Userland/Libraries/LibUnicode/CodeGenerators/GenerateUnicodeData.cpp | Blocky-studio/serenity | 8337e6cb52076e7f3e2cb5f9a5fd270141e8bbfe | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2021, Tim Flynn <trflynn89@pm.me>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/AllOf.h>
#include <AK/Array.h>
#include <AK/CharacterTypes.h>
#include <AK/HashMap.h>
#include <AK/Optional.h>
#include <AK/QuickSort.h>
#include <AK/SourceGenerator.h>
#include <AK/String.h>
#include <AK/StringUtils.h>
#include <AK/Types.h>
#include <AK/Vector.h>
#include <LibCore/ArgsParser.h>
#include <LibCore/File.h>
// Some code points are excluded from UnicodeData.txt, and instead are part of a "range" of code
// points, as indicated by the "name" field. For example:
// 3400;<CJK Ideograph Extension A, First>;Lo;0;L;;;;;N;;;;;
// 4DBF;<CJK Ideograph Extension A, Last>;Lo;0;L;;;;;N;;;;;
struct CodePointRange {
u32 first;
u32 last;
};
// SpecialCasing source: https://www.unicode.org/Public/13.0.0/ucd/SpecialCasing.txt
// Field descriptions: https://www.unicode.org/reports/tr44/tr44-13.html#SpecialCasing.txt
struct SpecialCasing {
u32 index { 0 };
u32 code_point { 0 };
Vector<u32> lowercase_mapping;
Vector<u32> uppercase_mapping;
Vector<u32> titlecase_mapping;
String locale;
String condition;
};
// PropList source: https://www.unicode.org/Public/13.0.0/ucd/PropList.txt
// Property descriptions: https://www.unicode.org/reports/tr44/tr44-13.html#PropList.txt
// https://www.unicode.org/reports/tr44/tr44-13.html#WordBreakProperty.txt
using PropList = HashMap<String, Vector<CodePointRange>>;
// PropertyAliases source: https://www.unicode.org/Public/13.0.0/ucd/PropertyAliases.txt
struct Alias {
String property;
String alias;
};
// UnicodeData source: https://www.unicode.org/Public/13.0.0/ucd/UnicodeData.txt
// Field descriptions: https://www.unicode.org/reports/tr44/tr44-13.html#UnicodeData.txt
// https://www.unicode.org/reports/tr44/#General_Category_Values
struct CodePointData {
u32 code_point { 0 };
String name;
String general_category;
u8 canonical_combining_class { 0 };
String bidi_class;
String decomposition_type;
Optional<i8> numeric_value_decimal;
Optional<i8> numeric_value_digit;
Optional<i8> numeric_value_numeric;
bool bidi_mirrored { false };
String unicode_1_name;
String iso_comment;
Optional<u32> simple_uppercase_mapping;
Optional<u32> simple_lowercase_mapping;
Optional<u32> simple_titlecase_mapping;
Vector<u32> special_casing_indices;
Vector<StringView> prop_list;
StringView script;
Vector<StringView> script_extensions;
StringView word_break_property;
};
struct UnicodeData {
Vector<SpecialCasing> special_casing;
u32 largest_casing_transform_size { 0 };
u32 largest_special_casing_size { 0 };
Vector<String> locales;
Vector<String> conditions;
Vector<CodePointData> code_point_data;
Vector<CodePointRange> code_point_ranges;
// The Unicode standard defines General Category values which are not in any UCD file. These
// values are simply unions of other values.
// https://www.unicode.org/reports/tr44/#GC_Values_Table
Vector<String> general_categories;
Vector<Alias> general_category_unions {
{ "Ll | Lu | Lt"sv, "LC"sv },
{ "Lu | Ll | Lt | Lm | Lo"sv, "L"sv },
{ "Mn | Mc | Me"sv, "M"sv },
{ "Nd | Nl | No"sv, "N"sv },
{ "Pc | Pd | Ps | Pe | Pi | Pf | Po"sv, "P"sv },
{ "Sm | Sc | Sk | So"sv, "S"sv },
{ "Zs | Zl | Zp"sv, "Z"sv },
{ "Cc | Cf | Cs | Co"sv, "C"sv }, // FIXME: This union should also contain "Cn" (Unassigned), which we don't parse yet.
};
Vector<Alias> general_category_aliases;
// The Unicode standard defines additional properties (Any, Assigned, ASCII) which are not in
// any UCD file. Assigned is set as the default enum value 0 so "property & Assigned == Assigned"
// is always true. Any is not assigned code points here because this file only parses assigned
// code points, whereas Any will include unassigned code points.
// https://unicode.org/reports/tr18/#General_Category_Property
PropList prop_list {
{ "Any"sv, {} },
{ "ASCII"sv, { { 0, 0x7f } } },
};
Vector<Alias> prop_aliases;
PropList script_list {
{ "Unknown"sv, {} },
};
Vector<Alias> script_aliases;
PropList script_extensions;
u32 largest_script_extensions_size { 0 };
PropList word_break_prop_list;
};
static constexpr auto s_desired_fields = Array {
"general_category"sv,
"simple_uppercase_mapping"sv,
"simple_lowercase_mapping"sv,
};
static void write_to_file_if_different(Core::File& file, StringView contents)
{
auto const current_contents = file.read_all();
if (StringView { current_contents.bytes() } == contents)
return;
VERIFY(file.seek(0));
VERIFY(file.truncate(0));
VERIFY(file.write(contents));
}
static void parse_special_casing(Core::File& file, UnicodeData& unicode_data)
{
auto parse_code_point_list = [&](auto const& line) {
Vector<u32> code_points;
auto segments = line.split(' ');
for (auto const& code_point : segments)
code_points.append(AK::StringUtils::convert_to_uint_from_hex<u32>(code_point).value());
return code_points;
};
while (file.can_read_line()) {
auto line = file.read_line();
if (line.is_empty() || line.starts_with('#'))
continue;
if (auto index = line.find('#'); index.has_value())
line = line.substring(0, *index);
auto segments = line.split(';', true);
VERIFY(segments.size() == 5 || segments.size() == 6);
SpecialCasing casing {};
casing.index = static_cast<u32>(unicode_data.special_casing.size());
casing.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
casing.lowercase_mapping = parse_code_point_list(segments[1]);
casing.titlecase_mapping = parse_code_point_list(segments[2]);
casing.uppercase_mapping = parse_code_point_list(segments[3]);
if (auto condition = segments[4].trim_whitespace(); !condition.is_empty()) {
auto conditions = condition.split(' ', true);
VERIFY(conditions.size() == 1 || conditions.size() == 2);
if (conditions.size() == 2) {
casing.locale = move(conditions[0]);
casing.condition = move(conditions[1]);
} else if (all_of(conditions[0], is_ascii_lower_alpha)) {
casing.locale = move(conditions[0]);
} else {
casing.condition = move(conditions[0]);
}
casing.locale = casing.locale.to_uppercase();
casing.condition.replace("_", "", true);
if (!casing.locale.is_empty() && !unicode_data.locales.contains_slow(casing.locale))
unicode_data.locales.append(casing.locale);
if (!casing.condition.is_empty() && !unicode_data.conditions.contains_slow(casing.condition))
unicode_data.conditions.append(casing.condition);
}
unicode_data.largest_casing_transform_size = max(unicode_data.largest_casing_transform_size, casing.lowercase_mapping.size());
unicode_data.largest_casing_transform_size = max(unicode_data.largest_casing_transform_size, casing.titlecase_mapping.size());
unicode_data.largest_casing_transform_size = max(unicode_data.largest_casing_transform_size, casing.uppercase_mapping.size());
unicode_data.special_casing.append(move(casing));
}
}
static void parse_prop_list(Core::File& file, PropList& prop_list, bool multi_value_property = false)
{
while (file.can_read_line()) {
auto line = file.read_line();
if (line.is_empty() || line.starts_with('#'))
continue;
if (auto index = line.find('#'); index.has_value())
line = line.substring(0, *index);
auto segments = line.split_view(';', true);
VERIFY(segments.size() == 2);
auto code_point_range = segments[0].trim_whitespace();
Vector<StringView> properties;
if (multi_value_property)
properties = segments[1].trim_whitespace().split_view(' ');
else
properties = { segments[1].trim_whitespace() };
for (auto const& property : properties) {
auto& code_points = prop_list.ensure(property.trim_whitespace());
if (code_point_range.contains(".."sv)) {
segments = code_point_range.split_view(".."sv);
VERIFY(segments.size() == 2);
auto begin = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
auto end = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[1]).value();
code_points.append({ begin, end });
} else {
auto code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(code_point_range).value();
code_points.append({ code_point, code_point });
}
}
}
}
static void parse_alias_list(Core::File& file, PropList const& prop_list, Vector<Alias>& prop_aliases)
{
String current_property;
auto append_alias = [&](auto alias, auto property) {
// Note: The alias files contain lines such as "Hyphen = Hyphen", which we should just skip.
if (alias == property)
return;
// FIXME: We will, eventually, need to find where missing properties are located and parse them.
if (!prop_list.contains(property))
return;
prop_aliases.append({ property, alias });
};
while (file.can_read_line()) {
auto line = file.read_line();
if (line.is_empty() || line.starts_with('#')) {
if (line.ends_with("Properties"sv))
current_property = line.substring(2);
continue;
}
// Note: For now, we only care about Binary Property aliases for Unicode property escapes.
if (current_property != "Binary Properties"sv)
continue;
auto segments = line.split_view(';', true);
VERIFY((segments.size() == 2) || (segments.size() == 3));
auto alias = segments[0].trim_whitespace();
auto property = segments[1].trim_whitespace();
append_alias(alias, property);
if (segments.size() == 3) {
alias = segments[2].trim_whitespace();
append_alias(alias, property);
}
}
}
static void parse_value_alias_list(Core::File& file, StringView desired_category, Vector<String> const& value_list, Vector<Alias> const& prop_unions, Vector<Alias>& prop_aliases, bool primary_value_is_first = true)
{
VERIFY(file.seek(0));
auto append_alias = [&](auto alias, auto value) {
// Note: The value alias file contains lines such as "Ahom = Ahom", which we should just skip.
if (alias == value)
return;
// FIXME: We will, eventually, need to find where missing properties are located and parse them.
if (!value_list.contains_slow(value) && !any_of(prop_unions, [&](auto const& u) { return value == u.alias; }))
return;
prop_aliases.append({ value, alias });
};
while (file.can_read_line()) {
auto line = file.read_line();
if (line.is_empty() || line.starts_with('#'))
continue;
if (auto index = line.find('#'); index.has_value())
line = line.substring(0, *index);
auto segments = line.split_view(';', true);
auto category = segments[0].trim_whitespace();
if (category != desired_category)
continue;
VERIFY((segments.size() == 3) || (segments.size() == 4));
auto value = primary_value_is_first ? segments[1].trim_whitespace() : segments[2].trim_whitespace();
auto alias = primary_value_is_first ? segments[2].trim_whitespace() : segments[1].trim_whitespace();
append_alias(alias, value);
if (segments.size() == 4) {
alias = segments[3].trim_whitespace();
append_alias(alias, value);
}
}
}
static void parse_unicode_data(Core::File& file, UnicodeData& unicode_data)
{
Optional<u32> code_point_range_start;
auto assign_code_point_property = [&](u32 code_point, auto const& list, auto& property, StringView default_) {
using PropertyType = RemoveCVReference<decltype(property)>;
constexpr bool is_single_item = IsSame<PropertyType, StringView>;
auto assign_property = [&](auto const& item) {
if constexpr (is_single_item)
property = item;
else
property.append(item);
};
for (auto const& item : list) {
for (auto const& range : item.value) {
if ((range.first <= code_point) && (code_point <= range.last)) {
assign_property(item.key);
break;
}
}
if constexpr (is_single_item) {
if (!property.is_empty())
break;
}
}
if (property.is_empty() && !default_.is_empty())
assign_property(default_);
};
while (file.can_read_line()) {
auto line = file.read_line();
if (line.is_empty())
continue;
auto segments = line.split(';', true);
VERIFY(segments.size() == 15);
CodePointData data {};
data.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
data.name = move(segments[1]);
data.general_category = move(segments[2]);
data.canonical_combining_class = AK::StringUtils::convert_to_uint<u8>(segments[3]).value();
data.bidi_class = move(segments[4]);
data.decomposition_type = move(segments[5]);
data.numeric_value_decimal = AK::StringUtils::convert_to_int<i8>(segments[6]);
data.numeric_value_digit = AK::StringUtils::convert_to_int<i8>(segments[7]);
data.numeric_value_numeric = AK::StringUtils::convert_to_int<i8>(segments[8]);
data.bidi_mirrored = segments[9] == "Y"sv;
data.unicode_1_name = move(segments[10]);
data.iso_comment = move(segments[11]);
data.simple_uppercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[12]);
data.simple_lowercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[13]);
data.simple_titlecase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[14]);
if (data.name.starts_with("<"sv) && data.name.ends_with(", First>")) {
VERIFY(!code_point_range_start.has_value());
code_point_range_start = data.code_point;
data.name = data.name.substring(1, data.name.length() - 9);
} else if (data.name.starts_with("<"sv) && data.name.ends_with(", Last>")) {
VERIFY(code_point_range_start.has_value());
unicode_data.code_point_ranges.append({ *code_point_range_start, data.code_point });
data.name = data.name.substring(1, data.name.length() - 8);
code_point_range_start.clear();
}
for (auto const& casing : unicode_data.special_casing) {
if (casing.code_point == data.code_point)
data.special_casing_indices.append(casing.index);
}
assign_code_point_property(data.code_point, unicode_data.prop_list, data.prop_list, "Assigned"sv);
assign_code_point_property(data.code_point, unicode_data.script_list, data.script, "Unknown"sv);
assign_code_point_property(data.code_point, unicode_data.script_extensions, data.script_extensions, {});
assign_code_point_property(data.code_point, unicode_data.word_break_prop_list, data.word_break_property, "Other"sv);
unicode_data.largest_special_casing_size = max(unicode_data.largest_special_casing_size, data.special_casing_indices.size());
unicode_data.largest_script_extensions_size = max(unicode_data.largest_script_extensions_size, data.script_extensions.size());
if (!unicode_data.general_categories.contains_slow(data.general_category))
unicode_data.general_categories.append(data.general_category);
unicode_data.code_point_data.append(move(data));
}
}
static void generate_unicode_data_header(Core::File& file, UnicodeData& unicode_data)
{
StringBuilder builder;
SourceGenerator generator { builder };
generator.set("casing_transform_size", String::number(unicode_data.largest_casing_transform_size));
generator.set("special_casing_size", String::number(unicode_data.largest_special_casing_size));
generator.set("script_extensions_size", String::number(unicode_data.largest_script_extensions_size));
auto generate_enum = [&](StringView name, StringView default_, Vector<String> values, Vector<Alias> unions = {}, Vector<Alias> aliases = {}, bool as_bitmask = false) {
VERIFY(!as_bitmask || (values.size() <= 64));
quick_sort(values);
quick_sort(unions, [](auto& union1, auto& union2) { return union1.alias < union2.alias; });
quick_sort(aliases, [](auto& alias1, auto& alias2) { return alias1.alias < alias2.alias; });
generator.set("name", name);
generator.set("underlying", String::formatted("{}UnderlyingType", name));
if (as_bitmask) {
generator.append(R"~~~(
using @underlying@ = u64;
enum class @name@ : @underlying@ {)~~~");
} else {
generator.append(R"~~~(
enum class @name@ {)~~~");
}
if (!default_.is_empty()) {
generator.set("default", default_);
generator.append(R"~~~(
@default@,)~~~");
}
u8 index = 0;
for (auto const& value : values) {
generator.set("value", value);
if (as_bitmask) {
generator.set("index", String::number(index++));
generator.append(R"~~~(
@value@ = static_cast<@underlying@>(1) << @index@,)~~~");
} else {
generator.append(R"~~~(
@value@,)~~~");
}
}
for (auto const& union_ : unions) {
generator.set("union", union_.alias);
generator.set("value", union_.property);
generator.append(R"~~~(
@union@ = @value@,)~~~");
}
for (auto const& alias : aliases) {
generator.set("alias", alias.alias);
generator.set("value", alias.property);
generator.append(R"~~~(
@alias@ = @value@,)~~~");
}
generator.append(R"~~~(
};
)~~~");
if (as_bitmask) {
generator.append(R"~~~(
constexpr @name@ operator&(@name@ value1, @name@ value2)
{
return static_cast<@name@>(static_cast<@underlying@>(value1) & static_cast<@underlying@>(value2));
}
constexpr @name@ operator|(@name@ value1, @name@ value2)
{
return static_cast<@name@>(static_cast<@underlying@>(value1) | static_cast<@underlying@>(value2));
}
)~~~");
}
};
generator.append(R"~~~(
#pragma once
#include <AK/Optional.h>
#include <AK/Types.h>
#include <LibUnicode/Forward.h>
namespace Unicode {
)~~~");
generate_enum("Locale"sv, "None"sv, move(unicode_data.locales));
generate_enum("Condition"sv, "None"sv, move(unicode_data.conditions));
generate_enum("GeneralCategory"sv, "None"sv, unicode_data.general_categories, unicode_data.general_category_unions, unicode_data.general_category_aliases, true);
generate_enum("Property"sv, "Assigned"sv, unicode_data.prop_list.keys(), {}, unicode_data.prop_aliases, true);
generate_enum("Script"sv, {}, unicode_data.script_list.keys(), {}, unicode_data.script_aliases);
generate_enum("WordBreakProperty"sv, "Other"sv, unicode_data.word_break_prop_list.keys());
generator.append(R"~~~(
struct SpecialCasing {
u32 code_point { 0 };
u32 lowercase_mapping[@casing_transform_size@];
u32 lowercase_mapping_size { 0 };
u32 uppercase_mapping[@casing_transform_size@];
u32 uppercase_mapping_size { 0 };
u32 titlecase_mapping[@casing_transform_size@];
u32 titlecase_mapping_size { 0 };
Locale locale { Locale::None };
Condition condition { Condition::None };
};
struct UnicodeData {
u32 code_point;)~~~");
auto append_field = [&](StringView type, StringView name) {
if (!s_desired_fields.span().contains_slow(name))
return;
generator.set("type", type);
generator.set("name", name);
generator.append(R"~~~(
@type@ @name@;)~~~");
};
// Note: For compile-time performance, only primitive types are used.
append_field("char const*"sv, "name"sv);
append_field("GeneralCategory"sv, "general_category"sv);
append_field("u8"sv, "canonical_combining_class"sv);
append_field("char const*"sv, "bidi_class"sv);
append_field("char const*"sv, "decomposition_type"sv);
append_field("i8"sv, "numeric_value_decimal"sv);
append_field("i8"sv, "numeric_value_digit"sv);
append_field("i8"sv, "numeric_value_numeric"sv);
append_field("bool"sv, "bidi_mirrored"sv);
append_field("char const*"sv, "unicode_1_name"sv);
append_field("char const*"sv, "iso_comment"sv);
append_field("u32"sv, "simple_uppercase_mapping"sv);
append_field("u32"sv, "simple_lowercase_mapping"sv);
append_field("u32"sv, "simple_titlecase_mapping"sv);
generator.append(R"~~~(
SpecialCasing const* special_casing[@special_casing_size@] {};
u32 special_casing_size { 0 };
Property properties { Property::Assigned };
Script script { Script::Unknown };
Script script_extensions[@script_extensions_size@];
u32 script_extensions_size { 0 };
WordBreakProperty word_break_property { WordBreakProperty::Other };
};
namespace Detail {
Optional<UnicodeData> unicode_data_for_code_point(u32 code_point);
Optional<Property> property_from_string(StringView const& property);
Optional<GeneralCategory> general_category_from_string(StringView const& general_category);
Optional<Script> script_from_string(StringView const& script);
}
}
)~~~");
write_to_file_if_different(file, generator.as_string_view());
}
static void generate_unicode_data_implementation(Core::File& file, UnicodeData const& unicode_data)
{
StringBuilder builder;
SourceGenerator generator { builder };
generator.set("special_casing_size", String::number(unicode_data.special_casing.size()));
generator.set("code_point_data_size", String::number(unicode_data.code_point_data.size()));
generator.append(R"~~~(
#include <AK/Array.h>
#include <AK/CharacterTypes.h>
#include <AK/HashMap.h>
#include <AK/StringView.h>
#include <LibUnicode/UnicodeData.h>
namespace Unicode {
)~~~");
auto append_list_and_size = [&](auto const& list, StringView format) {
if (list.is_empty()) {
generator.append(", {}, 0");
return;
}
bool first = true;
generator.append(", {");
for (auto const& item : list) {
generator.append(first ? " " : ", ");
generator.append(String::formatted(format, item));
first = false;
}
generator.append(String::formatted(" }}, {}", list.size()));
};
generator.append(R"~~~(
static constexpr Array<SpecialCasing, @special_casing_size@> s_special_casing { {)~~~");
for (auto const& casing : unicode_data.special_casing) {
generator.set("code_point", String::formatted("{:#x}", casing.code_point));
generator.append(R"~~~(
{ @code_point@)~~~");
constexpr auto format = "0x{:x}"sv;
append_list_and_size(casing.lowercase_mapping, format);
append_list_and_size(casing.uppercase_mapping, format);
append_list_and_size(casing.titlecase_mapping, format);
generator.set("locale", casing.locale.is_empty() ? "None" : casing.locale);
generator.append(", Locale::@locale@");
generator.set("condition", casing.condition.is_empty() ? "None" : casing.condition);
generator.append(", Condition::@condition@");
generator.append(" },");
}
generator.append(R"~~~(
} };
static constexpr Array<UnicodeData, @code_point_data_size@> s_unicode_data { {)~~~");
auto append_field = [&](StringView name, String value) {
if (!s_desired_fields.span().contains_slow(name))
return;
generator.set("value", move(value));
generator.append(", @value@");
};
for (auto const& data : unicode_data.code_point_data) {
generator.set("code_point", String::formatted("{:#x}", data.code_point));
generator.append(R"~~~(
{ @code_point@)~~~");
append_field("name", String::formatted("\"{}\"", data.name));
append_field("general_category", String::formatted("GeneralCategory::{}", data.general_category));
append_field("canonical_combining_class", String::number(data.canonical_combining_class));
append_field("bidi_class", String::formatted("\"{}\"", data.bidi_class));
append_field("decomposition_type", String::formatted("\"{}\"", data.decomposition_type));
append_field("numeric_value_decimal", String::number(data.numeric_value_decimal.value_or(-1)));
append_field("numeric_value_digit", String::number(data.numeric_value_digit.value_or(-1)));
append_field("numeric_value_numeric", String::number(data.numeric_value_numeric.value_or(-1)));
append_field("bidi_mirrored", String::formatted("{}", data.bidi_mirrored));
append_field("unicode_1_name", String::formatted("\"{}\"", data.unicode_1_name));
append_field("iso_comment", String::formatted("\"{}\"", data.iso_comment));
append_field("simple_uppercase_mapping", String::formatted("{:#x}", data.simple_uppercase_mapping.value_or(data.code_point)));
append_field("simple_lowercase_mapping", String::formatted("{:#x}", data.simple_lowercase_mapping.value_or(data.code_point)));
append_field("simple_titlecase_mapping", String::formatted("{:#x}", data.simple_titlecase_mapping.value_or(data.code_point)));
append_list_and_size(data.special_casing_indices, "&s_special_casing[{}]"sv);
bool first = true;
for (auto const& property : data.prop_list) {
generator.append(first ? ", " : " | ");
generator.append(String::formatted("Property::{}", property));
first = false;
}
generator.append(String::formatted(", Script::{}", data.script));
append_list_and_size(data.script_extensions, "Script::{}"sv);
generator.append(String::formatted(", WordBreakProperty::{}", data.word_break_property));
generator.append(" },");
}
generator.append(R"~~~(
} };
static HashMap<u32, UnicodeData const*> const& ensure_code_point_map()
{
static HashMap<u32, UnicodeData const*> code_point_to_data_map;
code_point_to_data_map.ensure_capacity(s_unicode_data.size());
for (auto const& unicode_data : s_unicode_data)
code_point_to_data_map.set(unicode_data.code_point, &unicode_data);
return code_point_to_data_map;
}
static Optional<u32> index_of_code_point_in_range(u32 code_point)
{)~~~");
for (auto const& range : unicode_data.code_point_ranges) {
generator.set("first", String::formatted("{:#x}", range.first));
generator.set("last", String::formatted("{:#x}", range.last));
generator.append(R"~~~(
if ((code_point > @first@) && (code_point < @last@))
return @first@;)~~~");
}
generator.append(R"~~~(
return {};
}
namespace Detail {
Optional<UnicodeData> unicode_data_for_code_point(u32 code_point)
{
static auto const& code_point_to_data_map = ensure_code_point_map();
VERIFY(is_unicode(code_point));
if (auto data = code_point_to_data_map.get(code_point); data.has_value())
return *(data.value());
if (auto index = index_of_code_point_in_range(code_point); index.has_value()) {
auto data_for_range = *(code_point_to_data_map.get(*index).value());
data_for_range.simple_uppercase_mapping = code_point;
data_for_range.simple_lowercase_mapping = code_point;
return data_for_range;
}
return {};
}
Optional<Property> property_from_string(StringView const& property)
{
if (property == "Assigned"sv)
return Property::Assigned;)~~~");
for (auto const& property : unicode_data.prop_list) {
generator.set("property", property.key);
generator.append(R"~~~(
if (property == "@property@"sv)
return Property::@property@;)~~~");
}
for (auto const& alias : unicode_data.prop_aliases) {
generator.set("property", alias.alias);
generator.append(R"~~~(
if (property == "@property@"sv)
return Property::@property@;)~~~");
}
generator.append(R"~~~(
return {};
}
Optional<GeneralCategory> general_category_from_string(StringView const& general_category)
{)~~~");
for (auto const& general_category : unicode_data.general_categories) {
generator.set("general_category", general_category);
generator.append(R"~~~(
if (general_category == "@general_category@"sv)
return GeneralCategory::@general_category@;)~~~");
}
for (auto const& union_ : unicode_data.general_category_unions) {
generator.set("general_category", union_.alias);
generator.append(R"~~~(
if (general_category == "@general_category@"sv)
return GeneralCategory::@general_category@;)~~~");
}
for (auto const& alias : unicode_data.general_category_aliases) {
generator.set("general_category", alias.alias);
generator.append(R"~~~(
if (general_category == "@general_category@"sv)
return GeneralCategory::@general_category@;)~~~");
}
generator.append(R"~~~(
return {};
}
Optional<Script> script_from_string(StringView const& script)
{)~~~");
for (auto const& script : unicode_data.script_list) {
generator.set("script", script.key);
generator.append(R"~~~(
if (script == "@script@"sv)
return Script::@script@;)~~~");
}
for (auto const& alias : unicode_data.script_aliases) {
generator.set("script", alias.alias);
generator.append(R"~~~(
if (script == "@script@"sv)
return Script::@script@;)~~~");
}
generator.append(R"~~~(
return {};
}
}
}
)~~~");
write_to_file_if_different(file, generator.as_string_view());
}
int main(int argc, char** argv)
{
char const* generated_header_path = nullptr;
char const* generated_implementation_path = nullptr;
char const* unicode_data_path = nullptr;
char const* special_casing_path = nullptr;
char const* prop_list_path = nullptr;
char const* derived_core_prop_path = nullptr;
char const* derived_binary_prop_path = nullptr;
char const* prop_alias_path = nullptr;
char const* prop_value_alias_path = nullptr;
char const* scripts_path = nullptr;
char const* script_extensions_path = nullptr;
char const* word_break_path = nullptr;
char const* emoji_data_path = nullptr;
Core::ArgsParser args_parser;
args_parser.add_option(generated_header_path, "Path to the Unicode Data header file to generate", "generated-header-path", 'h', "generated-header-path");
args_parser.add_option(generated_implementation_path, "Path to the Unicode Data implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
args_parser.add_option(unicode_data_path, "Path to UnicodeData.txt file", "unicode-data-path", 'u', "unicode-data-path");
args_parser.add_option(special_casing_path, "Path to SpecialCasing.txt file", "special-casing-path", 's', "special-casing-path");
args_parser.add_option(prop_list_path, "Path to PropList.txt file", "prop-list-path", 'p', "prop-list-path");
args_parser.add_option(derived_core_prop_path, "Path to DerivedCoreProperties.txt file", "derived-core-prop-path", 'd', "derived-core-prop-path");
args_parser.add_option(derived_binary_prop_path, "Path to DerivedBinaryProperties.txt file", "derived-binary-prop-path", 'b', "derived-binary-prop-path");
args_parser.add_option(prop_alias_path, "Path to PropertyAliases.txt file", "prop-alias-path", 'a', "prop-alias-path");
args_parser.add_option(prop_value_alias_path, "Path to PropertyValueAliases.txt file", "prop-value-alias-path", 'v', "prop-value-alias-path");
args_parser.add_option(scripts_path, "Path to Scripts.txt file", "scripts-path", 'r', "scripts-path");
args_parser.add_option(script_extensions_path, "Path to ScriptExtensions.txt file", "script-extensions-path", 'x', "script-extensions-path");
args_parser.add_option(word_break_path, "Path to WordBreakProperty.txt file", "word-break-path", 'w', "word-break-path");
args_parser.add_option(emoji_data_path, "Path to emoji-data.txt file", "emoji-data-path", 'e', "emoji-data-path");
args_parser.parse(argc, argv);
auto open_file = [&](StringView path, StringView flags, Core::OpenMode mode = Core::OpenMode::ReadOnly) {
if (path.is_empty()) {
warnln("{} is required", flags);
args_parser.print_usage(stderr, argv[0]);
exit(1);
}
auto file_or_error = Core::File::open(path, mode);
if (file_or_error.is_error()) {
warnln("Failed to open {}: {}", path, file_or_error.release_error());
exit(1);
}
return file_or_error.release_value();
};
auto generated_header_file = open_file(generated_header_path, "-h/--generated-header-path", Core::OpenMode::ReadWrite);
auto generated_implementation_file = open_file(generated_implementation_path, "-c/--generated-implementation-path", Core::OpenMode::ReadWrite);
auto unicode_data_file = open_file(unicode_data_path, "-u/--unicode-data-path");
auto special_casing_file = open_file(special_casing_path, "-s/--special-casing-path");
auto prop_list_file = open_file(prop_list_path, "-p/--prop-list-path");
auto derived_core_prop_file = open_file(derived_core_prop_path, "-d/--derived-core-prop-path");
auto derived_binary_prop_file = open_file(derived_binary_prop_path, "-b/--derived-binary-prop-path");
auto prop_alias_file = open_file(prop_alias_path, "-a/--prop-alias-path");
auto prop_value_alias_file = open_file(prop_value_alias_path, "-v/--prop-value-alias-path");
auto scripts_file = open_file(scripts_path, "-r/--scripts-path");
auto script_extensions_file = open_file(script_extensions_path, "-x/--script-extensions-path");
auto word_break_file = open_file(word_break_path, "-w/--word-break-path");
auto emoji_data_file = open_file(emoji_data_path, "-e/--emoji-data-path");
UnicodeData unicode_data {};
parse_special_casing(special_casing_file, unicode_data);
parse_prop_list(prop_list_file, unicode_data.prop_list);
parse_prop_list(derived_core_prop_file, unicode_data.prop_list);
parse_prop_list(derived_binary_prop_file, unicode_data.prop_list);
parse_prop_list(emoji_data_file, unicode_data.prop_list);
parse_alias_list(prop_alias_file, unicode_data.prop_list, unicode_data.prop_aliases);
parse_prop_list(scripts_file, unicode_data.script_list);
parse_prop_list(script_extensions_file, unicode_data.script_extensions, true);
parse_prop_list(word_break_file, unicode_data.word_break_prop_list);
parse_unicode_data(unicode_data_file, unicode_data);
parse_value_alias_list(prop_value_alias_file, "gc"sv, unicode_data.general_categories, unicode_data.general_category_unions, unicode_data.general_category_aliases);
parse_value_alias_list(prop_value_alias_file, "sc"sv, unicode_data.script_list.keys(), {}, unicode_data.script_aliases, false);
generate_unicode_data_header(generated_header_file, unicode_data);
generate_unicode_data_implementation(generated_implementation_file, unicode_data);
return 0;
}
| 40.083333 | 214 | 0.662564 | Blocky-studio |
b9f64e7519efdf9f94327dbbc6d2229ed1017bdf | 2,405 | cpp | C++ | samples/cpp/3_2_1/3_2_1.cpp | 971586331/opencv-2.4.9 | d0ecc6013340ce505bade94a61946ba7654e381d | [
"BSD-3-Clause"
] | null | null | null | samples/cpp/3_2_1/3_2_1.cpp | 971586331/opencv-2.4.9 | d0ecc6013340ce505bade94a61946ba7654e381d | [
"BSD-3-Clause"
] | null | null | null | samples/cpp/3_2_1/3_2_1.cpp | 971586331/opencv-2.4.9 | d0ecc6013340ce505bade94a61946ba7654e381d | [
"BSD-3-Clause"
] | null | null | null | //---------------------------------【头文件、命名空间包含部分】-------------------------------
// 描述:包含程序所使用的头文件和命名空间
//-------------------------------------------------------------------------------------------------
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
//-----------------------------------【宏定义部分】--------------------------------------------
// 描述:定义一些辅助宏
//------------------------------------------------------------------------------------------------
#define WINDOW_NAME "【滑动条的创建&线性混合示例】" //为窗口标题定义的宏
//-----------------------------------【全局变量声明部分】--------------------------------------
// 描述:全局变量声明
//-----------------------------------------------------------------------------------------------
const int g_nMaxAlphaValue = 100;//Alpha值的最大值
int g_nAlphaValueSlider;//滑动条对应的变量
double g_dAlphaValue;
double g_dBetaValue;
//声明存储图像的变量
Mat g_srcImage1;
Mat g_srcImage2;
Mat g_dstImage;
//-----------------------------------【on_Trackbar( )函数】--------------------------------
// 描述:响应滑动条的回调函数
//------------------------------------------------------------------------------------------
void on_Trackbar( int, void* )
{
//求出当前alpha值相对于最大值的比例
g_dAlphaValue = (double) g_nAlphaValueSlider/g_nMaxAlphaValue ;
//则beta值为1减去alpha值
g_dBetaValue = ( 1.0 - g_dAlphaValue );
//根据alpha和beta值进行线性混合
addWeighted( g_srcImage1, g_dAlphaValue, g_srcImage2, g_dBetaValue, 0.0, g_dstImage);
//显示效果图
imshow( WINDOW_NAME, g_dstImage );
}
//--------------------------------------【main( )函数】-----------------------------------------
// 描述:控制台应用程序的入口函数,我们的程序从这里开始执行
//-----------------------------------------------------------------------------------------------
int main( int argc, char** argv )
{
//加载图像 (两图像的尺寸需相同)
g_srcImage1 = imread("1.jpg");
g_srcImage2 = imread("2.jpg");
if( !g_srcImage1.data ) { printf("读取第一幅图片错误,请确定目录下是否有imread函数指定图片存在~! \n"); return -1; }
if( !g_srcImage2.data ) { printf("读取第二幅图片错误,请确定目录下是否有imread函数指定图片存在~!\n"); return -1; }
//设置滑动条初值为70
g_nAlphaValueSlider = 70;
//创建窗体
namedWindow(WINDOW_NAME, 1);
//在创建的窗体中创建一个滑动条控件
char TrackbarName[50];
sprintf( TrackbarName, "透明值 %d", g_nMaxAlphaValue );
createTrackbar( TrackbarName, WINDOW_NAME, &g_nAlphaValueSlider, g_nMaxAlphaValue, on_Trackbar );
//结果在回调函数中显示
on_Trackbar( g_nAlphaValueSlider, 0 );
//按任意键退出
waitKey(0);
return 0;
} | 30.833333 | 99 | 0.469439 | 971586331 |
b9f8e2bdcc240f989912e5a9f609e22c769214ce | 7,030 | cc | C++ | third_party/blink/renderer/core/mojo/mojo_watcher.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/core/mojo/mojo_watcher.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/core/mojo/mojo_watcher.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // 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 "third_party/blink/renderer/core/mojo/mojo_watcher.h"
#include "base/single_thread_task_runner.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_mojo_handle_signals.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_mojo_watch_callback.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
// static
MojoWatcher* MojoWatcher::Create(mojo::Handle handle,
const MojoHandleSignals* signals_dict,
V8MojoWatchCallback* callback,
ExecutionContext* context) {
MojoWatcher* watcher = MakeGarbageCollected<MojoWatcher>(context, callback);
MojoResult result = watcher->Watch(handle, signals_dict);
// TODO(alokp): Consider raising an exception.
// Current clients expect to recieve the initial error returned by MojoWatch
// via watch callback.
//
// Note that the usage of WrapPersistent is intentional so that the initial
// error is guaranteed to be reported to the client in case where the given
// handle is invalid and garbage collection happens before the callback
// is scheduled.
if (result != MOJO_RESULT_OK) {
watcher->task_runner_->PostTask(
FROM_HERE,
WTF::Bind(&V8MojoWatchCallback::InvokeAndReportException,
WrapPersistent(callback), WrapPersistent(watcher), result));
}
return watcher;
}
MojoWatcher::~MojoWatcher() = default;
MojoResult MojoWatcher::cancel() {
if (!trap_handle_.is_valid())
return MOJO_RESULT_INVALID_ARGUMENT;
trap_handle_.reset();
return MOJO_RESULT_OK;
}
void MojoWatcher::Trace(Visitor* visitor) {
visitor->Trace(callback_);
ScriptWrappable::Trace(visitor);
ExecutionContextLifecycleObserver::Trace(visitor);
}
bool MojoWatcher::HasPendingActivity() const {
return handle_.is_valid();
}
void MojoWatcher::ContextDestroyed() {
cancel();
}
MojoWatcher::MojoWatcher(ExecutionContext* context,
V8MojoWatchCallback* callback)
: ExecutionContextLifecycleObserver(context),
task_runner_(context->GetTaskRunner(TaskType::kInternalDefault)),
callback_(callback) {}
MojoResult MojoWatcher::Watch(mojo::Handle handle,
const MojoHandleSignals* signals_dict) {
::MojoHandleSignals signals = MOJO_HANDLE_SIGNAL_NONE;
if (signals_dict->readable())
signals |= MOJO_HANDLE_SIGNAL_READABLE;
if (signals_dict->writable())
signals |= MOJO_HANDLE_SIGNAL_WRITABLE;
if (signals_dict->peerClosed())
signals |= MOJO_HANDLE_SIGNAL_PEER_CLOSED;
MojoResult result =
mojo::CreateTrap(&MojoWatcher::OnHandleReady, &trap_handle_);
DCHECK_EQ(MOJO_RESULT_OK, result);
result = MojoAddTrigger(trap_handle_.get().value(), handle.value(), signals,
MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED,
reinterpret_cast<uintptr_t>(this), nullptr);
if (result != MOJO_RESULT_OK)
return result;
handle_ = handle;
MojoResult ready_result;
result = Arm(&ready_result);
if (result == MOJO_RESULT_OK)
return result;
if (result == MOJO_RESULT_FAILED_PRECONDITION) {
// We couldn't arm the watcher because the handle is already ready to
// trigger a success notification. Post a notification manually.
task_runner_->PostTask(FROM_HERE,
WTF::Bind(&MojoWatcher::RunReadyCallback,
WrapPersistent(this), ready_result));
return MOJO_RESULT_OK;
}
// If MojoAddTrigger succeeds but Arm does not, that means another thread
// closed the watched handle in between. Treat it like we'd treat
// MojoAddTrigger trying to watch an invalid handle.
trap_handle_.reset();
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult MojoWatcher::Arm(MojoResult* ready_result) {
// Nothing to do if the watcher is inactive.
if (!handle_.is_valid())
return MOJO_RESULT_OK;
uint32_t num_blocking_events = 1;
MojoTrapEvent blocking_event = {sizeof(blocking_event)};
MojoResult result = MojoArmTrap(trap_handle_.get().value(), nullptr,
&num_blocking_events, &blocking_event);
if (result == MOJO_RESULT_OK)
return MOJO_RESULT_OK;
if (result == MOJO_RESULT_FAILED_PRECONDITION) {
DCHECK_EQ(1u, num_blocking_events);
DCHECK_EQ(reinterpret_cast<uintptr_t>(this),
blocking_event.trigger_context);
*ready_result = blocking_event.result;
return result;
}
return result;
}
// static
void MojoWatcher::OnHandleReady(const MojoTrapEvent* event) {
// It is safe to assume the MojoWathcer still exists. It stays alive at least
// as long as |handle_| is valid, and |handle_| is only reset after we
// dispatch a |MOJO_RESULT_CANCELLED| notification. That is always the last
// notification received by this callback.
MojoWatcher* watcher = reinterpret_cast<MojoWatcher*>(event->trigger_context);
PostCrossThreadTask(
*watcher->task_runner_, FROM_HERE,
CrossThreadBindOnce(&MojoWatcher::RunReadyCallback,
WrapCrossThreadWeakPersistent(watcher),
event->result));
}
void MojoWatcher::RunReadyCallback(MojoResult result) {
if (result == MOJO_RESULT_CANCELLED) {
// Last notification.
handle_ = mojo::Handle();
// Only dispatch to the callback if this cancellation was implicit due to
// |handle_| closure. If it was explicit, |trap_handlde_| has already been
// reset.
if (trap_handle_.is_valid()) {
trap_handle_.reset();
callback_->InvokeAndReportException(this, result);
}
return;
}
// Ignore callbacks if not watching.
if (!trap_handle_.is_valid())
return;
callback_->InvokeAndReportException(this, result);
// The user callback may have canceled watching.
if (!trap_handle_.is_valid())
return;
// Rearm the watcher so another notification can fire.
//
// TODO(rockot): MojoWatcher should expose some better approximation of the
// new watcher API, including explicit add and removal of handles from the
// watcher, as well as explicit arming.
MojoResult ready_result;
MojoResult arm_result = Arm(&ready_result);
if (arm_result == MOJO_RESULT_OK)
return;
if (arm_result == MOJO_RESULT_FAILED_PRECONDITION) {
task_runner_->PostTask(FROM_HERE,
WTF::Bind(&MojoWatcher::RunReadyCallback,
WrapWeakPersistent(this), ready_result));
return;
}
}
} // namespace blink
| 35.867347 | 88 | 0.70697 | sarang-apps |
b9f94ea1fc98c728d023d6a1893a30dfddd34297 | 4,817 | cpp | C++ | R0Bypass/GPUZ/GPUZ/sys.cpp | fengjixuchui/Antivirus_R3_bypass_demo | d8f95382755bdcbad983bbc83555fe6a3dc144c8 | [
"MIT"
] | 23 | 2022-01-07T04:28:40.000Z | 2022-01-26T12:19:43.000Z | R0Bypass/GPUZ/GPUZ/sys.cpp | fengjixuchui/Antivirus_R3_bypass_demo | d8f95382755bdcbad983bbc83555fe6a3dc144c8 | [
"MIT"
] | null | null | null | R0Bypass/GPUZ/GPUZ/sys.cpp | fengjixuchui/Antivirus_R3_bypass_demo | d8f95382755bdcbad983bbc83555fe6a3dc144c8 | [
"MIT"
] | 2 | 2020-03-19T00:43:14.000Z | 2020-03-19T12:21:46.000Z | #include "Global.h"
#define CI_DLL "ci.dll"
#define CI_PATTERN "89 0D ? ? ? ? 49 8B F8"
#define NTOS_EXE "ntoskrnl.exe"
#define NTOS_PATTERN "C6 05 ? ? ? ? ? 8D 7B 06"
/* Initialization Routine */
sys::sys(uint32_t BuildNumber)
: dwBuildNumber(BuildNumber)
{
if (BuildNumber < 7601) // Check if OSBuildNumber Is Supported
throw std::runtime_error("OS Not Supported.");
Driver = new gpuz(); // Initialize gpuz.sys IOCTL functions used for reading/writing System Memory
if (Driver == nullptr)
throw std::runtime_error("gpuz Class Object Is Not Initialized.");
g_CiVar = QueryVar() - 0x100000000; // Query The Global System Variable For Patching
}
/* Call to gpuz.sys to patch the global system variable */
BOOLEAN sys::DisableDSE()
{
std::cout << "Disabling DSE...\n";
int val = dwBuildNumber < 9200 ? 0 : 8; // Get Correct Value To Patch Depending On The OS Version
return Driver->WriteSystemAddress<uint32_t>(g_CiVar, val);
}
/* Call to gpuz.sys to re enable DSE */
BOOLEAN sys::EnableDSE()
{
std::cout << "Enabling DSE...\n";
int val = dwBuildNumber < 9200 ? 1 : 6; // Get Correct Value To Patch Depending On The OS Version
return Driver->WriteSystemAddress<uint32_t>(g_CiVar, val);
}
sys::~sys()
{
Driver->~gpuz();
}
uint64_t sys::QueryVar()
{
uint64_t SystemImageBase = 0;
GetSystemDirectoryA(szSystemPath, MAX_PATH);
strcat_s(szSystemPath, "\\");
/* Initialize Dynamic Data */
if (dwBuildNumber < 9200) // Windows 7
{
ImageName = NTOS_EXE; // Global Variable Is Located In ntoskrnl.exe
VariablePattern = NTOS_PATTERN;
AddressOffset = 7;
}
else // Rest of the supported OS
{
ImageName = CI_DLL; // Global Variable Is Located In CI.dll
VariablePattern = CI_PATTERN;
AddressOffset = 6;
}
strcat_s(szSystemPath, ImageName);
HMODULE MappedImage = LoadLibraryExA(szSystemPath, NULL, DONT_RESOLVE_DLL_REFERENCES); // Load the system module to memory
if (!MappedImage)
throw std::runtime_error("Cannot Load System Image.");
if (!GetModuleInformation(GetCurrentProcess(), MappedImage, &ModInfo, sizeof(ModInfo))) // Get Information About It
throw std::runtime_error("Could Not Get Module Information.");
auto& utils = Utils::instance();
uint64_t varAddress = utils.FindPattern((uint64_t)ModInfo.lpBaseOfDll, ModInfo.SizeOfImage, VariablePattern, 0); // Pattern Search For The OS Specified Variable
if (!varAddress)
throw std::runtime_error("Could Not Find System Module Address.");
uint32_t relative = *(uint32_t*)(varAddress + 2); // Dereference the relative offset
FreeModule(MappedImage);
uint64_t g_CiVar = varAddress + relative + AddressOffset; // GlobalVar = FoundAddress + relative + OSSpecifiedAddressOffset
g_CiVar -= (uint64_t)ModInfo.lpBaseOfDll; // GlobalVarAddress - MappedSystemModuleBaseAddress = GlobalVarOffsetFromModuleBase
if (!GetSystemImageInformation(ImageName, &SystemImageBase)) // Get System Module Base Loaded By The OS
throw std::runtime_error("Could Not Get System Image Information.");
g_CiVar += SystemImageBase; // Add its BaseAddress To GlobalVarOffset
return g_CiVar;
}
/* Queries OS Loaded System Modules */
BOOLEAN sys::GetSystemImageInformation(const char* SystemModuleName, uint64_t* ImageBase)
{
PRTL_PROCESS_MODULES pModInfo = (PRTL_PROCESS_MODULES)GetSystemInformation((SYSTEM_INFORMATION_CLASS)11); // Query System Module Information
int i = pModInfo->NumberOfModules - 1;
if (pModInfo)
{
auto& utils = Utils::instance();
/* Iterate System Module For Desired Module And Return Its ImageBase */
for (; i != -1; --i)
{
RTL_PROCESS_MODULE_INFORMATION entry = pModInfo->Modules[i];
char* ImageName = utils.ToLower((char*)&entry.FullPathName[entry.OffsetToFileName]);
BOOLEAN Found = !strcmp(ImageName, SystemModuleName)
|| !strcmp((char*)&entry.FullPathName[entry.OffsetToFileName], SystemModuleName);
free(ImageName);
if (Found)
{
*ImageBase = (uint64_t)entry.ImageBase;
break;
}
}
}
VirtualFree(pModInfo, 0, MEM_RELEASE);
return i != -1;
}
/* Call To Native QuerySystemInformation To Get SystemModuleInformation */
PVOID sys::GetSystemInformation(SYSTEM_INFORMATION_CLASS InfoClass)
{
ULONG RetLen = 0;
NTSTATUS status = NtQuerySystemInformation(InfoClass, NULL, 0, &RetLen);
if (status != STATUS_INFO_LENGTH_MISMATCH)
{
std::cout << "Status: " << std::hex << status << std::endl;
return 0;
}
PVOID pBuffer = VirtualAlloc(NULL, RetLen, MEM_COMMIT, PAGE_READWRITE);
if (!pBuffer)
{
std::cout << "Could not allocate buffer\n";
return 0;
}
status = NtQuerySystemInformation(InfoClass, pBuffer, RetLen, &RetLen);
if (!NT_SUCCESS(status))
{
std::cout << "Could not query info. Status: " << std::hex << status << std::endl;
VirtualFree(pBuffer, 0, MEM_RELEASE);
return 0;
}
return pBuffer;
} | 32.328859 | 161 | 0.722026 | fengjixuchui |
b9fabb221e09845021c1f3c72846b493c8e4020a | 2,982 | cpp | C++ | catboost/libs/metrics/ut/balanced_accuracy_ut.cpp | gwjknvwjn/catboost | a5644bf80e2e37985012fb3bdd285fc6d798c61c | [
"Apache-2.0"
] | 4 | 2020-06-24T06:07:52.000Z | 2021-04-16T22:58:09.000Z | catboost/libs/metrics/ut/balanced_accuracy_ut.cpp | gwjknvwjn/catboost | a5644bf80e2e37985012fb3bdd285fc6d798c61c | [
"Apache-2.0"
] | null | null | null | catboost/libs/metrics/ut/balanced_accuracy_ut.cpp | gwjknvwjn/catboost | a5644bf80e2e37985012fb3bdd285fc6d798c61c | [
"Apache-2.0"
] | null | null | null | #include <catboost/libs/metrics/metric.h>
#include <catboost/libs/metrics/metric_holder.h>
#include <library/cpp/unittest/registar.h>
// use balanced_accuracy_score from sklearn to compute benchmark value
Y_UNIT_TEST_SUITE(BalancedAccuracyMetricTest) {
Y_UNIT_TEST(BalancedAccuracyTest) {
{
TVector<TVector<double>> approx{{0, 1, 0, 0, 1, 0}};
TVector<float> target{0, 1, 0, 0, 0, 1};
TVector<float> weight{1, 1, 1, 1, 1, 1};
NPar::TLocalExecutor executor;
auto metric = std::move(CreateMetric(ELossFunction::BalancedAccuracy,
TLossParams(), /*approxDimension=*/1)[0]);
TMetricHolder score = metric->Eval(approx, target, weight, {}, 0, target.size(), executor);
UNIT_ASSERT_DOUBLES_EQUAL(metric->GetFinalError(score), 0.625, 1e-3);
}
{
TVector<TVector<double>> approx{{0, 0, 1}};
TVector<float> target{0, 1, 1};
TVector<float> weight{1, 1, 1};
NPar::TLocalExecutor executor;
auto metric = std::move(CreateMetric(ELossFunction::BalancedAccuracy,
TLossParams(), /*approxDimension=*/1)[0]);
TMetricHolder score = metric->Eval(approx, target, weight, {}, 0, target.size(), executor);;
UNIT_ASSERT_DOUBLES_EQUAL(metric->GetFinalError(score), 0.75, 1e-2);
}
{
TVector<TVector<double>> approx{{1, 1, 1, 0}};
TVector<float> target{1, 1, 1, 0};
TVector<float> weight{1, 1, 1, 1};
NPar::TLocalExecutor executor;
auto metric = std::move(CreateMetric(ELossFunction::BalancedAccuracy,
TLossParams(), /*approxDimension=*/1)[0]);
TMetricHolder score = metric->Eval(approx, target, weight, {}, 0, target.size(), executor);
UNIT_ASSERT_DOUBLES_EQUAL(metric->GetFinalError(score), 1, 1e-1);
}
{
TVector<TVector<double>> approx{{1, 1, 1, 1}};
TVector<float> target{1, 1, 1, 1};
TVector<float> weight{1, 1, 1, 1};
NPar::TLocalExecutor executor;
auto metric = std::move(CreateMetric(ELossFunction::BalancedAccuracy,
TLossParams(), /*approxDimension=*/1)[0]);
TMetricHolder score = metric->Eval(approx, target, weight, {}, 1, target.size(), executor);
UNIT_ASSERT_DOUBLES_EQUAL(metric->GetFinalError(score), 1, 1e-1);
}
{
TVector<TVector<double>> approx{{0, 0, 0, 0}};
TVector<float> target{0, 0, 0, 0};
TVector<float> weight{1, 1, 1, 1};
NPar::TLocalExecutor executor;
auto metric = std::move(CreateMetric(ELossFunction::BalancedAccuracy,
TLossParams(), /*approxDimension=*/1)[0]);
TMetricHolder score = metric->Eval(approx, target, weight, {}, 1, target.size(), executor);
UNIT_ASSERT_DOUBLES_EQUAL(metric->GetFinalError(score), 1, 1e-1);
}
}
}
| 42 | 100 | 0.593226 | gwjknvwjn |
b9fbc29db558bb43b7156b6602d6b5a171bb5e7b | 370 | cpp | C++ | src/crossserver/crossserver/protocal/msgcpp.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 3 | 2021-12-16T13:57:28.000Z | 2022-03-26T07:50:08.000Z | src/crossserver/crossserver/protocal/msgcpp.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | null | null | null | src/crossserver/crossserver/protocal/msgcpp.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 1 | 2022-03-26T07:50:11.000Z | 2022-03-26T07:50:11.000Z | #include "servercommon/userprotocal/msgheader.h"
#include "servercommon/userprotocal/systemmsgcode.h"
#include "servercommon/userprotocal/crossmsgcode.h"
#include "servercommon/userprotocal/msgsystem.h"
#include "msgcross.h"
namespace Protocol
{
SCNoticeNum::SCNoticeNum():header(MT_SYSTEM_NOTICE_CODE_SC){}
SCSystemMsg::SCSystemMsg():header(MT_SYSTEM_MSG_SC){}
}
| 24.666667 | 62 | 0.810811 | mage-game |
b9fc2f160dc079511a18821fdc0c231f7a63561a | 42,423 | cpp | C++ | src/helics/shared_api_library/FederateExport.cpp | GMLC-TDC/HELICS-src | 5e37168bca0ea9e16b939e052e257182ca6e24bd | [
"BSD-3-Clause"
] | 31 | 2017-06-29T19:50:25.000Z | 2019-05-17T14:10:14.000Z | src/helics/shared_api_library/FederateExport.cpp | GMLC-TDC/HELICS-src | 5e37168bca0ea9e16b939e052e257182ca6e24bd | [
"BSD-3-Clause"
] | 511 | 2017-08-18T02:14:00.000Z | 2019-06-18T20:11:02.000Z | src/helics/shared_api_library/FederateExport.cpp | GMLC-TDC/HELICS-src | 5e37168bca0ea9e16b939e052e257182ca6e24bd | [
"BSD-3-Clause"
] | 11 | 2017-10-27T15:03:37.000Z | 2019-05-03T19:35:14.000Z | /*
Copyright (c) 2017-2022,
Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See the top-level NOTICE for
additional details. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
*/
#include "../core/core-exceptions.hpp"
#include "../core/coreTypeOperations.hpp"
#include "../helics.hpp"
#include "gmlc/concurrency/TripWire.hpp"
#include "helicsCallbacks.h"
#include "helicsCore.h"
#include "internal/api_objects.h"
#include <iostream>
#include <map>
#include <mutex>
#include <vector>
/** this is a random identifier put in place when the federate or core or broker gets created*/
static const int fedValidationIdentifier = 0x2352188;
static const char* invalidFedString = "federate object is not valid";
static constexpr char nullcstr[] = "";
namespace helics {
FedObject* getFedObject(HelicsFederate fed, HelicsError* err) noexcept
{
HELICS_ERROR_CHECK(err, nullptr);
if (fed == nullptr) {
assignError(err, HELICS_ERROR_INVALID_OBJECT, invalidFedString);
return nullptr;
}
auto* fedObj = reinterpret_cast<helics::FedObject*>(fed);
if (fedObj->valid == fedValidationIdentifier) {
return fedObj;
}
assignError(err, HELICS_ERROR_INVALID_OBJECT, invalidFedString);
return nullptr;
}
} // namespace helics
helics::Federate* getFed(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = helics::getFedObject(fed, err);
return (fedObj == nullptr) ? nullptr : fedObj->fedptr.get();
}
static const char* notValueFedString = "Federate must be a value federate";
helics::ValueFederate* getValueFed(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = helics::getFedObject(fed, err);
if (fedObj == nullptr) {
return nullptr;
}
if ((fedObj->type == helics::FederateType::VALUE) || (fedObj->type == helics::FederateType::COMBINATION)) {
auto* rval = dynamic_cast<helics::ValueFederate*>(fedObj->fedptr.get());
if (rval != nullptr) {
return rval;
}
}
assignError(err, HELICS_ERROR_INVALID_OBJECT, notValueFedString);
return nullptr;
}
static const char* notMessageFedString = "Federate must be a message federate";
helics::MessageFederate* getMessageFed(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = helics::getFedObject(fed, err);
if (fedObj == nullptr) {
return nullptr;
}
if ((fedObj->type == helics::FederateType::MESSAGE) || (fedObj->type == helics::FederateType::COMBINATION)) {
auto* rval = dynamic_cast<helics::MessageFederate*>(fedObj->fedptr.get());
if (rval != nullptr) {
return rval;
}
}
assignError(err, HELICS_ERROR_INVALID_OBJECT, notMessageFedString);
return nullptr;
}
std::shared_ptr<helics::Federate> getFedSharedPtr(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = helics::getFedObject(fed, err);
if (fedObj == nullptr) {
return nullptr;
}
return fedObj->fedptr;
}
std::shared_ptr<helics::ValueFederate> getValueFedSharedPtr(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = helics::getFedObject(fed, err);
if (fedObj == nullptr) {
return nullptr;
}
if ((fedObj->type == helics::FederateType::VALUE) || (fedObj->type == helics::FederateType::COMBINATION)) {
auto rval = std::dynamic_pointer_cast<helics::ValueFederate>(fedObj->fedptr);
if (rval) {
return rval;
}
}
assignError(err, HELICS_ERROR_INVALID_OBJECT, notValueFedString);
return nullptr;
}
std::shared_ptr<helics::MessageFederate> getMessageFedSharedPtr(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = helics::getFedObject(fed, err);
if (fedObj == nullptr) {
return nullptr;
}
if ((fedObj->type == helics::FederateType::MESSAGE) || (fedObj->type == helics::FederateType::COMBINATION)) {
auto rval = std::dynamic_pointer_cast<helics::MessageFederate>(fedObj->fedptr);
if (rval) {
return rval;
}
}
assignError(err, HELICS_ERROR_INVALID_OBJECT, notMessageFedString);
return nullptr;
}
// random integer for validation purposes of endpoints
static constexpr int FederateInfoValidationIdentifier = 0x6bfb'bce1;
HelicsFederateInfo helicsCreateFederateInfo()
{
auto* fi = new helics::FederateInfo;
fi->uniqueKey = FederateInfoValidationIdentifier;
return reinterpret_cast<void*>(fi);
}
static const char* invalidFedInfoString = "helics Federate info object was not valid";
static helics::FederateInfo* getFedInfo(HelicsFederateInfo fi, HelicsError* err)
{
if ((err != nullptr) && (err->error_code != 0)) {
return nullptr;
}
if (fi == nullptr) {
assignError(err, HELICS_ERROR_INVALID_OBJECT, invalidFedInfoString);
return nullptr;
}
auto* ptr = reinterpret_cast<helics::FederateInfo*>(fi);
if (ptr->uniqueKey != FederateInfoValidationIdentifier) {
assignError(err, HELICS_ERROR_INVALID_OBJECT, invalidFedInfoString);
return nullptr;
}
return ptr;
}
HelicsFederateInfo helicsFederateInfoClone(HelicsFederateInfo fi, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return nullptr;
}
auto* fi_new = new helics::FederateInfo(*info);
return reinterpret_cast<void*>(fi_new);
}
void helicsFederateInfoFree(HelicsFederateInfo fi)
{
auto* info = getFedInfo(fi, nullptr);
if (info == nullptr) {
// fprintf(stderr, "The HelicsFederateInfo object is not valid\n");
return;
}
info->uniqueKey = 0;
delete info;
}
void helicsFederateInfoLoadFromArgs(HelicsFederateInfo fi, int argc, const char* const* argv, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return;
}
try {
std::vector<std::string> args;
args.reserve(static_cast<size_t>(argc) - 1);
for (int ii = argc - 1; ii > 0; --ii) {
args.emplace_back(argv[ii]);
}
info->loadInfoFromArgs(args);
}
catch (...) {
return helicsErrorHandler(err);
}
}
void helicsFederateInfoLoadFromString(HelicsFederateInfo fi, const char* args, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return;
}
try {
info->loadInfoFromArgs(args);
}
catch (...) {
return helicsErrorHandler(err);
}
}
void helicsFederateInfoSetCoreName(HelicsFederateInfo fi, const char* corename, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return;
}
try {
info->coreName = AS_STRING(corename);
}
catch (...) { // LCOV_EXCL_LINE
return helicsErrorHandler(err); // LCOV_EXCL_LINE
}
}
void helicsFederateInfoSetCoreInitString(HelicsFederateInfo fi, const char* coreinit, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return;
}
try {
info->coreInitString = AS_STRING(coreinit);
}
catch (...) { // LCOV_EXCL_LINE
return helicsErrorHandler(err); // LCOV_EXCL_LINE
}
}
void helicsFederateInfoSetBrokerInitString(HelicsFederateInfo fi, const char* brokerinit, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return;
}
try {
info->brokerInitString = AS_STRING(brokerinit);
}
catch (...) { // LCOV_EXCL_LINE
return helicsErrorHandler(err); // LCOV_EXCL_LINE
}
}
void helicsFederateInfoSetCoreType(HelicsFederateInfo fi, int coretype, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return;
}
info->coreType = static_cast<helics::CoreType>(coretype);
}
void helicsFederateInfoSetCoreTypeFromString(HelicsFederateInfo fi, const char* coretype, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return;
}
if (coretype == nullptr) {
info->coreType = helics::CoreType::DEFAULT;
return;
}
auto ctype = helics::core::coreTypeFromString(coretype);
if (ctype == helics::CoreType::UNRECOGNIZED) {
if (err != nullptr) {
err->error_code = HELICS_ERROR_INVALID_ARGUMENT;
err->message = getMasterHolder()->addErrorString(std::string(coretype) + " is not a valid core type");
return;
}
}
info->coreType = ctype;
}
void helicsFederateInfoSetBroker(HelicsFederateInfo fi, const char* broker, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return;
}
try {
info->broker = AS_STRING(broker);
}
catch (...) { // LCOV_EXCL_LINE
return helicsErrorHandler(err); // LCOV_EXCL_LINE
}
}
void helicsFederateInfoSetBrokerKey(HelicsFederateInfo fi, const char* brokerkey, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return;
}
try {
info->key = AS_STRING(brokerkey);
}
catch (...) { // LCOV_EXCL_LINE
return helicsErrorHandler(err); // LCOV_EXCL_LINE
}
}
void helicsFederateInfoSetBrokerPort(HelicsFederateInfo fi, int brokerPort, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return;
}
info->brokerPort = brokerPort;
}
void helicsFederateInfoSetLocalPort(HelicsFederateInfo fi, const char* localPort, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return;
}
info->localport = AS_STRING(localPort);
}
int helicsGetPropertyIndex(const char* val)
{
if (val == nullptr) {
return -1;
}
return helics::getPropertyIndex(val);
}
int helicsGetFlagIndex(const char* val)
{
if (val == nullptr) {
return -1;
}
return helics::getFlagIndex(val);
}
int helicsGetOptionIndex(const char* val)
{
if (val == nullptr) {
return -1;
}
return helics::getOptionIndex(val);
}
int helicsGetOptionValue(const char* val)
{
if (val == nullptr) {
return -1;
}
return helics::getOptionValue(val);
}
int helicsGetDataType(const char* val)
{
if (val == nullptr) {
return -1;
}
return static_cast<int>(helics::getTypeFromString(val));
}
void helicsFederateInfoSetFlagOption(HelicsFederateInfo fi, int flag, HelicsBool value, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return;
}
switch (flag) {
case HELICS_FLAG_OBSERVER:
info->observer = (value != HELICS_FALSE);
break;
case HELICS_FLAG_DEBUGGING:
info->debugging = (value != HELICS_FALSE);
break;
case HELICS_FLAG_USE_JSON_SERIALIZATION:
info->useJsonSerialization = (value != HELICS_FALSE);
break;
default:
break;
}
info->setFlagOption(flag, (value != HELICS_FALSE));
}
void helicsFederateInfoSetTimeProperty(HelicsFederateInfo fi, int timeProperty, HelicsTime propertyValue, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return;
}
info->setProperty(timeProperty, propertyValue);
}
void helicsFederateInfoSetSeparator(HelicsFederateInfo fi, char separator, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return;
}
info->separator = separator;
}
void helicsFederateInfoSetIntegerProperty(HelicsFederateInfo fi, int integerProperty, int propertyValue, HelicsError* err)
{
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return;
}
info->setProperty(integerProperty, propertyValue);
}
/* Creation and destruction of Federates */
HelicsFederate helicsCreateValueFederate(const char* fedName, HelicsFederateInfo fi, HelicsError* err)
{
HELICS_ERROR_CHECK(err, nullptr);
auto FedI = std::make_unique<helics::FedObject>();
try {
if (fi == nullptr) {
FedI->fedptr = std::make_shared<helics::ValueFederate>(AS_STRING(fedName), helics::FederateInfo());
} else {
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return nullptr;
}
FedI->fedptr = std::make_shared<helics::ValueFederate>(AS_STRING(fedName), *info);
}
}
catch (...) {
helicsErrorHandler(err);
return nullptr;
}
FedI->type = helics::FederateType::VALUE;
FedI->valid = fedValidationIdentifier;
auto* fed = reinterpret_cast<HelicsFederate>(FedI.get());
getMasterHolder()->addFed(std::move(FedI));
return (fed);
}
HelicsFederate helicsCreateValueFederateFromConfig(const char* configFile, HelicsError* err)
{
HELICS_ERROR_CHECK(err, nullptr);
auto FedI = std::make_unique<helics::FedObject>();
try {
FedI->fedptr = std::make_shared<helics::ValueFederate>(AS_STRING(configFile));
}
catch (...) {
helicsErrorHandler(err);
return nullptr;
}
FedI->type = helics::FederateType::VALUE;
FedI->valid = fedValidationIdentifier;
auto* fed = reinterpret_cast<HelicsFederate>(FedI.get());
getMasterHolder()->addFed(std::move(FedI));
return (fed);
}
/* Creation and destruction of Federates */
HelicsFederate helicsCreateMessageFederate(const char* fedName, HelicsFederateInfo fi, HelicsError* err)
{
HELICS_ERROR_CHECK(err, nullptr);
auto FedI = std::make_unique<helics::FedObject>();
try {
if (fi == nullptr) {
FedI->fedptr = std::make_shared<helics::MessageFederate>(AS_STRING(fedName), helics::FederateInfo());
} else {
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return nullptr;
}
FedI->fedptr = std::make_shared<helics::MessageFederate>(AS_STRING(fedName), *info);
}
}
catch (...) {
helicsErrorHandler(err);
return nullptr;
}
FedI->type = helics::FederateType::MESSAGE;
FedI->valid = fedValidationIdentifier;
auto* fed = reinterpret_cast<HelicsFederate>(FedI.get());
getMasterHolder()->addFed(std::move(FedI));
return (fed);
}
HelicsFederate helicsCreateMessageFederateFromConfig(const char* configFile, HelicsError* err)
{
HELICS_ERROR_CHECK(err, nullptr);
auto FedI = std::make_unique<helics::FedObject>();
try {
FedI->fedptr = std::make_shared<helics::MessageFederate>(AS_STRING(configFile));
}
catch (...) {
helicsErrorHandler(err);
return nullptr;
}
FedI->type = helics::FederateType::MESSAGE;
FedI->valid = fedValidationIdentifier;
auto* fed = reinterpret_cast<HelicsFederate>(FedI.get());
getMasterHolder()->addFed(std::move(FedI));
return (fed);
}
/* Creation and destruction of Federates */
HelicsFederate helicsCreateCombinationFederate(const char* fedName, HelicsFederateInfo fi, HelicsError* err)
{
HELICS_ERROR_CHECK(err, nullptr);
auto FedI = std::make_unique<helics::FedObject>();
try {
if (fi == nullptr) {
FedI->fedptr = std::make_shared<helics::CombinationFederate>(AS_STRING(fedName), helics::FederateInfo());
} else {
auto* info = getFedInfo(fi, err);
if (info == nullptr) {
return nullptr;
}
FedI->fedptr = std::make_shared<helics::CombinationFederate>(AS_STRING(fedName), *info);
}
}
catch (...) {
helicsErrorHandler(err);
return nullptr;
}
FedI->type = helics::FederateType::COMBINATION;
FedI->valid = fedValidationIdentifier;
auto* fed = reinterpret_cast<HelicsFederate>(FedI.get());
getMasterHolder()->addFed(std::move(FedI));
return (fed);
}
HelicsFederate helicsCreateCombinationFederateFromConfig(const char* configFile, HelicsError* err)
{
HELICS_ERROR_CHECK(err, nullptr);
auto FedI = std::make_unique<helics::FedObject>();
try {
FedI->fedptr = std::make_shared<helics::CombinationFederate>(AS_STRING(configFile));
}
catch (...) {
helicsErrorHandler(err);
return nullptr;
}
FedI->type = helics::FederateType::COMBINATION;
FedI->valid = fedValidationIdentifier;
auto* fed = reinterpret_cast<HelicsFederate>(FedI.get());
getMasterHolder()->addFed(std::move(FedI));
return (fed);
}
HelicsFederate helicsFederateClone(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = helics::getFedObject(fed, err);
if (fedObj == nullptr) {
return nullptr;
}
auto fedClone = std::make_unique<helics::FedObject>();
fedClone->fedptr = fedObj->fedptr;
fedClone->type = fedObj->type;
fedClone->valid = fedObj->valid;
auto* fedB = reinterpret_cast<HelicsFederate>(fedClone.get());
getMasterHolder()->addFed(std::move(fedClone));
return (fedB);
}
HelicsBool helicsFederateIsValid(HelicsFederate fed)
{
auto* fedObj = getFed(fed, nullptr);
return (fedObj == nullptr) ? HELICS_FALSE : HELICS_TRUE;
}
HelicsCore helicsFederateGetCore(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return nullptr;
}
auto core = std::make_unique<helics::CoreObject>();
core->valid = gCoreValidationIdentifier;
core->coreptr = fedObj->getCorePointer();
auto* retcore = reinterpret_cast<HelicsCore>(core.get());
getMasterHolder()->addCore(std::move(core));
return retcore;
}
static constexpr char invalidFile[] = "Invalid File specification";
void helicsFederateRegisterInterfaces(HelicsFederate fed, const char* file, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
if (file == nullptr) {
assignError(err, HELICS_ERROR_INVALID_ARGUMENT, invalidFile);
return;
}
try {
fedObj->registerInterfaces(file);
}
catch (...) {
return helicsErrorHandler(err);
}
}
void helicsFederateGlobalError(HelicsFederate fed, int errorCode, const char* errorString, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->globalError(errorCode, AS_STRING(errorString));
}
// LCOV_EXCL_START
catch (...) {
return helicsErrorHandler(err);
}
// LCOV_EXCL_STOP
}
void helicsFederateLocalError(HelicsFederate fed, int errorCode, const char* errorString, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->localError(errorCode, AS_STRING(errorString));
}
// LCOV_EXCL_START
catch (...) {
return helicsErrorHandler(err);
}
// LCOV_EXCL_STOP
}
void helicsFederateFinalize(HelicsFederate fed, HelicsError* err)
{
helicsFederateDisconnect(fed, err);
}
void helicsFederateFinalizeAsync(HelicsFederate fed, HelicsError* err)
{
helicsFederateDisconnectAsync(fed, err);
}
void helicsFederateFinalizeComplete(HelicsFederate fed, HelicsError* err)
{
helicsFederateDisconnectComplete(fed, err);
}
void helicsFederateDisconnect(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->finalize();
}
// LCOV_EXCL_START
catch (...) {
helicsErrorHandler(err);
}
// LCOV_EXCL_STOP
}
void helicsFederateDisconnectAsync(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->finalizeAsync();
}
// LCOV_EXCL_START
catch (...) {
helicsErrorHandler(err);
}
// LCOV_EXCL_STOP
}
void helicsFederateDisconnectComplete(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->finalizeComplete();
}
// LCOV_EXCL_START
catch (...) {
helicsErrorHandler(err);
}
// LCOV_EXCL_STOP
}
/* initialization, execution, and time requests */
void helicsFederateEnterInitializingMode(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->enterInitializingMode();
}
catch (...) {
return helicsErrorHandler(err);
}
}
void helicsFederateEnterInitializingModeAsync(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->enterInitializingModeAsync();
}
catch (...) {
return helicsErrorHandler(err);
}
}
HelicsBool helicsFederateIsAsyncOperationCompleted(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return HELICS_FALSE;
}
return (fedObj->isAsyncOperationCompleted()) ? HELICS_TRUE : HELICS_FALSE;
}
void helicsFederateEnterInitializingModeComplete(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->enterInitializingModeComplete();
}
catch (...) {
return helicsErrorHandler(err);
}
}
void helicsFederateEnterExecutingMode(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
// printf("current state=%d\n", static_cast<int>(fedObj->getCurrentState()));
fedObj->enterExecutingMode();
}
catch (...) {
return helicsErrorHandler(err);
}
}
static helics::IterationRequest getIterationRequest(HelicsIterationRequest iterate)
{
switch (iterate) {
case HELICS_ITERATION_REQUEST_NO_ITERATION:
default:
return helics::IterationRequest::NO_ITERATIONS;
case HELICS_ITERATION_REQUEST_FORCE_ITERATION:
return helics::IterationRequest::FORCE_ITERATION;
case HELICS_ITERATION_REQUEST_ITERATE_IF_NEEDED:
return helics::IterationRequest::ITERATE_IF_NEEDED;
}
}
static HelicsIterationResult getIterationStatus(helics::IterationResult iterationState)
{
switch (iterationState) {
case helics::IterationResult::NEXT_STEP:
return HELICS_ITERATION_RESULT_NEXT_STEP;
case helics::IterationResult::ITERATING:
return HELICS_ITERATION_RESULT_ITERATING;
case helics::IterationResult::ERROR_RESULT:
default:
// most cases of this return error directly without going through this function
return HELICS_ITERATION_RESULT_ERROR; // LCOV_EXCL_LINE
case helics::IterationResult::HALTED:
return HELICS_ITERATION_RESULT_HALTED;
}
}
HelicsIterationResult helicsFederateEnterExecutingModeIterative(HelicsFederate fed, HelicsIterationRequest iterate, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return HELICS_ITERATION_RESULT_ERROR;
}
try {
auto val = fedObj->enterExecutingMode(getIterationRequest(iterate));
return getIterationStatus(val);
}
catch (...) {
helicsErrorHandler(err);
return HELICS_ITERATION_RESULT_ERROR;
}
}
void helicsFederateEnterExecutingModeAsync(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->enterExecutingModeAsync();
}
catch (...) {
helicsErrorHandler(err);
}
}
void helicsFederateEnterExecutingModeIterativeAsync(HelicsFederate fed, HelicsIterationRequest iterate, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->enterExecutingModeAsync(getIterationRequest(iterate));
}
catch (...) {
return helicsErrorHandler(err);
}
}
void helicsFederateEnterExecutingModeComplete(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->enterExecutingModeComplete();
}
catch (...) {
return helicsErrorHandler(err);
}
}
HelicsIterationResult helicsFederateEnterExecutingModeIterativeComplete(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return HELICS_ITERATION_RESULT_ERROR;
}
try {
auto val = fedObj->enterExecutingModeComplete();
return getIterationStatus(val);
}
catch (...) {
helicsErrorHandler(err);
return HELICS_ITERATION_RESULT_ERROR;
}
}
HelicsTime helicsFederateRequestTime(HelicsFederate fed, HelicsTime requestTime, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return HELICS_TIME_INVALID;
}
try {
auto timeret = fedObj->requestTime(requestTime);
return (timeret < helics::Time::maxVal()) ? static_cast<double>(timeret) : HELICS_TIME_MAXTIME;
}
catch (...) {
helicsErrorHandler(err);
return HELICS_TIME_INVALID;
}
}
HelicsTime helicsFederateRequestTimeAdvance(HelicsFederate fed, HelicsTime timeDelta, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return HELICS_TIME_INVALID;
}
try {
auto timeret = fedObj->requestTimeAdvance(timeDelta);
return (timeret < helics::Time::maxVal()) ? static_cast<double>(timeret) : HELICS_TIME_MAXTIME;
}
catch (...) {
helicsErrorHandler(err);
return HELICS_TIME_INVALID;
}
}
HelicsTime helicsFederateRequestNextStep(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return HELICS_TIME_INVALID;
}
try {
auto timeret = fedObj->requestNextStep();
return (timeret < helics::Time::maxVal()) ? static_cast<double>(timeret) : HELICS_TIME_MAXTIME;
}
catch (...) {
helicsErrorHandler(err);
return HELICS_TIME_INVALID;
}
}
HelicsTime helicsFederateRequestTimeIterative(HelicsFederate fed,
HelicsTime requestTime,
HelicsIterationRequest iterate,
HelicsIterationResult* outIteration,
HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
if (outIteration != nullptr) {
*outIteration = HELICS_ITERATION_RESULT_ERROR;
}
return HELICS_TIME_INVALID;
}
try {
auto val = fedObj->requestTimeIterative(requestTime, getIterationRequest(iterate));
if (outIteration != nullptr) {
*outIteration = getIterationStatus(val.state);
}
return (val.grantedTime < helics::Time::maxVal()) ? static_cast<double>(val.grantedTime) : HELICS_TIME_MAXTIME;
}
catch (...) {
helicsErrorHandler(err);
if (outIteration != nullptr) {
*outIteration = HELICS_ITERATION_RESULT_ERROR;
}
return HELICS_TIME_INVALID;
}
}
void helicsFederateRequestTimeAsync(HelicsFederate fed, HelicsTime requestTime, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->requestTimeAsync(requestTime);
}
catch (...) {
return helicsErrorHandler(err);
}
}
HelicsTime helicsFederateRequestTimeComplete(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return HELICS_TIME_INVALID;
}
try {
auto timeret = fedObj->requestTimeComplete();
return (timeret < helics::Time::maxVal()) ? static_cast<double>(timeret) : HELICS_TIME_MAXTIME;
}
catch (...) {
helicsErrorHandler(err);
return HELICS_TIME_INVALID;
}
}
void helicsFederateRequestTimeIterativeAsync(HelicsFederate fed, HelicsTime requestTime, HelicsIterationRequest iterate, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->requestTimeIterativeAsync(requestTime, getIterationRequest(iterate));
}
catch (...) {
return helicsErrorHandler(err);
}
}
HelicsTime helicsFederateRequestTimeIterativeComplete(HelicsFederate fed, HelicsIterationResult* outIteration, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
if (outIteration != nullptr) {
*outIteration = HELICS_ITERATION_RESULT_ERROR;
}
return HELICS_TIME_INVALID;
}
try {
auto val = fedObj->requestTimeIterativeComplete();
if (outIteration != nullptr) {
*outIteration = getIterationStatus(val.state);
}
return (val.grantedTime < helics::Time::maxVal()) ? static_cast<double>(val.grantedTime) : HELICS_TIME_MAXTIME;
}
catch (...) {
helicsErrorHandler(err);
if (outIteration != nullptr) {
*outIteration = HELICS_ITERATION_RESULT_ERROR;
}
return HELICS_TIME_INVALID;
}
}
void helicsFederateProcessCommunications(HelicsFederate fed, HelicsTime period, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->processCommunication(helics::Time(period).to_ms());
}
catch (...) {
helicsErrorHandler(err);
}
}
static const std::map<helics::Federate::Modes, HelicsFederateState> modeEnumConversions{
{helics::Federate::Modes::ERROR_STATE, HelicsFederateState::HELICS_STATE_ERROR},
{helics::Federate::Modes::STARTUP, HelicsFederateState::HELICS_STATE_STARTUP},
{helics::Federate::Modes::EXECUTING, HelicsFederateState::HELICS_STATE_EXECUTION},
{helics::Federate::Modes::FINALIZE, HelicsFederateState::HELICS_STATE_FINALIZE},
{helics::Federate::Modes::PENDING_EXEC, HelicsFederateState::HELICS_STATE_PENDING_EXEC},
{helics::Federate::Modes::PENDING_INIT, HelicsFederateState::HELICS_STATE_PENDING_INIT},
{helics::Federate::Modes::PENDING_ITERATIVE_TIME, HelicsFederateState::HELICS_STATE_PENDING_ITERATIVE_TIME},
{helics::Federate::Modes::PENDING_TIME, HelicsFederateState::HELICS_STATE_PENDING_TIME},
{helics::Federate::Modes::INITIALIZING, HelicsFederateState::HELICS_STATE_INITIALIZATION},
{helics::Federate::Modes::PENDING_FINALIZE, HelicsFederateState::HELICS_STATE_PENDING_FINALIZE},
{helics::Federate::Modes::FINISHED, HelicsFederateState::HELICS_STATE_FINISHED}};
HelicsFederateState helicsFederateGetState(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return HELICS_STATE_ERROR;
}
try {
auto FedMode = fedObj->getCurrentMode();
return modeEnumConversions.at(FedMode);
}
// LCOV_EXCL_START
catch (...) {
helicsErrorHandler(err);
return HELICS_STATE_ERROR;
}
// LCOV_EXCL_STOP
}
void helicsFederateSetTimeRequestEntryCallback(
HelicsFederate fed,
void (*requestTimeEntry)(HelicsTime currentTime, HelicsTime requestTime, HelicsBool iterating, void* userdata),
void* userdata,
HelicsError* err)
{
auto* fedptr = getFed(fed, err);
if (fedptr == nullptr) {
return;
}
try {
if (requestTimeEntry == nullptr) {
fedptr->setTimeRequestEntryCallback({});
} else {
fedptr->setTimeRequestEntryCallback(
[requestTimeEntry, userdata](helics::Time currentTime, helics::Time requestTime, bool iterating) {
requestTimeEntry(currentTime, requestTime, (iterating) ? HELICS_TRUE : HELICS_FALSE, userdata);
});
}
}
catch (...) { // LCOV_EXCL_LINE
helicsErrorHandler(err); // LCOV_EXCL_LINE
}
}
void helicsFederateSetStateChangeCallback(HelicsFederate fed,
void (*stateChange)(HelicsFederateState newState, HelicsFederateState oldState, void* userdata),
void* userdata,
HelicsError* err)
{
auto* fedptr = getFed(fed, err);
if (fedptr == nullptr) {
return;
}
try {
if (stateChange == nullptr) {
fedptr->setModeUpdateCallback({});
} else {
fedptr->setModeUpdateCallback([stateChange, userdata](helics::Federate::Modes newMode, helics::Federate::Modes oldMode) {
stateChange(modeEnumConversions.at(newMode), modeEnumConversions.at(oldMode), userdata);
});
}
}
catch (...) { // LCOV_EXCL_LINE
helicsErrorHandler(err); // LCOV_EXCL_LINE
}
}
void helicsFederateSetTimeRequestReturnCallback(HelicsFederate fed,
void (*requestTimeReturn)(HelicsTime newTime, HelicsBool iterating, void* userdata),
void* userdata,
HelicsError* err)
{
auto* fedptr = getFed(fed, err);
if (fedptr == nullptr) {
return;
}
try {
if (requestTimeReturn == nullptr) {
fedptr->setTimeRequestReturnCallback({});
} else {
fedptr->setTimeRequestReturnCallback([requestTimeReturn, userdata](helics::Time newTime, bool iterating) {
requestTimeReturn(newTime, (iterating) ? HELICS_TRUE : HELICS_FALSE, userdata);
});
}
}
catch (...) { // LCOV_EXCL_LINE
helicsErrorHandler(err); // LCOV_EXCL_LINE
}
}
const char* helicsFederateGetName(HelicsFederate fed)
{
auto* fedObj = getFed(fed, nullptr);
if (fedObj == nullptr) {
return nullcstr;
}
const auto& ident = fedObj->getName();
return ident.c_str();
}
void helicsFederateSetTimeProperty(HelicsFederate fed, int timeProperty, HelicsTime time, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->setProperty(timeProperty, time);
}
catch (...) {
return helicsErrorHandler(err);
}
}
void helicsFederateSetFlagOption(HelicsFederate fed, int flag, HelicsBool flagValue, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->setFlagOption(flag, (flagValue != HELICS_FALSE));
}
// LCOV_EXCL_START
catch (...) {
return helicsErrorHandler(err);
}
// LCOV_EXCL_STOP
}
void helicsFederateSetIntegerProperty(HelicsFederate fed, int intProperty, int propVal, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
try {
fedObj->setProperty(intProperty, propVal);
}
// LCOV_EXCL_START
catch (...) {
return helicsErrorHandler(err);
}
// LCOV_EXCL_STOP
}
HelicsTime helicsFederateGetTimeProperty(HelicsFederate fed, int timeProperty, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return HELICS_TIME_INVALID;
}
try {
auto T = fedObj->getTimeProperty(timeProperty);
return (T < helics::Time::maxVal()) ? static_cast<double>(T) : HELICS_TIME_MAXTIME;
}
// LCOV_EXCL_START
catch (...) {
helicsErrorHandler(err);
return HELICS_TIME_INVALID;
}
// LCOV_EXCL_STOP
}
HelicsBool helicsFederateGetFlagOption(HelicsFederate fed, int flag, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return HELICS_FALSE;
}
try {
bool res = fedObj->getFlagOption(flag);
return (res) ? HELICS_TRUE : HELICS_FALSE;
}
// LCOV_EXCL_START
catch (...) {
helicsErrorHandler(err);
return HELICS_FALSE;
}
// LCOV_EXCL_STOP
}
int helicsFederateGetIntegerProperty(HelicsFederate fed, int intProperty, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return -101;
}
try {
return fedObj->getIntegerProperty(intProperty);
}
// LCOV_EXCL_START
catch (...) {
helicsErrorHandler(err);
return -101;
}
// LCOV_EXCL_STOP
}
void helicsFederateSetSeparator(HelicsFederate fed, char separator, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
fedObj->setSeparator(separator);
}
HelicsTime helicsFederateGetCurrentTime(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return HELICS_TIME_INVALID;
}
auto T = fedObj->getCurrentTime();
return (T < helics::Time::maxVal()) ? static_cast<double>(T) : HELICS_TIME_MAXTIME;
}
static constexpr char invalidGlobalString[] = "Global name cannot be null";
void helicsFederateSetGlobal(HelicsFederate fed, const char* valueName, const char* value, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
if (valueName == nullptr) {
assignError(err, HELICS_ERROR_INVALID_ARGUMENT, invalidGlobalString);
return;
}
try {
fedObj->setGlobal(valueName, AS_STRING(value));
}
// LCOV_EXCL_START
catch (...) {
helicsErrorHandler(err);
}
// LCOV_EXCL_STOP
}
static constexpr char invalidTagString[] = "Tag name cannot be null";
void helicsFederateSetTag(HelicsFederate fed, const char* tagName, const char* value, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
if (tagName == nullptr) {
assignError(err, HELICS_ERROR_INVALID_ARGUMENT, invalidTagString);
return;
}
try {
fedObj->setTag(tagName, AS_STRING(value));
}
// LCOV_EXCL_START
catch (...) {
helicsErrorHandler(err);
}
// LCOV_EXCL_STOP
}
const char* helicsFederateGetTag(HelicsFederate fed, const char* tagName, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return nullcstr;
}
if (tagName == nullptr) {
assignError(err, HELICS_ERROR_INVALID_ARGUMENT, invalidTagString);
return nullcstr;
}
try {
const auto& str = fedObj->getTag(tagName);
return str.c_str();
}
// LCOV_EXCL_START
catch (...) {
helicsErrorHandler(err);
return nullcstr;
}
// LCOV_EXCL_STOP
}
static constexpr char invalidFedNameString[] = "Federate name for dependency cannot be null";
void helicsFederateAddDependency(HelicsFederate fed, const char* fedName, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
if (fedName == nullptr) {
assignError(err, HELICS_ERROR_INVALID_ARGUMENT, invalidFedNameString);
return;
}
try {
fedObj->addDependency(fedName);
}
// LCOV_EXCL_START
catch (...) {
helicsErrorHandler(err);
}
// LCOV_EXCL_STOP
}
static constexpr char invalidFederateCore[] = "Federate core is not connected";
void helicsFederateSetLogFile(HelicsFederate fed, const char* logFile, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
auto cr = fedObj->getCorePointer();
try {
if (cr) {
cr->setLogFile(AS_STRING(logFile));
// LCOV_EXCL_START
} else { // this can theoretically happen but it would be pretty odd
assignError(err, HELICS_ERROR_INVALID_FUNCTION_CALL, invalidFederateCore);
return;
// LCOV_EXCL_STOP
}
}
// LCOV_EXCL_START
catch (...) {
helicsErrorHandler(err);
}
// LCOV_EXCL_STOP
}
void helicsFederateLogErrorMessage(HelicsFederate fed, const char* logmessage, HelicsError* err)
{
helicsFederateLogLevelMessage(fed, HELICS_LOG_LEVEL_ERROR, logmessage, err);
}
void helicsFederateLogWarningMessage(HelicsFederate fed, const char* logmessage, HelicsError* err)
{
helicsFederateLogLevelMessage(fed, HELICS_LOG_LEVEL_WARNING, logmessage, err);
}
void helicsFederateLogInfoMessage(HelicsFederate fed, const char* logmessage, HelicsError* err)
{
helicsFederateLogLevelMessage(fed, HELICS_LOG_LEVEL_SUMMARY, logmessage, err);
}
void helicsFederateLogDebugMessage(HelicsFederate fed, const char* logmessage, HelicsError* err)
{
helicsFederateLogLevelMessage(fed, HELICS_LOG_LEVEL_DEBUG, logmessage, err);
}
void helicsFederateLogLevelMessage(HelicsFederate fed, int loglevel, const char* logmessage, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
fedObj->logMessage(loglevel, AS_STRING(logmessage));
}
void helicsFederateSendCommand(HelicsFederate fed, const char* target, const char* command, HelicsError* err)
{
auto* fedObj = getFed(fed, err);
if (fedObj == nullptr) {
return;
}
fedObj->sendCommand(AS_STRING(target), AS_STRING(command));
}
const char* helicsFederateGetCommand(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = helics::getFedObject(fed, err);
if (fedObj == nullptr) {
return gEmptyStr.c_str();
}
auto res = fedObj->fedptr->getCommand();
if (res.first.empty()) {
return gEmptyStr.c_str();
}
fedObj->commandBuffer = std::move(res);
return fedObj->commandBuffer.first.c_str();
}
const char* helicsFederateGetCommandSource(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = helics::getFedObject(fed, err);
if (fedObj == nullptr) {
return gEmptyStr.c_str();
}
return fedObj->commandBuffer.second.c_str();
}
const char* helicsFederateWaitCommand(HelicsFederate fed, HelicsError* err)
{
auto* fedObj = helics::getFedObject(fed, err);
if (fedObj == nullptr) {
return gEmptyStr.c_str();
}
auto res = fedObj->fedptr->waitCommand();
if (res.first.empty()) {
return gEmptyStr.c_str();
}
fedObj->commandBuffer = std::move(res);
return fedObj->commandBuffer.first.c_str();
}
| 29.096708 | 139 | 0.647008 | GMLC-TDC |
b9fca4bd5b616fc969f2fe6a231287c029bafb1b | 1,579 | cpp | C++ | clang/test/CXX/dcl.dcl/basic.namespace/namespace.udecl/p18.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,102 | 2015-01-04T02:28:35.000Z | 2022-03-30T12:53:41.000Z | clang/test/CXX/dcl.dcl/basic.namespace/namespace.udecl/p18.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | clang/test/CXX/dcl.dcl/basic.namespace/namespace.udecl/p18.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 1,868 | 2015-01-03T04:27:11.000Z | 2022-03-25T13:37:35.000Z | // RUN: %clang_cc1 -std=c++11 -verify %s
struct Public {} public_;
struct Protected {} protected_;
struct Private {} private_;
class A {
public:
A(Public);
void f(Public);
protected:
A(Protected); // expected-note {{protected here}}
void f(Protected);
private:
A(Private); // expected-note 4{{private here}}
void f(Private); // expected-note {{private here}}
friend void Friend();
};
class B : private A {
using A::A; // ok
using A::f; // expected-error {{private member}}
void f() {
B a(public_);
B b(protected_);
B c(private_); // expected-error {{private}}
}
B(Public p, int) : B(p) {}
B(Protected p, int) : B(p) {}
B(Private p, int) : B(p) {} // expected-error {{private}}
};
class C : public B {
C(Public p) : B(p) {}
// There is no access check on the conversion from derived to base here;
// protected constructors of A act like protected constructors of B.
C(Protected p) : B(p) {}
C(Private p) : B(p) {} // expected-error {{private}}
};
void Friend() {
// There is no access check on the conversion from derived to base here.
B a(public_);
B b(protected_);
B c(private_);
}
void NonFriend() {
B a(public_);
B b(protected_); // expected-error {{protected}}
B c(private_); // expected-error {{private}}
}
namespace ProtectedAccessFromMember {
namespace a {
struct ES {
private:
ES(const ES &) = delete;
protected:
ES(const char *);
};
}
namespace b {
struct DES : a::ES {
DES *f();
private:
using a::ES::ES;
};
}
b::DES *b::DES::f() { return new b::DES("foo"); }
}
| 20.24359 | 74 | 0.61178 | medismailben |
b9fd7d8c1bf20e8968297aae72ed825276e13430 | 24,061 | cpp | C++ | robot/common/Body/jhcManusBody.cpp | jconnell11/ALIA | f7a6c9dfd775fbd41239051aeed7775adb878b0a | [
"Apache-2.0"
] | null | null | null | robot/common/Body/jhcManusBody.cpp | jconnell11/ALIA | f7a6c9dfd775fbd41239051aeed7775adb878b0a | [
"Apache-2.0"
] | null | null | null | robot/common/Body/jhcManusBody.cpp | jconnell11/ALIA | f7a6c9dfd775fbd41239051aeed7775adb878b0a | [
"Apache-2.0"
] | null | null | null | // jhcManusBody.cpp : basic control of Manus small forklift robot
//
// Written by Jonathan H. Connell, jconnell@alum.mit.edu
//
///////////////////////////////////////////////////////////////////////////
//
// Copyright 2019-2020 IBM Corporation
// Copyright 2020 Etaoin Systems
//
// 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 <math.h>
#include "Interface/jhcMessage.h" // common video
#include "Interface/jms_x.h"
#include "Video/jhcOcv3VSrc.h"
#include "Body/jhcManusBody.h"
///////////////////////////////////////////////////////////////////////////
// Creation and Initialization //
///////////////////////////////////////////////////////////////////////////
//= Default destructor does necessary cleanup.
jhcManusBody::~jhcManusBody ()
{
ser.Close();
if (wifi > 0)
delete vid;
}
//= Default constructor initializes certain values.
// large transaction pod send to servo control for best speed
// ask = 4 channel target commands (4*4 = 16)
// 1 channel speed command (1*4 = 4)
// 6 channel position request (6*2 = 12)
jhcManusBody::jhcManusBody ()
{
UC8 *req = ask + 20;
int i;
// prepare multiple target commands (start at 0, 4, 8, 12)
for (i = 0; i < 16; i += 4)
ask[i] = 0x84;
ask[1] = LFW;
ask[5] = LIFT;
ask[9] = RTW;
ask[13] = HAND;
// prepare multiple position requests (all 6 channels)
for (i = 0; i < 12; i += 2)
{
req[i] = 0x90;
req[i + 1] = (UC8)(i / 2);
}
// expect external video source to be bound
now.SetSize(640, 360, 3);
vid = NULL;
wifi = 0;
// default robot ID and serial port
port0 = 10;
id = 0;
// set processing parameters and initial state
Defaults();
clr_state();
}
//= Set image sizes directly.
void jhcManusBody::SetSize (int x, int y)
{
jhcManusX::SetSize(x, y);
now.SetSize(frame);
}
///////////////////////////////////////////////////////////////////////////
// Processing Parameters //
///////////////////////////////////////////////////////////////////////////
//= Parameters describing camera warping and pose.
int jhcManusBody::cam_params (const char *fname)
{
jhcParam *ps = &cps;
int ok;
ps->SetTag("man_cam", 0);
ps->NextSpecF( &w2, -3.0, "R^2 warp coefficient");
ps->NextSpecF( &w4, 6.5, "R^4 warp coefficient");
ps->NextSpecF( &mag, 0.9, "Magnification");
ps->NextSpecF( &roll, -1.0, "Roll (deg)");
ok = ps->LoadDefs(fname);
ps->RevertAll();
return ok;
}
//= Parameters for distance sensor and miscellaneous reporting.
int jhcManusBody::range_params (const char *fname)
{
jhcParam *ps = &rps;
int ok;
ps->SetTag("man_rng", 0);
ps->NextSpec4( &v0, 426, "Sensor close value");
ps->NextSpecF( &r0, 0.0, "Close range (in)");
ps->NextSpec4( &v4, 106, "Sensor middle val");
ps->NextSpecF( &r4, 4.0, "Middle range (in)");
ps->NextSpec4( &v12, 64, "Sensor far value");
ps->NextSpecF( &r12, 6.0, "Far range (in)");
ok = ps->LoadDefs(fname);
ps->RevertAll();
return ok;
}
//= Parameters used for interpreting gripper width.
int jhcManusBody::width_params (const char *fname)
{
jhcParam *ps = &wps;
int ok;
ps->SetTag("man_wid", 0);
ps->NextSpecF( &vmax, 23.0, "Full open val (us)");
ps->NextSpecF( &vfat, 99.0, "Holding fat val (us)");
ps->NextSpecF( &vmed, 121.5, "Holding medium val (us)");
ps->NextSpecF( &vmin, 125.0, "Full close val (us)");
ps->NextSpecF( &wfat, 1.7, "Fat object (in)");
ps->NextSpecF( &wmed, 1.4, "Medium object (in)");
ps->NextSpecF( &wsm, 0.94, "Decrease for inner pads (in)");
ok = ps->LoadDefs(fname);
ps->RevertAll();
return ok;
}
//= Parameters used for controlling wheel motion.
int jhcManusBody::drive_params (const char *fname)
{
jhcParam *ps = &dps;
int ok;
ps->SetTag("man_drive", 0);
ps->NextSpec4( &lf0, 1484, "Left zero value (us)");
ps->NextSpec4( &rt0, 1484, "Right zero value (us)");
ps->NextSpecF( &vcal, 9.0, "Calibrated speed (ips)"); // cal 18" @ 9 ips
ps->NextSpec4( &ccal, 339, "Diff cmd for speed (us)");
ps->NextSpecF( &bal, 0.0, "Right vs. left balance");
ps->NextSpecF( &sep, 4.2, "Virtual turn circle (in)"); // cal 180 degs @ 9 ips
ps->NextSpec4( &dacc, 40, "Acceleration limit");
ok = ps->LoadDefs(fname);
ps->RevertAll();
return ok;
}
//= Parameters used for controlling forklift stage.
int jhcManusBody::lift_params (const char *fname)
{
jhcParam *ps = &lps;
int ok;
ps->SetTag("man_lift", 0);
ps->NextSpec4( &ldef, 1780, "Default lift value (us)");
ps->NextSpecF( &hdef, 0.3, "Default height (in)");
ps->NextSpec4( &lout, 1320, "Horizontal lift val (us)");
ps->NextSpecF( &hout, 2.0, "Horizontal height (in)");
ps->NextSpecF( &arm, 2.5, "Lift arm length (in)");
ps->Skip();
ps->NextSpec4( &lsp, 100, "Lift speed limit"); // was 50
ps->NextSpec4( &lacc, 15, "Lift acceleration");
ok = ps->LoadDefs(fname);
ps->RevertAll();
return ok;
}
//= Parameters used for controlling gripper.
int jhcManusBody::grip_params (const char *fname)
{
jhcParam *ps = &gps;
int ok;
ps->SetTag("man_grip", 0);
ps->NextSpec4( &gmax, 433, "Open gripper value (us)");
ps->NextSpec4( &gmin, 2282, "Closed gripper value (us)");
ps->Skip();
ps->NextSpecF( &wtol, 0.1, "Offset for closed test (in)");
ps->NextSpecF( &wprog, 0.05, "Insignificant change (in)");
ps->NextSpec4( &wstop, 5, "Count for no motion");
ps->NextSpec4( &gsp, 100, "Grip speed limit");
ok = ps->LoadDefs(fname);
ps->RevertAll();
return ok;
}
///////////////////////////////////////////////////////////////////////////
// Parameter Bundles //
///////////////////////////////////////////////////////////////////////////
//= Read all relevant defaults variable values from a file.
int jhcManusBody::Defaults (const char *fname)
{
int ok = 1;
ok &= cam_params(fname);
ok &= range_params(fname);
ok &= width_params(fname);
ok &= drive_params(fname);
ok &= lift_params(fname);
ok &= grip_params(fname);
return ok;
}
//= Write current processing variable values to a file.
int jhcManusBody::SaveVals (const char *fname) const
{
int ok = 1;
ok &= cps.SaveVals(fname);
ok &= rps.SaveVals(fname);
ok &= wps.SaveVals(fname);
ok &= dps.SaveVals(fname);
ok &= lps.SaveVals(fname);
ok &= gps.SaveVals(fname);
return ok;
}
//= Possibly change robot ID number then reload calibration parameters.
int jhcManusBody::LoadCfg (const char *dir, int robot, int noisy)
{
if (robot > 0)
id = robot;
CfgName(dir);
jprintf(1, noisy, "Reading robot calibration from: %s\n", cfile);
return Defaults(cfile);
}
//= Save values to standard file name.
int jhcManusBody::SaveCfg (const char *dir)
{
return SaveVals(CfgName(dir));
}
//= Get canonical name of configuration file based on retrieved ID.
// can optionally preface name with supplied path
// returns pointer to internal string
const char *jhcManusBody::CfgName (const char *dir)
{
if (dir != NULL)
sprintf_s(cfile, "%s/Manus-%d.cfg", dir, id);
else
sprintf_s(cfile, "Manus-%d.cfg", id);
return cfile;
}
///////////////////////////////////////////////////////////////////////////
// Camera Connection //
///////////////////////////////////////////////////////////////////////////
//= Bind an external video source to be used.
void jhcManusBody::BindVideo (jhcVideoSrc *v)
{
if (wifi > 0)
delete vid;
wifi = 0;
vid = v;
if (vid != NULL)
vid->SizeFor(frame);
}
//= Bind the SQ13 WiFi cube camera for image acquistion.
int jhcManusBody::SetWifiCam (int rpt)
{
jhcOcv3VSrc *v;
// make sure not already bound
if (wifi > 0)
return 1;
// try connecting
if (rpt > 0)
jprintf("Connecting to wifi camera ...\n");
if ((v = new jhcOcv3VSrc("ttp://192.168.25.1:8080/?action=stream.ocv3")) == NULL)
{
if (rpt >= 2)
Complain("Could not connect to SQ13 camera");
else if (rpt > 0)
jprintf(">>> Could not connect to SQ13 camera !\n");
return 0;
}
// configure images
if (rpt > 0)
jprintf(" ** good **\n\n");
BindVideo(v);
wifi = 1;
return 1;
}
///////////////////////////////////////////////////////////////////////////
// Main Functions //
///////////////////////////////////////////////////////////////////////////
//= Reset state for the beginning of a sequence.
// will also automatically read in correct calibration file from "dir"
// returns 1 if connected, 0 or negative for problem
int jhcManusBody::Reset (int noisy, const char *dir, int prefer)
{
UC8 pod[2];
int com = 0;
// try to connect to particular robot
if (prefer > 0)
com = find_robot(prefer, noisy);
// set up conversion factors and gripper state
chan_coefs();
v2d_eqn();
clr_state();
lvel = 0.0; // no translation or rotation
rvel = 0.0;
wcmd = wmax; // fully open
pgrip = 0;
// reconnect serial port and clear any controller errors
mok = 0;
if (com > 0)
if (ser.Xmit(0xA1) > 0)
{
// get response but ignore details (wait required)
jms_sleep(30);
if (ser.RxArray(pod, 2) >= 2)
mok = 1;
// set up initial pose then wait for it to be achieved
servo_defs();
rcv_all();
jms_sleep(500);
req_all(); // request positions for first Update
}
// create image rectification pattern and rewind video (if file)
wp.InitSize(frame.XDim(), frame.YDim(), 3);
wp.Rectify(w2, w4, mag, roll);
if (vid != NULL)
if (vid->Rewind() <= 0)
return 0;
return mok;
}
//= Look for the preferred robot then set the valid port and id.
// if prefer = 0 then scans all standard serial ports
// returns 1 something found, 0 for no robots available
int jhcManusBody::find_robot (int prefer, int noisy)
{
int rid, rnum = prefer;
// try port associated with preferred robot or scan all
if (prefer > 0)
rid = test_port(rnum, noisy);
else
for (rnum = 1; rnum <= 9; rnum++)
if ((rid = test_port(rnum, noisy)) > 0)
break;
// save parameters if robot actually found
if (rid > 0)
{
id = rid;
return 1;
}
// failure
jprintf(1, noisy, ">>> Could not talk to robot!\n");
return 0;
}
//= Try connecting to robot on given serial port.
// returns hardware ID if successful (and leaves port open)
int jhcManusBody::test_port (int n, int noisy)
{
UC8 pod[2];
int i, p = port0 + n;
// see if connection exists
jprintf(1, noisy, "Looking for robot on serial port %d ...\n", p);
if (ser.SetSource(p, 230400) <= 0)
return 0;
ser.wtime = 0.2; // for HC-05 Bluetooth latency
// make sure a robot is there
if (ser.Xmit(0xA1) > 0)
if (ser.RxArray(pod, 2) >= 2)
{
// try to get ID number
if (test_id(n))
return n;
for (i = 1; i < 256; i++)
if (i != n)
if (test_id(i))
return i;
// assume given number was correct
jprintf(1, noisy, ">>> Unable to determine robot ID!\n\n");
return n;
}
// close port if no response to basic probe
ser.Close();
return 0;
}
//= See if the robot responds to the given hardware ID.
bool jhcManusBody::test_id (int i)
{
UC8 pod[3] = {0xAA, (UC8) i, 0x21};
if (ser.TxArray(pod, 3) < 3)
return false;
return(ser.RxArray(pod, 2) >= 2);
}
//= Precompute coefficients for turning commands into pulse widths.
void jhcManusBody::chan_coefs ()
{
// fork rate at 50 Hz based on change from default to straight out
lsf = 4.0 * abs(lout - ldef) / (50.0 * (hout - hdef));
// width sensor conversion
wsc = (wfat - wmed) / (vfat - vmed);
wmin = get_grip(vmin);
wmax = get_grip(vmax);
// position command conversion factors
msc = ccal / vcal;
tsc = msc * PI * 0.5 * sep / 180.0;
lsc = (ldef - lout) / asin((hdef - hout) / arm);
gsc = (gmax - gmin) / (wmax - wmin);
}
//= Precompute values for turning voltage into distance.
// distance is roughly proportional to inverse voltage
// <pre>
// r = rsc / (v + voff) + roff
// v = rsc / (r - roff) - voff
//
// (v0 - v4) = rsc * [ 1 / (r0 - roff) - 1 / (r4 - roff) ]
// = rsc * [ (r4 - roff) - (r0 - roff) ] / (r0 - roff) * (r4 - roff)
// = rsc * (r4 - r0) / (r0 - roff) * (r4 - roff)
//
// rsc = (v0 - v4) * (r0 - roff) * (r4 - roff) / (r4 - r0)
// = [ (v0 - v4) / (r4 - r0) ] * (r0 - roff) * (r4 - roff)
// = S * (r0 - roff) * (r4 - roff) where S = (v0 - v4) / (r4 - r0)
//
// rsc = T * (r0 - roff) * (r12 - roff) where T = (v0 - v12) / (r12 - r0)
//
// S * (r0 - roff) * (r4 - roff) = T * (r0 - roff) * (r12 - roff)
// S * (r4 - roff) = T * (r12 - roff)
// S * r4 - S * roff = T * r12 - T * roff
// (T - S) * roff = T * r12 - S * r4
// roff = (T * r12 - S * r4) / (T - S)
//
// (v0 - v4) = rsc * [ 1 / (r0 - roff) - 1 / (r4 - roff) ]
// rsc = (v0 - v4) / [ 1 / (r0 - roff) - 1 / (r4 - roff) ]
//
// v12 = rsc / (r12 - roff) - voff
// voff = rsc / (r12 - roff) - v12
//
// </pre>
void jhcManusBody::v2d_eqn ()
{
double S = (v0 - v4) / (r4 - r0), T = (v0 - v12) / (r12 - r0);
roff = (T * r12 - S * r4) / (T - S);
rsc = (v0 - v4) / (1.0 / (r0 - roff) - 1.0 / (r4 - roff));
voff = rsc / (r12 - roff) - v12;
}
//= Set initial servo positions and motion profiling parameters.
void jhcManusBody::servo_defs ()
{
// set servo max speeds and accelerations
set_speed(HAND, gsp, 1);
set_speed(LIFT, lsp, 1);
set_accel(LIFT, lacc);
set_speed(LFW, dacc, 1); // really acceleration
set_speed(RTW, dacc, 1);
// set initial targets (in microseconds)
set_target(LFW, lf0);
set_target(RTW, rt0);
set_target(LIFT, ldef);
set_target(HAND, gmax);
req_all();
}
//= Freezes all motion servos, sets hand to passive.
void jhcManusBody::Stop ()
{
// set up actuator commands
send_wheels(0.0, 0.0);
send_lift(0.0);
send_grip(0);
// send to robot (skip getting sensors)
if (mok > 0)
{
ser.TxArray(ask, 20);
jms_sleep(100);
}
// always kill comm link (must be re-established later)
ser.Close();
mok = 0;
}
///////////////////////////////////////////////////////////////////////////
// Rough Odometry //
///////////////////////////////////////////////////////////////////////////
//= Reset odometry so current direction is angle zero and path length zero.
// also resets Cartesian coordinates to (0, 0) and x axis points forward
void jhcManusBody::Zero ()
{
}
///////////////////////////////////////////////////////////////////////////
// Core Interaction //
///////////////////////////////////////////////////////////////////////////
//= Read and interpret base odometry as well as grip force and distance.
// assumes req_all() has already been called to prompt status return
// automatically resets "lock" for new bids and specifies default motion
// HC-05 Bluetooth has an instrinsic latency of 36 +/- 10ms so 27 Hz max
// returns 1 for okay, 0 or negative for problem
int jhcManusBody::Update (int img)
{
int rc = 0;
// wait until next video frame is ready then rectify
if (img > 0)
if ((rc = UpdateImg(1)) < 0)
return -1;
// check for sensors on Bluetooth
if (rcv_all() > 0)
{
// record sensor values
lvel = get_lf(pos[LFW]);
rvel = get_rt(pos[RTW]);
ht = get_lift(pos[LIFT]);
wid = get_grip(pos[WID]);
dist = get_dist(pos[DIST]);
// do additional interpretation
inc_odom(jms_now());
}
// set up for next cycle
cmd_defs();
return mok;
}
//= Load new image from video source and possibly rectify.
// sometimes useful for debugging vison (robot sensors are irrelevant)
// can forego rectification in order to leave shared images unlocked
// returns 1 if okay, 0 or negative for problem
// NOTE: always blocks until new frame is ready
int jhcManusBody::UpdateImg (int rect)
{
got = 0;
if (vid == NULL)
return 0;
if (vid->Get(now) <= 0) // only affected image
return -1;
if (rect > 0)
Rectify();
return 1;
}
//= Correct lens distortion in recently acquired image.
void jhcManusBody::Rectify ()
{
wp.Warp(frame, now);
got = 1;
}
//= Compute likely speed of left wheel based on current servo set points.
// assume wheel's actual velocity is zero if zero microseconds reported
double jhcManusBody::get_lf (double us) const
{
if (us == 0.0)
return 0.0;
return((us - lf0) / ((1.0 - bal) * msc));
}
//= Compute likely speed of right wheel based on current servo set points.
// assume wheel's actual velocity is zero if zero microseconds reported
double jhcManusBody::get_rt (double us) const
{
if (us == 0.0)
return 0.0;
return((rt0 - us) / ((1.0 + bal) * msc));
}
//= Determine actual position of lift stage.
double jhcManusBody::get_lift (double us) const
{
return(hout + arm * sin((us - lout) / lsc));
}
//= Determine width of gripper.
// converts of A/D reading to actual separation in inches
double jhcManusBody::get_grip (double ad) const
{
return(wsc * (ad - vmed) + wmed);
}
//= Determine forward distance to obstacle.
double jhcManusBody::get_dist (double ad) const
{
double d = roff + rsc / (4.0 * ad + voff);
return __max(0.0, d); // 2cm min
}
//= Update odometry based on wheel speeds over last time interval.
// uses saved values "lvel" and "rvel"
void jhcManusBody::inc_odom (UL32 tnow)
{
UL32 t0 = tlast;
double secs, ins, degs, mid;
// set up for next cycle then find elapsed time
tlast = tnow;
if (t0 == 0)
return;
secs = jms_secs(tnow, t0);
// find length of recent segment and change in direction
ins = 0.5 * (rvel + lvel) * secs;
degs = 0.5 * (rvel - lvel) * secs / tsc;
// update inferred global Cartesian position
mid = D2R * (head + 0.5 * degs);
xpos += ins * cos(mid);
ypos += ins * sin(mid);
// update path length and current global orientation
trav += ins;
head += degs;
//jprintf("[%3.1 %3.1] -> dist %4.2f, turn %4.2f -> x = %3.1f, y = %3.1f\n", lvel, rvel, ins, degs, xpos, ypos);
}
//= Send wheel speeds, desired forklift height, and adjust gripper.
// assumes Update has already been called to get gripper force
// returns 1 if successful, 0 or negative for problem
int jhcManusBody::Issue ()
{
// send motor commands
send_wheels(move, turn);
send_lift(fork);
send_grip(grip);
// update local state and request new sensor data
inc_odom(jms_now());
req_all();
return mok;
}
//= Compute wheel speeds based on commands and send to robot.
// relies on digital servo's deadband (will keep moving otherwise)
void jhcManusBody::send_wheels (double ips, double dps)
{
double mv = msc * ips, tv = tsc * dps;
set_target(LFW, lf0 + (1.0 - bal) * (mv - tv));
set_target(RTW, rt0 - (1.0 + bal) * (mv + tv));
}
//= Compute lift setting and send to robot.
// assumes Update already called to provide current height
void jhcManusBody::send_lift (double ips)
{
double hcmd = ht, dead = 0.25, stop = 4.0; // inches per second
int fvel = ROUND(lsf * fabs(ips));
if (ips > dead)
hcmd = 4.0;
else if (ips < -dead)
hcmd = 0.0;
else
fvel = ROUND(lsf * stop);
set_target(LIFT, lout + lsc * asin((hcmd - hout) / arm));
set_speed(LIFT, __max(1, fvel), 0);
}
//= Compute grip setting and send to robot.
// 1 = active close, -1 = active open, 0 = finish last action
void jhcManusBody::send_grip (int dir)
{
// zero stability if active motion changes
if ((dir != 0) && (dir != pgrip))
wcnt = 0;
//jprintf("grip dir %d vs prev %d -> wcnt = %d\n", dir, pgrip, wcnt);
pgrip = dir;
// open or close gripper, else remember single stable width (no drift)
if (dir != 0)
wcmd = ((dir > 0) ? 2500.0 : 500.0);
else if (wcnt == wstop)
wcmd = gmin + gsc * (wid - wmin);
//jprintf(" hand target: %4.2f\n", wcmd);
set_target(HAND, wcmd);
}
///////////////////////////////////////////////////////////////////////////
// Low Level Serial //
///////////////////////////////////////////////////////////////////////////
//= Set the target position for some channel to given number of microseconds.
// part of single large "ask" packet, initialized in constructor
// NOTE: commands only transmitted when req_all() called
void jhcManusBody::set_target (int ch, double us)
{
int off[5] = {0, 4, 0, 8, 12};
int v = ROUND(4.0 * us);
UC8 *pod;
if ((ch < LFW) || (ch == DIST) || (ch > HAND))
return;
pod = ask + off[ch]; // where channel packet starts
pod[2] = v & 0x7F;
pod[3] = (v >> 7) & 0x7F;
}
//= Set the maximum speed for changing position of servo toward target.
// typically updates pulse width by inc_t / 4 microseconds at 50 Hz
// if "imm" > 0 then sends command right now, else waits for req_all()
void jhcManusBody::set_speed (int ch, int inc_t, int imm)
{
UC8 *pod = ask + 16; // same slot for all (usually LIFT)
if ((ch < LFW) || (ch == DIST) || (ch > HAND) || (mok <= 0))
return;
pod[0] = 0x87;
pod[1] = (UC8) ch;
pod[2] = inc_t & 0x7F;
pod[3] = (inc_t >> 7) & 0x7F;
if (imm > 0)
if (ser.TxArray(pod, 4) < 4)
mok = 0;
}
//= Set the maximum acceleration for changing speed of target position.
// typically updates speed by inc_v at 50 Hz
void jhcManusBody::set_accel (int ch, int inc_v)
{
UC8 pod[4];
if ((ch < LFW) || (ch == DIST) || (ch > HAND) || (mok <= 0))
return;
pod[0] = 0x89;
pod[1] = (UC8) ch;
pod[2] = inc_v & 0x7F;
pod[3] = (inc_v >> 7) & 0x7F;
if (ser.TxArray(pod, 4) < 4)
mok = 0;
}
//= Ask for positions of all channels (but do not wait for response).
int jhcManusBody::req_all ()
{
if (mok <= 0)
return mok;
if (ser.TxArray(ask, 32) < 32) // should just instantly queue
mok = 0;
return mok;
}
//= Read position of all channels in terms of microseconds.
// assumes servo controller has already been prompted with req_all()
// returns 1 if okay, 0 or negative for error
// NOTE: always blocks until all data received
int jhcManusBody::rcv_all ()
{
int i;
// get full response from robot
if (mok > 0)
{
// convert 16 bit values to milliseconds
if (ser.RxArray(pod, 12) < 12)
mok = 0;
else
for (i = 0; i < 12; i += 2)
pos[i / 2] = 0.25 * ((pod[i + 1] << 8) | pod[i]);
}
return mok;
}
/*
// non-blocking version
int jhcManusBody::rcv_all ()
{
int i;
// sanity check
if (mok <= 0)
return mok;
if (fill >= 12)
return 1;
// read as many bytes as currently available
while (ser.Check() > 0)
{
// save each byte in "pod" array
if ((i = ser.Rcv()) < 0)
{
mok = 0;
return -1;
}
pod[fill++] = (UC8) i;
// if all received, convert 16 bit values to milliseconds
if (fill >= 12)
{
for (i = 0; i < 12; i += 2)
pos[i / 2] = 0.25 * ((pod[i + 1] << 8) | pod[i]);
return 1;
}
}
// still more to go
return 0;
}
*/
| 25.651386 | 113 | 0.560866 | jconnell11 |
6a00fcb87077030c482a5264ae9b89d479cb4871 | 1,047 | cpp | C++ | CH10/CH1004/TcpServer/tcpserver.cpp | yangbo/Qt5-StudyNote | 14d533f8631310ff27cf707548e48c19c3aa2a05 | [
"MIT"
] | 2 | 2022-03-18T07:31:30.000Z | 2022-03-24T02:03:34.000Z | CH10/CH1004/TcpServer/tcpserver.cpp | yangbo/Qt5-StudyNote | 14d533f8631310ff27cf707548e48c19c3aa2a05 | [
"MIT"
] | null | null | null | CH10/CH1004/TcpServer/tcpserver.cpp | yangbo/Qt5-StudyNote | 14d533f8631310ff27cf707548e48c19c3aa2a05 | [
"MIT"
] | 1 | 2022-03-24T02:03:40.000Z | 2022-03-24T02:03:40.000Z | #include "tcpserver.h"
TcpServer::TcpServer(QWidget *parent,Qt::WindowFlags f)
: QDialog(parent,f)
{
setWindowTitle(tr("TCP Server"));
ContentListWidget = new QListWidget;
PortLabel = new QLabel(tr("端口:"));
PortLineEdit = new QLineEdit;
CreateBtn = new QPushButton(tr("创建聊天室"));
mainLayout = new QGridLayout(this);
mainLayout->addWidget(ContentListWidget,0,0,1,2);
mainLayout->addWidget(PortLabel,1,0);
mainLayout->addWidget(PortLineEdit,1,1);
mainLayout->addWidget(CreateBtn,2,0,1,2);
port=8010;
PortLineEdit->setText(QString::number(port));
connect(CreateBtn,SIGNAL(clicked()),this,SLOT(slotCreateServer()));
}
void TcpServer::slotCreateServer()
{
server = new Server(this,port); //创建一个Server对象
connect(server,SIGNAL(updateServer(QString,int)),this,
SLOT(updateServer(QString,int))); //(a)
CreateBtn->setEnabled(false);
}
void TcpServer::updateServer(QString msg,int length)
{
ContentListWidget->addItem(msg.left(length));
}
TcpServer::~TcpServer()
{
}
| 27.552632 | 71 | 0.694365 | yangbo |
6a05ff7974763bd852c606a70952678ea5240868 | 1,208 | cpp | C++ | src/symUtilities.cpp | SyrtcevVadim/SymCalc | 28051768cd7c24e6b906939a61cb8f208226cfd3 | [
"Apache-2.0"
] | null | null | null | src/symUtilities.cpp | SyrtcevVadim/SymCalc | 28051768cd7c24e6b906939a61cb8f208226cfd3 | [
"Apache-2.0"
] | null | null | null | src/symUtilities.cpp | SyrtcevVadim/SymCalc | 28051768cd7c24e6b906939a61cb8f208226cfd3 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2021 Syrtcev Vadim Igorevich
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"symUtilities.h"
#include"SymHelper.h"
#include<sstream>
#include<string>
using std::string;
using std::stringstream;
using std::to_string;
string trim(string str)
{
stringstream ss{ str };
ss >> str;
return str;
}
string removeSpaces(string str)
{
stringstream ss{ str };
string result{ "" };
while (!ss.eof())
{
string current;
ss >> current;
result += current;
}
return result;
}
string numberToString(double number)
{
stringstream ss;
ss << number;
string result;
ss >> result;
return result;
}
double stringToNumber(string str)
{
stringstream ss{ str };
double result;
ss >> result;
return result;
} | 20.133333 | 72 | 0.738411 | SyrtcevVadim |
6a0632b74e975b3c93cdee13444e82df8f40ffbd | 18,039 | cpp | C++ | src/replay.cpp | quazm/GHOST_CB_DOTS | 603b9f979628ddaa3ccbcb3c0163b124ae1e0551 | [
"Apache-2.0"
] | null | null | null | src/replay.cpp | quazm/GHOST_CB_DOTS | 603b9f979628ddaa3ccbcb3c0163b124ae1e0551 | [
"Apache-2.0"
] | null | null | null | src/replay.cpp | quazm/GHOST_CB_DOTS | 603b9f979628ddaa3ccbcb3c0163b124ae1e0551 | [
"Apache-2.0"
] | null | null | null | /*
Copyright [2008] [Trevor Hogan]
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.
CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/
*/
#include "replay.h"
#include "gameprotocol.h"
#include "ghost.h"
#include "util.h"
#include "gameslot.h"
//
// CReplay
//
CReplay::CReplay() : CPacked()
{
m_HostPID = 0;
m_PlayerCount = 0;
m_MapGameType = 0;
m_RandomSeed = 0;
m_SelectMode = 0;
m_StartSpotCount = 0;
m_CompiledBlocks.reserve(262144);
}
CReplay::~CReplay()
{
}
void CReplay::AddLeaveGame(uint32_t reason, unsigned char PID, uint32_t result)
{
BYTEARRAY Block;
Block.push_back(REPLAY_LEAVEGAME);
UTIL_AppendByteArray(Block, reason, false);
Block.push_back(PID);
UTIL_AppendByteArray(Block, result, false);
UTIL_AppendByteArray(Block, (uint32_t)1, false);
m_CompiledBlocks += std::string(Block.begin(), Block.end());
}
void CReplay::AddLeaveGameDuringLoading(uint32_t reason, unsigned char PID, uint32_t result)
{
BYTEARRAY Block;
Block.push_back(REPLAY_LEAVEGAME);
UTIL_AppendByteArray(Block, reason, false);
Block.push_back(PID);
UTIL_AppendByteArray(Block, result, false);
UTIL_AppendByteArray(Block, (uint32_t)1, false);
m_LoadingBlocks.push(Block);
}
void CReplay::AddTimeSlot2(std::queue<CIncomingAction *> actions)
{
BYTEARRAY Block;
Block.push_back(REPLAY_TIMESLOT2);
UTIL_AppendByteArray(Block, (uint16_t)0, false);
UTIL_AppendByteArray(Block, (uint16_t)0, false);
while (!actions.empty())
{
CIncomingAction *Action = actions.front();
actions.pop();
Block.push_back(Action->GetPID());
UTIL_AppendByteArray(Block, (uint16_t)Action->GetAction()->size(), false);
UTIL_AppendByteArrayFast(Block, *Action->GetAction());
}
// assign length
BYTEARRAY LengthBytes = UTIL_CreateByteArray((uint16_t)(Block.size() - 3), false);
Block[1] = LengthBytes[0];
Block[2] = LengthBytes[1];
m_CompiledBlocks += std::string(Block.begin(), Block.end());
}
void CReplay::AddTimeSlot(uint16_t timeIncrement, std::queue<CIncomingAction *> actions)
{
BYTEARRAY Block;
Block.push_back(REPLAY_TIMESLOT);
UTIL_AppendByteArray(Block, (uint16_t)0, false);
UTIL_AppendByteArray(Block, timeIncrement, false);
while (!actions.empty())
{
CIncomingAction *Action = actions.front();
actions.pop();
Block.push_back(Action->GetPID());
UTIL_AppendByteArray(Block, (uint16_t)Action->GetAction()->size(), false);
UTIL_AppendByteArrayFast(Block, *Action->GetAction());
}
// assign length
BYTEARRAY LengthBytes = UTIL_CreateByteArray((uint16_t)(Block.size() - 3), false);
Block[1] = LengthBytes[0];
Block[2] = LengthBytes[1];
m_CompiledBlocks += std::string(Block.begin(), Block.end());
m_ReplayLength += timeIncrement;
}
void CReplay::AddChatMessage(unsigned char PID, unsigned char flags, uint32_t chatMode, std::string message)
{
BYTEARRAY Block;
Block.push_back(REPLAY_CHATMESSAGE);
Block.push_back(PID);
UTIL_AppendByteArray(Block, (uint16_t)0, false);
Block.push_back(flags);
UTIL_AppendByteArray(Block, chatMode, false);
UTIL_AppendByteArrayFast(Block, message);
// assign length
BYTEARRAY LengthBytes = UTIL_CreateByteArray((uint16_t)(Block.size() - 4), false);
Block[2] = LengthBytes[0];
Block[3] = LengthBytes[1];
m_CompiledBlocks += std::string(Block.begin(), Block.end());
}
void CReplay::AddLoadingBlock(BYTEARRAY &loadingBlock)
{
m_LoadingBlocks.push(loadingBlock);
}
void CReplay::BuildReplay(std::string gameName, std::string statString, uint32_t war3Version, uint16_t buildNumber)
{
m_War3Version = war3Version;
m_BuildNumber = buildNumber;
m_Flags = 32768;
CONSOLE_Print("[REPLAY] building replay");
uint32_t LanguageID = 0x0012F8B0;
BYTEARRAY Replay;
Replay.push_back(16); // Unknown (4.0)
Replay.push_back(1); // Unknown (4.0)
Replay.push_back(0); // Unknown (4.0)
Replay.push_back(0); // Unknown (4.0)
Replay.push_back(0); // Host RecordID (4.1)
Replay.push_back(m_HostPID); // Host PlayerID (4.1)
UTIL_AppendByteArrayFast(Replay, m_HostName); // Host PlayerName (4.1)
Replay.push_back(1); // Host AdditionalSize (4.1)
Replay.push_back(0); // Host AdditionalData (4.1)
UTIL_AppendByteArrayFast(Replay, gameName); // GameName (4.2)
Replay.push_back(0); // Null (4.0)
UTIL_AppendByteArrayFast(Replay, statString); // StatString (4.3)
UTIL_AppendByteArray(Replay, (uint32_t)m_Slots.size(), false); // PlayerCount (4.6)
UTIL_AppendByteArray(Replay, m_MapGameType, false); // GameType (4.7)
UTIL_AppendByteArray(Replay, LanguageID, false); // LanguageID (4.8)
// PlayerList (4.9)
for (std::vector<PIDPlayer>::iterator i = m_Players.begin(); i != m_Players.end(); i++)
{
if ((*i).first != m_HostPID)
{
Replay.push_back(22); // Player RecordID (4.1)
Replay.push_back((*i).first); // Player PlayerID (4.1)
UTIL_AppendByteArrayFast(Replay, (*i).second); // Player PlayerName (4.1)
Replay.push_back(1); // Player AdditionalSize (4.1)
Replay.push_back(0); // Player AdditionalData (4.1)
UTIL_AppendByteArray(Replay, (uint32_t)0, false); // Unknown
}
}
// GameStartRecord (4.10)
Replay.push_back(25); // RecordID (4.10)
UTIL_AppendByteArray(Replay, (uint16_t)(7 + m_Slots.size() * 9), false); // Size (4.10)
Replay.push_back(m_Slots.size()); // NumSlots (4.10)
for (unsigned char i = 0; i < m_Slots.size(); i++)
UTIL_AppendByteArray(Replay, m_Slots[i].GetByteArray());
UTIL_AppendByteArray(Replay, m_RandomSeed, false); // RandomSeed (4.10)
Replay.push_back(m_SelectMode); // SelectMode (4.10)
Replay.push_back(m_StartSpotCount); // StartSpotCount (4.10)
// ReplayData (5.0)
Replay.push_back(REPLAY_FIRSTSTARTBLOCK);
UTIL_AppendByteArray(Replay, (uint32_t)1, false);
Replay.push_back(REPLAY_SECONDSTARTBLOCK);
UTIL_AppendByteArray(Replay, (uint32_t)1, false);
// leavers during loading need to be stored between the second and third start blocks
while (!m_LoadingBlocks.empty())
{
UTIL_AppendByteArray(Replay, m_LoadingBlocks.front());
m_LoadingBlocks.pop();
}
Replay.push_back(REPLAY_THIRDSTARTBLOCK);
UTIL_AppendByteArray(Replay, (uint32_t)1, false);
// done
m_Decompressed = std::string(Replay.begin(), Replay.end());
m_Decompressed += m_CompiledBlocks;
}
#define READB(x, y, z) (x).read((char *)(y), (z))
#define READSTR(x, y) getline((x), (y), '\0')
void CReplay::ParseReplay(bool parseBlocks)
{
m_HostPID = 0;
m_HostName.clear();
m_GameName.clear();
m_StatString.clear();
m_PlayerCount = 0;
m_MapGameType = 0;
m_Players.clear();
m_Slots.clear();
m_RandomSeed = 0;
m_SelectMode = 0;
m_StartSpotCount = 0;
m_LoadingBlocks = std::queue<BYTEARRAY>();
m_Blocks = std::queue<BYTEARRAY>();
m_CheckSums = std::queue<uint32_t>();
if (m_Flags != 32768)
{
CONSOLE_Print("[REPLAY] invalid replay (flags mismatch)");
m_Valid = false;
return;
}
std::istringstream ISS(m_Decompressed);
unsigned char Garbage1;
uint32_t Garbage4;
std::string GarbageString;
unsigned char GarbageData[65535];
READB(ISS, &Garbage4, 4); // Unknown (4.0)
if (Garbage4 != 272)
{
CONSOLE_Print("[REPLAY] invalid replay (4.0 Unknown mismatch)");
m_Valid = false;
return;
}
READB(ISS, &Garbage1, 1); // Host RecordID (4.1)
if (Garbage1 != 0)
{
CONSOLE_Print("[REPLAY] invalid replay (4.1 Host RecordID mismatch)");
m_Valid = false;
return;
}
READB(ISS, &m_HostPID, 1);
if (m_HostPID > 15)
{
CONSOLE_Print("[REPLAY] invalid replay (4.1 Host PlayerID is invalid)");
m_Valid = false;
return;
}
READSTR(ISS, m_HostName); // Host PlayerName (4.1)
READB(ISS, &Garbage1, 1); // Host AdditionalSize (4.1)
if (Garbage1 != 1)
{
CONSOLE_Print("[REPLAY] invalid replay (4.1 Host AdditionalSize mismatch)");
m_Valid = false;
return;
}
READB(ISS, &Garbage1, 1); // Host AdditionalData (4.1)
if (Garbage1 != 0)
{
CONSOLE_Print("[REPLAY] invalid replay (4.1 Host AdditionalData mismatch)");
m_Valid = false;
return;
}
AddPlayer(m_HostPID, m_HostName);
READSTR(ISS, m_GameName); // GameName (4.2)
READSTR(ISS, GarbageString); // Null (4.0)
READSTR(ISS, m_StatString); // StatString (4.3)
READB(ISS, &m_PlayerCount, 4); // PlayerCount (4.6)
if (m_PlayerCount > 12)
{
CONSOLE_Print("[REPLAY] invalid replay (4.6 PlayerCount is invalid)");
m_Valid = false;
return;
}
READB(ISS, &m_MapGameType, 4); // GameType (4.7)
READB(ISS, &Garbage4, 4); // LanguageID (4.8)
while (1)
{
READB(ISS, &Garbage1, 1); // Player RecordID (4.1)
if (Garbage1 == 22)
{
unsigned char PlayerID;
std::string PlayerName;
READB(ISS, &PlayerID, 1); // Player PlayerID (4.1)
if (PlayerID > 15)
{
CONSOLE_Print("[REPLAY] invalid replay (4.9 Player PlayerID is invalid)");
m_Valid = false;
return;
}
READSTR(ISS, PlayerName); // Player PlayerName (4.1)
READB(ISS, &Garbage1, 1); // Player AdditionalSize (4.1)
if (Garbage1 != 1)
{
CONSOLE_Print("[REPLAY] invalid replay (4.9 Player AdditionalSize mismatch)");
m_Valid = false;
return;
}
READB(ISS, &Garbage1, 1); // Player AdditionalData (4.1)
if (Garbage1 != 0)
{
CONSOLE_Print("[REPLAY] invalid replay (4.9 Player AdditionalData mismatch)");
m_Valid = false;
return;
}
READB(ISS, &Garbage4, 4); // Unknown
if (Garbage4 != 0)
{
CONSOLE_Print("[REPLAY] invalid replay (4.9 Unknown mismatch)");
m_Valid = false;
return;
}
AddPlayer(PlayerID, PlayerName);
}
else if (Garbage1 == 25)
break;
else
{
CONSOLE_Print("[REPLAY] invalid replay (4.9 Player RecordID mismatch)");
m_Valid = false;
return;
}
}
uint16_t Size;
unsigned char NumSlots;
READB(ISS, &Size, 2); // Size (4.10)
READB(ISS, &NumSlots, 1); // NumSlots (4.10)
if (Size != 7 + NumSlots * 9)
{
CONSOLE_Print("[REPLAY] invalid replay (4.10 Size is invalid)");
m_Valid = false;
return;
}
if (NumSlots == 0 || NumSlots > 12)
{
CONSOLE_Print("[REPLAY] invalid replay (4.10 NumSlots is invalid)");
m_Valid = false;
return;
}
for (int i = 0; i < NumSlots; i++)
{
unsigned char SlotData[9];
READB(ISS, SlotData, 9);
BYTEARRAY SlotDataBA = UTIL_CreateByteArray(SlotData, 9);
m_Slots.push_back(CGameSlot(SlotDataBA));
}
READB(ISS, &m_RandomSeed, 4); // RandomSeed (4.10)
READB(ISS, &m_SelectMode, 1); // SelectMode (4.10)
READB(ISS, &m_StartSpotCount, 1); // StartSpotCount (4.10)
if (ISS.eof() || ISS.fail())
{
CONSOLE_Print("[SAVEGAME] failed to parse replay header");
m_Valid = false;
return;
}
if (!parseBlocks)
return;
READB(ISS, &Garbage1, 1); // first start block ID (5.0)
if (Garbage1 != CReplay::REPLAY_FIRSTSTARTBLOCK)
{
CONSOLE_Print("[REPLAY] invalid replay (5.0 first start block ID mismatch)");
m_Valid = false;
return;
}
READB(ISS, &Garbage4, 4); // first start block data (5.0)
if (Garbage4 != 1)
{
CONSOLE_Print("[REPLAY] invalid replay (5.0 first start block data mismatch)");
m_Valid = false;
return;
}
READB(ISS, &Garbage1, 1); // second start block ID (5.0)
if (Garbage1 != CReplay::REPLAY_SECONDSTARTBLOCK)
{
CONSOLE_Print("[REPLAY] invalid replay (5.0 second start block ID mismatch)");
m_Valid = false;
return;
}
READB(ISS, &Garbage4, 4); // second start block data (5.0)
if (Garbage4 != 1)
{
CONSOLE_Print("[REPLAY] invalid replay (5.0 second start block data mismatch)");
m_Valid = false;
return;
}
while (1)
{
READB(ISS, &Garbage1, 1); // third start block ID *or* loading block ID (5.0)
if (ISS.eof() || ISS.fail())
{
CONSOLE_Print("[REPLAY] invalid replay (5.0 third start block unexpected end of file found)");
m_Valid = false;
return;
}
if (Garbage1 == CReplay::REPLAY_LEAVEGAME)
{
READB(ISS, GarbageData, 13);
BYTEARRAY LoadingBlock;
LoadingBlock.push_back(Garbage1);
UTIL_AppendByteArray(LoadingBlock, GarbageData, 13);
m_LoadingBlocks.push(LoadingBlock);
}
else if (Garbage1 == CReplay::REPLAY_THIRDSTARTBLOCK)
break;
else
{
CONSOLE_Print("[REPLAY] invalid replay (5.0 third start block ID mismatch)");
m_Valid = false;
return;
}
}
READB(ISS, &Garbage4, 4); // third start block data (5.0)
if (Garbage4 != 1)
{
CONSOLE_Print("[REPLAY] invalid replay (5.0 third start block data mismatch)");
m_Valid = false;
return;
}
if (ISS.eof() || ISS.fail())
{
CONSOLE_Print("[SAVEGAME] failed to parse replay start blocks");
m_Valid = false;
return;
}
uint32_t ActualReplayLength = 0;
while (1)
{
READB(ISS, &Garbage1, 1); // block ID (5.0)
if (ISS.eof() || ISS.fail())
break;
else if (Garbage1 == CReplay::REPLAY_LEAVEGAME)
{
READB(ISS, GarbageData, 13);
// reconstruct the block
BYTEARRAY Block;
Block.push_back(CReplay::REPLAY_LEAVEGAME);
UTIL_AppendByteArray(Block, GarbageData, 13);
m_Blocks.push(Block);
}
else if (Garbage1 == CReplay::REPLAY_TIMESLOT)
{
uint16_t BlockSize;
READB(ISS, &BlockSize, 2);
READB(ISS, GarbageData, BlockSize);
if (BlockSize >= 2)
ActualReplayLength += GarbageData[0] | GarbageData[1] << 8;
// reconstruct the block
BYTEARRAY Block;
Block.push_back(CReplay::REPLAY_TIMESLOT);
UTIL_AppendByteArray(Block, BlockSize, false);
UTIL_AppendByteArray(Block, GarbageData, BlockSize);
m_Blocks.push(Block);
}
else if (Garbage1 == CReplay::REPLAY_CHATMESSAGE)
{
unsigned char PID;
uint16_t BlockSize;
READB(ISS, &PID, 1);
if (PID > 15)
{
CONSOLE_Print("[REPLAY] invalid replay (5.0 chatmessage pid is invalid)");
m_Valid = false;
return;
}
READB(ISS, &BlockSize, 2);
READB(ISS, GarbageData, BlockSize);
// reconstruct the block
BYTEARRAY Block;
Block.push_back(CReplay::REPLAY_CHATMESSAGE);
Block.push_back(PID);
UTIL_AppendByteArray(Block, BlockSize, false);
UTIL_AppendByteArray(Block, GarbageData, BlockSize);
m_Blocks.push(Block);
}
else if (Garbage1 == CReplay::REPLAY_CHECKSUM)
{
READB(ISS, &Garbage1, 1);
if (Garbage1 != 4)
{
CONSOLE_Print("[REPLAY] invalid replay (5.0 checksum unknown mismatch)");
m_Valid = false;
return;
}
uint32_t CheckSum;
READB(ISS, &CheckSum, 4);
m_CheckSums.push(CheckSum);
}
else
{
// it's not necessarily an error if we encounter an unknown block ID since replays can contain extra data
break;
}
}
if (m_ReplayLength != ActualReplayLength)
CONSOLE_Print("[REPLAY] warning - replay length mismatch (" + UTIL_ToString(m_ReplayLength) + "ms/" + UTIL_ToString(ActualReplayLength) + "ms)");
m_Valid = true;
}
| 30.994845 | 153 | 0.572371 | quazm |
6a06b6b983f99fd4eb17f278c6638871729ba00f | 612 | cpp | C++ | DeclareVariableInNamespaceAndClassScope.cpp | haxpor/cpp_st | 43d1492266c6e01e6e243c834fba26eedf1ab9f3 | [
"MIT"
] | 2 | 2021-06-10T22:05:01.000Z | 2021-09-17T08:21:20.000Z | DeclareVariableInNamespaceAndClassScope.cpp | haxpor/cpp_st | 43d1492266c6e01e6e243c834fba26eedf1ab9f3 | [
"MIT"
] | null | null | null | DeclareVariableInNamespaceAndClassScope.cpp | haxpor/cpp_st | 43d1492266c6e01e6e243c834fba26eedf1ab9f3 | [
"MIT"
] | 1 | 2020-02-25T04:26:52.000Z | 2020-02-25T04:26:52.000Z | /**
* Demonstrate that we can initialize non-static data member of namespace, and class scope
* without problem. This is possible since c++11 (ref https://web.archive.org/web/20160316174223/https://blogs.oracle.com/pcarlini/entry/c_11_tidbits_non_static).
*/
#include <cassert>
struct StructVar
{
StructVar(int val):
m_val(val)
{
}
int m_val;
};
namespace A
{
namespace B
{
StructVar myStructVar = StructVar(2);
}
}
class Widget
{
public:
StructVar myStructVar = StructVar(3);
};
int main()
{
assert(A::B::myStructVar.m_val == 2);
Widget w;
assert(w.myStructVar.m_val == 3);
return 0;
}
| 15.692308 | 162 | 0.70098 | haxpor |
6a0a49109ae57063b17507b3f7a55184b6d96a20 | 5,348 | cpp | C++ | src/tests/execution_context/service_inheritance.cpp | jjzhang166/executors | 9b42e193b27cc5c3308dd3bc4e52712c2e442c4b | [
"BSL-1.0"
] | 406 | 2015-01-19T06:35:42.000Z | 2022-03-30T04:38:12.000Z | src/tests/execution_context/service_inheritance.cpp | rongming-lu/executors | 9b42e193b27cc5c3308dd3bc4e52712c2e442c4b | [
"BSL-1.0"
] | 1 | 2018-06-13T03:17:24.000Z | 2019-03-05T20:09:47.000Z | src/tests/execution_context/service_inheritance.cpp | rongming-lu/executors | 9b42e193b27cc5c3308dd3bc4e52712c2e442c4b | [
"BSL-1.0"
] | 66 | 2015-01-22T09:01:17.000Z | 2022-03-30T04:38:13.000Z | #include <experimental/executor>
#include <experimental/loop_scheduler>
#include <cassert>
class base_service1
: public std::experimental::execution_context::service
{
public:
typedef base_service1 key_type;
virtual void do_something() {}
protected:
explicit base_service1(std::experimental::execution_context& ctx)
: std::experimental::execution_context::service(ctx)
{
}
private:
void shutdown_service() {}
};
class service1
: public base_service1
{
public:
explicit service1(std::experimental::execution_context& ctx)
: base_service1(ctx)
{
}
virtual void do_something()
{
}
};
class base_service2
: public std::experimental::execution_context::service
{
public:
typedef base_service2 key_type;
explicit base_service2(std::experimental::execution_context& ctx)
: std::experimental::execution_context::service(ctx)
{
}
virtual void do_something() = 0;
private:
void shutdown_service() {}
};
class service2
: public base_service2
{
public:
explicit service2(std::experimental::execution_context& ctx)
: base_service2(ctx)
{
}
virtual void do_something()
{
}
};
class base_service3
: public std::experimental::execution_context::service
{
public:
typedef base_service3 key_type;
explicit base_service3(std::experimental::execution_context& ctx)
: std::experimental::execution_context::service(ctx)
{
}
virtual void do_something()
{
}
private:
void shutdown_service() {}
};
class service3
: public base_service3
{
public:
explicit service3(std::experimental::execution_context& ctx)
: base_service3(ctx)
{
}
virtual void do_something()
{
}
};
int main()
{
{
std::experimental::loop_scheduler scheduler;
assert(!std::experimental::has_service<base_service1>(scheduler));
assert(!std::experimental::has_service<service1>(scheduler));
try
{
std::experimental::use_service<base_service1>(scheduler);
assert(0);
}
catch (std::bad_cast&)
{
}
assert(!std::experimental::has_service<base_service1>(scheduler));
assert(!std::experimental::has_service<service1>(scheduler));
}
{
std::experimental::loop_scheduler scheduler;
assert(!std::experimental::has_service<base_service1>(scheduler));
assert(!std::experimental::has_service<service1>(scheduler));
std::experimental::use_service<service1>(scheduler);
assert(std::experimental::has_service<base_service1>(scheduler));
assert(std::experimental::has_service<service1>(scheduler));
}
{
std::experimental::loop_scheduler scheduler;
assert(!std::experimental::has_service<base_service1>(scheduler));
assert(!std::experimental::has_service<service1>(scheduler));
std::experimental::make_service<service1>(scheduler);
assert(std::experimental::has_service<base_service1>(scheduler));
assert(std::experimental::has_service<service1>(scheduler));
}
{
std::experimental::loop_scheduler scheduler;
assert(!std::experimental::has_service<base_service2>(scheduler));
assert(!std::experimental::has_service<service2>(scheduler));
try
{
std::experimental::use_service<base_service2>(scheduler);
assert(0);
}
catch (std::bad_cast&)
{
}
assert(!std::experimental::has_service<base_service2>(scheduler));
assert(!std::experimental::has_service<service2>(scheduler));
}
{
std::experimental::loop_scheduler scheduler;
assert(!std::experimental::has_service<base_service2>(scheduler));
assert(!std::experimental::has_service<service2>(scheduler));
std::experimental::use_service<service2>(scheduler);
assert(std::experimental::has_service<base_service2>(scheduler));
assert(std::experimental::has_service<service2>(scheduler));
}
{
std::experimental::loop_scheduler scheduler;
assert(!std::experimental::has_service<base_service2>(scheduler));
assert(!std::experimental::has_service<service2>(scheduler));
std::experimental::make_service<service2>(scheduler);
assert(std::experimental::has_service<base_service2>(scheduler));
assert(std::experimental::has_service<service2>(scheduler));
}
{
std::experimental::loop_scheduler scheduler;
assert(!std::experimental::has_service<base_service3>(scheduler));
assert(!std::experimental::has_service<service3>(scheduler));
std::experimental::use_service<base_service3>(scheduler);
assert(std::experimental::has_service<base_service3>(scheduler));
assert(std::experimental::has_service<service3>(scheduler));
}
{
std::experimental::loop_scheduler scheduler;
assert(!std::experimental::has_service<base_service3>(scheduler));
assert(!std::experimental::has_service<service3>(scheduler));
std::experimental::use_service<service3>(scheduler);
assert(std::experimental::has_service<base_service3>(scheduler));
assert(std::experimental::has_service<service3>(scheduler));
}
{
std::experimental::loop_scheduler scheduler;
assert(!std::experimental::has_service<base_service3>(scheduler));
assert(!std::experimental::has_service<service3>(scheduler));
std::experimental::make_service<service3>(scheduler);
assert(std::experimental::has_service<base_service3>(scheduler));
assert(std::experimental::has_service<service3>(scheduler));
}
}
| 27.010101 | 70 | 0.722326 | jjzhang166 |
6a0c168af224b2c3fe2ea341d32cb6e507bfa6e7 | 870 | cpp | C++ | src/test/logical_query_plan/show_columns_node_test.cpp | IanJamesMcKay/InMemoryDB | a267d9522926eca9add2ad4512f8ce352daac879 | [
"MIT"
] | 1 | 2021-04-14T11:16:52.000Z | 2021-04-14T11:16:52.000Z | src/test/logical_query_plan/show_columns_node_test.cpp | IanJamesMcKay/InMemoryDB | a267d9522926eca9add2ad4512f8ce352daac879 | [
"MIT"
] | null | null | null | src/test/logical_query_plan/show_columns_node_test.cpp | IanJamesMcKay/InMemoryDB | a267d9522926eca9add2ad4512f8ce352daac879 | [
"MIT"
] | 1 | 2020-11-30T13:11:04.000Z | 2020-11-30T13:11:04.000Z | #include <memory>
#include "gtest/gtest.h"
#include "base_test.hpp"
#include "logical_query_plan/show_columns_node.hpp"
namespace opossum {
class ShowColumnsNodeTest : public BaseTest {
protected:
void SetUp() override { _show_columns_node = ShowColumnsNode::make("table_a"); }
std::shared_ptr<ShowColumnsNode> _show_columns_node;
};
TEST_F(ShowColumnsNodeTest, Description) {
EXPECT_EQ(_show_columns_node->description(), "[ShowColumns] Table: 'table_a'");
}
TEST_F(ShowColumnsNodeTest, TableName) { EXPECT_EQ(_show_columns_node->table_name(), "table_a"); }
TEST_F(ShowColumnsNodeTest, ShallowEquals) {
EXPECT_TRUE(_show_columns_node->shallow_equals(*_show_columns_node));
const auto other_show_columns_node = ShowColumnsNode::make("table_b");
EXPECT_FALSE(other_show_columns_node->shallow_equals(*_show_columns_node));
}
} // namespace opossum
| 27.1875 | 98 | 0.781609 | IanJamesMcKay |
6a0d550358cda6b23f9589f30e90ba9de1466bb4 | 1,656 | cpp | C++ | Leetcode Daily Challenge/January-2021/14. Minimum Operations to Reduce X to Zero.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 5 | 2021-08-10T18:47:49.000Z | 2021-08-21T15:42:58.000Z | Leetcode Daily Challenge/January-2021/14. Minimum Operations to Reduce X to Zero.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 2 | 2022-02-25T13:36:46.000Z | 2022-02-25T14:06:44.000Z | Leetcode Daily Challenge/January-2021/14. Minimum Operations to Reduce X to Zero.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 1 | 2022-01-23T22:00:48.000Z | 2022-01-23T22:00:48.000Z | /*
Minimum Operations to Reduce X to Zero
=========================================
You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.
Return the minimum number of operations to reduce x to exactly 0 if it's possible, otherwise, return -1.
Example 1:
Input: nums = [1,1,4,2,3], x = 5
Output: 2
Explanation: The optimal solution is to remove the last two elements to reduce x to zero.
Example 2:
Input: nums = [5,6,7,8,9], x = 4
Output: -1
Example 3:
Input: nums = [3,2,20,1,1,3], x = 10
Output: 5
Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 104
1 <= x <= 109
Hint #1
Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray.
Hint #2
Finding the maximum subarray is standard and can be done greedily.
*/
class Solution
{
public:
int minOperations(vector<int> &nums, int x)
{
unordered_map<int, int> left;
int res = INT_MAX;
for (auto l = 0, sum = 0; l < nums.size() && sum <= x; ++l)
{
left[sum] = l;
sum += nums[l];
}
for (int r = nums.size() - 1, sum = 0; r >= 0 && sum <= x; --r)
{
auto it = left.find(x - sum);
if (it != end(left) && r + 1 >= it->second)
{
res = min(res, (int)nums.size() - r - 1 + it->second);
}
sum += nums[r];
}
return res == INT_MAX ? -1 : res;
}
};
| 27.6 | 239 | 0.61715 | Akshad7829 |
6a0e1367169fc2943048ee69870dfc52ecec2abd | 1,474 | hpp | C++ | include/lol/def/CollectionsLcdsChampionSkinDTO.hpp | Maufeat/LeagueAPI | be7cb5093aab3f27d95b3c0e1d5700aa50126c47 | [
"BSD-3-Clause"
] | 1 | 2020-07-22T11:14:55.000Z | 2020-07-22T11:14:55.000Z | include/lol/def/CollectionsLcdsChampionSkinDTO.hpp | Maufeat/LeagueAPI | be7cb5093aab3f27d95b3c0e1d5700aa50126c47 | [
"BSD-3-Clause"
] | null | null | null | include/lol/def/CollectionsLcdsChampionSkinDTO.hpp | Maufeat/LeagueAPI | be7cb5093aab3f27d95b3c0e1d5700aa50126c47 | [
"BSD-3-Clause"
] | 4 | 2018-12-01T22:48:21.000Z | 2020-07-22T11:14:56.000Z | #pragma once
#include "../base_def.hpp"
namespace lol {
struct CollectionsLcdsChampionSkinDTO {
uint64_t endDate;
uint64_t purchaseDate;
int32_t winCountRemaining;
std::vector<std::string> sources;
int32_t championId;
bool freeToPlayReward;
bool lastSelected;
bool owned;
int32_t skinId;
bool stillObtainable;
};
inline void to_json(json& j, const CollectionsLcdsChampionSkinDTO& v) {
j["endDate"] = v.endDate;
j["purchaseDate"] = v.purchaseDate;
j["winCountRemaining"] = v.winCountRemaining;
j["sources"] = v.sources;
j["championId"] = v.championId;
j["freeToPlayReward"] = v.freeToPlayReward;
j["lastSelected"] = v.lastSelected;
j["owned"] = v.owned;
j["skinId"] = v.skinId;
j["stillObtainable"] = v.stillObtainable;
}
inline void from_json(const json& j, CollectionsLcdsChampionSkinDTO& v) {
v.endDate = j.at("endDate").get<uint64_t>();
v.purchaseDate = j.at("purchaseDate").get<uint64_t>();
v.winCountRemaining = j.at("winCountRemaining").get<int32_t>();
v.sources = j.at("sources").get<std::vector<std::string>>();
v.championId = j.at("championId").get<int32_t>();
v.freeToPlayReward = j.at("freeToPlayReward").get<bool>();
v.lastSelected = j.at("lastSelected").get<bool>();
v.owned = j.at("owned").get<bool>();
v.skinId = j.at("skinId").get<int32_t>();
v.stillObtainable = j.at("stillObtainable").get<bool>();
}
} | 36.85 | 75 | 0.651967 | Maufeat |
6a0f3fd051c2d1c78dfc051f67ac9f4cdf1aa854 | 328 | cpp | C++ | Before Summer 2017/SummerTrain Archieve/void-pointer.cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | 1 | 2019-12-19T06:51:20.000Z | 2019-12-19T06:51:20.000Z | Before Summer 2017/SummerTrain Archieve/void-pointer.cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | null | null | null | Before Summer 2017/SummerTrain Archieve/void-pointer.cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | null | null | null | /*
// void-pointer.cpp by Bill Weinman <http://bw.org/>
#include <stdio.h>
void * func( void * );
int main( int argc, char ** argv ) {
printf("this is void-pointer.c\n");
const char * cp = "1234";
int * vp = (int *) func( (void *) cp );
printf("%08x\n", * vp);
return 0;
}
void * func ( void * vp ) {
return vp;
}
*/
| 15.619048 | 52 | 0.554878 | mohamedGamalAbuGalala |
6a0fbea5f87db20bc7fd075a49fd5a639b25ebec | 10,075 | cpp | C++ | apps/src/openni_grab_frame.cpp | yxlao/StanfordPCL | 98a8663f896c1ba880d14efa2338b7cfbd01b6ef | [
"MIT"
] | null | null | null | apps/src/openni_grab_frame.cpp | yxlao/StanfordPCL | 98a8663f896c1ba880d14efa2338b7cfbd01b6ef | [
"MIT"
] | null | null | null | apps/src/openni_grab_frame.cpp | yxlao/StanfordPCL | 98a8663f896c1ba880d14efa2338b7cfbd01b6ef | [
"MIT"
] | null | null | null | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Nico Blodow (blodow@cs.tum.edu)
* Christian Potthast (potthast@usc.edu)
*/
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/io/pcd_io.h>
#include <pcl/common/time.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <boost/filesystem.hpp>
#include <pcl/visualization/pcl_visualizer.h>
using namespace pcl::console;
using namespace boost::filesystem;
template <typename PointType> class OpenNIGrabFrame {
typedef pcl::PointCloud<PointType> Cloud;
typedef typename Cloud::ConstPtr CloudConstPtr;
public:
OpenNIGrabFrame()
: visualizer_(new pcl::visualization::PCLVisualizer("OpenNI Viewer")),
writer_(), quit_(false), continuous_(false), trigger_(false),
file_name_(""), dir_name_(""), format_(4) {}
void cloud_cb_(const CloudConstPtr &cloud) {
if (quit_)
return;
boost::mutex::scoped_lock lock(cloud_mutex_);
cloud_ = cloud;
if (continuous_ || trigger_)
saveCloud();
trigger_ = false;
}
void keyboard_callback(const pcl::visualization::KeyboardEvent &event,
void *) {
if (event.keyUp()) {
switch (event.getKeyCode()) {
case 27:
case 'Q':
case 'q':
quit_ = true;
visualizer_->close();
break;
case ' ':
continuous_ = !continuous_;
break;
}
}
}
void mouse_callback(const pcl::visualization::MouseEvent &mouse_event,
void *) {
if (mouse_event.getType() ==
pcl::visualization::MouseEvent::MouseButtonPress &&
mouse_event.getButton() ==
pcl::visualization::MouseEvent::LeftButton) {
trigger_ = true;
}
}
CloudConstPtr getLatestCloud() {
// lock while we swap our cloud and reset it.
boost::mutex::scoped_lock lock(cloud_mutex_);
CloudConstPtr temp_cloud;
temp_cloud.swap(cloud_); // here we set cloud_ to null, so that
// it is safe to set it again from our
// callback
return (temp_cloud);
}
void saveCloud() {
std::stringstream ss;
ss << dir_name_ << "/" << file_name_ << "_"
<< boost::posix_time::to_iso_string(
boost::posix_time::microsec_clock::local_time())
<< ".pcd";
if (format_ & 1) {
writer_.writeBinary<PointType>(ss.str(), *cloud_);
std::cerr << "Data saved in BINARY format to " << ss.str()
<< std::endl;
}
if (format_ & 2) {
writer_.writeBinaryCompressed<PointType>(ss.str(), *cloud_);
std::cerr << "Data saved in BINARY COMPRESSED format to "
<< ss.str() << std::endl;
}
if (format_ & 4) {
writer_.writeBinaryCompressed<PointType>(ss.str(), *cloud_);
std::cerr << "Data saved in BINARY COMPRESSED format to "
<< ss.str() << std::endl;
}
}
void run() {
// register the keyboard and mouse callback for the visualizer
visualizer_->registerMouseCallback(&OpenNIGrabFrame::mouse_callback,
*this);
visualizer_->registerKeyboardCallback(
&OpenNIGrabFrame::keyboard_callback, *this);
// create a new grabber for OpenNI devices
pcl::Grabber *interface = new pcl::OpenNIGrabber();
// make callback function from member function
boost::function<void(const CloudConstPtr &)> f =
boost::bind(&OpenNIGrabFrame::cloud_cb_, this, _1);
// connect callback function for desired signal. In this case its a
// point cloud with color values
boost::signals2::connection c = interface->registerCallback(f);
// start receiving point clouds
interface->start();
// wait until user quits program with Ctrl-C, but no busy-waiting ->
// sleep (1);
while (!visualizer_->wasStopped()) {
visualizer_->spinOnce();
if (cloud_) {
CloudConstPtr cloud = getLatestCloud();
if (!visualizer_->updatePointCloud(cloud, "OpenNICloud")) {
visualizer_->addPointCloud(cloud, "OpenNICloud");
visualizer_->resetCameraViewpoint("OpenNICloud");
}
}
boost::this_thread::sleep(boost::posix_time::microseconds(100));
}
// while (!quit_)
// boost::this_thread::sleep (boost::posix_time::seconds (1));
// stop the grabber
interface->stop();
}
void setOptions(std::string filename, std::string pcd_format, bool paused) {
boost::filesystem::path path(filename);
if (filename.empty()) {
dir_name_ = ".";
file_name_ = "frame";
} else {
dir_name_ = path.parent_path().string();
if (!dir_name_.empty() &&
!boost::filesystem::exists(path.parent_path())) {
std::cerr << "directory \"" << path.parent_path()
<< "\" does not exist!\n";
exit(1);
}
#if BOOST_FILESYSTEM_VERSION == 3
file_name_ = path.stem().string();
#else
file_name_ = path.stem();
#endif
}
std::cout << "dir: " << dir_name_ << " :: " << path.parent_path()
<< std::endl;
#if BOOST_FILESYSTEM_VERSION == 3
std::cout << "file: " << file_name_ << " :: " << path.stem().string()
<< std::endl;
#else
std::cout << "file: " << file_name_ << " :: " << path.stem()
<< std::endl;
#endif
if (pcd_format == "b" || pcd_format == "all")
format_ |= 1;
else if (pcd_format == "ascii" || pcd_format == "all")
format_ |= 2;
else if (pcd_format == "bc" || pcd_format == "all")
format_ |= 4;
continuous_ = !paused;
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> visualizer_;
pcl::PCDWriter writer_;
bool quit_;
bool continuous_;
bool trigger_;
std::string file_name_;
std::string dir_name_;
unsigned format_;
CloudConstPtr cloud_;
mutable boost::mutex cloud_mutex_;
};
void usage(char **argv) {
std::cout << "usage: " << argv[0] << " <filename> <options>\n\n";
print_info(" filename: if no filename is provided a generic timestamp "
"will be set as filename\n\n");
print_info(" where options are:\n");
print_info(" -format = PCD file format (b=binary; "
"bc=binary compressed; ascii=ascii; all=all) (default: bc)\n");
print_info(" -XYZ = store just a XYZ cloud\n");
print_info(" -paused = start grabber in paused mode. "
"Toggle pause by pressing the space bar\n");
print_info(" or grab single frames by just "
"pressing the left mouse button.\n");
}
int main(int argc, char **argv) {
std::string arg;
if (argc > 1)
arg = std::string(argv[1]);
if (arg == "--help" || arg == "-h") {
usage(argv);
return 1;
}
std::string format = "bc";
std::string filename;
bool paused = false;
bool xyz = false;
if (argc > 1) {
// Parse the command line arguments for .pcd file
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument(argc, argv, ".pcd");
if (p_file_indices.size() > 0)
filename = argv[p_file_indices[0]];
std::cout << "fname: " << filename << std::endl;
// Command line parsing
parse_argument(argc, argv, "-format", format);
xyz = find_switch(argc, argv, "-XYZ");
paused = find_switch(argc, argv, "-paused");
}
if (xyz) {
OpenNIGrabFrame<pcl::PointXYZ> grab_frame;
grab_frame.setOptions(filename, format, paused);
grab_frame.run();
} else {
OpenNIGrabFrame<pcl::PointXYZRGBA> grab_frame;
grab_frame.setOptions(filename, format, paused);
grab_frame.run();
}
return (0);
}
| 35.10453 | 80 | 0.580645 | yxlao |
6a1612415a99fcd1a2d8c5cf6965a5dfc091d838 | 26,619 | cpp | C++ | Deprecated/Controls/Styles/Win8Styles/GuiWin8StylesCommon.cpp | cameled/GacUI | 939856c1045067dc7b78eb80cdb7174ae5c76799 | [
"RSA-MD"
] | 2,342 | 2015-04-01T22:12:53.000Z | 2022-03-31T07:00:33.000Z | Deprecated/Controls/Styles/Win8Styles/GuiWin8StylesCommon.cpp | vczh2/GacUI | ce100ec13357bbf03ed3d2040c48d6b2b2fefd2f | [
"RSA-MD"
] | 68 | 2015-04-04T15:42:06.000Z | 2022-03-29T04:33:51.000Z | Deprecated/Controls/Styles/Win8Styles/GuiWin8StylesCommon.cpp | vczh2/GacUI | ce100ec13357bbf03ed3d2040c48d6b2b2fefd2f | [
"RSA-MD"
] | 428 | 2015-04-02T00:25:48.000Z | 2022-03-25T16:37:56.000Z | #include "GuiWin8StylesCommon.h"
namespace vl
{
namespace presentation
{
namespace win8
{
using namespace collections;
using namespace elements;
using namespace compositions;
using namespace controls;
/***********************************************************************
Win8ButtonColors
***********************************************************************/
void Win8ButtonColors::SetAlphaWithoutText(unsigned char a)
{
borderColor.a=a;
g1.a=a;
g2.a=a;
}
Win8ButtonColors Win8ButtonColors::Blend(const Win8ButtonColors& c1, const Win8ButtonColors& c2, vint ratio, vint total)
{
if(ratio<0) ratio=0;
else if(ratio>total) ratio=total;
Win8ButtonColors result;
result.borderColor=BlendColor(c1.borderColor, c2.borderColor, ratio, total);
result.g1=BlendColor(c1.g1, c2.g1, ratio, total);
result.g2=BlendColor(c1.g2, c2.g2, ratio, total);
result.textColor=BlendColor(c1.textColor, c2.textColor, ratio, total);
result.bullet=BlendColor(c1.bullet, c2.bullet, ratio, total);
return result;
}
//---------------------------------------------------------
Win8ButtonColors Win8ButtonColors::ButtonNormal()
{
Win8ButtonColors colors=
{
Color(172, 172, 172),
Color(239, 239, 239),
Color(229, 229, 229),
Win8GetSystemTextColor(true),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ButtonActive()
{
Win8ButtonColors colors=
{
Color(126, 180, 234),
Color(235, 244, 252),
Color(220, 236, 252),
Win8GetSystemTextColor(true),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ButtonPressed()
{
Win8ButtonColors colors=
{
Color(86, 157, 229),
Color(218, 236, 252),
Color(196, 224, 252),
Win8GetSystemTextColor(true),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ButtonDisabled()
{
Win8ButtonColors colors=
{
Color(173, 178, 181),
Color(252, 252, 252),
Color(252, 252, 252),
Win8GetSystemTextColor(false),
};
return colors;
}
//---------------------------------------------------------
Win8ButtonColors Win8ButtonColors::ItemNormal()
{
Win8ButtonColors colors=
{
Color(112, 192, 231, 0),
Color(229, 243, 251, 0),
Color(229, 243, 251, 0),
Win8GetSystemTextColor(true),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ItemActive()
{
Win8ButtonColors colors=
{
Color(112, 192, 231),
Color(229, 243, 251),
Color(229, 243, 251),
Win8GetSystemTextColor(true),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ItemSelected()
{
Win8ButtonColors colors=
{
Color(102, 167, 232),
Color(209, 232, 255),
Color(209, 232, 255),
Win8GetSystemTextColor(true),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ItemDisabled()
{
Win8ButtonColors colors=
{
Color(112, 192, 231, 0),
Color(229, 243, 251, 0),
Color(229, 243, 251, 0),
Win8GetSystemTextColor(false),
};
return colors;
}
//---------------------------------------------------------
Win8ButtonColors Win8ButtonColors::CheckedNormal(bool selected)
{
Win8ButtonColors colors=
{
Color(112, 112, 112),
Color(255, 255, 255),
Color(255, 255, 255),
Win8GetSystemTextColor(true),
Color(0, 0, 0),
};
if(!selected)
{
colors.bullet.a=0;
}
return colors;
}
Win8ButtonColors Win8ButtonColors::CheckedActive(bool selected)
{
Win8ButtonColors colors=
{
Color(51, 153, 255),
Color(243, 249, 255),
Color(243, 249, 255),
Win8GetSystemTextColor(true),
Color(33, 33, 33),
};
if(!selected)
{
colors.bullet.a=0;
}
return colors;
}
Win8ButtonColors Win8ButtonColors::CheckedPressed(bool selected)
{
Win8ButtonColors colors=
{
Color(0, 124, 222),
Color(217, 236, 255),
Color(217, 236, 255),
Win8GetSystemTextColor(true),
Color(0, 0, 0),
};
if(!selected)
{
colors.bullet.a=0;
}
return colors;
}
Win8ButtonColors Win8ButtonColors::CheckedDisabled(bool selected)
{
Win8ButtonColors colors=
{
Color(188, 188, 188),
Color(230, 230, 230),
Color(230, 230, 230),
Win8GetSystemTextColor(false),
Color(112, 112, 112),
};
if(!selected)
{
colors.bullet.a=0;
}
return colors;
}
//---------------------------------------------------------
Win8ButtonColors Win8ButtonColors::ToolstripButtonNormal()
{
Win8ButtonColors colors=
{
Win8GetSystemWindowColor(),
Win8GetSystemWindowColor(),
Win8GetSystemWindowColor(),
Win8GetSystemTextColor(true),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ToolstripButtonActive()
{
Win8ButtonColors colors=
{
Color(120, 174, 229),
Color(209, 226, 242),
Color(209, 226, 242),
Win8GetSystemTextColor(true),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ToolstripButtonPressed()
{
Win8ButtonColors colors=
{
Color(96, 161, 226),
Color(180, 212, 244),
Color(180, 212, 244),
Win8GetSystemTextColor(true),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ToolstripButtonSelected()
{
Win8ButtonColors colors=
{
Color(96, 161, 226),
Color(233, 241, 250),
Color(233, 241, 250),
Win8GetSystemTextColor(true),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ToolstripButtonDisabled()
{
Win8ButtonColors colors=
{
Win8GetSystemWindowColor(),
Win8GetSystemWindowColor(),
Win8GetSystemWindowColor(),
Win8GetSystemTextColor(false),
};
return colors;
}
//---------------------------------------------------------
Win8ButtonColors Win8ButtonColors::ScrollHandleNormal()
{
Win8ButtonColors colors=
{
Color(205, 205, 205),
Color(205, 205, 205),
Color(205, 205, 205),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ScrollHandleActive()
{
Win8ButtonColors colors=
{
Color(166, 166, 166),
Color(166, 166, 166),
Color(166, 166, 166),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ScrollHandlePressed()
{
Win8ButtonColors colors=
{
Color(166, 166, 166),
Color(166, 166, 166),
Color(166, 166, 166),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ScrollHandleDisabled()
{
Win8ButtonColors colors=
{
Win8GetSystemWindowColor(),
Win8GetSystemWindowColor(),
Win8GetSystemWindowColor(),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ScrollArrowNormal()
{
Win8ButtonColors colors=
{
Win8GetSystemWindowColor(),
Win8GetSystemWindowColor(),
Win8GetSystemWindowColor(),
Color(96, 96, 96),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ScrollArrowActive()
{
Win8ButtonColors colors=
{
Color(218, 218, 218),
Color(218, 218, 218),
Color(218, 218, 218),
Color(0, 0, 0),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ScrollArrowPressed()
{
Win8ButtonColors colors=
{
Color(96, 96, 96),
Color(96, 96, 96),
Color(96, 96, 96),
Color(255, 255, 255),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::ScrollArrowDisabled()
{
Win8ButtonColors colors=
{
Win8GetSystemWindowColor(),
Win8GetSystemWindowColor(),
Win8GetSystemWindowColor(),
Color(191, 191, 191),
};
return colors;
}
//---------------------------------------------------------
Win8ButtonColors Win8ButtonColors::MenuBarButtonNormal()
{
Win8ButtonColors colors=
{
Color(245, 246, 247),
Color(245, 246, 247),
Color(245, 246, 247),
Win8GetSystemTextColor(true),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::MenuBarButtonActive()
{
Win8ButtonColors colors=
{
Color(122, 177, 232),
Color(213, 231, 248),
Color(213, 231, 248),
Win8GetSystemTextColor(true),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::MenuBarButtonPressed()
{
Win8ButtonColors colors=
{
Color(98, 163, 229),
Color(184, 216, 249),
Color(184, 216, 249),
Win8GetSystemTextColor(true),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::MenuBarButtonDisabled()
{
Win8ButtonColors colors=
{
Color(245, 246, 247),
Color(245, 246, 247),
Color(245, 246, 247),
Win8GetSystemTextColor(false),
};
return colors;
}
//---------------------------------------------------------
Win8ButtonColors Win8ButtonColors::MenuItemButtonNormal()
{
Win8ButtonColors colors=
{
Color(240, 240, 240),
Color(240, 240, 240),
Color(240, 240, 240),
Win8GetSystemTextColor(true),
Win8GetMenuSplitterColor(),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::MenuItemButtonNormalActive()
{
Win8ButtonColors colors=
{
Color(120, 174, 229),
Color(209, 226, 242),
Color(209, 226, 242),
Win8GetSystemTextColor(true),
Color(187, 204, 220),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::MenuItemButtonSelected()
{
Win8ButtonColors colors=
{
Color(120, 174, 229),
Color(233, 241, 250),
Color(233, 241, 250),
Win8GetSystemTextColor(true),
Color(233, 241, 250),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::MenuItemButtonSelectedActive()
{
Win8ButtonColors colors=
{
Color(120, 174, 229),
Color(233, 241, 250),
Color(233, 241, 250),
Win8GetSystemTextColor(true),
Color(187, 204, 220),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::MenuItemButtonDisabled()
{
Win8ButtonColors colors=
{
Color(240, 240, 240),
Color(240, 240, 240),
Color(240, 240, 240),
Win8GetSystemTextColor(false),
Win8GetMenuSplitterColor(),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::MenuItemButtonDisabledActive()
{
Win8ButtonColors colors=
{
Color(120, 174, 229),
Color(209, 226, 242),
Color(209, 226, 242),
Win8GetSystemTextColor(false),
Win8GetMenuSplitterColor(),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::TabPageHeaderNormal()
{
Win8ButtonColors colors=
{
Color(172, 172, 172),
Color(239, 239, 239),
Color(229, 229, 229),
Win8GetSystemTextColor(true),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::TabPageHeaderActive()
{
Win8ButtonColors colors=
{
Color(126, 180, 234),
Color(236, 244, 252),
Color(221, 237, 252),
Win8GetSystemTextColor(true),
};
return colors;
}
Win8ButtonColors Win8ButtonColors::TabPageHeaderSelected()
{
Win8ButtonColors colors=
{
Color(172, 172, 172),
Color(255, 255, 255),
Color(255, 255, 255),
Win8GetSystemTextColor(true),
};
return colors;
}
/***********************************************************************
Win8ButtonElements
***********************************************************************/
Win8ButtonElements Win8ButtonElements::Create(Alignment horizontal, Alignment vertical)
{
Win8ButtonElements button;
{
button.mainComposition=new GuiBoundsComposition;
button.mainComposition->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElementAndChildren);
}
{
GuiSolidBorderElement* element=GuiSolidBorderElement::Create();
button.rectBorderElement=element;
GuiBoundsComposition* composition=new GuiBoundsComposition;
button.mainComposition->AddChild(composition);
composition->SetAlignmentToParent(Margin(0, 0, 0, 0));
composition->SetOwnedElement(element);
}
{
GuiGradientBackgroundElement* element=GuiGradientBackgroundElement::Create();
button.backgroundElement=element;
element->SetDirection(GuiGradientBackgroundElement::Vertical);
element->SetShape(ElementShape::Rectangle);
GuiBoundsComposition* composition=new GuiBoundsComposition;
button.backgroundComposition=composition;
button.mainComposition->AddChild(composition);
composition->SetAlignmentToParent(Margin(1, 1, 1, 1));
composition->SetOwnedElement(element);
}
{
Win8CreateSolidLabelElement(button.textElement, button.textComposition, horizontal, vertical);
button.mainComposition->AddChild(button.textComposition);
}
return button;
}
void Win8ButtonElements::Apply(const Win8ButtonColors& colors)
{
if(rectBorderElement)
{
rectBorderElement->SetColor(colors.borderColor);
}
backgroundElement->SetColors(colors.g1, colors.g2);
textElement->SetColor(colors.textColor);
}
/***********************************************************************
Win8CheckedButtonElements
***********************************************************************/
Win8CheckedButtonElements Win8CheckedButtonElements::Create(elements::ElementShape shape, bool backgroundVisible)
{
const vint checkSize=13;
const vint checkPadding=2;
Win8CheckedButtonElements button;
{
button.mainComposition=new GuiBoundsComposition;
button.mainComposition->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElementAndChildren);
}
{
GuiTableComposition* mainTable=new GuiTableComposition;
button.mainComposition->AddChild(mainTable);
if(backgroundVisible)
{
GuiSolidBackgroundElement* element=GuiSolidBackgroundElement::Create();
element->SetColor(Win8GetSystemWindowColor());
mainTable->SetOwnedElement(element);
}
mainTable->SetRowsAndColumns(1, 2);
mainTable->SetAlignmentToParent(Margin(0, 0, 0, 0));
mainTable->SetRowOption(0, GuiCellOption::PercentageOption(1.0));
mainTable->SetColumnOption(0, GuiCellOption::AbsoluteOption(checkSize+2*checkPadding));
mainTable->SetColumnOption(1, GuiCellOption::PercentageOption(1.0));
{
GuiCellComposition* cell=new GuiCellComposition;
mainTable->AddChild(cell);
cell->SetSite(0, 0, 1, 1);
GuiTableComposition* table=new GuiTableComposition;
cell->AddChild(table);
table->SetRowsAndColumns(3, 1);
table->SetAlignmentToParent(Margin(0, 0, 0, 0));
table->SetRowOption(0, GuiCellOption::PercentageOption(0.5));
table->SetRowOption(1, GuiCellOption::MinSizeOption());
table->SetRowOption(2, GuiCellOption::PercentageOption(0.5));
{
GuiCellComposition* checkCell=new GuiCellComposition;
table->AddChild(checkCell);
checkCell->SetSite(1, 0, 1, 1);
{
GuiBoundsComposition* borderBounds=new GuiBoundsComposition;
checkCell->AddChild(borderBounds);
borderBounds->SetAlignmentToParent(Margin(checkPadding, -1, checkPadding, -1));
borderBounds->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElementAndChildren);
{
GuiSolidBorderElement* element=GuiSolidBorderElement::Create();
button.bulletBorderElement=element;
element->SetShape(shape);
GuiBoundsComposition* bounds=new GuiBoundsComposition;
borderBounds->AddChild(bounds);
bounds->SetOwnedElement(element);
bounds->SetAlignmentToParent(Margin(0, 0, 0, 0));
bounds->SetBounds(Rect(Point(0, 0), Size(checkSize, checkSize)));
}
{
GuiGradientBackgroundElement* element=GuiGradientBackgroundElement::Create();
button.bulletBackgroundElement=element;
element->SetShape(shape);
element->SetDirection(GuiGradientBackgroundElement::Vertical);
GuiBoundsComposition* bounds=new GuiBoundsComposition;
borderBounds->AddChild(bounds);
bounds->SetOwnedElement(element);
bounds->SetAlignmentToParent(Margin(1, 1, 1, 1));
}
}
button.bulletCheckElement=0;
button.bulletRadioElement=0;
if(shape==ElementShape::Rectangle)
{
button.bulletCheckElement=GuiSolidLabelElement::Create();
{
FontProperties font;
font.fontFamily=L"Webdings";
font.size=16;
font.bold=true;
button.bulletCheckElement->SetFont(font);
}
button.bulletCheckElement->SetText(L"a");
button.bulletCheckElement->SetAlignments(Alignment::Center, Alignment::Center);
GuiBoundsComposition* composition=new GuiBoundsComposition;
composition->SetOwnedElement(button.bulletCheckElement);
composition->SetAlignmentToParent(Margin(0, 0, 0, 0));
checkCell->AddChild(composition);
}
else
{
button.bulletRadioElement=GuiSolidBackgroundElement::Create();
button.bulletRadioElement->SetShape(ElementShape::Ellipse);
GuiBoundsComposition* composition=new GuiBoundsComposition;
composition->SetOwnedElement(button.bulletRadioElement);
composition->SetAlignmentToParent(Margin(checkPadding+3, 3, checkPadding+3, 3));
checkCell->AddChild(composition);
}
}
}
{
GuiCellComposition* textCell=new GuiCellComposition;
mainTable->AddChild(textCell);
textCell->SetSite(0, 1, 1, 1);
{
Win8CreateSolidLabelElement(button.textElement, button.textComposition, Alignment::Left, Alignment::Center);
textCell->AddChild(button.textComposition);
}
}
}
return button;
}
void Win8CheckedButtonElements::Apply(const Win8ButtonColors& colors)
{
bulletBorderElement->SetColor(colors.borderColor);
bulletBackgroundElement->SetColors(colors.g1, colors.g2);
textElement->SetColor(colors.textColor);
if(bulletCheckElement)
{
bulletCheckElement->SetColor(colors.bullet);
}
if(bulletRadioElement)
{
bulletRadioElement->SetColor(colors.bullet);
}
}
/***********************************************************************
Win8MenuItemButtonElements
***********************************************************************/
Win8MenuItemButtonElements Win8MenuItemButtonElements::Create()
{
Win8MenuItemButtonElements button;
{
button.mainComposition=new GuiBoundsComposition;
button.mainComposition->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElementAndChildren);
}
{
GuiSolidBorderElement* element=GuiSolidBorderElement::Create();
button.borderElement=element;
GuiBoundsComposition* composition=new GuiBoundsComposition;
button.mainComposition->AddChild(composition);
composition->SetAlignmentToParent(Margin(0, 0, 0, 0));
composition->SetOwnedElement(element);
}
{
GuiGradientBackgroundElement* element=GuiGradientBackgroundElement::Create();
button.backgroundElement=element;
element->SetDirection(GuiGradientBackgroundElement::Vertical);
GuiBoundsComposition* composition=new GuiBoundsComposition;
button.mainComposition->AddChild(composition);
composition->SetAlignmentToParent(Margin(1, 1, 1, 1));
composition->SetOwnedElement(element);
}
{
GuiTableComposition* table=new GuiTableComposition;
button.mainComposition->AddChild(table);
table->SetAlignmentToParent(Margin(2, 0, 2, 0));
table->SetRowsAndColumns(1, 5);
table->SetRowOption(0, GuiCellOption::PercentageOption(1.0));
table->SetColumnOption(0, GuiCellOption::AbsoluteOption(24));
table->SetColumnOption(1, GuiCellOption::AbsoluteOption(1));
table->SetColumnOption(2, GuiCellOption::PercentageOption(1.0));
table->SetColumnOption(3, GuiCellOption::MinSizeOption());
table->SetColumnOption(4, GuiCellOption::AbsoluteOption(10));
{
GuiCellComposition* cell=new GuiCellComposition;
table->AddChild(cell);
cell->SetSite(0, 0, 1, 1);
button.splitterComposition=cell;
GuiImageFrameElement* element=GuiImageFrameElement::Create();
button.imageElement=element;
element->SetStretch(false);
element->SetAlignments(Alignment::Center, Alignment::Center);
cell->SetOwnedElement(element);
}
{
GuiCellComposition* cell=new GuiCellComposition;
table->AddChild(cell);
cell->SetSite(0, 1, 1, 1);
button.splitterComposition=cell;
GuiSolidBorderElement* element=GuiSolidBorderElement::Create();
button.splitterElement=element;
cell->SetOwnedElement(element);
}
{
GuiCellComposition* cell=new GuiCellComposition;
table->AddChild(cell);
cell->SetSite(0, 2, 1, 1);
Win8CreateSolidLabelElement(button.textElement, button.textComposition, L"MenuItem-Text", Alignment::Left, Alignment::Center);
cell->AddChild(button.textComposition);
}
{
GuiCellComposition* cell=new GuiCellComposition;
table->AddChild(cell);
cell->SetSite(0, 3, 1, 1);
Win8CreateSolidLabelElement(button.shortcutElement, button.shortcutComposition, L"MenuItem-Shortcut", Alignment::Right, Alignment::Center);
cell->AddChild(button.shortcutComposition);
}
{
button.subMenuArrowElement=common_styles::CommonFragmentBuilder::BuildRightArrow();
GuiCellComposition* cell=new GuiCellComposition;
button.subMenuArrowComposition=cell;
cell->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElement);
table->AddChild(cell);
cell->SetSite(0, 4, 1, 1);
cell->SetOwnedElement(button.subMenuArrowElement);
cell->SetVisible(false);
}
}
return button;
}
void Win8MenuItemButtonElements::Apply(const Win8ButtonColors& colors)
{
borderElement->SetColor(colors.borderColor);
backgroundElement->SetColors(colors.g1, colors.g2);
splitterElement->SetColor(colors.bullet);
textElement->SetColor(colors.textColor);
shortcutElement->SetColor(colors.textColor);
subMenuArrowElement->SetBackgroundColor(colors.textColor);
subMenuArrowElement->SetBorderColor(colors.textColor);
}
void Win8MenuItemButtonElements::SetActive(bool value)
{
if(value)
{
splitterComposition->SetMargin(Margin(0, 1, 0, 2));
}
else
{
splitterComposition->SetMargin(Margin(0, 0, 0, 0));
}
}
void Win8MenuItemButtonElements::SetSubMenuExisting(bool value)
{
subMenuArrowComposition->SetVisible(value);
}
/***********************************************************************
Win8TextBoxColors
***********************************************************************/
Win8TextBoxColors Win8TextBoxColors::Blend(const Win8TextBoxColors& c1, const Win8TextBoxColors& c2, vint ratio, vint total)
{
if(ratio<0) ratio=0;
else if(ratio>total) ratio=total;
Win8TextBoxColors result;
result.borderColor=BlendColor(c1.borderColor, c2.borderColor, ratio, total);
result.backgroundColor=BlendColor(c1.backgroundColor, c2.backgroundColor, ratio, total);
return result;
}
Win8TextBoxColors Win8TextBoxColors::Normal()
{
Win8TextBoxColors result=
{
Color(171, 173, 179),
Color(255, 255, 255),
};
return result;
}
Win8TextBoxColors Win8TextBoxColors::Active()
{
Win8TextBoxColors result=
{
Color(126, 180, 234),
Color(255, 255, 255),
};
return result;
}
Win8TextBoxColors Win8TextBoxColors::Focused()
{
Win8TextBoxColors result=
{
Color(86, 157, 229),
Color(255, 255, 255),
};
return result;
}
Win8TextBoxColors Win8TextBoxColors::Disabled()
{
Win8TextBoxColors result=
{
Color(217, 217, 217),
Win8GetSystemWindowColor(),
};
return result;
}
/***********************************************************************
Helpers
***********************************************************************/
Color Win8GetSystemWindowColor()
{
return Color(240, 240, 240);
}
Color Win8GetSystemTabContentColor()
{
return Color(255, 255, 255);
}
Color Win8GetSystemBorderColor()
{
return Color(171, 173, 179);
}
Color Win8GetSystemTextColor(bool enabled)
{
return enabled?Color(0, 0, 0):Color(131, 131, 131);
}
Color Win8GetMenuBorderColor()
{
return Color(151, 151, 151);
}
Color Win8GetMenuSplitterColor()
{
return Color(215, 215, 215);
}
void Win8SetFont(GuiSolidLabelElement* element, GuiBoundsComposition* composition, const FontProperties& fontProperties)
{
vint margin=3;
element->SetFont(fontProperties);
composition->SetMargin(Margin(margin, margin, margin, margin));
}
void Win8CreateSolidLabelElement(GuiSolidLabelElement*& element, GuiBoundsComposition*& composition, Alignment horizontal, Alignment vertical)
{
element=GuiSolidLabelElement::Create();
element->SetAlignments(horizontal, vertical);
composition=new GuiBoundsComposition;
composition->SetOwnedElement(element);
composition->SetMargin(Margin(0, 0, 0, 0));
composition->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElement);
composition->SetAlignmentToParent(Margin(0, 0, 0, 0));
}
void Win8CreateSolidLabelElement(elements::GuiSolidLabelElement*& element, compositions::GuiSharedSizeItemComposition*& composition, const WString& group, Alignment horizontal, Alignment vertical)
{
element=GuiSolidLabelElement::Create();
element->SetAlignments(horizontal, vertical);
composition=new GuiSharedSizeItemComposition;
composition->SetGroup(group);
composition->SetSharedWidth(true);
composition->SetOwnedElement(element);
composition->SetMargin(Margin(0, 0, 0, 0));
composition->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElement);
composition->SetAlignmentToParent(Margin(0, 0, 0, 0));
}
elements::text::ColorEntry Win8GetTextBoxTextColor()
{
elements::text::ColorEntry entry;
entry.normal.text=Color(0, 0, 0);
entry.normal.background=Color(0, 0, 0, 0);
entry.selectedFocused.text=Color(255, 255, 255);
entry.selectedFocused.background=Color(51, 153, 255);
entry.selectedUnfocused.text=Color(255, 255, 255);
entry.selectedUnfocused.background=Color(51, 153, 255);
return entry;
}
}
}
} | 27.301538 | 199 | 0.638341 | cameled |
6a1a2e607af3eeede8351b4734ac578d77c68543 | 9,188 | cpp | C++ | libhpx/actions/ffi.cpp | luglio/hpx5 | 6cbeebb8e730ee9faa4487dba31a38e3139e1ce7 | [
"BSD-3-Clause"
] | 1 | 2019-11-05T21:11:32.000Z | 2019-11-05T21:11:32.000Z | libhpx/actions/ffi.cpp | ldalessa/hpx | c8888c38f5c12c27bfd80026d175ceb3839f0b40 | [
"BSD-3-Clause"
] | null | null | null | libhpx/actions/ffi.cpp | ldalessa/hpx | c8888c38f5c12c27bfd80026d175ceb3839f0b40 | [
"BSD-3-Clause"
] | 3 | 2019-06-21T07:05:43.000Z | 2020-11-21T15:24:04.000Z | // =============================================================================
// High Performance ParalleX Library (libhpx)
//
// Copyright (c) 2013-2017, Trustees of Indiana University,
// All rights reserved.
//
// This software may be modified and distributed under the terms of the BSD
// license. See the COPYING file for details.
//
// This software was created at the Indiana University Center for Research in
// Extreme Scale Technologies (CREST).
// =============================================================================
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdlib.h>
#include <hpx/hpx.h>
#include <libhpx/action.h>
#include <libhpx/debug.h>
#include <libhpx/parcel.h>
#include "init.h"
#include "exit.h"
static void _pack_ffi_0(const void *o, hpx_parcel_t *p, int n, va_list *args) {
}
static void _pack_ffi_n(const void *obj, hpx_parcel_t *p, int n, va_list *args)
{
const action_t *action = static_cast<const action_t *>(obj);
const ffi_cif *cif = static_cast<const ffi_cif *>(action->env);
ffi_raw *buffer = static_cast<ffi_raw *>(hpx_parcel_get_data(p));
DEBUG_IF (unsigned(n) != cif->nargs) {
const char *key = action->key;
dbg_error("%s requires %d arguments (%d given).\n", key, cif->nargs, n);
}
// copy the vaargs (pointers) to my stack array, which is what ffi
// wants---this seems wasteful since va_args are likely *already* on my stack,
// but that's not public information
void *argps[n];
for (int i = 0, e = n; i < e; ++i) {
argps[i] = va_arg(*args, void*);
}
// use ffi to copy them to the buffer
ffi_ptrarray_to_raw(const_cast<ffi_cif*>(cif), argps, buffer);
}
static void _pack_pinned_ffi_n(const void *obj, hpx_parcel_t *p, int n,
va_list *args) {
const action_t *action = static_cast<const action_t *>(obj);
const ffi_cif *cif = static_cast<const ffi_cif *>(action->env);
DEBUG_IF (unsigned(n + 1) != cif->nargs) {
const char *key = action->key;
dbg_error("%s requires %d arguments (%d given).\n", key, cif->nargs, n + 1);
}
// Copy the vaargs (pointers) to my stack array, which is what ffi wants,
// adding an extra "slot" for the pinned parameter.
void *argps[++n];
// Special case pinned actions.
//
// ffi actually thinks that it needs to serialize a pointer as its first
// argument. This is the pinned pointer that we need at the call site. We
// don't have this pointer here though, and we don't want to serialize it. No
// matter what we do ffi_ptrarray_to_raw is going to need to process the first
// pointer though.
//
// We cleverly spoof this pointer to be sizeof(void*) bytes off the front of
// the parcel buffer. During serialization, this will cause ffi to overwrite
// the first 8 bytes of the target buffer with the 8 bytes that were there,
// thus no header data is changed and the rest of the payload is handled
// properly.
ffi_raw *buffer = reinterpret_cast<ffi_raw *>(p->buffer - sizeof(void*));
argps[0] = buffer;
// Copy the individual vaargs.
for (int i = 1, e = n; i < e; ++i) {
argps[i] = va_arg(*args, void*);
}
// Use ffi to copy them to the buffer.
ffi_ptrarray_to_raw(const_cast<ffi_cif*>(cif), argps, buffer);
}
static hpx_parcel_t *_new_ffi_0(const void *obj, hpx_addr_t addr,
hpx_addr_t c_addr, hpx_action_t c_action,
int n, va_list *args) {
const action_t *action = static_cast<const action_t *>(obj);
hpx_action_t id = *action->id;
hpx_pid_t pid = hpx_thread_current_pid();
return parcel_new(addr, id, c_addr, c_action, pid, NULL, 0);
}
static hpx_parcel_t *_new_ffi_n(const void *obj, hpx_addr_t addr,
hpx_addr_t c_addr, hpx_action_t c_action,
int n, va_list *args) {
const action_t *action = static_cast<const action_t *>(obj);
hpx_action_t id = *action->id;
hpx_pid_t pid = hpx_thread_current_pid();
ffi_cif *cif = static_cast<ffi_cif *>(action->env);
size_t bytes = ffi_raw_size(cif);
hpx_parcel_t *p = parcel_new(addr, id, c_addr, c_action, pid, NULL, bytes);
_pack_ffi_n(obj, p, n, args);
return p;
}
static hpx_parcel_t *_new_pinned_ffi_n(const void *obj, hpx_addr_t addr,
hpx_addr_t c_addr, hpx_action_t c_action,
int n, va_list *args) {
const action_t *action = static_cast<const action_t *>(obj);
hpx_action_t id = *action->id;
hpx_pid_t pid = hpx_thread_current_pid();
// The ffi cif thinks we're going to send one more pointer than we're actually
// going to send, so we adjust the size before parcel allocation.
ffi_cif *cif = static_cast<ffi_cif *>(action->env);
size_t bytes = ffi_raw_size(cif) - sizeof(void*);
hpx_parcel_t *p = parcel_new(addr, id, c_addr, c_action, pid, NULL, bytes);
_pack_pinned_ffi_n(obj, p, n, args);
return p;
}
static int _exec_ffi_n(const void *obj, hpx_parcel_t *p) {
const action_t *action = static_cast<const action_t *>(obj);
char ffiret[8]; // https://github.com/atgreen/libffi/issues/35
int *ret = (int*)&ffiret[0];
ffi_raw *args = static_cast<ffi_raw *>(hpx_parcel_get_data(p));
ffi_cif *cif = static_cast<ffi_cif*>(action->env);
ffi_raw_call(cif, action->handler, ret, args);
return *ret;
}
static int _exec_pinned_ffi_n(const void *obj, hpx_parcel_t *p) {
void *target;
if (!hpx_gas_try_pin(p->target, &target)) {
log_action("pinned action resend.\n");
return HPX_RESEND;
}
const action_t *action = static_cast<const action_t *>(obj);
// We need to pack a void* array from the parcel data buffer using the ffi cif
// information. ffi thinks that we have one more parameter then we sent in the
// parcel though, the pinned pointer. We roll-back the pointer we give to ffi
// to deal with this---it reads garbage into the first element but we then
// overwrite that with the pointer to the pinned target, so we get the right
// value in the end.
ffi_cif *cif = static_cast<ffi_cif *>(action->env);
ffi_raw *args = reinterpret_cast<ffi_raw *>(p->buffer - sizeof(void*));
void *avalue[cif->nargs];
ffi_raw_to_ptrarray(cif, args, avalue);
avalue[0] = ⌖
char ffiret[8]; // https://github.com/atgreen/libffi/issues/35
int *ret = (int*)&ffiret[0];
ffi_call(cif, action->handler, ret, avalue);
hpx_gas_unpin(p->target);
return *ret;
}
static void _ffi_finish(void *act) {
action_t *action = static_cast<action_t *>(act);
log_action("%d: %s (%p) %s %x.\n", *action->id, action->key,
(void*)(uintptr_t)action->handler,
HPX_ACTION_TYPE_TO_STRING[action->type],
action->attr);
}
static void _ffi_fini(void *act) {
action_t *action = static_cast<action_t *>(act);
ffi_cif *cif = static_cast<ffi_cif *>(action->env);
free(cif->arg_types);
free(action->env);
}
static const parcel_management_vtable_t _ffi_0_vtable = {
.exec_parcel = _exec_ffi_n,
.pack_parcel = _pack_ffi_0,
.new_parcel = _new_ffi_0,
.exit = exit_action
};
static const parcel_management_vtable_t _pinned_ffi_0_vtable = {
.exec_parcel = _exec_pinned_ffi_n,
.pack_parcel = _pack_ffi_0,
.new_parcel = _new_ffi_0,
.exit = exit_pinned_action
};
static const parcel_management_vtable_t _ffi_n_vtable = {
.exec_parcel = _exec_ffi_n,
.pack_parcel = _pack_ffi_n,
.new_parcel = _new_ffi_n,
.exit = exit_action
};
static const parcel_management_vtable_t _pinned_ffi_n_vtable = {
.exec_parcel = _exec_pinned_ffi_n,
.pack_parcel = _pack_pinned_ffi_n,
.new_parcel = _new_pinned_ffi_n,
.exit = exit_pinned_action
};
void action_init_ffi(action_t *action, int n, va_list *vargs) {
// Translate the argument types into a stack allocated buffer suitable for use
// with ffi.
hpx_type_t *args = static_cast<hpx_type_t *>(calloc(n, sizeof(args[0])));
for (int i = 0; i < n; ++i) {
args[i] = va_arg(*vargs, hpx_type_t);
}
// Check to make sure that pinned actions start with a pointer type.
uint32_t pinned = action->attr & HPX_PINNED;
if (pinned && (args[0] != HPX_POINTER)) {
dbg_error("First type of a pinned action should be HPX_POINTER\n");
}
// Allocate and initialize an ffi_cif, which is the structure that ffi uses to
// encode calling conventions.
action->env = calloc(1, sizeof(ffi_cif));
dbg_assert(action->env);
ffi_cif *cif = static_cast<ffi_cif *>(action->env);
ffi_status s = ffi_prep_cif(cif, FFI_DEFAULT_ABI, n, HPX_INT, args);
if (s != FFI_OK) {
dbg_error("failed to process type information for action id %d.\n",
*action->id);
}
// Initialize the parcel class.
if (pinned && cif->nargs > 1) {
action->parcel_class = &_pinned_ffi_n_vtable;
}
else if (pinned) {
action->parcel_class = &_pinned_ffi_0_vtable;
}
else if (cif->nargs) {
action->parcel_class = &_ffi_n_vtable;
}
else {
action->parcel_class = &_ffi_0_vtable;
}
// Initialize the action class.
action_init_call_by_parcel(action);
// Initialize the destructor.
action->fini = _ffi_fini;
action->finish = _ffi_finish;
}
| 36.031373 | 80 | 0.665215 | luglio |
6a1b8aecfcec3c9417b62bc147408795cf20b728 | 643 | cpp | C++ | src/sprite/delete_closet.cpp | Damdoshi/LibLapin | 800e0f17ed8f3c47797c48feea4c280bb0e4bdc9 | [
"BSD-3-Clause"
] | 38 | 2016-07-30T09:35:19.000Z | 2022-03-04T10:13:48.000Z | src/sprite/delete_closet.cpp | Elania-Marvers/LibLapin | 800e0f17ed8f3c47797c48feea4c280bb0e4bdc9 | [
"BSD-3-Clause"
] | 15 | 2017-02-12T19:20:52.000Z | 2021-06-09T09:30:52.000Z | src/sprite/delete_closet.cpp | Elania-Marvers/LibLapin | 800e0f17ed8f3c47797c48feea4c280bb0e4bdc9 | [
"BSD-3-Clause"
] | 12 | 2016-10-06T09:06:59.000Z | 2022-03-04T10:14:00.000Z | // Jason Brillante "Damdoshi"
// Hanged Bunny Studio 2014-2018
//
// Lapin library
#include "lapin_private.h"
static void delete_clothe(t_bunny_map *nod,
void *param)
{
t_bunny_clothe *clo;
(void)param;
if ((clo = bunny_map_data(nod, t_bunny_clothe*)) != NULL)
{
bunny_free((void*)clo->name);
bunny_delete_clipable(&clo->sprite->clipable);
bunny_free(clo);
}
}
void bunny_delete_closet(t_bunny_closet *closet)
{
bunny_map_foreach(closet->clothes, delete_clothe, NULL);
bunny_delete_map(closet->clothes);
if (closet->name)
bunny_free((void*)closet->name);
bunny_free(closet);
}
| 20.741935 | 59 | 0.676516 | Damdoshi |
6a1bfbbccb76da017cae638af4f22aa549db0852 | 10,143 | cpp | C++ | programs/library-bridge/Handlers.cpp | tianyiYoung/ClickHouse | 41012b5ba49df807af52fc17ab475a21fadda9b3 | [
"Apache-2.0"
] | 5 | 2021-05-14T02:46:44.000Z | 2021-11-23T04:58:20.000Z | programs/library-bridge/Handlers.cpp | tianyiYoung/ClickHouse | 41012b5ba49df807af52fc17ab475a21fadda9b3 | [
"Apache-2.0"
] | 5 | 2021-05-21T06:26:01.000Z | 2021-08-04T04:57:36.000Z | programs/library-bridge/Handlers.cpp | tianyiYoung/ClickHouse | 41012b5ba49df807af52fc17ab475a21fadda9b3 | [
"Apache-2.0"
] | 8 | 2021-05-12T01:38:18.000Z | 2022-02-10T06:08:41.000Z | #include "Handlers.h"
#include "SharedLibraryHandlerFactory.h"
#include <DataStreams/copyData.h>
#include <Formats/FormatFactory.h>
#include <Server/HTTP/WriteBufferFromHTTPServerResponse.h>
#include <IO/WriteHelpers.h>
#include <IO/ReadHelpers.h>
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/Net/HTTPServerResponse.h>
#include <Poco/Net/HTMLForm.h>
#include <Poco/ThreadPool.h>
#include <Processors/Formats/InputStreamFromInputFormat.h>
#include <Server/HTTP/HTMLForm.h>
#include <IO/ReadBufferFromString.h>
namespace DB
{
namespace
{
std::shared_ptr<Block> parseColumns(std::string && column_string)
{
auto sample_block = std::make_shared<Block>();
auto names_and_types = NamesAndTypesList::parse(column_string);
for (const NameAndTypePair & column_data : names_and_types)
sample_block->insert({column_data.type, column_data.name});
return sample_block;
}
std::vector<uint64_t> parseIdsFromBinary(const std::string & ids_string)
{
ReadBufferFromString buf(ids_string);
std::vector<uint64_t> ids;
readVectorBinary(ids, buf);
return ids;
}
std::vector<std::string> parseNamesFromBinary(const std::string & names_string)
{
ReadBufferFromString buf(names_string);
std::vector<std::string> names;
readVectorBinary(names, buf);
return names;
}
}
void LibraryRequestHandler::handleRequest(HTTPServerRequest & request, HTTPServerResponse & response)
{
LOG_TRACE(log, "Request URI: {}", request.getURI());
HTMLForm params(request);
if (!params.has("method"))
{
processError(response, "No 'method' in request URL");
return;
}
if (!params.has("dictionary_id"))
{
processError(response, "No 'dictionary_id in request URL");
return;
}
std::string method = params.get("method");
std::string dictionary_id = params.get("dictionary_id");
LOG_TRACE(log, "Library method: '{}', dictionary id: {}", method, dictionary_id);
WriteBufferFromHTTPServerResponse out(response, request.getMethod() == Poco::Net::HTTPRequest::HTTP_HEAD, keep_alive_timeout);
try
{
if (method == "libNew")
{
auto & read_buf = request.getStream();
params.read(read_buf);
if (!params.has("library_path"))
{
processError(response, "No 'library_path' in request URL");
return;
}
if (!params.has("library_settings"))
{
processError(response, "No 'library_settings' in request URL");
return;
}
std::string library_path = params.get("library_path");
const auto & settings_string = params.get("library_settings");
std::vector<std::string> library_settings = parseNamesFromBinary(settings_string);
/// Needed for library dictionary
if (!params.has("attributes_names"))
{
processError(response, "No 'attributes_names' in request URL");
return;
}
const auto & attributes_string = params.get("attributes_names");
std::vector<std::string> attributes_names = parseNamesFromBinary(attributes_string);
/// Needed to parse block from binary string format
if (!params.has("sample_block"))
{
processError(response, "No 'sample_block' in request URL");
return;
}
std::string sample_block_string = params.get("sample_block");
std::shared_ptr<Block> sample_block;
try
{
sample_block = parseColumns(std::move(sample_block_string));
}
catch (const Exception & ex)
{
processError(response, "Invalid 'sample_block' parameter in request body '" + ex.message() + "'");
LOG_WARNING(log, ex.getStackTraceString());
return;
}
if (!params.has("null_values"))
{
processError(response, "No 'null_values' in request URL");
return;
}
ReadBufferFromString read_block_buf(params.get("null_values"));
auto format = FormatFactory::instance().getInput(FORMAT, read_block_buf, *sample_block, getContext(), DEFAULT_BLOCK_SIZE);
auto reader = std::make_shared<InputStreamFromInputFormat>(format);
auto sample_block_with_nulls = reader->read();
LOG_DEBUG(log, "Dictionary sample block with null values: {}", sample_block_with_nulls.dumpStructure());
SharedLibraryHandlerFactory::instance().create(dictionary_id, library_path, library_settings, sample_block_with_nulls, attributes_names);
writeStringBinary("1", out);
}
else if (method == "libClone")
{
if (!params.has("from_dictionary_id"))
{
processError(response, "No 'from_dictionary_id' in request URL");
return;
}
std::string from_dictionary_id = params.get("from_dictionary_id");
LOG_TRACE(log, "Calling libClone from {} to {}", from_dictionary_id, dictionary_id);
SharedLibraryHandlerFactory::instance().clone(from_dictionary_id, dictionary_id);
writeStringBinary("1", out);
}
else if (method == "libDelete")
{
SharedLibraryHandlerFactory::instance().remove(dictionary_id);
writeStringBinary("1", out);
}
else if (method == "isModified")
{
auto library_handler = SharedLibraryHandlerFactory::instance().get(dictionary_id);
bool res = library_handler->isModified();
writeStringBinary(std::to_string(res), out);
}
else if (method == "supportsSelectiveLoad")
{
auto library_handler = SharedLibraryHandlerFactory::instance().get(dictionary_id);
bool res = library_handler->supportsSelectiveLoad();
writeStringBinary(std::to_string(res), out);
}
else if (method == "loadAll")
{
auto library_handler = SharedLibraryHandlerFactory::instance().get(dictionary_id);
const auto & sample_block = library_handler->getSampleBlock();
auto input = library_handler->loadAll();
BlockOutputStreamPtr output = FormatFactory::instance().getOutputStream(FORMAT, out, sample_block, getContext());
copyData(*input, *output);
}
else if (method == "loadIds")
{
params.read(request.getStream());
if (!params.has("ids"))
{
processError(response, "No 'ids' in request URL");
return;
}
std::vector<uint64_t> ids = parseIdsFromBinary(params.get("ids"));
auto library_handler = SharedLibraryHandlerFactory::instance().get(dictionary_id);
const auto & sample_block = library_handler->getSampleBlock();
auto input = library_handler->loadIds(ids);
BlockOutputStreamPtr output = FormatFactory::instance().getOutputStream(FORMAT, out, sample_block, getContext());
copyData(*input, *output);
}
else if (method == "loadKeys")
{
if (!params.has("requested_block_sample"))
{
processError(response, "No 'requested_block_sample' in request URL");
return;
}
std::string requested_block_string = params.get("requested_block_sample");
std::shared_ptr<Block> requested_sample_block;
try
{
requested_sample_block = parseColumns(std::move(requested_block_string));
}
catch (const Exception & ex)
{
processError(response, "Invalid 'requested_block' parameter in request body '" + ex.message() + "'");
LOG_WARNING(log, ex.getStackTraceString());
return;
}
auto & read_buf = request.getStream();
auto format = FormatFactory::instance().getInput(FORMAT, read_buf, *requested_sample_block, getContext(), DEFAULT_BLOCK_SIZE);
auto reader = std::make_shared<InputStreamFromInputFormat>(format);
auto block = reader->read();
auto library_handler = SharedLibraryHandlerFactory::instance().get(dictionary_id);
const auto & sample_block = library_handler->getSampleBlock();
auto input = library_handler->loadKeys(block.getColumns());
BlockOutputStreamPtr output = FormatFactory::instance().getOutputStream(FORMAT, out, sample_block, getContext());
copyData(*input, *output);
}
}
catch (...)
{
auto message = getCurrentExceptionMessage(true);
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR, message); // can't call process_error, because of too soon response sending
try
{
writeStringBinary(message, out);
out.finalize();
}
catch (...)
{
tryLogCurrentException(log);
}
tryLogCurrentException(log);
}
try
{
out.finalize();
}
catch (...)
{
tryLogCurrentException(log);
}
}
void LibraryRequestHandler::processError(HTTPServerResponse & response, const std::string & message)
{
response.setStatusAndReason(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
if (!response.sent())
*response.send() << message << std::endl;
LOG_WARNING(log, message);
}
void PingHandler::handleRequest(HTTPServerRequest & /* request */, HTTPServerResponse & response)
{
try
{
setResponseDefaultHeaders(response, keep_alive_timeout);
const char * data = "Ok.\n";
response.sendBuffer(data, strlen(data));
}
catch (...)
{
tryLogCurrentException("PingHandler");
}
}
}
| 35.096886 | 164 | 0.605935 | tianyiYoung |
6a1d4e97c7004eccf8e1038bd0946e8e2b78fe99 | 1,618 | cc | C++ | syntaxnet/dragnn/core/resource_container_test.cc | FrancisTembo/tensorflow-models | 042f74690d0cf412cb6b7fc19f4a41afdf547905 | [
"Apache-2.0"
] | 58 | 2017-04-21T02:52:30.000Z | 2021-03-08T18:58:52.000Z | syntaxnet/dragnn/core/resource_container_test.cc | FrancisTembo/tensorflow-models | 042f74690d0cf412cb6b7fc19f4a41afdf547905 | [
"Apache-2.0"
] | 1 | 2017-03-19T20:12:15.000Z | 2017-03-20T14:25:54.000Z | syntaxnet/dragnn/core/resource_container_test.cc | FrancisTembo/tensorflow-models | 042f74690d0cf412cb6b7fc19f4a41afdf547905 | [
"Apache-2.0"
] | 60 | 2016-12-27T12:00:37.000Z | 2022-03-11T17:35:11.000Z | // Tests the methods of ResourceContainer.
//
// NOTE(danielandor): For all tests: ResourceContainer is derived from
// RefCounted, which requires the use of Unref to reduce the ref count
// to zero and automatically delete the pointer.
#include "dragnn/core/resource_container.h"
#include <gmock/gmock.h>
#include "tensorflow/core/platform/test.h"
namespace syntaxnet {
namespace dragnn {
class MockDatatype {};
TEST(ResourceContainerTest, Get) {
std::unique_ptr<MockDatatype> data(new MockDatatype());
MockDatatype *data_ptr = data.get();
auto *container = new ResourceContainer<MockDatatype>(std::move(data));
EXPECT_EQ(data_ptr, container->get());
container->Unref();
}
TEST(ResourceContainerTest, Release) {
std::unique_ptr<MockDatatype> data(new MockDatatype());
MockDatatype *data_ptr = data.get();
auto *container = new ResourceContainer<MockDatatype>(std::move(data));
std::unique_ptr<MockDatatype> data_again = container->release();
container->Unref();
EXPECT_EQ(data_ptr, data_again.get());
}
TEST(ResourceContainerTest, NullptrOnGetAfterRelease) {
std::unique_ptr<MockDatatype> data(new MockDatatype());
auto *container = new ResourceContainer<MockDatatype>(std::move(data));
container->release();
EXPECT_EQ(nullptr, container->get());
container->Unref();
}
TEST(ResourceContainerTest, DebugString) {
std::unique_ptr<MockDatatype> data(new MockDatatype());
auto *container = new ResourceContainer<MockDatatype>(std::move(data));
EXPECT_EQ("ResourceContainer", container->DebugString());
container->Unref();
}
} // namespace dragnn
} // namespace syntaxnet
| 32.36 | 73 | 0.747219 | FrancisTembo |
6a1fb4b39ef750f05eb9398360bfd31870cbc9a4 | 687 | cpp | C++ | hackerrank/practice/mathematics/geometry/sherlock_and_geometry.cpp | Loks-/competitions | 3bb231ba9dd62447048832f45b09141454a51926 | [
"MIT"
] | 4 | 2018-06-05T14:15:52.000Z | 2022-02-08T05:14:23.000Z | hackerrank/practice/mathematics/geometry/sherlock_and_geometry.cpp | Loks-/competitions | 3bb231ba9dd62447048832f45b09141454a51926 | [
"MIT"
] | null | null | null | hackerrank/practice/mathematics/geometry/sherlock_and_geometry.cpp | Loks-/competitions | 3bb231ba9dd62447048832f45b09141454a51926 | [
"MIT"
] | 1 | 2018-10-21T11:01:35.000Z | 2018-10-21T11:01:35.000Z | // https://www.hackerrank.com/challenges/sherlock-and-geometry
#include "common/geometry/d2/circle_int_io.h"
#include "common/geometry/d2/point_io.h"
#include "common/geometry/d2/segment.h"
#include "common/geometry/d2/utils/intersect_segment_icircle.h"
#include "common/stl/base.h"
#include "common/vector/read.h"
int main_sherlock_and_geometry() {
unsigned T;
cin >> T;
for (unsigned it = 0; it < T; ++it) {
I2Circle c;
cin >> c;
auto vp = nvector::Read<I2Point>(3);
bool b = false;
for (unsigned i = 0; i < 3; ++i) {
if (Intersect(I2ClosedSegment(vp[i], vp[(i + 1) % 3]), c)) b = true;
}
cout << (b ? "YES" : "NO") << endl;
}
return 0;
}
| 27.48 | 74 | 0.633188 | Loks- |
6a21c6ae556f6b8442dbb57c5e506ce1badaefa8 | 584 | hpp | C++ | include/mexcppclass/matlab/classid.hpp | rymut/mexcppclass | a6a1873a4c4d4f588490d3dc070cb7500fb82214 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-07-28T23:59:48.000Z | 2019-07-28T23:59:48.000Z | include/mexcppclass/matlab/classid.hpp | rymut/mexcppclass | a6a1873a4c4d4f588490d3dc070cb7500fb82214 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | include/mexcppclass/matlab/classid.hpp | rymut/mexcppclass | a6a1873a4c4d4f588490d3dc070cb7500fb82214 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2017-08-25T03:02:36.000Z | 2020-04-08T17:02:42.000Z | /// Copyright (C) 2017 by Boguslaw Rymut
///
/// This file is distributed under the Apache 2.0 License
/// See LICENSE for details.
#ifndef MEXCPPCLASS_MATLAB_CLASSID_HPP_
#define MEXCPPCLASS_MATLAB_CLASSID_HPP_
namespace mexcppclass {
namespace matlab {
enum class ClassId {
Single,
Double,
Char,
String,
Logical,
Int8,
Int16,
Int32,
Int64,
Uint8,
Uint16,
Uint32,
Uint64,
Numeric,
Scalar,
Struct,
Cell,
Table
};
} // namespace matlab
} // namespace mexcppclass
#endif // MEXCPPCLASS_MATLAB_CLASSID_HPP_
| 15.783784 | 58 | 0.664384 | rymut |
6a229df7189b2fc4388d0d4a28261b3836be1dfc | 4,036 | hpp | C++ | ios/Pods/boost-for-react-native/boost/log/detail/locking_ptr.hpp | rudylee/expo | b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc | [
"Apache-2.0",
"MIT"
] | 8,805 | 2015-11-03T00:52:29.000Z | 2022-03-29T22:30:03.000Z | ios/Pods/boost-for-react-native/boost/log/detail/locking_ptr.hpp | rudylee/expo | b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc | [
"Apache-2.0",
"MIT"
] | 14,694 | 2015-02-24T15:13:42.000Z | 2022-03-31T13:16:45.000Z | ios/Pods/boost-for-react-native/boost/log/detail/locking_ptr.hpp | rudylee/expo | b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc | [
"Apache-2.0",
"MIT"
] | 1,329 | 2015-11-03T20:25:51.000Z | 2022-03-31T18:10:38.000Z | /*
* Copyright Andrey Semashev 2007 - 2015.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
/*!
* \file locking_ptr.hpp
* \author Andrey Semashev
* \date 15.07.2009
*
* This header is the Boost.Log library implementation, see the library documentation
* at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
*/
#ifndef BOOST_LOG_DETAIL_LOCKING_PTR_HPP_INCLUDED_
#define BOOST_LOG_DETAIL_LOCKING_PTR_HPP_INCLUDED_
#include <cstddef>
#include <boost/move/core.hpp>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/thread/lock_options.hpp>
#include <boost/log/detail/config.hpp>
#include <boost/utility/explicit_operator_bool.hpp>
#include <boost/log/detail/header.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
namespace boost {
BOOST_LOG_OPEN_NAMESPACE
namespace aux {
//! A pointer type that locks the backend until it's destroyed
template< typename T, typename LockableT >
class locking_ptr
{
typedef locking_ptr this_type;
BOOST_COPYABLE_AND_MOVABLE_ALT(this_type)
public:
//! Pointed type
typedef T element_type;
private:
//! Lockable type
typedef LockableT lockable_type;
private:
//! The pointer to the backend
shared_ptr< element_type > m_pElement;
//! Reference to the shared lock control object
lockable_type* m_pLock;
public:
//! Default constructor
locking_ptr() BOOST_NOEXCEPT : m_pLock(NULL)
{
}
//! Constructor
locking_ptr(shared_ptr< element_type > const& p, lockable_type& l) : m_pElement(p), m_pLock(&l)
{
m_pLock->lock();
}
//! Constructor
locking_ptr(shared_ptr< element_type > const& p, lockable_type& l, try_to_lock_t const&) : m_pElement(p), m_pLock(&l)
{
if (!m_pLock->try_lock())
{
m_pElement.reset();
m_pLock = NULL;
}
}
//! Copy constructor
locking_ptr(locking_ptr const& that) : m_pElement(that.m_pElement), m_pLock(that.m_pLock)
{
if (m_pLock)
m_pLock->lock();
}
//! Move constructor
locking_ptr(BOOST_RV_REF(this_type) that) BOOST_NOEXCEPT : m_pLock(that.m_pLock)
{
m_pElement.swap(that.m_pElement);
that.m_pLock = NULL;
}
//! Destructor
~locking_ptr()
{
if (m_pLock)
m_pLock->unlock();
}
//! Assignment
locking_ptr& operator= (locking_ptr that) BOOST_NOEXCEPT
{
this->swap(that);
return *this;
}
//! Indirection
element_type* operator-> () const BOOST_NOEXCEPT { return m_pElement.get(); }
//! Dereferencing
element_type& operator* () const BOOST_NOEXCEPT { return *m_pElement; }
//! Accessor to the raw pointer
element_type* get() const BOOST_NOEXCEPT { return m_pElement.get(); }
//! Checks for null pointer
BOOST_EXPLICIT_OPERATOR_BOOL_NOEXCEPT()
//! Checks for null pointer
bool operator! () const BOOST_NOEXCEPT { return !m_pElement; }
//! Swaps two pointers
void swap(locking_ptr& that) BOOST_NOEXCEPT
{
m_pElement.swap(that.m_pElement);
lockable_type* p = m_pLock;
m_pLock = that.m_pLock;
that.m_pLock = p;
}
};
//! Free raw pointer getter to assist generic programming
template< typename T, typename LockableT >
inline T* get_pointer(locking_ptr< T, LockableT > const& p) BOOST_NOEXCEPT
{
return p.get();
}
//! Free swap operation
template< typename T, typename LockableT >
inline void swap(locking_ptr< T, LockableT >& left, locking_ptr< T, LockableT >& right) BOOST_NOEXCEPT
{
left.swap(right);
}
} // namespace aux
BOOST_LOG_CLOSE_NAMESPACE // namespace log
} // namespace boost
#include <boost/log/detail/footer.hpp>
#endif // BOOST_LOG_DETAIL_LOCKING_PTR_HPP_INCLUDED_
| 27.087248 | 122 | 0.654361 | rudylee |
6a242b9f1718c727d87f0c99120d0fffbfcd02cd | 823 | cpp | C++ | opencl/source/xe_hpc_core/gtpin_setup_xe_hpc_core.cpp | mattcarter2017/compute-runtime | 1f52802aac02c78c19d5493dd3a2402830bbe438 | [
"Intel",
"MIT"
] | null | null | null | opencl/source/xe_hpc_core/gtpin_setup_xe_hpc_core.cpp | mattcarter2017/compute-runtime | 1f52802aac02c78c19d5493dd3a2402830bbe438 | [
"Intel",
"MIT"
] | null | null | null | opencl/source/xe_hpc_core/gtpin_setup_xe_hpc_core.cpp | mattcarter2017/compute-runtime | 1f52802aac02c78c19d5493dd3a2402830bbe438 | [
"Intel",
"MIT"
] | null | null | null | /*
* Copyright (C) 2021-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "opencl/source/gtpin/gtpin_hw_helper.h"
#include "opencl/source/gtpin/gtpin_hw_helper.inl"
#include "opencl/source/gtpin/gtpin_hw_helper_xehp_and_later.inl"
#include "ocl_igc_shared/gtpin/gtpin_ocl_interface.h"
namespace NEO {
extern GTPinHwHelper *gtpinHwHelperFactory[IGFX_MAX_CORE];
using Family = XE_HPC_COREFamily;
static const auto gfxFamily = IGFX_XE_HPC_CORE;
template class GTPinHwHelperHw<Family>;
struct GTPinEnableXeHpcCore {
GTPinEnableXeHpcCore() {
gtpinHwHelperFactory[gfxFamily] = >PinHwHelperHw<Family>::get();
}
};
template <>
uint32_t GTPinHwHelperHw<Family>::getGenVersion() {
return gtpin::GTPIN_XE_HPC_CORE;
}
static GTPinEnableXeHpcCore gtpinEnable;
} // namespace NEO
| 22.243243 | 74 | 0.771567 | mattcarter2017 |
6a2a6457c1b4d0022fefb30b4c5bfa7814284e04 | 152,503 | cpp | C++ | src/Scripts.cpp | TijmenUU/VVVVVV | ce6c07c800f3dce98e0bd40f32311b98a01a4cd6 | [
"RSA-MD"
] | null | null | null | src/Scripts.cpp | TijmenUU/VVVVVV | ce6c07c800f3dce98e0bd40f32311b98a01a4cd6 | [
"RSA-MD"
] | null | null | null | src/Scripts.cpp | TijmenUU/VVVVVV | ce6c07c800f3dce98e0bd40f32311b98a01a4cd6 | [
"RSA-MD"
] | null | null | null | #ifndef SCRIPTS_H
#define SCRIPTS_H
#include <Script.hpp>
#include <algorithm>
extern scriptclass script;
void scriptclass::load(std::string t)
{
//loads script name t into the array
position = 0;
scriptlength = 0;
running = true;
int maxlength = (std::min(int(t.length()), 7));
std::string customstring = "";
for(int i = 0; i < maxlength; i++)
{
customstring += t[i];
}
if(customstring == "custom_")
{
//this magic function breaks down the custom script and turns into real scripting!
std::string cscriptname = "";
for(size_t i = 0; i < t.length(); i++)
{
if(i >= 7)
cscriptname += t[i];
}
int scriptstart = -1;
int scriptend = -1;
std::string tstring;
for(size_t i = 0; i < customscript.size(); i++)
{
if(scriptstart == -1)
{
//Find start of the script
if(script.customscript[i] == cscriptname + ":")
{
scriptstart = i + 1;
}
}
else if(scriptend == -1)
{
//Find the end
tstring = script.customscript[i];
tstring = tstring[tstring.size() - 1];
if(tstring == ":")
{
scriptend = i;
}
}
}
if(scriptstart > -1)
{
if(scriptend == -1)
{
scriptend = customscript.size();
}
//Ok, we've got the relavent script segment, we do a pass to assess it, then run it!
int customcutscenemode = 0;
for(int i = scriptstart; i < scriptend; i++)
{
tokenize(script.customscript[i]);
if(words[0] == "say")
{
customcutscenemode = 1;
}
else if(words[0] == "reply")
{
customcutscenemode = 1;
}
}
if(customcutscenemode == 1)
{
add("cutscene()");
add("untilbars()");
}
int customtextmode = 0;
int speakermode = 0; //0, terminal, numbers for crew
int squeakmode = 0; //default on
//Now run the script
for(int i = scriptstart; i < scriptend; i++)
{
words[0] = "nothing"; //Default!
words[1] = "1"; //Default!
tokenize(script.customscript[i]);
std::transform(words[0].begin(), words[0].end(), words[0].begin(), ::tolower);
if(words[0] == "music")
{
if(customtextmode == 1)
{
add("endtext");
customtextmode = 0;
}
if(words[1] == "0")
{
tstring = "stopmusic()";
}
else
{
if(words[1] == "11")
{
tstring = "play(14)";
}
else if(words[1] == "10")
{
tstring = "play(13)";
}
else if(words[1] == "9")
{
tstring = "play(12)";
}
else if(words[1] == "8")
{
tstring = "play(11)";
}
else if(words[1] == "7")
{
tstring = "play(10)";
}
else if(words[1] == "6")
{
tstring = "play(8)";
}
else if(words[1] == "5")
{
tstring = "play(6)";
}
else
{
tstring = "play(" + words[1] + ")";
}
}
add(tstring);
}
else if(words[0] == "playremix")
{
add("play(15)");
}
else if(words[0] == "flash")
{
if(customtextmode == 1)
{
add("endtext");
customtextmode = 0;
}
add("flash(5)");
add("shake(20)");
add("playef(9,10)");
}
else if(words[0] == "sad" || words[0] == "cry")
{
if(customtextmode == 1)
{
add("endtext");
customtextmode = 0;
}
if(words[1] == "player")
{
add("changemood(player,1)");
}
else if(words[1] == "cyan" || words[1] == "viridian" || words[1] == "1")
{
add("changecustommood(customcyan,1)");
}
else if(words[1] == "purple" || words[1] == "violet" || words[1] == "pink" || words[1] == "2")
{
add("changecustommood(purple,1)");
}
else if(words[1] == "yellow" || words[1] == "vitellary" || words[1] == "3")
{
add("changecustommood(yellow,1)");
}
else if(words[1] == "red" || words[1] == "vermilion" || words[1] == "4")
{
add("changecustommood(red,1)");
}
else if(words[1] == "green" || words[1] == "verdigris" || words[1] == "5")
{
add("changecustommood(green,1)");
}
else if(words[1] == "blue" || words[1] == "victoria" || words[1] == "6")
{
add("changecustommood(blue,1)");
}
else if(words[1] == "all" || words[1] == "everybody" || words[1] == "everyone")
{
add("changemood(player,1)");
add("changecustommood(customcyan,1)");
add("changecustommood(purple,1)");
add("changecustommood(yellow,1)");
add("changecustommood(red,1)");
add("changecustommood(green,1)");
add("changecustommood(blue,1)");
}
else
{
add("changemood(player,1)");
}
if(squeakmode == 0)
add("squeak(cry)");
}
else if(words[0] == "happy")
{
if(customtextmode == 1)
{
add("endtext");
customtextmode = 0;
}
if(words[1] == "player")
{
add("changemood(player,0)");
if(squeakmode == 0)
add("squeak(player)");
}
else if(words[1] == "cyan" || words[1] == "viridian" || words[1] == "1")
{
add("changecustommood(customcyan,0)");
if(squeakmode == 0)
add("squeak(player)");
}
else if(words[1] == "purple" || words[1] == "violet" || words[1] == "pink" || words[1] == "2")
{
add("changecustommood(purple,0)");
if(squeakmode == 0)
add("squeak(purple)");
}
else if(words[1] == "yellow" || words[1] == "vitellary" || words[1] == "3")
{
add("changecustommood(yellow,0)");
if(squeakmode == 0)
add("squeak(yellow)");
}
else if(words[1] == "red" || words[1] == "vermilion" || words[1] == "4")
{
add("changecustommood(red,0)");
if(squeakmode == 0)
add("squeak(red)");
}
else if(words[1] == "green" || words[1] == "verdigris" || words[1] == "5")
{
add("changecustommood(green,0)");
if(squeakmode == 0)
add("squeak(green)");
}
else if(words[1] == "blue" || words[1] == "victoria" || words[1] == "6")
{
add("changecustommood(blue,0)");
if(squeakmode == 0)
add("squeak(blue)");
}
else if(words[1] == "all" || words[1] == "everybody" || words[1] == "everyone")
{
add("changemood(player,0)");
add("changecustommood(customcyan,0)");
add("changecustommood(purple,0)");
add("changecustommood(yellow,0)");
add("changecustommood(red,0)");
add("changecustommood(green,0)");
add("changecustommood(blue,0)");
}
else
{
add("changemood(player,0)");
if(squeakmode == 0)
add("squeak(player)");
}
}
else if(words[0] == "squeak")
{
if(customtextmode == 1)
{
add("endtext");
customtextmode = 0;
}
if(words[1] == "player")
{
add("squeak(player)");
}
else if(words[1] == "cyan" || words[1] == "viridian" || words[1] == "1")
{
add("squeak(player)");
}
else if(words[1] == "purple" || words[1] == "violet" || words[1] == "pink" || words[1] == "2")
{
add("squeak(purple)");
}
else if(words[1] == "yellow" || words[1] == "vitellary" || words[1] == "3")
{
add("squeak(yellow)");
}
else if(words[1] == "red" || words[1] == "vermilion" || words[1] == "4")
{
add("squeak(red)");
}
else if(words[1] == "green" || words[1] == "verdigris" || words[1] == "5")
{
add("squeak(green)");
}
else if(words[1] == "blue" || words[1] == "victoria" || words[1] == "6")
{
add("squeak(blue)");
}
else if(words[1] == "cry" || words[1] == "sad")
{
add("squeak(cry)");
}
else if(words[1] == "on")
{
squeakmode = 0;
}
else if(words[1] == "off")
{
squeakmode = 1;
}
}
else if(words[0] == "delay")
{
if(customtextmode == 1)
{
add("endtext");
customtextmode = 0;
}
add(script.customscript[i]);
}
else if(words[0] == "flag")
{
if(customtextmode == 1)
{
add("endtext");
customtextmode = 0;
}
add(script.customscript[i]);
}
else if(words[0] == "map")
{
if(customtextmode == 1)
{
add("endtext");
customtextmode = 0;
}
add("custom" + script.customscript[i]);
}
else if(words[0] == "warpdir")
{
if(customtextmode == 1)
{
add("endtext");
customtextmode = 0;
}
add(script.customscript[i]);
}
else if(words[0] == "ifwarp")
{
if(customtextmode == 1)
{
add("endtext");
customtextmode = 0;
}
add(script.customscript[i]);
}
else if(words[0] == "iftrinkets")
{
if(customtextmode == 1)
{
add("endtext");
customtextmode = 0;
}
add("custom" + script.customscript[i]);
}
else if(words[0] == "ifflag")
{
if(customtextmode == 1)
{
add("endtext");
customtextmode = 0;
}
add("custom" + script.customscript[i]);
}
else if(words[0] == "iftrinketsless")
{
if(customtextmode == 1)
{
add("endtext");
customtextmode = 0;
}
add("custom" + script.customscript[i]);
}
else if(words[0] == "destroy")
{
if(customtextmode == 1)
{
add("endtext");
customtextmode = 0;
}
if(words[1] == "gravitylines")
{
add("destroy(gravitylines)");
}
else if(words[1] == "warptokens")
{
add("destroy(warptokens)");
}
else if(words[1] == "platforms")
{
add("destroy(platforms)");
}
}
else if(words[0] == "speaker")
{
speakermode = 0;
if(words[1] == "gray" || words[1] == "grey" || words[1] == "terminal" || words[1] == "0")
speakermode = 0;
if(words[1] == "cyan" || words[1] == "viridian" || words[1] == "player" || words[1] == "1")
speakermode = 1;
if(words[1] == "purple" || words[1] == "violet" || words[1] == "pink" || words[1] == "2")
speakermode = 2;
if(words[1] == "yellow" || words[1] == "vitellary" || words[1] == "3")
speakermode = 3;
if(words[1] == "red" || words[1] == "vermilion" || words[1] == "4")
speakermode = 4;
if(words[1] == "green" || words[1] == "verdigris" || words[1] == "5")
speakermode = 5;
if(words[1] == "blue" || words[1] == "victoria" || words[1] == "6")
speakermode = 6;
}
else if(words[0] == "say")
{
//Speakers!
if(words[2] == "terminal" || words[2] == "gray" || words[2] == "grey" || words[2] == "0")
speakermode = 0;
if(words[2] == "cyan" || words[2] == "viridian" || words[2] == "player" || words[2] == "1")
speakermode = 1;
if(words[2] == "purple" || words[2] == "violet" || words[2] == "pink" || words[2] == "2")
speakermode = 2;
if(words[2] == "yellow" || words[2] == "vitellary" || words[2] == "3")
speakermode = 3;
if(words[2] == "red" || words[2] == "vermilion" || words[2] == "4")
speakermode = 4;
if(words[2] == "green" || words[2] == "verdigris" || words[2] == "5")
speakermode = 5;
if(words[2] == "blue" || words[2] == "victoria" || words[2] == "6")
speakermode = 6;
switch(speakermode)
{
case 0:
if(squeakmode == 0)
add("squeak(terminal)");
add("text(gray,0,114," + words[1] + ")");
break;
case 1: //NOT THE PLAYER
if(squeakmode == 0)
add("squeak(cyan)");
add("text(cyan,0,0," + words[1] + ")");
break;
case 2:
if(squeakmode == 0)
add("squeak(purple)");
add("text(purple,0,0," + words[1] + ")");
break;
case 3:
if(squeakmode == 0)
add("squeak(yellow)");
add("text(yellow,0,0," + words[1] + ")");
break;
case 4:
if(squeakmode == 0)
add("squeak(red)");
add("text(red,0,0," + words[1] + ")");
break;
case 5:
if(squeakmode == 0)
add("squeak(green)");
add("text(green,0,0," + words[1] + ")");
break;
case 6:
if(squeakmode == 0)
add("squeak(blue)");
add("text(blue,0,0," + words[1] + ")");
break;
}
int ti = atoi(words[1].c_str());
if(ti >= 0 && ti <= 50)
{
for(int ti2 = 0; ti2 < ti; ti2++)
{
i++;
add(script.customscript[i]);
}
}
else
{
i++;
add(script.customscript[i]);
}
switch(speakermode)
{
case 0:
add("customposition(center)");
break;
case 1:
add("customposition(cyan,above)");
break;
case 2:
add("customposition(purple,above)");
break;
case 3:
add("customposition(yellow,above)");
break;
case 4:
add("customposition(red,above)");
break;
case 5:
add("customposition(green,above)");
break;
case 6:
add("customposition(blue,above)");
break;
}
add("speak_active");
customtextmode = 1;
}
else if(words[0] == "reply")
{
//For this version, terminal only
if(squeakmode == 0)
add("squeak(player)");
add("text(cyan,0,0," + words[1] + ")");
int ti = atoi(words[1].c_str());
if(ti >= 0 && ti <= 50)
{
for(int ti2 = 0; ti2 < ti; ti2++)
{
i++;
add(script.customscript[i]);
}
}
else
{
i++;
add(script.customscript[i]);
}
add("position(player,above)");
add("speak_active");
customtextmode = 1;
}
}
if(customtextmode == 1)
{
add("endtext");
customtextmode = 0;
}
if(customcutscenemode == 1)
{
add("endcutscene()");
add("untilbars()");
}
}
}
else if(t == "intro")
{
add("ifskip(quickstart)");
//add("createcrewman(232,113,cyan,0,faceright)");
add("createcrewman(96,177,green,0,faceright)");
add("createcrewman(122,177,purple,0,faceleft)");
add("fadein()");
add("untilfade()");
add("delay(90)");
add("flash(5)");
add("shake(20)");
add("playef(9,10)");
add("musicfadeout()");
add("changemood(player,1)");
add("delay(15)");
add("squeak(player)");
add("text(cyan,0,0,1)");
add("Uh oh...");
add("position(player,above)");
//add("backgroundtext");
add("speak_active");
add("squeak(purple)");
add("changeai(purple,followposition,175)");
add("text(purple,145,150,1)");
add("Is everything ok?");
//add("position(purple,above)");
//add("backgroundtext");
add("speak_active");
add("squeak(player)");
add("walk(left,2)");
add("text(cyan,0,0,2)");
add("No! We've hit some");
add("kind of interference...");
add("position(player,above)");
//add("backgroundtext");
add("speak_active");
//add("delay(30)");
add("endtext");
add("flash(5)");
add("shake(50)");
add("playef(9,10)");
add("changemood(green,1)");
add("changemood(purple,1)");
add("alarmon");
add("changedir(player,1)");
add("delay(30)");
add("endtext");
add("squeak(player)");
add("text(cyan,0,0,2)");
add("Something's wrong! We're");
add("going to crash!");
add("position(player,above)");
//add("backgroundtext");
add("speak_active");
//add("delay(100)");
add("endtext");
add("flash(5)");
add("shake(50)");
add("playef(9,10)");
add("changeai(green,followposition,-60)");
add("changeai(purple,followposition,-60)");
add("squeak(player)");
add("text(cyan,70,140,1)");
add("Evacuate!");
add("backgroundtext");
add("speak_active");
add("walk(left,35)");
add("endtextfast");
//Ok, next room!
add("flash(5)");
add("shake(50)");
add("playef(9,10)");
add("gotoroom(3,10)");
add("gotoposition(310,177,0)");
add("createcrewman(208,177,green,1,followposition,120)");
add("createcrewman(240,177,purple,1,followposition,120)");
add("createcrewman(10,177,blue,1,followposition,180)");
add("squeak(blue)");
add("text(blue,80,150,1)");
add("Oh no!");
add("backgroundtext");
add("speak_active");
add("walk(left,20)");
add("endtextfast");
//and the next!
add("flash(5)");
add("shake(50)");
add("playef(9,10)");
add("gotoroom(3,11)");
add("gotoposition(140,0,0)");
add("createcrewman(90,105,green,1,followblue)");
add("createcrewman(125,105,purple,1,followgreen)");
add("createcrewman(55,105,blue,1,followposition,-200)");
add("createcrewman(120,177,yellow,1,followposition,-200)");
add("createcrewman(240,177,red,1,faceleft)");
add("delay(5)");
add("changeai(red,followposition,-200)");
add("squeak(red)");
add("text(red,100,150,1)");
add("Everyone off the ship!");
add("backgroundtext");
add("speak_active");
add("walk(left,25)");
add("endtextfast");
//final room:
add("flash(5)");
add("shake(80)");
add("playef(9,10)");
add("gotoroom(2,11)");
add("gotoposition(265,153,0)");
add("createcrewman(130,153,blue,1,faceleft)");
add("createcrewman(155,153,green,1,faceleft)");
add("createcrewman(180,153,purple,1,faceleft)");
add("createcrewman(205,153,yellow,1,faceleft)");
add("createcrewman(230,153,red,1,faceleft)");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("This shouldn't be happening!");
add("position(yellow,below)");
add("backgroundtext");
add("speak_active");
add("activateteleporter()");
add("delay(10)");
add("changecolour(blue,teleporter)");
add("delay(10)");
add("changecolour(green,teleporter)");
add("delay(10)");
add("changecolour(purple,teleporter)");
add("delay(10)");
add("changecolour(yellow,teleporter)");
add("delay(10)");
add("changecolour(red,teleporter)");
add("delay(10)");
//and teleport!
add("endtext");
add("alarmoff");
add("flash(5)");
add("shake(20)");
add("playef(10,10)");
add("blackout()");
add("changemood(player,0)");
add("changedir(player,1)");
add("delay(100)");
add("blackon()");
add("shake(20)");
add("playef(10,10)");
//Finally, appear at the start of the game:
add("gotoroom(13,5)");
add("gotoposition(80,96,0)");
add("walk(right,20)");
//add("delay(45)");
add("squeak(player)");
add("text(cyan,0,0,1)");
add("Phew! That was scary!");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(cyan,0,0,2)");
add("At least we all");
add("escaped, right guys?");
add("position(player,above)");
add("speak_active");
add("endtext");
add("delay(45)");
add("walk(left,3)");
add("delay(45)");
add("setcheckpoint()");
add("squeak(player)");
add("text(cyan,0,0,1)");
add("...guys?");
add("position(player,above)");
add("speak_active");
add("endtext");
add("delay(25)");
add("changemood(player,1)");
add("squeak(cry)");
add("delay(25)");
add("play(1)");
add("endcutscene()");
add("untilbars()");
add("hideship()");
add("gamestate(4)");
}
else if(t == "quickstart")
{
//Finally, appear at the start of the game:
add("gotoroom(13,5)");
add("gotoposition(80,96,0)");
add("walk(right,17)");
add("fadein()");
add("setcheckpoint()");
add("play(1)");
add("endcutscene()");
add("untilbars()");
add("hideship()");
}
else if(t == "firststeps")
{
add("cutscene()");
add("untilbars()");
add("squeak(player)");
add("text(cyan,0,0,2)");
add("I wonder why the ship");
add("teleported me here alone?");
add("position(player,above)");
add("speak_active");
add("squeak(cry)");
add("text(cyan,0,0,2)");
add("I hope everyone else");
add("got out ok...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "trenchwarfare")
{
add("cutscene()");
add("untilbars()");
add("iftrinkets(1,newtrenchwarfare)");
add("squeak(player)");
add("text(cyan,0,0,1)");
add("Ohh! I wonder what that is?");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(cyan,0,0,3)");
add("I probably don't really need it,");
add("but it might be nice to take it");
add("back to the ship to study...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "newtrenchwarfare")
{
add("squeak(player)");
add("text(cyan,0,0,2)");
add("Oh! It's another one of");
add("those shiny things!");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(cyan,0,0,3)");
add("I probably don't really need it,");
add("but it might be nice to take it");
add("back to the ship to study...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "trinketcollector")
{
add("cutscene()");
add("untilbars()");
add("iftrinkets(1,newtrinketcollector)");
add("squeak(player)");
add("text(cyan,0,0,3)");
add("This seems like a good");
add("place to store anything");
add("I find out there...");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(cyan,0,0,3)");
add("Victoria loves to study the");
add("interesting things we find");
add("on our adventures!");
add("position(player,above)");
add("speak_active");
add("ifcrewlost(5,new2trinketcollector)");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "newtrinketcollector")
{
add("squeak(player)");
add("text(cyan,0,0,3)");
add("This seems like a good");
add("place to store those");
add("shiny things.");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(cyan,0,0,3)");
add("Victoria loves to study the");
add("interesting things we find");
add("on our adventures!");
add("position(player,above)");
add("speak_active");
add("ifcrewlost(5,new2trinketcollector)");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "new2trinketcollector")
{
add("squeak(cry)");
add("changemood(player,1)");
add("text(cyan,0,0,1)");
add("I hope she's ok...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("changemood(player,0)");
add("endcutscene()");
add("untilbars()");
return;
}
if(t == "communicationstation")
{
add("ifskip(communicationstationskip)");
add("cutscene()");
add("untilbars()");
add("changemood(player,0)");
add("tofloor");
add("play(5)");
add("delay(10)");
add("squeak(player)");
add("text(cyan,0,0,1)");
add("Violet! Is that you?");
add("position(player,above)");
add("speak_active");
add("endtext");
add("squeak(purple)");
add("text(purple,45,18,1)");
add("Captain! You're ok!");
add("speak_active");
add("squeak(cry)");
add("text(purple,20,16,3)");
add("Something has gone");
add("horribly wrong with the");
add("ship's teleporter!");
add("speak_active");
add("squeak(purple)");
add("text(purple,8,14,3)");
add("I think everyone has been");
add("teleported away randomly!");
add("They could be anywhere!");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1)");
add("text(cyan,0,0,1)");
add("Oh no!");
add("position(player,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,10,19,2)");
add("I'm on the ship - it's damaged");
add("badly, but it's still intact!");
add("speak_active");
add("squeak(purple)");
add("text(purple,10,15,1)");
add("Where are you, Captain?");
add("speak_active");
add("squeak(player)");
add("changemood(player,0)");
add("text(cyan,0,0,3)");
add("I'm on some sort of");
add("space station... It");
add("seems pretty modern...");
add("position(player,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,15,16,2)");
add("There seems to be some sort of");
add("interference in this dimension...");
add("speak_active");
add("hideteleporters()");
add("endtextfast");
add("delay(10)");
//add map mode here and wrap up...
add("gamemode(teleporter)");
add("delay(20)");
add("squeak(purple)");
add("text(purple,25,205,2)");
add("I'm broadcasting the coordinates");
add("of the ship to you now.");
add("speak_active");
add("endtext");
add("squeak(terminal)");
add("showship()");
add("delay(10)");
add("hideship()");
add("delay(10)");
add("showship()");
add("delay(10)");
add("hideship()");
add("delay(10)");
add("showship()");
add("delay(20)");
add("squeak(purple)");
add("text(purple,10,200,1)");
add("I can't teleport you back, but...");
add("speak_active");
add("squeak(purple)");
add("text(purple,25,195,3)");
add("If YOU can find a teleporter");
add("anywhere nearby, you should be");
add("able to teleport back to me!");
add("speak_active");
add("endtext");
add("squeak(terminal)");
add("delay(20)");
add("showteleporters()");
add("delay(10)");
add("hideteleporters()");
add("delay(10)");
add("showteleporters()");
add("delay(10)");
add("hideteleporters()");
add("delay(10)");
add("showteleporters()");
add("delay(20)");
add("squeak(player)");
add("text(cyan,20,190,1)");
add("Ok! I'll try to find one!");
add("speak_active");
add("endtext");
add("delay(20)");
add("gamemode(game)");
add("delay(20)");
add("squeak(purple)");
add("text(purple,40,22,1)");
add("Good luck, Captain!");
add("speak_active");
add("endtext");
add("squeak(purple)");
add("text(purple,10,19,2)");
add("I'll keep trying to find");
add("the rest of the crew...");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("play(1)");
}
else if(t == "communicationstationskip")
{
add("changemood(player,0)");
add("delay(10)");
add("endtext");
//add map mode here and wrap up...
add("gamemode(teleporter)");
add("delay(5)");
add("squeak(terminal)");
add("showship()");
add("showteleporters()");
add("delay(10)");
add("hideship()");
add("hideteleporters()");
add("delay(10)");
add("showship()");
add("showteleporters()");
add("delay(10)");
add("hideship()");
add("hideteleporters()");
add("delay(10)");
add("showship()");
add("showteleporters()");
add("delay(20)");
add("gamemode(game)");
}
else if(t == "teleporterback")
{
add("cutscene()");
add("untilbars()");
add("squeak(player)");
add("text(cyan,0,0,1)");
add("A teleporter!");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(cyan,0,0,2)");
add("I can get back to the");
add("ship with this!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("teleportscript(levelonecomplete)");
add("endcutscene()");
add("untilbars()");
}
else if(t == "levelonecomplete")
{
add("nocontrol()");
add("createcrewman(230,153,purple,0,faceleft)");
add("cutscene()");
add("untilbars()");
add("delay(30)");
add("rescued(purple)");
add("delay(10)");
add("gamestate(4090)");
}
else if(t == "levelonecomplete_ending")
{
add("squeak(purple)");
add("text(purple,0,0,1)");
add("Captain!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("nocontrol()");
add("endcutscene()");
add("untilbars()");
add("gamestate(3050)");
}
else if(t == "levelonecompleteskip")
{
add("nocontrol()");
add("gamestate(3050)");
}
else if(t == "bigopenworld")
{
add("play(5)");
add("cutscene()");
add("untilbars()");
add("gotoroom(4,10)");
add("gotoposition(100,177,0)");
add("createcrewman(150,177,purple,0,faceleft)");
//set all the crew as rescued to avoid companion issues!
add("rescued(red)");
add("rescued(green)");
add("rescued(blue)");
add("rescued(yellow)");
add("fadein()");
add("untilfade()");
add("delay(15)");
add("squeak(player)");
add("text(player,0,0,2)");
add("So, Doctor - have you any");
add("idea what caused the crash?");
add("position(player,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,3)");
add("There's some sort of bizarre");
add("signal here that's interfering");
add("with our equipment...");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,3)");
add("It caused the ship to lose");
add("its quantum position, collapsing");
add("us into this dimension!");
add("position(purple,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,1)");
add("Oh no!");
add("position(player,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("But I think we should be able to fix");
add("the ship and get out of here...");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("... as long as we can");
add("find the rest of the crew.");
add("position(purple,above)");
add("speak_active");
add("endtext");
//Cut to Red
add("fadeout()");
add("untilfade()");
add("changeplayercolour(red)");
add("gotoroom(10,4)");
add("gotoposition(200,185,0)");
add("hideplayer()");
add("createcrewman(200,185,red,1,panic)");
add("fadein()");
add("untilfade()");
//add("walk(right,10)");
add("squeak(purple)");
add("text(purple,60,40,2)");
add("We really don't know anything");
add("about this place...");
add("speak_active");
add("endtext");
add("delay(15)");
//Cut to Green
add("fadeout()");
add("untilfade()");
add("showplayer()");
add("changeplayercolour(green)");
add("gotoroom(13,0)");
add("gotoposition(143,20,0)");
add("fadein()");
add("untilfade()");
add("squeak(purple)");
add("text(purple,40,30,2)");
add("Our friends could be anywhere - they");
add("could be lost, or in danger!");
add("speak_active");
add("endtext");
add("delay(15)");
//Cut to Blue
add("fadeout()");
add("untilfade()");
add("changeplayercolour(blue)");
add("gotoroom(3,4)");
add("gotoposition(190,177,0)");
add("fadein()");
add("untilfade()");
add("squeak(player)");
add("text(player,10,60,1)");
add("Can they teleport back here?");
add("speak_active");
add("squeak(purple)");
add("text(purple,50,80,2)");
add("Not unless they find some way");
add("to communicate with us!");
add("speak_active");
add("squeak(purple)");
add("text(purple,30,100,3)");
add("We can't pick up their signal and");
add("they can't teleport here unless");
add("they know where the ship is...");
add("speak_active");
add("endtext");
add("delay(15)");
//Cut to Yellow
add("fadeout()");
add("untilfade()");
add("changeplayercolour(yellow)");
add("gotoroom(15,9)");
//(6*8)-21
add("gotoposition(300,27,0)");
add("hideplayer()");
add("createcrewman(280,25,yellow,1,panic)");
//add("hascontrol()");
//add("walk(left,4)");
add("fadein()");
add("untilfade()");
add("squeak(player)");
add("text(player,25,60,1)");
add("So what do we do?");
add("speak_active");
add("squeak(purple)");
add("text(purple,80,125,4)");
add("We need to find them! Head");
add("out into the dimension and");
add("look for anywhere they might");
add("have ended up...");
add("speak_active");
add("endtext");
add("delay(15)");
//Back to ship
add("fadeout()");
add("untilfade()");
add("showplayer()");
add("missing(red)");
add("missing(green)");
add("missing(blue)");
add("missing(yellow)");
add("changeplayercolour(cyan)");
add("changemood(player,0)");
add("gotoroom(4,10)");
add("gotoposition(90,177,0)");
add("walk(right,2)");
add("createcrewman(150,177,purple,0,faceleft)");
add("fadein()");
add("untilfade()");
add("squeak(player)");
add("text(player,0,0,1)");
add("Ok! Where do we start?");
add("position(player,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("Well, I've been trying to find");
add("them with the ship's scanners!");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("It's not working, but I did");
add("find something...");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("delay(15)");
add("hidecoordinates(10,4)");
add("hidecoordinates(13,0)");
add("hidecoordinates(3,4)");
add("hidecoordinates(15,9)");
add("showteleporters()");
//Cut to map
//add map mode here and wrap up...
add("gamemode(teleporter)");
add("delay(20)");
add("squeak(terminal)");
add("showtargets()");
add("delay(10)");
add("hidetargets()");
add("delay(10)");
add("showtargets()");
add("delay(10)");
add("hidetargets()");
add("delay(10)");
add("showtargets()");
add("delay(20)");
add("squeak(purple)");
add("text(purple,25,205,2)");
add("These points show up on our scans");
add("as having high energy patterns!");
add("speak_active");
add("endtext");
add("squeak(purple)");
add("text(purple,35,185,4)");
add("There's a good chance they're");
add("teleporters - which means");
add("they're probably built near");
add("something important...");
add("speak_active");
add("squeak(purple)");
add("text(purple,25,205,2)");
add("They could be a very good");
add("place to start looking.");
add("speak_active");
add("endtext");
add("delay(20)");
add("gamemode(game)");
add("delay(20)");
//And finally, back to the ship!
add("squeak(player)");
add("text(player,0,0,2)");
add("Ok! I'll head out and see");
add("what I can find!");
add("position(player,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("I'll be right here if");
add("you need any help!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("rescued(purple)");
add("play(4)");
add("endcutscene()");
add("untilbars()");
add("hascontrol()");
add("createactivityzone(purple)");
}
else if(t == "bigopenworldskip")
{
add("gotoroom(4,10)");
add("gotoposition(100,177,0)");
add("createcrewman(150,177,purple,0,faceleft)");
add("fadein()");
add("untilfade()");
add("hidecoordinates(10,4)");
add("hidecoordinates(13,0)");
add("hidecoordinates(3,4)");
add("hidecoordinates(15,9)");
add("showteleporters()");
//Cut to map
//add map mode here and wrap up...
add("gamemode(teleporter)");
add("delay(20)");
add("squeak(terminal)");
add("showtargets()");
add("delay(10)");
add("hidetargets()");
add("delay(10)");
add("showtargets()");
add("delay(10)");
add("hidetargets()");
add("delay(10)");
add("showtargets()");
add("delay(20)");
add("gamemode(game)");
add("delay(20)");
//And finally, back to the ship!
add("squeak(purple)");
add("text(purple,0,0,2)");
add("I'll be right here if");
add("you need any help!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("rescued(purple)");
add("play(4)");
add("endcutscene()");
add("untilbars()");
add("hascontrol()");
add("createactivityzone(purple)");
}
else if(t == "rescueblue")
{
add("ifskip(skipblue)");
add("cutscene()");
add("tofloor()");
add("changeai(blue,followplayer)");
add("untilbars()");
add("rescued(blue)");
add("squeak(blue)");
add("text(blue,0,0,2)");
add("Oh no! Captain! Are you");
add("stuck here too?");
add("position(blue,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("It's ok - I'm here to rescue you!");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Let me explain everything...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("fadeout()");
add("untilfade()");
add("delay(30)");
add("fadein()");
add("untilfade()");
add("squeak(cry)");
add("text(blue,0,0,2)");
add("What? I didn't understand");
add("any of that!");
add("position(blue,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Oh... well, don't worry.");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("Follow me! Everything");
add("will be alright!");
add("position(player,above)");
add("speak_active");
add("squeak(blue)");
add("changemood(blue,0)");
add("text(blue,0,0,1)");
add("Sniff... Really?");
add("position(blue,above)");
add("speak_active");
add("squeak(blue)");
add("text(blue,0,0,1)");
add("Ok then!");
add("position(blue,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("companion(8)");
add("setcheckpoint()");
}
else if(t == "skipblue")
{
add("changeai(blue,followplayer)");
add("squeak(blue)");
add("changemood(blue,0)");
add("companion(8)");
add("rescued(blue)");
add("setcheckpoint()");
}
else if(t == "rescueyellow")
{
add("ifskip(skipyellow)");
add("cutscene()");
add("changeai(yellow,followplayer)");
add("changetile(yellow,6)");
add("untilbars()");
add("rescued(yellow)");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("Ah, Viridian! You got off");
add("the ship alright too? ");
add("position(yellow,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("It's good to see you're");
add("alright, Professor!");
add("position(player,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("Is the ship ok?");
add("position(yellow,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("It's badly damaged, but Violet's");
add("been working on fixing it.");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("We could really use your help...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("fadeout()");
add("untilfade()");
add("delay(30)");
add("fadein()");
add("untilfade()");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("Ah, of course!");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,4)");
add("The background interference");
add("in this dimension prevented");
add("the ship from finding a");
add("teleporter when we crashed!");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("We've all been teleported");
add("to different locations!");
add("position(yellow,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Er, that sounds about right!");
add("position(player,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("Let's get back to");
add("the ship, then!");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("After you, Captain!");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("companion(7)");
add("endcutscene()");
add("untilbars()");
}
else if(t == "skipyellow")
{
add("changeai(yellow,followplayer)");
add("changetile(yellow,6)");
add("squeak(yellow)");
add("rescued(yellow)");
add("companion(7)");
}
else if(t == "rescuegreen")
{
add("ifskip(skipgreen)");
add("cutscene()");
add("tofloor()");
add("changemood(green,0)");
add("untilbars()");
add("rescued(green)");
add("squeak(green)");
add("text(green,0,0,1)");
add("Captain! I've been so worried!");
add("position(green,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Chief Verdigris! You're ok!");
add("position(player,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(green,1)");
add("text(green,0,0,2)");
add("I've been trying to get out, but");
add("I keep going around in circles...");
add("position(green,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("I've come from the ship. I'm here");
add("to teleport you back to it.");
add("position(player,above)");
add("speak_active");
add("squeak(green)");
add("text(green,0,0,2)");
add("Is everyone else");
add("alright? Is Violet...");
add("position(green,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("She's fine - she's back on the ship!");
add("position(player,above)");
add("speak_active");
add("squeak(green)");
add("changemood(green,0)");
add("text(green,0,0,2)");
add("Oh! Great - Let's");
add("get going, then!");
add("position(green,above)");
add("speak_active");
add("endtext");
add("companion(6)");
add("endcutscene()");
add("untilbars()");
add("changeai(green,followplayer)");
}
else if(t == "skipgreen")
{
add("changeai(green,followplayer)");
add("squeak(green)");
add("rescued(green)");
add("changemood(green,0)");
add("companion(6)");
}
else if(t == "rescuered")
{
add("ifskip(skipred)");
add("cutscene()");
add("tofloor()");
add("changemood(red,0)");
add("untilbars()");
add("rescued(red)");
add("squeak(red)");
add("text(red,0,0,1)");
add("Captain!");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,3)");
add("Am I ever glad to see you!");
add("I thought I was the only");
add("one to escape the ship...");
add("position(red,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Vermilion! I knew you'd be ok!");
add("position(player,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,1)");
add("So, what's the situation?");
add("position(red,above)");
add("speak_active");
add("endtext");
add("fadeout()");
add("untilfade()");
add("delay(30)");
add("fadein()");
add("untilfade()");
add("squeak(red)");
add("text(red,0,0,2)");
add("I see! Well, we'd better");
add("get back then.");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,2)");
add("There's a teleporter");
add("in the next room.");
add("position(red,above)");
add("speak_active");
add("endtext");
add("companion(9)");
add("endcutscene()");
add("untilbars()");
add("changeai(red,followplayer)");
}
else if(t == "skipred")
{
add("changeai(red,followplayer)");
add("squeak(red)");
add("rescued(red)");
add("changemood(red,0)");
add("companion(9)");
}
else if(t == "startexpolevel_station1")
{
//For the Eurogamer EXPO! Scrap later.
add("fadeout()");
add("musicfadeout()");
add("untilfade()");
add("cutscene()");
add("untilbars()");
add("resetgame");
add("gotoroom(4,10)");
add("gotoposition(232,113,0)");
add("setcheckpoint()");
add("changedir(player,1)");
add("fadein()");
add("play(5)");
add("loadscript(intro)");
}
else if(t == "startexpolevel_lab")
{
//For the Eurogamer EXPO! Scrap later.
add("fadeout()");
add("musicfadeout()");
add("untilfade()");
add("delay(30)");
add("resetgame");
add("gotoroom(2,16)");
add("gotoposition(58,193,0)");
add("setcheckpoint()");
add("changedir(player,1)");
add("fadein()");
add("stopmusic()");
add("play(3)");
}
else if(t == "startexpolevel_warp")
{
//For the Eurogamer EXPO! Scrap later.
add("fadeout()");
add("musicfadeout()");
add("untilfade()");
add("delay(30)");
add("resetgame");
add("gotoroom(14,1)");
add("gotoposition(45,73,0)");
add("setcheckpoint()");
add("changedir(player,1)");
add("fadein()");
add("stopmusic()");
add("play(3)");
}
else if(t == "startexpolevel_tower")
{
//For the Eurogamer EXPO! Scrap later.
add("fadeout()");
add("musicfadeout()");
add("untilfade()");
add("delay(30)");
add("resetgame");
add("gotoroom(8,9)");
add("gotoposition(95,193,0)");
add("setcheckpoint()");
add("changedir(player,1)");
add("fadein()");
add("stopmusic()");
add("play(2)");
}
else if(t == "skipint1")
{
add("finalmode(41,56)");
add("gotoposition(52,89,0)");
add("changedir(player,1)");
add("setcheckpoint()");
add("delay(15)");
add("flash(5)");
add("shake(20)");
add("playef(9,10)");
add("showplayer()");
add("play(8)");
add("hascontrol()");
add("befadein()");
}
else if(t == "intermission_1")
{
add("ifskip(skipint1)");
add("finalmode(41,56)");
add("gotoposition(52,89,0)");
add("changedir(player,1)");
add("setcheckpoint()");
add("cutscene()");
add("delay(15)");
add("flash(5)");
add("shake(20)");
add("playef(9,10)");
add("delay(35)");
add("flash(5)");
add("shake(20)");
add("playef(9,10)");
add("delay(25)");
add("flash(5)");
add("shake(20)");
add("playef(10,10)");
add("showplayer()");
add("play(8)");
add("befadein()");
add("iflast(2,int1yellow_1)");
add("iflast(3,int1red_1)");
add("iflast(4,int1green_1)");
add("iflast(5,int1blue_1)");
}
else if(t == "int1blue_1")
{
add("delay(45)");
add("squeak(cry)");
add("text(blue,0,0,1)");
add("Waaaa!");
add("position(blue,above)");
add("speak_active");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(blue)");
add("text(blue,0,0,1)");
add("Captain! Are you ok?");
add("position(blue,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("I'm ok... this...");
add("this isn't the ship...");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Where are we?");
add("position(player,above)");
add("speak_active");
add("squeak(cry)");
add("text(blue,0,0,1)");
add("Waaaa!");
add("position(blue,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("Something's gone wrong... We");
add("should look for a way back!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("telesave()");
add("endcutscene()");
add("untilbars()");
add("gamestate(14)");
}
else if(t == "int1blue_2")
{
add("cutscene()");
add("untilbars()");
add("squeak(player)");
add("text(player,0,0,1)");
add("Follow me! I'll help you!");
add("position(player,above)");
add("speak_active");
add("squeak(cry)");
add("text(blue,0,0,1)");
add("Promise you won't leave without me!");
add("position(blue,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("I promise! Don't worry!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("gamestate(11)");
}
else if(t == "int1blue_3")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(player)");
add("text(player,0,0,1)");
add("Are you ok down there, Doctor?");
add("position(player,below)");
add("speak_active");
add("squeak(cry)");
add("text(blue,0,0,1)");
add("I wanna go home!");
add("position(blue,above)");
add("speak_active");
add("squeak(blue)");
add("text(blue,0,0,2)");
add("Where are we? How did");
add("we even get here?");
add("position(blue,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,4)");
add("Well, Violet did say that the");
add("interference in the dimension");
add("we crashed in was causing");
add("problems with the teleporters...");
add("position(player,below)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("I guess something went wrong...");
add("position(player,below)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,3)");
add("But if we can find another");
add("teleporter, I think we can");
add("get back to the ship!");
add("position(player,below)");
add("speak_active");
add("squeak(blue)");
add("text(blue,0,0,1)");
add("Sniff...");
add("position(blue,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1blue_4")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(cry)");
add("text(blue,0,0,1)");
add("Captain! Captain! Wait for me!");
add("position(blue,above)");
add("speak_active");
add("squeak(blue)");
add("text(blue,0,0,2)");
add("Please don't leave me behind!");
add("I don't mean to be a burden!");
add("position(blue,above)");
add("speak_active");
add("squeak(cry)");
add("text(blue,0,0,1)");
add("I'm scared!");
add("position(blue,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("Oh... don't worry Victoria,");
add("I'll look after you!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1blue_5")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(cry)");
add("text(blue,0,0,2)");
add("We're never going to get");
add("out of here, are we?");
add("position(blue,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,1)");
add("I.. I don't know...");
add("position(player,above)");
add("speak_active");
add("squeak(cry)");
add("text(player,0,0,2)");
add("I don't know where we are or");
add("how we're going to get out...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1blue_6")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(cry)");
add("text(blue,0,0,1)");
add("We're going to be lost forever!");
add("position(blue,above)");
add("speak_active");
add("squeak(player)");
add("changemood(player,0)");
add("text(player,0,0,2)");
add("Ok, come on... Things");
add("aren't that bad.");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("I have a feeling that");
add("we're nearly home!");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("We can't be too far");
add("from another teleporter!");
add("position(player,above)");
add("speak_active");
add("squeak(cry)");
add("text(blue,0,0,1)");
add("I hope you're right, captain...");
add("position(blue,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1blue_7")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(blue)");
add("text(blue,0,0,2");
add("Captain! You were right!");
add("It's a teleporter!");
add("position(blue,above)");
add("speak_active");
add("squeak(player)");
add("changemood(player,0)");
add("text(player,0,0,3)");
add("Phew! You had me worried for a");
add("while there... I thought we");
add("were never going to find one.");
add("position(player,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(blue,1)");
add("text(blue,0,0,1");
add("What? Really?");
add("position(blue,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("Anyway, let's go");
add("back to the ship.");
add("position(player,above)");
add("speak_active");
add("changemood(blue,0)");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1green_1")
{
add("delay(45)");
add("squeak(green)");
add("text(green,0,0,1)");
add("Huh? This isn't the ship...");
add("position(green,above)");
add("speak_active");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,1)");
add("Captain! What's going on?");
add("position(green,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1");
add("text(player,0,0,1)");
add("I... I don't know!");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Where are we?");
add("position(player,above)");
add("speak_active");
add("squeak(green)");
add("text(green,0,0,3)");
add("Uh oh, this isn't good...");
add("Something must have gone");
add("wrong with the teleporter!");
add("position(green,above)");
add("speak_active");
add("squeak(player)");
add("changemood(player,0");
add("text(player,0,0,1)");
add("Ok... no need to panic!");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("changemood(player,0");
add("text(player,0,0,1)");
add("Let's look for another teleporter!");
add("There's bound to be one around");
add("here somewhere!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("telesave()");
add("endcutscene()");
add("untilbars()");
add("gamestate(14)");
}
else if(t == "int1green_2")
{
add("cutscene()");
add("untilbars()");
add("squeak(player)");
add("text(player,0,0,1)");
add("Let's go this way!");
add("position(player,above)");
add("speak_active");
add("squeak(green)");
add("text(green,0,0,1)");
add("After you, Captain!");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("gamestate(11)");
}
else if(t == "int1green_3")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,2)");
add("So Violet's back on the");
add("ship? She's really ok?");
add("position(green,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("She's fine! She helped");
add("me find my way back!");
add("position(player,below)");
add("speak_active");
add("squeak(green)");
add("text(green,0,0,1)");
add("Oh, phew! I was worried about her.");
add("position(green,above)");
add("speak_active");
add("endtext");
add("delay(45)");
add("squeak(green)");
add("text(green,0,0,1)");
add("Captain, I have a secret...");
add("position(green,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(green,1)");
add("text(green,0,0,1)");
add("I really like Violet!");
add("position(green,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Is that so?");
add("position(player,below)");
add("speak_active");
add("squeak(green)");
add("changemood(green,0)");
add("text(green,0,0,2)");
add("Please promise you");
add("won't tell her!");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1green_4")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,1)");
add("Hey again!");
add("position(green,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Hey!");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Are you doing ok?");
add("position(player,above)");
add("speak_active");
add("squeak(green)");
add("text(green,0,0,3)");
add("I think so! I really");
add("hope we can find a way");
add("back to the ship...");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1green_5")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,1)");
add("So, about Violet...");
add("position(green,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Um, yeah?");
add("position(player,above)");
add("speak_active");
add("squeak(green)");
add("text(green,0,0,1)");
add("Do you have any advice?");
add("position(green,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Oh!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("delay(45)");
add("squeak(player)");
add("text(player,0,0,1)");
add("Hmm...");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Um... you should... be yourself!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("delay(15)");
add("squeak(green)");
add("text(green,0,0,1)");
add("Oh.");
add("position(green,above)");
add("speak_active");
add("endtext");
add("delay(75)");
add("squeak(green)");
add("text(green,0,0,1)");
add("Thanks Captain!");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1green_6")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(player)");
add("text(player,0,0,2)");
add("So, do you think you'll");
add("be able to fix the ship?");
add("position(player,above)");
add("speak_active");
add("squeak(green)");
add("text(green,0,0,2)");
add("Depends on how bad it ");
add("is... I think so, though!");
add("position(green,above)");
add("speak_active");
add("squeak(green)");
add("text(green,0,0,5)");
add("It's not very hard, really. The");
add("basic dimensional warping engine");
add("design is pretty simple, and if we");
add("can get that working we shouldn't");
add("have any trouble getting home.");
add("position(green,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Oh! Good!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1green_7")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,1)");
add("Finally! A teleporter!");
add("position(green,above)");
add("speak_active");
add("squeak(green)");
add("text(green,0,0,2)");
add("I was getting worried");
add("we wouldn't find one...");
add("position(green,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Let's head back to the ship!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1red_1")
{
add("cutscene()");
add("untilbars()");
add("squeak(red)");
add("text(red,0,0,1)");
add("Wow! Where are we?");
add("position(red,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,3)");
add("This... isn't right...");
add("Something must have gone");
add("wrong with the teleporter!");
add("position(player,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,3)");
add("Oh well... We can work");
add("it out when we get");
add("back to the ship!");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,1)");
add("Let's go exploring!");
add("position(red,above)");
add("speak_active");
add("squeak(player)");
add("changemood(player,0)");
add("text(player,0,0,1)");
add("Ok then!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("telesave()");
add("endcutscene()");
add("untilbars()");
add("gamestate(14)");
}
else if(t == "int1red_2")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(player)");
add("text(player,0,0,1)");
add("Follow me!");
add("position(player,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,1)");
add("Aye aye, Captain!");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("gamestate(11)");
}
else if(t == "int1red_3")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,2)");
add("Hey Viridian... how did");
add("the crash happen, exactly?");
add("position(red,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("Oh, I don't really know -");
add("some sort of interference...");
add("position(player,below)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("...or something sciencey like");
add("that. It's not really my area.");
add("position(player,below)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,3)");
add("Ah! Well, do you think");
add("we'll be able to fix");
add("the ship and go home?");
add("position(red,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Of course! Everything will be ok!");
add("position(player,below)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1red_4")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,1)");
add("Hi again! You doing ok?");
add("position(red,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("I think so! But I really want");
add("to get back to the ship...");
add("position(player,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,3)");
add("We'll be ok! If we can find");
add("a teleporter somewhere we");
add("should be able to get back!");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1red_5")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,1)");
add("Are we there yet?");
add("position(red,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("We're getting closer, I think...");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("I hope...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1red_6")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(player)");
add("text(player,0,0,1)");
add("I wonder where we are, anyway?");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,3)");
add("This seems different from");
add("that dimension we crashed");
add("in, somehow...");
add("position(player,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,2)");
add("I dunno... But we must be");
add("close to a teleporter by now...");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1red_7")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(player)");
add("text(player,0,0,1)");
add("We're there!");
add("position(player,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,2)");
add("See? I told you! Let's");
add("get back to the ship!");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1yellow_1")
{
add("cutscene()");
add("untilbars()");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("Oooh! This is interesting...");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("Captain! Have you");
add("been here before?");
add("position(yellow,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,1)");
add("What? Where are we?");
add("position(player,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,3)");
add("I suspect something deflected");
add("our teleporter transmission!");
add("This is somewhere new...");
add("position(yellow,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,1)");
add("Oh no!");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("changemood(player,0)");
add("text(player,0,0,3)");
add("We should try to find a");
add("teleporter and get back");
add("to the ship...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("telesave()");
add("endcutscene()");
add("untilbars()");
add("gamestate(14)");
}
else if(t == "int1yellow_2")
{
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(player)");
add("text(player,0,0,1)");
add("Follow me!");
add("position(player,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("Right behind you, Captain!");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("gamestate(11)");
}
else if(t == "int1yellow_3")
{
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(player)");
add("text(player,0,0,2)");
add("What do you make of");
add("all this, Professor?");
add("position(player,below)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,4)");
add("I'm guessing this dimension");
add("has something to do with the");
add("interference that caused");
add("us to crash!");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("Maybe we'll find the");
add("cause of it here?");
add("position(yellow,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Oh wow! Really?");
add("position(player,below)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,4)");
add("Well, it's just a guess.");
add("I'll need to get back to");
add("the ship before I can do");
add("any real tests...");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1yellow_4")
{
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("Ohh! What was that?");
add("position(yellow,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("What was what?");
add("position(player,above)");
add("speak_active");
add("squeak(yellow)");
add("changedir(yellow,0)");
add("text(yellow,0,0,2)");
add("That big... C thing!");
add("I wonder what it does?");
add("position(yellow,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,2)");
add("Em... I don't really know");
add("how to answer that question...");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("changemood(player,0)");
add("text(player,0,0,3)");
add("It's probably best not");
add("to acknowledge that");
add("it's there at all.");
add("position(player,above)");
add("speak_active");
add("squeak(yellow)");
add("changedir(yellow,1)");
add("text(yellow,0,0,2)");
add("Maybe we should take it back");
add("to the ship to study it?");
add("position(yellow,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,3)");
add("We really shouldn't think");
add("about it too much... Let's");
add("keep moving!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1yellow_5")
{
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,3)");
add("You know, there's");
add("something really odd");
add("about this dimension...");
add("position(yellow,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Yeah?");
add("position(player,above)");
add("speak_active");
add("squeak(yellow)");
add("changedir(yellow,0)");
add("text(yellow,0,0,3)");
add("We shouldn't really be able");
add("to move between dimensions");
add("with a regular teleporter...");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("changedir(yellow,0)");
add("text(yellow,0,0,2)");
add("Maybe this isn't a proper");
add("dimension at all?");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("changedir(yellow,0)");
add("text(yellow,0,0,4)");
add("Maybe it's some kind of");
add("polar dimension? Something");
add("artificially created for");
add("some reason?");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("changedir(yellow,1)");
add("text(yellow,0,0,2)");
add("I can't wait to get back to the");
add("ship. I have a lot of tests to run!");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1yellow_6")
{
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,3)");
add("I wonder if there's anything");
add("else in this dimension");
add("worth exploring?");
add("position(yellow,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,3)");
add("Maybe... but we should probably");
add("just focus on finding the rest");
add("of the crew for now...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int1yellow_7")
{
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("At last!");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("Let's go back to the ship!");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
}
else if(t == "skipint2")
{
add("finalmode(53,49)");
add("gotoposition(228,129,0)");
add("changedir(player,1)");
add("setcheckpoint()");
add("flash(5)");
add("shake(20)");
add("playef(10,10)");
add("showplayer()");
add("play(8)");
add("hascontrol()");
add("befadein()");
}
else if(t == "intermission_2")
{
add("ifskip(skipint2)");
add("finalmode(53,49)");
add("gotoposition(228,129,0)");
add("changedir(player,1)");
add("setcheckpoint()");
add("cutscene()");
add("delay(15)");
add("flash(5)");
add("shake(20)");
add("playef(9,10)");
add("delay(35)");
add("flash(5)");
add("shake(20)");
add("playef(9,10)");
add("delay(25)");
add("flash(5)");
add("shake(20)");
add("playef(10,10)");
add("showplayer()");
add("play(8)");
add("befadein()");
add("changemood(player,1)");
add("text(player,0,0,1)");
add("Uh oh...");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("changemood(player,1)");
add("text(player,0,0,1)");
add("Not again!");
add("position(player,above)");
add("speak_active");
add("iflast(2,int2intro_yellow)");
add("iflast(3,int2intro_red)");
add("iflast(4,int2intro_green)");
add("iflast(5,int2intro_blue)");
}
else if(t == "int2intro_yellow")
{
add("squeak(cry)");
add("text(player,0,0,1)");
add("Vitellary? Where are you?");
add("position(player,above)");
add("speak_active");
add("endtext");
add("delay(15)");
add("flash(5)");
add("shake(20)");
add("playef(10,10)");
add("delay(15)");
add("changedir(player,0)");
add("createcrewman(150,-20,yellow,1,17,1)");
add("squeak(cry)");
add("text(yellow,170,50,1)");
add("Captain!");
add("speak_active");
add("endtext");
add("delay(15)");
add("squeak(player)");
add("changemood(player,0)");
add("text(player,0,0,1)");
add("Hang on! I'll save you!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("telesave()");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int2intro_red")
{
add("squeak(cry)");
add("text(player,0,0,1)");
add("Vermilion? Where are you?");
add("position(player,above)");
add("speak_active");
add("endtext");
add("delay(15)");
add("flash(5)");
add("shake(20)");
add("playef(10,10)");
add("delay(15)");
add("changedir(player,0)");
add("createcrewman(150,-20,red,0,17,1)");
add("squeak(red)");
add("text(red,170,50,1)");
add("Wheeeee!");
add("speak_active");
add("endtext");
add("delay(15)");
add("squeak(player)");
add("changemood(player,0)");
add("text(player,0,0,1)");
add("Hang on! I'll save you!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("telesave()");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int2intro_green")
{
add("squeak(cry)");
add("text(player,0,0,1)");
add("Verdigris? Where are you?");
add("position(player,above)");
add("speak_active");
add("endtext");
add("delay(15)");
add("flash(5)");
add("shake(20)");
add("playef(10,10)");
add("delay(15)");
add("changedir(player,0)");
add("createcrewman(150,-20,green,1,17,1)");
add("squeak(cry)");
add("text(green,170,50,1)");
add("Aaagghh!");
add("speak_active");
add("endtext");
add("delay(15)");
add("squeak(player)");
add("changemood(player,0)");
add("text(player,0,0,1)");
add("Hang on! I'll save you!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("telesave()");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int2intro_blue")
{
add("squeak(cry)");
add("text(player,0,0,1)");
add("Victoria? Where are you?");
add("position(player,above)");
add("speak_active");
add("endtext");
add("delay(15)");
add("flash(5)");
add("shake(20)");
add("playef(10,10)");
add("delay(15)");
add("changedir(player,0)");
add("createcrewman(150,-20,blue,1,17,1)");
add("squeak(cry)");
add("text(blue,170,50,1)");
add("Help!");
add("speak_active");
add("endtext");
add("delay(15)");
add("squeak(player)");
add("changemood(player,0)");
add("text(player,0,0,1)");
add("Hang on! I'll save you!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("telesave()");
add("endcutscene()");
add("untilbars()");
}
else if(t == "int2_yellow")
{
add("ifskip(skipint2yellow)");
add("cutscene()");
add("tofloor()");
add("changeai(yellow,followplayer)");
add("untilbars()");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("That was interesting, wasn't it?");
add("position(yellow,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,1)");
add("I feel dizzy...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("changemood(player,0)");
add("endcutscene()");
add("untilbars()");
add("companion(10)");
}
else if(t == "skipint2yellow")
{
add("squeak(yellow)");
add("companion(10)");
}
else if(t == "int2_red")
{
add("ifskip(skipint2red)");
add("cutscene()");
add("tofloor()");
add("changeai(red,followplayer)");
add("untilbars()");
add("squeak(red)");
add("text(red,0,0,1)");
add("Again! Let's go again!");
add("position(red,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,1)");
add("I feel dizzy...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("changemood(player,0)");
add("endcutscene()");
add("untilbars()");
add("companion(10)");
}
else if(t == "skipint2red")
{
add("squeak(red)");
add("companion(10)");
}
else if(t == "int2_green")
{
add("ifskip(skipint2green)");
add("cutscene()");
add("tofloor()");
add("changeai(green,followplayer)");
add("untilbars()");
add("squeak(green)");
add("text(green,0,0,1)");
add("Phew! You're ok!");
add("position(green,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,1)");
add("I feel dizzy...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("changemood(player,0)");
add("endcutscene()");
add("untilbars()");
add("companion(10)");
}
else if(t == "skipint2green")
{
add("squeak(green)");
add("companion(10)");
}
else if(t == "int2_blue")
{
add("ifskip(skipint2blue)");
add("cutscene()");
add("tofloor()");
add("changeai(blue,followplayer)");
add("untilbars()");
add("squeak(cry)");
add("text(blue,0,0,1)");
add("I think I'm going to be sick...");
add("position(blue,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,1)");
add("I feel dizzy...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("changemood(player,0)");
add("changemood(blue,0)");
add("endcutscene()");
add("untilbars()");
add("companion(10)");
}
else if(t == "skipint2blue")
{
add("squeak(blue)");
add("companion(10)");
}
else if(t == "startexpolevel_station2")
{
//For the Eurogamer EXPO! Scrap later.
add("fadeout()");
add("musicfadeout()");
add("untilfade()");
add("delay(30)");
add("resetgame");
add("gotoroom(12,14)");
add("gotoposition(126,38,1)");
add("setcheckpoint()");
add("changedir(player,0)");
add("fadein()");
add("stopmusic()");
add("play(1)");
}
else if(t == "finallevel_teleporter")
{
add("delay(10)");
add("squeak(purple)");
add("text(purple,0,0,1)");
add("Welcome back!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("delay(30)");
add("squeak(purple)");
add("text(purple,0,0,1)");
add("...");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,1)");
add("Um, where's Captain Viridian?");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("delay(30)");
add("walk(left,3)");
add("delay(60)");
add("everybodysad()");
add("squeak(cry)");
add("delay(30)");
add("fadeout()");
add("untilfade()");
add("changemood(player,0)");
add("musicfadeout()");
add("finalmode(46,54)");
add("gotoposition(101,113,0)");
add("setcheckpoint()");
add("changedir(player,1)");
add("restoreplayercolour");
add("fadein()");
add("untilfade()");
add("delay(15)");
add("squeak(player)");
add("text(player,0,0,1)");
add("... Hello?");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Is anyone there?");
add("position(player,above)");
add("speak_active");
add("endtext");
add("missing(player)");
//add("squeak(cry)");
//add("changemood(player,1)");
add("endcutscene()");
add("untilbars()");
add("play(15)");
add("telesave()");
}
else if(t == "skipfinal")
{
add("finalmode(46,54)");
add("gotoposition(101,113,0)");
add("setcheckpoint()");
add("changedir(player,1)");
add("restoreplayercolour");
add("showplayer()");
add("hascontrol()");
add("missing(player)");
add("play(15)");
add("fadein()");
add("untilfade()");
}
else if(t == "startlevel_final")
{
add("ifskip(skipfinal)");
add("cutscene()");
add("untilbars()");
add("activeteleporter()");
add("stopmusic()");
add("play(5)");
add("gotoroom(2,11)");
add("gotoposition(160,120,0)");
add("createcrewman(190,153,purple,0,faceleft)");
add("createrescuedcrew()");
add("fadein()");
add("untilfade()");
add("gamestate(4070)");
}
else if(t == "regularreturn")
{
add("cutscene()");
add("untilbars()");
add("activeteleporter()");
add("stopmusic()");
add("play(4)");
add("gotoroom(2,11)");
add("gotoposition(160,120,0)");
add("createlastrescued()");
add("fadein()");
add("untilfade()");
add("endcutscene()");
add("setcheckpoint()");
add("gamestate(4010)");
}
else if(t == "returntohub")
{
//For the Eurogamer EXPO! Scrap later.
add("fadeout()");
add("musicfadeout()");
add("untilfade()");
add("delay(30)");
add("resetgame");
add("gotoroom(7,8)");
add("gotoposition(145,145,0)");
add("setcheckpoint()");
add("changedir(player,0)");
add("fadein()");
add("stopmusic()");
add("play(4)");
}
else if(t == "resetgame")
{
//For the Eurogamer EXPO! Scrap later.
add("resetgame");
add("gotoroom(4,6)");
add("fadein()");
}
else if(t == "talkred")
{
add("redcontrol");
}
else if(t == "talkyellow")
{
add("yellowcontrol");
}
else if(t == "talkgreen")
{
add("greencontrol");
}
else if(t == "talkblue")
{
add("bluecontrol");
}
else if(t == "talkpurple")
{
add("purplecontrol");
}
else if(t == "talkred_1")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,1)");
add("Don't worry, Sir!");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,2)");
add("We'll find a way");
add("out of here!");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(red)");
}
else if(t == "talkred_2")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,1)");
add("I hope Victoria is ok...");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,2)");
add("She doesn't handle");
add("surprises very well...");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(red)");
}
else if(t == "talkred_3")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,3)");
add("I don't know how we're");
add("going to get this ship");
add("working again!");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,2)");
add("Chief Verdigris would");
add("know what to do...");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(red)");
}
else if(t == "talkred_4")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,2)");
add("I wonder what caused");
add("the ship to crash here?");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,3)");
add("It's the shame the Professor");
add("isn't here, huh? I'm sure he");
add("could work it out!");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(red)");
}
else if(t == "talkred_5")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,1)");
add("It's great to be back!");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,2)");
add("I can't wait to help you");
add("find the rest of the crew!");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,2)");
add("It'll be like old");
add("times, huh, Captain?");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(red)");
}
else if(t == "talkred_6")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,2)");
add("It's good to have");
add("Victoria back with us.");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,2)");
add("She really seems happy to");
add("get back to work in her lab!");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(red)");
}
else if(t == "talkred_7")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,3)");
add("I think I saw Verdigris");
add("working on the outside");
add("of the ship!");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(red)");
}
else if(t == "talkred_8")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,2)");
add("You found Professor");
add("Vitellary! All right!");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,2)");
add("We'll have this interference");
add("thing worked out in no time now!");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(red)");
}
else if(t == "talkred_9")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,2)");
add("That other dimension was");
add("really strange, wasn't it?");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,2)");
add("I wonder what caused the");
add("teleporter to send us there?");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(red)");
}
else if(t == "talkred_10")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,1)");
add("Heya Captain!");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,2)");
add("This way looks a little");
add("dangerous...");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(red)");
}
else if(t == "talkred_11")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,1)");
add("I'm helping!");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(red)");
}
else if(t == "talkred_12")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,1)");
add("Hey Captain!");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,3)");
add("I found something interesting");
add("around here - the same warp");
add("signature I saw when I landed!");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,2)");
add("Someone from the ship");
add("must be nearby...");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(red)");
}
else if(t == "talkred_13")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,2)");
add("This dimension is pretty");
add("exciting, isn't it?");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,1)");
add("I wonder what we'll find?");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(red)");
}
else if(t == "talkred_14")
{
add("cutscene()");
add("untilbars()");
add("face(player,red)");
add("face(red,player)");
add("squeak(red)");
add("text(red,0,0,1)");
add("Look what I found!");
add("position(red,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,2)");
add("It's pretty hard, I can only");
add("last for about 10 seconds...");
add("position(red,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(red)");
}
else if(t == "talkyellow_1")
{
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("I'm making some fascinating");
add("discoveries, captain!");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(yellow)");
}
else if(t == "talkyellow_2")
{
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,3)");
add("This isn't like any");
add("other dimension we've");
add("been to, Captain.");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("There's something strange");
add("about this place...");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(yellow)");
}
else if(t == "talkyellow_3")
{
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,3)");
add("Captain, have you noticed");
add("that this dimension seems");
add("to wrap around?");
add("position(yellow,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Yeah, it's strange...");
add("position(player,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(yellow,1)");
add("text(yellow,0,0,3)");
add("It looks like this dimension");
add("is having the same stability");
add("problems as our own!");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("I hope we're not the");
add("ones causing it...");
add("position(yellow,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,1)");
add("What? Do you think we might be?");
add("position(player,above)");
add("speak_active");
add("squeak(yellow)");
add("changemood(yellow,0)");
add("changemood(player,0)");
add("text(yellow,0,0,2)");
add("No no... that's very");
add("unlikely, really...");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(yellow)");
}
else if(t == "talkyellow_4")
{
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,4)");
add("My guess is that whoever used");
add("to live here was experimenting");
add("with ways to stop the dimension");
add("from collapsing.");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("It would explain why they've");
add("wrapped the edges...");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("Hey, maybe that's what's");
add("causing the interference?");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(yellow)");
}
else if(t == "talkyellow_5")
{
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("I wonder where the people who");
add("used to live here have gone?");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(yellow)");
}
else if(t == "talkyellow_6")
{
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,3)");
add("I think it's no coincidence");
add("that the teleporter was drawn");
add("to that dimension...");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,4)");
add("There's something there. I");
add("think it might be causing the");
add("interference that's stopping");
add("us from leaving...");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(yellow)");
}
else if(t == "talkyellow_7")
{
//Vertigris is back
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("I'm glad Verdigris is alright.");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,3)");
add("It'll be a lot easier to find");
add("some way out of here now that");
add("we can get the ship working again!");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(yellow)");
}
else if(t == "talkyellow_8")
{
//Victoria is back
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("Ah, you've found Doctor");
add("Victoria? Excellent!");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("I have lots of questions for her!");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(yellow)");
}
else if(t == "talkyellow_9")
{
//Vermilion is back
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,3)");
add("Vermilion says that he");
add("was trapped in some");
add("sort of tunnel?");
add("position(yellow,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("Yeah, it just seemed to");
add("keep going and going...");
add("position(player,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("Interesting... I wonder");
add("why it was built?");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(yellow)");
}
else if(t == "talkyellow_10")
{
//Back on the ship!
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("It's good to be back!");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("I've got so much work");
add("to catch up on...");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(yellow)");
}
else if(t == "talkyellow_11")
{
//Game Complete
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,3)");
add("I know it's probably a little");
add("dangerous to stay here now that");
add("this dimension is collapsing...");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("...but it's so rare to find");
add("somewhere this interesting!");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("Maybe we'll find the answers");
add("to our own problems here?");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(yellow)");
}
else if(t == "talkyellow_12")
{
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("Captain! Have you seen this?");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,3)");
add("With their research and ours,");
add("we should be able to stabilise");
add("our own dimension!");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("We're saved!");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(yellow)");
}
else if(t == "talkgreen_1")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,1)");
add("I'm an engineer!");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(green)");
}
else if(t == "talkgreen_2")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,3)");
add("I think I can get this ship");
add("moving again, but it's going");
add("to take a while...");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(green)");
}
else if(t == "talkgreen_2")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,3)");
add("I think I can get this ship");
add("moving again, but it's going");
add("to take a while...");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(green)");
}
else if(t == "talkgreen_3")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,3)");
add("Victoria mentioned something");
add("about a lab? I wonder if she");
add("found anything down there?");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(green)");
}
else if(t == "talkgreen_4")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,1)");
add("Vermilion's back! Yey!");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(green)");
}
else if(t == "talkgreen_5")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,3)");
add("The Professor had lots of");
add("questions about this");
add("dimension for me...");
add("position(green,above)");
add("speak_active");
add("squeak(green)");
add("text(green,0,0,2)");
add("We still don't really know");
add("that much, though.");
add("position(green,above)");
add("speak_active");
add("squeak(green)");
add("text(green,0,0,3)");
add("Until we work out what's");
add("causing that interference,");
add("we can't go anywhere.");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(green)");
}
else if(t == "talkgreen_6")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,2)");
add("I'm so glad that");
add("Violet's alright!");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(green)");
}
else if(t == "talkgreen_7")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,3)");
add("That other dimension we ended");
add("up in must be related to this");
add("one, somehow...");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(green)");
}
else if(t == "talkgreen_8")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(cry)");
add("text(green,0,0,3)");
add("The antenna's broken!");
add("This is going to be");
add("very hard to fix...");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(green)");
}
else if(t == "talkgreen_9")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,2)");
add("It looks like we were warped");
add("into solid rock when we crashed!");
add("position(green,above)");
add("speak_active");
add("squeak(green)");
add("text(green,0,0,2)");
add("Hmm. It's going to be hard");
add("to separate from this...");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(green)");
}
else if(t == "talkgreen_10")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,2)");
add("The ship's all fixed up. We");
add("can leave at a moment's notice!");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(green)");
}
else if(t == "talkgreen_11")
{
add("cutscene()");
add("untilbars()");
add("face(player,green)");
add("face(green,player)");
add("squeak(green)");
add("text(green,0,0,3)");
add("I wonder why they abandoned this");
add("dimension? They were so close to");
add("working out how to fix it...");
add("position(green,above)");
add("speak_active");
add("squeak(green)");
add("text(green,0,0,2)");
add("Maybe we can fix it for them?");
add("Maybe they'll come back?");
add("position(green,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(green)");
}
if(t == "talkpurple_1")
{
add("cutscene()");
add("untilbars()");
add("face(player,purple)");
add("face(purple,player)");
add("squeak(cry)");
add("changemood(purple,1)");
add("text(purple,0,0,1)");
add("... I hope Verdigris is alright.");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("changemood(purple,0)");
add("text(purple,0,0,2)");
add("If you can find him, he'd be a");
add("a big help fixing the ship!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(purple)");
}
else if(t == "talkpurple_2")
{
add("cutscene()");
add("untilbars()");
add("face(player,purple)");
add("face(purple,player)");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("Chief Verdigris is so brave");
add("and ever so smart!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(purple)");
}
else if(t == "talkpurple_3")
{
add("cutscene()");
add("untilbars()");
add("face(player,purple)");
add("face(purple,player)");
add("squeak(purple)");
add("text(purple,0,0,1)");
add("Are you doing ok, Captain?");
add("position(purple,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,0)");
add("specialline(1)");
add("position(player,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("Oh - well, don't worry,");
add("they'll show up!");
add("position(purple,above)");
add("speak_active");
add("changemood(player,0)");
add("squeak(purple)");
add("text(purple,0,0,1)");
add("Here! Have a lollipop!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(purple)");
}
else if(t == "talkpurple_4")
{
add("cutscene()");
add("untilbars()");
add("face(player,purple)");
add("face(purple,player)");
add("squeak(purple)");
add("text(purple,0,0,1)");
add("Welcome back, Captain!");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("I think Victoria is quite happy");
add("to be back on the ship.");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("She really doesn't like adventuring.");
add("She gets very homesick!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(purple)");
}
else if(t == "talkpurple_5")
{
add("cutscene()");
add("untilbars()");
add("face(player,purple)");
add("face(purple,player)");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("Vermilion called in");
add("to say hello!");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,1)");
add("He's really looking forward");
add("specialline(2)");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(purple)");
}
else if(t == "talkpurple_6")
{
add("cutscene()");
add("untilbars()");
add("face(player,purple)");
add("face(purple,player)");
add("squeak(purple)");
add("text(purple,0,0,1)");
add("Captain! You found Verdigris!");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,1)");
add("Thank you so much!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(purple)");
}
else if(t == "talkpurple_7")
{
add("cutscene()");
add("untilbars()");
add("face(player,purple)");
add("face(purple,player)");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("I'm glad Professor");
add("Vitellary is ok!");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("He had lots of questions");
add("for me about this dimension.");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("He's already gotten to");
add("work with his research!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(purple)");
}
else if(t == "talkpurple_8")
{
add("cutscene()");
add("untilbars()");
add("face(player,purple)");
add("face(purple,player)");
add("squeak(purple)");
add("text(purple,0,0,4)");
add("Hey Captain! Now that you've turned");
add("off the source of the interference,");
add("we can warp everyone back to the");
add("ship instantly, if we need to!");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,3)");
add("Any time you want to come back");
add("to the ship, just select the");
add("new SHIP option in your menu!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(purple)");
}
else if(t == "talkpurple_9")
{
add("cutscene()");
add("untilbars()");
add("face(player,purple)");
add("face(purple,player)");
add("squeak(purple)");
add("text(purple,0,0,3)");
add("Look at all this research!");
add("This is going to be a big");
add("help back home!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(purple)");
}
else if(t == "talkpurple_intermission1")
{
add("cutscene()");
add("untilbars()");
add("face(player,purple)");
add("face(purple,player)");
add("squeak(player)");
add("text(player,0,0,3)");
add("Doctor, something strange");
add("happened when we teleported");
add("back to the ship...");
add("position(player,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,1)");
add("We got lost in another dimension!");
add("position(player,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(purple,1)");
add("text(purple,0,0,1)");
add("Oh no!");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("changemood(purple,0)");
add("changemood(player,0)");
add("text(purple,0,0,3)");
add("Maybe that dimension has something");
add("to do with the interference that");
add("caused us to crash here?");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,1)");
add("I'll look into it...");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(purple)");
}
else if(t == "talkpurple_intermission2")
{
add("cutscene()");
add("untilbars()");
add("face(player,purple)");
add("face(purple,player)");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,1)");
add("Doctor! Doctor! It happened again!");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("The teleporter brought us");
add("to that weird dimension...");
add("position(player,above)");
add("speak_active");
add("squeak(purple)");
add("changemood(player,0)");
add("changemood(purple,0)");
add("text(purple,0,0,2)");
add("Hmm, there's definitely");
add("something strange happening...");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("If only we could find the");
add("source of that interference!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(purple)");
}
else if(t == "talkpurple_intermission3")
{
add("cutscene()");
add("untilbars()");
add("face(player,purple)");
add("face(purple,player)");
add("squeak(player)");
add("text(player,0,0,3)");
add("Doctor, something strange has");
add("been happening when we teleport");
add("back to the ship...");
add("position(player,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,2)");
add("We keep getting brought to");
add("another weird dimension!");
add("position(player,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(purple,1)");
add("text(purple,0,0,1)");
add("Oh no!");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("changemood(purple,0)");
add("changemood(player,0)");
add("text(purple,0,0,3)");
add("Maybe that dimension has something");
add("to do with the interference that");
add("caused us to crash here?");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("changemood(player,0)");
add("changemood(purple,0)");
add("text(purple,0,0,2)");
add("Hmm, there's definitely");
add("something strange happening...");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("If only we could find the");
add("source of that interference!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(purple)");
}
else if(t == "talkpurple_intro")
{
add("cutscene()");
add("untilbars()");
add("face(player,purple)");
add("face(purple,player)");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,2)");
add("I'm feeling a bit");
add("overwhelmed, Doctor.");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Where do I begin?");
add("position(player,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("Remember that you can press ENTER");
add("to check where you are on the map!");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("Look for areas where the rest");
add("of the crew might be...");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("If you get lost, you can get back");
add("to the ship from any teleporter.");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("And don't worry!");
add("We'll find everyone!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("delay(30)");
add("changemood(player,0)");
add("squeak(purple)");
add("text(purple,0,0,1)");
add("Everything will be ok!");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(purple)");
}
else if(t == "talkblue_1")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,1)");
add("Any signs of Professor Vitellary?");
add("position(blue,below)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Sorry, not yet...");
add("position(player,above)");
add("speak_active");
add("squeak(cry)");
add("changetile(blue,150)"); //upside down frown :(
add("text(blue,0,0,1)");
add("I hope he's ok...");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(blue)");
}
else if(t == "talkblue_2")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,2)");
add("Thanks so much for");
add("saving me, Captain!");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(blue)");
}
else if(t == "talkblue_3")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,1)");
add("I'm so glad to be back!");
add("position(blue,below)");
add("speak_active");
add("squeak(cry)");
add("changetile(blue,150)"); //upside down frown :(
add("text(blue,0,0,3)");
add("That lab was so dark");
add("and scary! I didn't");
add("like it at all...");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(blue)");
}
else if(t == "talkblue_4")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,2)");
add("Vitellary's back? I");
add("knew you'd find him!");
add("position(blue,below)");
add("speak_active");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,2)");
add("I mean, I admit I was very");
add("worried that you wouldn't...");
add("position(blue,below)");
add("speak_active");
add("squeak(cry)");
add("changetile(blue,150)"); //upside down frown :(
add("text(blue,0,0,2)");
add("or that something might");
add("have happened to him...");
add("position(blue,below)");
add("speak_active");
add("squeak(blue)");
add("text(blue,0,0,1)");
add("sniff...");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("delay(30)");
add("squeak(player)");
add("text(player,0,0,1)");
add("Doctor Victoria? He's ok!");
add("position(player,above)");
add("speak_active");
add("squeak(cry)");
add("changetile(blue,150)"); //upside down frown :(
add("text(blue,0,0,3)");
add("Oh! Sorry! I was just");
add("thinking about what");
add("if he wasn't?");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("delay(30)");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,1)");
add("Thank you, Captain!");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(blue)");
}
else if(t == "talkblue_5")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,1)");
add("You found Vermilion! Great!");
add("position(blue,below)");
add("speak_active");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,2)");
add("I wish he wasn't");
add("so reckless!");
add("position(blue,below)");
add("speak_active");
add("squeak(cry)");
add("changetile(blue,150)"); //upside down frown :(
add("text(blue,0,0,2)");
add("He'll get himself");
add("into trouble...");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(blue)");
}
else if(t == "talkblue_6")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,2)");
add("Verdigris is ok! Violet");
add("will be so happy!");
add("position(blue,below)");
add("speak_active");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,1)");
add("I'm happy!");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("delay(30)");
add("squeak(cry)");
add("changetile(blue,150)"); //upside down frown :(
add("text(blue,0,0,1)");
add("Though I was very worried...");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(blue)");
}
else if(t == "talkblue_7")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(cry)");
add("changetile(blue,150)"); //upside down frown :(
add("text(blue,0,0,2)");
add("Why did the teleporter send");
add("us to that scary dimension?");
add("position(blue,below)");
add("speak_active");
add("squeak(blue)");
add("changetile(blue,150)"); //upside down frown :(
add("text(blue,0,0,1)");
add("What happened?");
add("position(blue,below)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("I don't know, Doctor...");
add("position(player,above)");
add("speak_active");
add("squeak(cry)");
add("changetile(blue,150)"); //upside down frown :(
add("text(blue,0,0,1)");
add("Why?");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(blue)");
}
else if(t == "talkblue_8")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,1)");
add("Heya Captain!");
add("position(blue,below)");
add("speak_active");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,3)");
add("Are you going to try");
add("and find the rest of");
add("these shiny things?");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(blue)");
}
else if(t == "talkblue_9")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(blue)");
add("text(blue,0,0,3)");
add("This lab is amazing! The scentists");
add("who worked here know a lot more");
add("about warp technology than we do!");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(blue)");
}
else if(t == "talkblue_trinket1")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,2)");
add("Hey Captain, I found");
add("this in that lab...");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("delay(30)");
//found a trinket!
add("foundtrinket(18)");
add("endtext");
//add("musicfadein");
add("trinketscriptmusic");
add("delay(30)");
add("createentity(136,80,22,18,0)");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,1)");
add("Any idea what it does?");
add("position(blue,below)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Sorry, I don't know!");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("They seem important, though...");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("Maybe something will happen");
add("if we find them all?");
add("position(player,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(blue)");
}
else if(t == "talkblue_trinket2")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,3)");
add("Captain! Come have a");
add("look at what I've");
add("been working on!");
add("position(blue,below)");
add("speak_active");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,3)");
add("It looks like these shiny");
add("things are giving off a");
add("strange energy reading!");
add("position(blue,below)");
add("speak_active");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,1)");
add("So I analysed it...");
add("position(blue,below)");
add("speak_active");
add("trinketbluecontrol()");
}
else if(t == "talkblue_trinket3")
{
//If you missed the first conversation
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,3)");
add("Captain! Come have a");
add("look at what I've");
add("been working on!");
add("position(blue,below)");
add("speak_active");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,1)");
add("I found this in that lab...");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("delay(30)");
//found a trinket!
add("foundtrinket(18)");
add("endtext");
//add("musicfadein");
add("trinketscriptmusic");
add("delay(30)");
add("createentity(136,80,22,18,0)");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,3)");
add("It seemed to be");
add("giving off a weird");
add("energy reading...");
add("position(blue,below)");
add("speak_active");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,1)");
add("So I analysed it...");
add("position(blue,below)");
add("speak_active");
add("trinketbluecontrol()");
}
else if(t == "talkblue_trinket4")
{
add("hidetrinkets()");
add("endtextfast");
add("delay(10)");
//add map mode here and wrap up...
add("gamemode(teleporter)");
add("delay(20)");
add("squeak(blue)");
add("text(blue,50,15,2)");
add("...and I was able to find more");
add("of them with the ship's scanner!");
add("speak_active");
add("endtext");
add("squeak(terminal)");
add("showtrinkets()");
add("delay(10)");
add("hidetrinkets()");
add("delay(10)");
add("showtrinkets()");
add("delay(10)");
add("hidetrinkets()");
add("delay(10)");
add("showtrinkets()");
add("delay(75)");
add("gamemode(game)");
add("delay(20)");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,3)");
add("If you get a chance, it");
add("might be worth finding");
add("the rest of them!");
add("position(blue,below)");
add("speak_active");
add("squeak(cry)");
add("changetile(blue,150)"); //upside down frown :(
add("text(blue,0,0,2)");
add("Don't put yourself in");
add("any danger, though!");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(blue)");
}
else if(t == "talkblue_trinket5")
{
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,3)");
add("...but it looks like you've");
add("already found all of them");
add("in this dimension!");
add("position(blue,below)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Oh? Really?");
add("position(player,above)");
add("speak_active");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,2)");
add("Yeah, well done! That");
add("can't have been easy!");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(blue)");
}
else if(t == "talkblue_trinket6")
{
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,3)");
add("...and they're related.");
add("They're all a part of");
add("something bigger!");
add("position(blue,below)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Oh? Really?");
add("position(player,above)");
add("speak_active");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,4)");
add("Yeah! There seem to be");
add("twenty variations of");
add("the fundamental energy");
add("signature...");
add("position(blue,below)");
add("speak_active");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,1)");
add("Wait...");
add("position(blue,below)");
add("speak_active");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,2)");
add("Does that mean you've");
add("found all of them?");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("loadscript(startepilogue)");
}
else if(t == "talkyellow_trinket1")
{
add("cutscene()");
add("untilbars()");
add("face(player,yellow)");
add("face(yellow,player)");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("Captain! I've been meaning");
add("to give this to you...");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("delay(30)");
//found a trinket!
add("foundtrinket(18)");
add("endtext");
//add("musicfadein");
add("trinketscriptmusic");
add("delay(30)");
add("squeak(player)");
add("text(player,0,0,1)");
add("Professor! Where did you find this?");
add("position(player,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("Oh, it was just lying");
add("around that space station.");
add("position(yellow,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(yellow,1)");
add("text(yellow,0,0,3)");
add("It's a pity Doctor Victoria");
add("isn't here, she loves studying");
add("that sort of thing...");
add("position(yellow,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Any idea what it does?");
add("position(player,above)");
add("speak_active");
add("squeak(yellow)");
add("changemood(yellow,0)");
add("text(yellow,0,0,2)");
add("Nope! But it is giving off");
add("a strange energy reading...");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("trinketyellowcontrol()");
}
else if(t == "talkyellow_trinket2")
{
add("hidetrinkets()");
add("endtextfast");
add("delay(10)");
//add map mode here and wrap up...
add("gamemode(teleporter)");
add("delay(20)");
add("squeak(yellow)");
add("text(yellow,50,15,2)");
add("...so I used the ship's scanner");
add("to find more of them!");
add("speak_active");
add("endtext");
add("squeak(terminal)");
add("showtrinkets()");
add("delay(10)");
add("hidetrinkets()");
add("delay(10)");
add("showtrinkets()");
add("delay(10)");
add("hidetrinkets()");
add("delay(10)");
add("showtrinkets()");
add("delay(75)");
add("gamemode(game)");
add("delay(20)");
add("squeak(yellow)");
add("changemood(yellow,0)");
add("text(yellow,0,0,3)");
add("...Please don't let them");
add("distract you from finding");
add("Victoria, though!");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("I hope she's ok...");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(yellow)");
}
else if(t == "talkyellow_trinket3")
{
add("squeak(yellow)");
add("changemood(yellow,0)");
add("text(yellow,0,0,2)");
add("Can't seem to detect any");
add("more of them nearby, though.");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("changemood(yellow,0)");
add("text(yellow,0,0,1)");
add("Maybe you've found them all?");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("endcutscene()");
add("untilbars()");
add("createactivityzone(yellow)");
}
else if(t == "gamecomplete")
{
add("gotoroom(2,11)");
add("gotoposition(160,120,0)");
add("nocontrol()");
add("createcrewman(185,153,purple,0,faceleft)");
add("createcrewman(205,153,yellow,0,faceleft)");
add("createcrewman(225,153,red,0,faceleft)");
add("createcrewman(245,153,green,0,faceleft)");
add("createcrewman(265,153,blue,1,faceleft)");
add("cutscene()");
add("untilbars()");
add("delay(30)");
add("rescued(player)");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("Any moment now...");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("nocontrol()");
add("delay(60)");
add("gamestate(4080)");
}
else if(t == "gamecomplete_ending")
{
add("delay(15)");
add("changemood(blue,0)");
add("play(10)");
add("delay(45)");
add("squeak(player)");
add("text(player,0,0,1)");
add("Hello!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("squeak(purple)");
add("delay(1)");
add("squeak(yellow)");
add("delay(1)");
add("squeak(red)");
add("delay(1)");
add("squeak(green)");
add("text(purple,0,0,1)");
add("Captain! ");
add("position(purple,above)");
add("backgroundtext");
add("speak");
add("text(yellow,0,0,1)");
add("Captain! ");
add("position(yellow,above)");
add("backgroundtext");
add("speak");
add("text(red,0,0,1)");
add("Captain! ");
add("position(red,above)");
add("backgroundtext");
add("speak");
add("text(green,0,0,1)");
add("Captain! ");
add("position(green,above)");
add("backgroundtext");
add("speak");
add("text(blue,0,0,1)");
add("Captain!");
add("position(blue,above)");
add("speak");
add("endtextfast");
add("squeak(blue)");
add("text(blue,0,0,1)");
add("You're alright!");
add("position(blue,above)");
add("speak_active");
add("squeak(blue)");
add("text(blue,0,0,1)");
add("I knew you'd be ok!");
add("position(blue,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("We were very worried when");
add("you didn't come back...");
add("position(purple,above)");
add("speak_active");
add("squeak(green)");
add("text(green,0,0,3)");
add("...but when you turned");
add("off the source of");
add("the interference...");
add("position(green,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,3)");
add("...we were able to");
add("find you with the");
add("ship's scanners...");
add("position(yellow,above)");
add("speak_active");
add("squeak(red)");
add("text(red,0,0,2)");
add("...and teleport you");
add("back on board!");
add("position(red,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("That was lucky!");
add("Thanks guys!");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Thanks guys!");
add("position(player,above)");
add("speak_active");
add("endtext");
//Move to Vitellary's lab
add("fadeout()");
add("untilfade()");
add("missing(purple)");
add("missing(red)");
add("missing(green)");
add("missing(blue)");
add("missing(yellow)");
add("gotoroom(3,11)");
add("gotoposition(117,105,0)");
add("changedir(player,0)");
add("createcrewman(75,105,yellow,0,faceright)");
add("createcrewman(190,105,red,0,faceleft)");
add("fadein()");
add("untilfade()");
add("squeak(yellow)");
add("text(yellow,0,0,4)");
add("...it looks like this");
add("dimension is starting");
add("to destabilise, just");
add("like our own...");
add("position(yellow,above)");
add("speak_active");
add("walk(right,3)");
add("squeak(red)");
add("text(red,0,0,3)");
add("...we can stay and");
add("explore for a little");
add("longer, but...");
add("position(red,above)");
add("speak_active");
add("walk(left,3)");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("...eventually, it'll");
add("collapse completely.");
add("position(yellow,above)");
add("speak_active");
add("endtext");
//Move to Vertigris' lab
add("fadeout()");
add("untilfade()");
add("gotoroom(3,10)");
add("gotoposition(210,177,0)");
add("changedir(player,1)");
add("createcrewman(245,177,green,0,faceleft)");
add("createcrewman(56,177,blue,0,faceright)");
add("fadein()");
add("untilfade()");
add("squeak(green)");
add("text(green,0,0,3)");
add("There's no telling exactly");
add("how long we have here. But");
add("the ship's fixed, so...");
add("position(green,above)");
add("speak_active");
add("walk(left,3)");
add("squeak(blue)");
add("text(blue,0,0,2)");
add("...as soon as we're");
add("ready, we can go home!");
add("position(blue,above)");
add("speak_active");
add("endtext");
//Move to the bridge!
add("fadeout()");
add("untilfade()");
add("gotoroom(4,10)");
add("gotoposition(227,113,0)");
add("changedir(player,0)");
add("createcrewman(140,177,purple,0,faceright)");
add("createcrewman(115,177,yellow,0,faceright)");
add("createcrewman(90,177,red,0,faceright)");
add("createcrewman(65,177,green,0,faceright)");
add("createcrewman(40,177,blue,0,faceright)");
add("rescued(purple)");
add("rescued(red)");
add("rescued(green)");
add("rescued(blue)");
add("rescued(yellow)");
add("fadein()");
add("untilfade()");
add("squeak(purple)");
add("text(purple,0,0,1)");
add("What now, Captain?");
add("position(purple,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("Let's find a way to save");
add("this dimension!");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("And a way to save our");
add("home dimension too!");
add("position(player,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("The answer is out there, somewhere!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("delay(30)");
add("squeak(player)");
add("text(player,0,0,1)");
add("Let's go!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("fadeout()");
add("untilfade()");
add("rollcredits()");
}
else if(t == "startepilogue")
{
add("cutscene()");
add("untilbars()");
add("face(player,blue)");
add("face(blue,player)");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,1)");
add("Wow! You found all of them!");
add("position(blue,below)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,1)");
add("Really? Great!");
add("position(player,above)");
add("speak_active");
add("squeak(blue)");
add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood
add("text(blue,0,0,3)");
add("I'll run some tests and");
add("see if I can work out");
add("what they're for...");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("flash(5)");
add("shake(20)");
add("playef(9,10)");
add("musicfadeout()");
add("delay(30)");
add("squeak(cry)");
add("changemood(player,1)");
add("changetile(blue,150)"); //upside down frown :(
add("text(player,0,0,2)");
add("That... that didn't");
add("sound good...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("delay(30)");
add("flash(5)");
add("shake(20)");
add("playef(9,10)");
add("alarmon");
add("delay(30)");
add("squeak(cry)");
add("text(blue,0,0,1)");
add("Run!");
add("position(blue,below)");
add("speak_active");
add("endtext");
add("delay(5)");
add("missing(green)");
add("missing(yellow)");
add("flash(5)");
add("shake(50)");
add("playef(9,10)");
add("gotoroom(3,10)");
add("gotoposition(40,177,0)");
add("createcrewman(208,177,green,1,followposition,120)");
add("createcrewman(240,177,purple,1,followposition,120)");
add("createcrewman(10,177,blue,1,followposition,180)");
add("squeak(player)");
add("text(player,80,150,1)");
add("Oh no!");
add("backgroundtext");
add("speak_active");
add("walk(right,20)");
add("endtextfast");
//and the next!
add("flash(5)");
add("shake(50)");
add("playef(9,10)");
add("gotoroom(3,11)");
add("gotoposition(140,0,0)");
add("createcrewman(90,105,green,1,followblue)");
add("createcrewman(125,105,purple,1,followgreen)");
add("createcrewman(55,105,blue,1,followposition,-200)");
add("createcrewman(120,177,yellow,1,followposition,-200)");
add("createcrewman(240,177,red,1,faceleft)");
add("delay(5)");
add("changeai(red,followposition,-200)");
add("squeak(red)");
add("text(red,100,150,1)");
add("Not again!");
add("backgroundtext");
add("speak_active");
add("walk(left,25)");
add("endtextfast");
//final room:
add("flash(5)");
add("alarmoff");
add("playef(9,10)");
add("gotoroom(2,11)");
add("gotoposition(265,153,0)");
add("createcrewman(130,153,blue,1,faceleft)");
add("createcrewman(155,153,green,1,faceleft)");
add("createcrewman(180,153,purple,1,faceleft)");
add("createcrewman(205,153,yellow,1,faceleft)");
add("createcrewman(230,153,red,1,faceleft)");
add("delay(75)");
add("squeak(player)");
add("changemood(player,0)");
add("text(player,0,0,1)");
add("Wait! It's stopped!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("delay(30)");
add("changemood(purple,0)");
add("changedir(purple,1)");
add("changemood(red,0)");
add("changedir(red,1)");
add("changemood(green,0)");
add("changedir(green,1)");
add("changemood(blue,0)");
add("changedir(blue,1)");
add("changemood(yellow,0)");
add("changedir(yellow,1)");
add("delay(30)");
add("rescued(green)");
add("rescued(yellow)");
add("missing(blue)");
add("altstates(1)");
add("fadeout()");
add("untilfade()");
add("gotoroom(2,10)");
add("gotoposition(227,113,0)");
add("changedir(player,0)");
add("rescued(blue)");
add("createcrewman(150,177,purple,0,faceleft)");
add("createcrewman(90,177,yellow,0,faceright)");
add("createcrewman(184,185,red,0,faceleft)");
add("createcrewman(65,177,green,0,faceright)");
add("createcrewman(35,177,blue,0,faceright)");
add("rescued(purple)");
add("rescued(red)");
add("rescued(green)");
add("rescued(yellow)");
add("fadein()");
add("untilfade()");
add("delay(30)");
add("squeak(purple)");
add("text(purple,0,0,3)");
add("This is where we were");
add("storing those shiny");
add("things? What happened?");
add("position(purple,above)");
add("speak_active");
add("squeak(player)");
add("text(player,0,0,2)");
add("We were just playing");
add("with them, and...");
add("position(player,above)");
add("speak_active");
add("endtext");
add("squeak(cry)");
add("changemood(player,1)");
add("text(player,0,0,1)");
add("...they suddenly exploded!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("squeak(blue)");
add("text(blue,0,0,2)");
add("But look what they made!");
add("Is that a teleporter?");
add("position(blue,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("I think so, but...");
add("position(yellow,above)");
add("speak_active");
add("squeak(yellow)");
add("text(yellow,0,0,2)");
add("I've never seen a teleporter");
add("like that before...");
add("position(yellow,above)");
add("speak_active");
add("endtext");
add("changemood(player,0)");
add("delay(30)");
add("squeak(red)");
add("text(red,0,0,1)");
add("We should investigate!");
add("position(red,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,1)");
add("What do you think, Captain?");
add("position(purple,above)");
add("speak_active");
add("squeak(purple)");
add("text(purple,0,0,2)");
add("Should we find out");
add("where it leads?");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("delay(15)");
add("squeak(player)");
add("text(player,0,0,1)");
add("Let's go!");
add("position(player,above)");
add("speak_active");
add("endtext");
add("walk(left,10)");
add("flip");
add("walk(left,5)");
add("flash(5)");
add("shake(20)");
add("playef(10,10)");
add("blackout()");
add("delay(45)");
add("gotoroom(17,6)");
add("gotoposition(80,109,1)");
add("changedir(player,1)");
add("flash(5)");
add("shake(20)");
add("playef(10,10)");
add("blackon()");
add("delay(15)");
add("flash(5)");
add("shake(20)");
add("playef(10,10)");
add("createcrewman(28,65,purple,0,faceright)");
add("delay(15)");
add("flash(5)");
add("shake(20)");
add("playef(10,10)");
add("createcrewman(145,169,yellow,0,faceleft)");
add("delay(15)");
add("flash(5)");
add("shake(20)");
add("playef(10,10)");
add("createcrewman(32,169,red,0,faceright)");
add("delay(15)");
add("flash(5)");
add("shake(20)");
add("playef(10,10)");
add("createcrewman(96,149,green,0,faceleft)");
add("delay(15)");
add("flash(5)");
add("shake(20)");
add("playef(10,10)");
add("createcrewman(155,57,blue,0,faceleft)");
add("delay(45)");
add("squeak(cry)");
add("changemood(blue,1)");
add("text(blue,0,0,1)");
add("Oh no! We're trapped!");
add("position(blue,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(yellow,1)");
add("text(yellow,0,0,1)");
add("Oh dear...");
add("position(yellow,above)");
add("speak_active");
add("squeak(cry)");
add("changemood(red,1)");
add("changemood(green,1)");
add("changemood(purple,1)");
add("changemood(player,1)");
add("text(player,0,0,2)");
add("Hmm... how should we");
add("get out of this?");
add("position(player,below)");
add("speak_active");
add("endtext");
add("delay(70)");
add("squeak(purple)");
add("delay(1)");
add("squeak(yellow)");
add("delay(1)");
add("squeak(red)");
add("delay(1)");
add("squeak(blue)");
add("delay(1)");
add("squeak(player)");
add("delay(1)");
add("squeak(green)");
add("changemood(yellow,0)");
add("changemood(blue,0)");
add("changemood(red,0)");
add("changemood(player,0)");
add("changemood(green,0)");
add("changemood(purple,0)");
add("text(player,0,0,1)");
add("COMBINE!");
add("position(player,above)");
add("backgroundtext");
add("speak");
add("text(purple,0,0,1)");
add("COMBINE!");
add("position(purple,above)");
add("backgroundtext");
add("speak");
add("text(yellow,0,0,1)");
add("COMBINE!");
add("position(yellow,above)");
add("backgroundtext");
add("speak");
add("text(red,0,0,1)");
add("COMBINE!");
add("position(red,above)");
add("backgroundtext");
add("speak");
add("text(green,0,0,1)");
add("COMBINE!");
add("position(green,above)");
add("backgroundtext");
add("speak");
add("text(blue,0,0,1)");
add("COMBINE!");
add("position(blue,above)");
add("speak");
add("endtextfast");
add("delay(15)");
add("flip");
add("changeai(purple,followplayer)");
add("changeai(blue,followplayer)");
add("changeai(red,followplayer)");
add("changeai(yellow,followplayer)");
add("changeai(green,followplayer)");
add("walk(right,3)");
add("delay(5)");
add("flash(10)");
add("shake(20)");
add("playef(24,10)");
add("gotoroom(17,6)");
add("vvvvvvman()");
add("delay(90)");
add("walk(right,6)");
add("flash(10)");
add("shake(20)");
add("playef(23,10)");
add("altstates(2)");
add("gotoroom(17,6)");
add("delay(20)");
add("walk(right,12)");
add("flash(10)");
add("shake(20)");
add("playef(23,10)");
add("altstates(0)");
add("gotoroom(17,6)");
add("delay(20)");
add("walk(right,15)");
add("gotoroom(18,6)");
add("gotoposition(0,46,0)");
add("walk(right,5)");
add("delay(20)");
add("flash(10)");
add("shake(20)");
add("playef(24,10)");
add("undovvvvvvman()");
add("createcrewman(30,99,purple,0,faceright)");
add("createcrewman(65,119,yellow,0,faceright)");
add("createcrewman(135,149,red,0,faceleft)");
add("createcrewman(170,159,green,0,faceleft)");
add("createcrewman(205,159,blue,0,faceleft)");
add("delay(60)");
add("changedir(yellow,0)");
add("changedir(player,0)");
add("delay(20)");
add("squeak(purple)");
add("text(purple,0,0,3)");
add("Or, you know... we could");
add("have just warped back");
add("to the ship...");
add("position(purple,above)");
add("speak_active");
add("endtext");
add("delay(30)");
add("changedir(purple,1)");
add("changedir(yellow,1)");
add("changedir(player,1)");
add("changedir(red,1)");
add("changedir(green,1)");
add("squeak(green)");
add("text(green,0,0,1)");
add("Wow! What is this?");
add("position(green,above)");
add("speak_active");
add("changedir(purple,1)");
add("changedir(yellow,1)");
add("changedir(player,0)");
add("changedir(red,0)");
add("changedir(green,0)");
add("squeak(yellow)");
add("text(yellow,0,0,1)");
add("It looks like another laboratory!");
add("position(yellow,above)");
add("speak_active");
add("changedir(purple,1)");
add("changedir(yellow,1)");
add("changedir(player,1)");
add("squeak(red)");
add("text(red,0,0,1)");
add("Let's have a look around!");
add("position(red,above)");
add("speak_active");
add("endtext");
add("delay(20)");
add("changeai(yellow,followposition,500)");
add("changeai(purple,followposition,500)");
add("changeai(blue,followposition,500)");
add("changeai(red,followposition,500)");
add("changeai(green,followposition,500)");
add("delay(21)");
add("changeai(yellow,faceright)");
add("flipgravity(yellow)");
add("playef(0,10)");
add("delay(2)");
add("changeai(purple,faceright)");
add("flipgravity(purple)");
add("playef(0,10)");
add("delay(48)");
add("foundlab");
add("endtext");
add("foundlab2");
add("endtext");
add("entersecretlab");
add("play(11)");
add("endcutscene()");
add("untilbars()");
}
else if(t == "returntolab")
{
//To get back to the lab from the gravitron
add("gotoroom(19,7)");
add("gotoposition(132,137,0)");
add("fadein()");
add("setcheckpoint()");
add("play(11)");
add("endcutscene()");
add("untilbars()");
}
else
{
loadother(t);
}
}
#endif /* SCRIPTS_H */
| 22.367703 | 99 | 0.588506 | TijmenUU |
6a2f9f1d53a021af03fc004b9528e7da9c4f00a1 | 3,061 | cc | C++ | release/src/router/aria2-1.18.1/test/MessageDigestTest.cc | ghsecuritylab/bcwifi | 4cd7a6989921930f39816583014728b9f07a09a3 | [
"FSFAP"
] | 18 | 2015-12-08T17:31:49.000Z | 2022-03-21T19:02:11.000Z | release/src/router/aria2-1.18.1/test/MessageDigestTest.cc | ghsecuritylab/bcwifi | 4cd7a6989921930f39816583014728b9f07a09a3 | [
"FSFAP"
] | null | null | null | release/src/router/aria2-1.18.1/test/MessageDigestTest.cc | ghsecuritylab/bcwifi | 4cd7a6989921930f39816583014728b9f07a09a3 | [
"FSFAP"
] | 8 | 2015-07-12T14:37:46.000Z | 2019-03-05T10:07:33.000Z | #include "MessageDigest.h"
#include <cppunit/extensions/HelperMacros.h>
#include "util.h"
namespace aria2 {
class MessageDigestTest:public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(MessageDigestTest);
CPPUNIT_TEST(testDigest);
CPPUNIT_TEST(testSupports);
CPPUNIT_TEST(testGetDigestLength);
CPPUNIT_TEST(testIsStronger);
CPPUNIT_TEST(testIsValidHash);
CPPUNIT_TEST(testGetCanonicalHashType);
CPPUNIT_TEST_SUITE_END();
std::unique_ptr<MessageDigest> sha1_;
std::unique_ptr<MessageDigest> md5_;
public:
void setUp()
{
md5_ = MessageDigest::create("md5");
sha1_ = MessageDigest::sha1();
}
void testDigest();
void testSupports();
void testGetDigestLength();
void testIsStronger();
void testIsValidHash();
void testGetCanonicalHashType();
};
CPPUNIT_TEST_SUITE_REGISTRATION( MessageDigestTest );
void MessageDigestTest::testDigest()
{
md5_->update("aria2", 5);
CPPUNIT_ASSERT_EQUAL(std::string("2c90cadbef42945f0dcff2b959977ff8"),
util::toHex(md5_->digest()));
md5_->reset();
md5_->update("abc", 3);
CPPUNIT_ASSERT_EQUAL(std::string("900150983cd24fb0d6963f7d28e17f72"),
util::toHex(md5_->digest()));
sha1_->update("aria2", 5);
CPPUNIT_ASSERT_EQUAL(std::string("f36003f22b462ffa184390533c500d8989e9f681"),
util::toHex(sha1_->digest()));
sha1_->reset();
sha1_->update("abc", 3);
CPPUNIT_ASSERT_EQUAL(std::string("a9993e364706816aba3e25717850c26c9cd0d89d"),
util::toHex(sha1_->digest()));
}
void MessageDigestTest::testSupports()
{
CPPUNIT_ASSERT(MessageDigest::supports("md5"));
CPPUNIT_ASSERT(MessageDigest::supports("sha-1"));
// Fails because sha1 is not valid name.
CPPUNIT_ASSERT(!MessageDigest::supports("sha1"));
}
void MessageDigestTest::testGetDigestLength()
{
CPPUNIT_ASSERT_EQUAL((size_t)16, MessageDigest::getDigestLength("md5"));
CPPUNIT_ASSERT_EQUAL((size_t)20, MessageDigest::getDigestLength("sha-1"));
CPPUNIT_ASSERT_EQUAL((size_t)20, sha1_->getDigestLength());
}
void MessageDigestTest::testIsStronger()
{
CPPUNIT_ASSERT(MessageDigest::isStronger("sha-1", "md5"));
CPPUNIT_ASSERT(!MessageDigest::isStronger("md5", "sha-1"));
CPPUNIT_ASSERT(!MessageDigest::isStronger("unknown", "sha-1"));
CPPUNIT_ASSERT(!MessageDigest::isStronger("sha-1", "unknown"));
}
void MessageDigestTest::testIsValidHash()
{
CPPUNIT_ASSERT(MessageDigest::isValidHash
("sha-1", "f36003f22b462ffa184390533c500d8989e9f681"));
CPPUNIT_ASSERT(!MessageDigest::isValidHash
("sha-1", "f36003f22b462ffa184390533c500d89"));
}
void MessageDigestTest::testGetCanonicalHashType()
{
CPPUNIT_ASSERT_EQUAL(std::string("sha-1"),
MessageDigest::getCanonicalHashType("sha1"));
CPPUNIT_ASSERT_EQUAL(std::string("sha-256"),
MessageDigest::getCanonicalHashType("sha256"));
CPPUNIT_ASSERT_EQUAL(std::string("unknown"),
MessageDigest::getCanonicalHashType("unknown"));
}
} // namespace aria2
| 30.306931 | 79 | 0.708592 | ghsecuritylab |
6a30e92ecc4497e24d6fd76e0318126d8704bdcc | 11,729 | cpp | C++ | TensorShaderAvxBackend/Complex/Convolution/Convolution2D/complex_kernelproduct_2d.cpp | tk-yoshimura/TensorShaderAVX | de47428efbeaa4df694e4a3584b0397162e711d9 | [
"MIT"
] | null | null | null | TensorShaderAvxBackend/Complex/Convolution/Convolution2D/complex_kernelproduct_2d.cpp | tk-yoshimura/TensorShaderAVX | de47428efbeaa4df694e4a3584b0397162e711d9 | [
"MIT"
] | null | null | null | TensorShaderAvxBackend/Complex/Convolution/Convolution2D/complex_kernelproduct_2d.cpp | tk-yoshimura/TensorShaderAVX | de47428efbeaa4df694e4a3584b0397162e711d9 | [
"MIT"
] | null | null | null | #include "../../../TensorShaderAvxBackend.h"
using namespace System;
__forceinline __m256d _mm256_complexmulkernelgrad_pd(__m256d u, __m256d v) {
__m256d vri = v;
__m256d urr = _mm256_permute4x64_pd(u, _MM_PERM_CCAA);
__m256d vir = _mm256_permute4x64_pd(v, _MM_PERM_CDAB);
__m256d uii = _mm256_permute4x64_pd(u, _MM_PERM_DDBB);
return _mm256_fmsubadd_pd(vri, urr, _mm256_mul_pd(vir, uii));
}
void complex_kernelproduct_2d(unsigned int inchannels, unsigned int outchannels,
unsigned int inwidth, unsigned int outwidth, unsigned int kwidth,
unsigned int inheight, unsigned int outheight, unsigned int kheight,
unsigned int stride, unsigned int batch, unsigned int outch,
float* inmap_ptr, float* outmap_ptr, float* kernel_ptr) {
const unsigned int inch_sep = inchannels & ~7u, inch_rem = inchannels - inch_sep, koutch = outch / 2;
const unsigned int kerneloutchannels = outchannels / 2;
const __m256i mask = TensorShaderAvxBackend::masktable_m256(inch_rem);
for (unsigned int inch = 0; inch < inch_sep; inch += 8) {
for (unsigned int ky = 0; ky < kheight; ky++) {
for (unsigned int kx = 0; kx < kwidth; kx++) {
__m256d uv_hi = _mm256_setzero_pd(), uv_lo = _mm256_setzero_pd();
for (unsigned int th = 0; th < batch; th++) {
for (unsigned int oy = 0, iy = ky; oy < outheight; oy++, iy += stride) {
for (unsigned int ox = 0, ix = kx; ox < outwidth; ox++, ix += stride) {
__m256 u = _mm256_loadu_ps(inmap_ptr + inch + inchannels * (ix + inwidth * (iy + inheight * th)));
float vr = outmap_ptr[outch + outchannels * (ox + outwidth * (oy + outheight * th))];
float vi = outmap_ptr[outch + 1 + outchannels * (ox + outwidth * (oy + outheight * th))];
__m256d v = _mm256_setr_pd(vr, vi, vr, vi);
__m256d u_hi = _mm256_cvtps_pd(_mm256_extractf128_ps(u, 1));
__m256d u_lo = _mm256_cvtps_pd(_mm256_castps256_ps128(u));
uv_hi = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(u_hi, v), uv_hi);
uv_lo = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(u_lo, v), uv_lo);
}
}
}
_mm_storeu_ps(kernel_ptr + inch + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), _mm256_cvtpd_ps(uv_lo));
_mm_storeu_ps(kernel_ptr + inch + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)) + 4, _mm256_cvtpd_ps(uv_hi));
}
}
}
if (inch_rem > 0) {
for (unsigned int ky = 0; ky < kheight; ky++) {
for (unsigned int kx = 0; kx < kwidth; kx++) {
__m256d uv_hi = _mm256_setzero_pd(), uv_lo = _mm256_setzero_pd();
for (unsigned int th = 0; th < batch; th++) {
for (unsigned int oy = 0, iy = ky; oy < outheight; oy++, iy += stride) {
for (unsigned int ox = 0, ix = kx; ox < outwidth; ox++, ix += stride) {
__m256 u = _mm256_maskload_ps(inmap_ptr + inch_sep + inchannels * (ix + inwidth * (iy + inheight * th)), mask);
float vr = outmap_ptr[outch + outchannels * (ox + outwidth * (oy + outheight * th))];
float vi = outmap_ptr[outch + 1 + outchannels * (ox + outwidth * (oy + outheight * th))];
__m256d v = _mm256_setr_pd(vr, vi, vr, vi);
__m256d u_hi = _mm256_cvtps_pd(_mm256_extractf128_ps(u, 1));
__m256d u_lo = _mm256_cvtps_pd(_mm256_castps256_ps128(u));
uv_hi = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(u_hi, v), uv_hi);
uv_lo = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(u_lo, v), uv_lo);
}
}
}
if (inch_rem > 4) {
_mm_storeu_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), _mm256_cvtpd_ps(uv_lo));
_mm_maskstore_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)) + 4, TensorShaderAvxBackend::masktable_m128(inch_rem - 4), _mm256_cvtpd_ps(uv_hi));
}
else if (inch_rem >= 4) {
_mm_storeu_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), _mm256_cvtpd_ps(uv_lo));
}
else {
_mm_maskstore_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), TensorShaderAvxBackend::masktable_m128(inch_rem), _mm256_cvtpd_ps(uv_lo));
}
}
}
}
}
void complex_kernelproduct_2d_transpose(unsigned int inchannels, unsigned int outchannels,
unsigned int inwidth, unsigned int outwidth, unsigned int kwidth,
unsigned int inheight, unsigned int outheight, unsigned int kheight,
unsigned int stride, unsigned int batch, unsigned int outch,
float* inmap_ptr, float* outmap_ptr, float* kernel_ptr) {
const unsigned int inch_sep = inchannels & ~7u, inch_rem = inchannels - inch_sep, koutch = outch / 2;
const unsigned int kerneloutchannels = outchannels / 2;
const __m256i mask = TensorShaderAvxBackend::masktable_m256(inch_rem);
for (unsigned int inch = 0; inch < inch_sep; inch += 8) {
for (unsigned int ky = 0; ky < kheight; ky++) {
for (unsigned int kx = 0; kx < kwidth; kx++) {
__m256d vu_hi = _mm256_setzero_pd(), vu_lo = _mm256_setzero_pd();
for (unsigned int th = 0; th < batch; th++) {
for (unsigned int oy = 0, iy = ky; oy < outheight; oy++, iy += stride) {
for (unsigned int ox = 0, ix = kx; ox < outwidth; ox++, ix += stride) {
__m256 u = _mm256_loadu_ps(inmap_ptr + inch + inchannels * (ix + inwidth * (iy + inheight * th)));
float vr = outmap_ptr[outch + outchannels * (ox + outwidth * (oy + outheight * th))];
float vi = outmap_ptr[outch + 1 + outchannels * (ox + outwidth * (oy + outheight * th))];
__m256d v = _mm256_setr_pd(vr, vi, vr, vi);
__m256d u_hi = _mm256_cvtps_pd(_mm256_extractf128_ps(u, 1));
__m256d u_lo = _mm256_cvtps_pd(_mm256_castps256_ps128(u));
vu_hi = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(v, u_hi), vu_hi);
vu_lo = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(v, u_lo), vu_lo);
}
}
}
_mm_storeu_ps(kernel_ptr + inch + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), _mm256_cvtpd_ps(vu_lo));
_mm_storeu_ps(kernel_ptr + inch + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)) + 4, _mm256_cvtpd_ps(vu_hi));
}
}
}
if (inch_rem > 0) {
for (unsigned int ky = 0; ky < kheight; ky++) {
for (unsigned int kx = 0; kx < kwidth; kx++) {
__m256d vu_hi = _mm256_setzero_pd(), vu_lo = _mm256_setzero_pd();
for (unsigned int th = 0; th < batch; th++) {
for (unsigned int oy = 0, iy = ky; oy < outheight; oy++, iy += stride) {
for (unsigned int ox = 0, ix = kx; ox < outwidth; ox++, ix += stride) {
__m256 u = _mm256_maskload_ps(inmap_ptr + inch_sep + inchannels * (ix + inwidth * (iy + inheight * th)), mask);
float vr = outmap_ptr[outch + outchannels * (ox + outwidth * (oy + outheight * th))];
float vi = outmap_ptr[outch + 1 + outchannels * (ox + outwidth * (oy + outheight * th))];
__m256d v = _mm256_setr_pd(vr, vi, vr, vi);
__m256d u_hi = _mm256_cvtps_pd(_mm256_extractf128_ps(u, 1));
__m256d u_lo = _mm256_cvtps_pd(_mm256_castps256_ps128(u));
vu_hi = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(v, u_hi), vu_hi);
vu_lo = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(v, u_lo), vu_lo);
}
}
}
if (inch_rem > 4) {
_mm_storeu_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), _mm256_cvtpd_ps(vu_lo));
_mm_maskstore_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)) + 4, TensorShaderAvxBackend::masktable_m128(inch_rem - 4), _mm256_cvtpd_ps(vu_hi));
}
else if (inch_rem >= 4) {
_mm_storeu_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), _mm256_cvtpd_ps(vu_lo));
}
else {
_mm_maskstore_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), TensorShaderAvxBackend::masktable_m128(inch_rem), _mm256_cvtpd_ps(vu_lo));
}
}
}
}
}
void TensorShaderAvxBackend::Complex::KernelProduct2D(unsigned int inchannels, unsigned int outchannels, unsigned int inwidth, unsigned int inheight,
unsigned int batch, unsigned int outch, unsigned int kwidth, unsigned int kheight, unsigned int stride, bool transpose,
AvxArray<float>^ inmap, AvxArray<float>^ outmap, AvxArray<float>^ kernel) {
Util::CheckDuplicateArray(inmap, kernel, outmap);
if (inchannels % 2 != 0 || outchannels % 2 != 0 || outch % 2 != 0) {
throw gcnew System::ArgumentException();
}
if (outch >= outchannels) {
throw gcnew System::ArgumentException();
}
unsigned int outwidth = (inwidth - kwidth) / stride + 1;
unsigned int outheight = (inheight - kheight) / stride + 1;
Util::CheckLength(inchannels * inwidth * inheight * batch, inmap);
Util::CheckLength(outchannels * outwidth * outheight * batch, outmap);
Util::CheckLength(inchannels * outchannels * kwidth * kheight / 2, kernel);
float* inmap_ptr = (float*)(inmap->Ptr.ToPointer());
float* outmap_ptr = (float*)(outmap->Ptr.ToPointer());
float* kernel_ptr = (float*)(kernel->Ptr.ToPointer());
if (transpose) {
complex_kernelproduct_2d_transpose(inchannels, outchannels,
inwidth, outwidth, kwidth,
inheight, outheight, kheight,
stride, batch, outch,
inmap_ptr, outmap_ptr, kernel_ptr);
}
else {
complex_kernelproduct_2d(inchannels, outchannels,
inwidth, outwidth, kwidth,
inheight, outheight, kheight,
stride, batch, outch,
inmap_ptr, outmap_ptr, kernel_ptr);
}
}
| 56.389423 | 207 | 0.541393 | tk-yoshimura |
6a33579b6c7590590fd3157e14cdc72bcc2bc27b | 5,006 | hpp | C++ | 3rdparty/stout/include/stout/check.hpp | sagar8192/mesos | a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7 | [
"Apache-2.0"
] | 4 | 2019-03-06T03:04:40.000Z | 2019-07-20T15:35:00.000Z | 3rdparty/stout/include/stout/check.hpp | sagar8192/mesos | a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7 | [
"Apache-2.0"
] | 6 | 2018-11-30T08:04:45.000Z | 2019-05-15T03:04:28.000Z | 3rdparty/stout/include/stout/check.hpp | sagar8192/mesos | a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7 | [
"Apache-2.0"
] | 4 | 2019-03-11T11:51:22.000Z | 2020-05-11T07:27:31.000Z | // 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 __STOUT_CHECK_HPP__
#define __STOUT_CHECK_HPP__
#include <ostream>
#include <sstream>
#include <string>
#include <glog/logging.h>
#include <stout/abort.hpp>
#include <stout/error.hpp>
#include <stout/none.hpp>
#include <stout/option.hpp>
#include <stout/result.hpp>
#include <stout/some.hpp>
#include <stout/try.hpp>
// A generic macro to facilitate definitions of CHECK_*, akin to CHECK.
// This appends the error if possible to the end of the log message,
// so there's no need to append the error message explicitly.
// To define a new CHECK_*, provide the name, the function that performs the
// check, and the expression. See below for examples (e.g. CHECK_SOME).
#define CHECK_STATE(name, check, expression) \
for (const Option<Error> _error = check(expression); _error.isSome();) \
_CheckFatal(__FILE__, \
__LINE__, \
#name, \
#expression, \
_error.get()).stream()
#define CHECK_SOME(expression) \
CHECK_STATE(CHECK_SOME, _check_some, expression)
#define CHECK_NONE(expression) \
CHECK_STATE(CHECK_NONE, _check_none, expression)
#define CHECK_ERROR(expression) \
CHECK_STATE(CHECK_ERROR, _check_error, expression)
// A private helper for CHECK_NOTNONE which is similar to the
// CHECK_NOTNULL provided by glog.
template <typename T>
T&& _check_not_none(
const char* file,
int line,
const char* message,
Option<T>&& t) {
if (t.isNone()) {
google::LogMessageFatal(file, line, new std::string(message));
}
return std::move(t).get();
}
template <typename T>
T& _check_not_none(
const char* file,
int line,
const char* message,
Option<T>& t) {
if (t.isNone()) {
google::LogMessageFatal(file, line, new std::string(message));
}
return t.get();
}
template <typename T>
const T& _check_not_none(
const char* file,
int line,
const char* message,
const Option<T>& t) {
if (t.isNone()) {
google::LogMessageFatal(file, line, new std::string(message));
}
return t.get();
}
#define CHECK_NOTNONE(expression) \
_check_not_none( \
__FILE__, \
__LINE__, \
"'" #expression "' Must be SOME", \
(expression))
// Private structs/functions used for CHECK_*.
template <typename T>
Option<Error> _check_some(const Option<T>& o)
{
if (o.isNone()) {
return Error("is NONE");
} else {
CHECK(o.isSome());
return None();
}
}
template <typename T>
Option<Error> _check_some(const Try<T>& t)
{
if (t.isError()) {
return Error(t.error());
} else {
CHECK(t.isSome());
return None();
}
}
template <typename T>
Option<Error> _check_some(const Result<T>& r)
{
if (r.isError()) {
return Error(r.error());
} else if (r.isNone()) {
return Error("is NONE");
} else {
CHECK(r.isSome());
return None();
}
}
template <typename T>
Option<Error> _check_none(const Option<T>& o)
{
if (o.isSome()) {
return Error("is SOME");
} else {
CHECK(o.isNone());
return None();
}
}
template <typename T>
Option<Error> _check_none(const Result<T>& r)
{
if (r.isError()) {
return Error("is ERROR");
} else if (r.isSome()) {
return Error("is SOME");
} else {
CHECK(r.isNone());
return None();
}
}
template <typename T>
Option<Error> _check_error(const Try<T>& t)
{
if (t.isSome()) {
return Error("is SOME");
} else {
CHECK(t.isError());
return None();
}
}
template <typename T>
Option<Error> _check_error(const Result<T>& r)
{
if (r.isNone()) {
return Error("is NONE");
} else if (r.isSome()) {
return Error("is SOME");
} else {
CHECK(r.isError());
return None();
}
}
struct _CheckFatal
{
_CheckFatal(const char* _file,
int _line,
const char* type,
const char* expression,
const Error& error)
: file(_file),
line(_line)
{
out << type << "(" << expression << "): " << error.message << " ";
}
~_CheckFatal()
{
google::LogMessageFatal(file.c_str(), line).stream() << out.str();
}
std::ostream& stream()
{
return out;
}
const std::string file;
const int line;
std::ostringstream out;
};
#endif // __STOUT_CHECK_HPP__
| 22.150442 | 76 | 0.609069 | sagar8192 |
6a345c9c202f2f9219fd7a9d0d9f2bfdd7a5d708 | 2,510 | cxx | C++ | src/larcv3/app/queueio/deprecated/BatchFillerMultiLabel.cxx | zhulcher/larcv3 | 26d1ad33f0c27ddf6bb2c56bc0238aeaddcb772b | [
"MIT"
] | 8 | 2019-05-14T21:53:42.000Z | 2021-12-10T13:09:33.000Z | src/larcv3/app/queueio/deprecated/BatchFillerMultiLabel.cxx | zhulcher/larcv3 | 26d1ad33f0c27ddf6bb2c56bc0238aeaddcb772b | [
"MIT"
] | 34 | 2019-05-15T13:33:10.000Z | 2022-03-22T17:54:49.000Z | src/larcv3/app/queueio/deprecated/BatchFillerMultiLabel.cxx | zhulcher/larcv3 | 26d1ad33f0c27ddf6bb2c56bc0238aeaddcb772b | [
"MIT"
] | 6 | 2019-10-24T16:11:50.000Z | 2021-11-26T14:06:30.000Z | #ifndef __LARCV3THREADIO_BATCHFILLERMULTILABEL_CXX__
#define __LARCV3THREADIO_BATCHFILLERMULTILABEL_CXX__
#include "BatchFillerMultiLabel.h"
#include <random>
#include "larcv3/core/dataformat/EventTensor.h"
#include "larcv3/core/dataformat/EventParticle.h"
namespace larcv3 {
static BatchFillerMultiLabelProcessFactory
__global_BatchFillerMultiLabelProcessFactory__;
BatchFillerMultiLabel::BatchFillerMultiLabel(const std::string name)
: BatchFillerTemplate<float>(name) {}
void BatchFillerMultiLabel::configure(const PSet& cfg) {
_part_producer = cfg.get<std::string>("ParticleProducer");
_pdg_list = cfg.get<std::vector<int> >("PdgClassList");
if (_pdg_list.empty()) {
LARCV_CRITICAL() << "PdgClassList needed to define classes!" << std::endl;
throw larbys();
}
_num_class = _pdg_list.size();
}
void BatchFillerMultiLabel::initialize() {}
void BatchFillerMultiLabel::_batch_begin_() {
if(!batch_data().dim().empty() && (int)(batch_size()) != batch_data().dim().front()) {
auto dim = batch_data().dim();
dim[0] = (int)(batch_size());
this->set_dim(dim);
}
}
void BatchFillerMultiLabel::_batch_end_() {
if (logger().level() <= msg::kINFO) {
LARCV_INFO() << "Total data size: " << batch_data().data_size()
<< std::endl;
std::vector<size_t> ctr_v;
for (auto const& v : batch_data().data()) {
if (v >= (int)(ctr_v.size())) ctr_v.resize(v + 1, 0);
ctr_v[v] += 1;
}
std::stringstream ss;
ss << "Used: ";
for (size_t i = 0; i < ctr_v.size(); ++i)
ss << ctr_v[i] << " of class " << i << " ... ";
LARCV_INFO() << ss.str() << std::endl;
}
}
void BatchFillerMultiLabel::finalize() {}
bool BatchFillerMultiLabel::process(IOManager& mgr) {
auto const& event_part = mgr.get_data<larcv3::EventParticle>(_part_producer);
if (batch_data().dim().empty()) {
std::vector<int> dim(2);
dim[0] = batch_size();
dim[1] = _num_class;
set_dim(dim);
}
// labels
auto const& part_v = event_part.as_vector();
// Prepare output:
_entry_data.resize(_num_class, 0);
for (auto& v : _entry_data) v = 0;
// Check presence of each class:
for (auto const& part : part_v) {
for (size_t class_idx = 0; class_idx < _pdg_list.size(); ++class_idx) {
// if (part.pdg_code() != _pdg_list[class_idx]) continue;
if (part.pdg_code() == _pdg_list[class_idx]) {
_entry_data[class_idx] = 1;
}
}
}
set_entry_data(_entry_data);
return true;
}
}
#endif
| 27.282609 | 88 | 0.65259 | zhulcher |
6a38780d1b710f066df14776ac3123ca67498177 | 8,807 | cpp | C++ | ugv_sdk/src/tracer_base.cpp | Wataru-Oshima-Tokyo/ugv_sdk | 689a872af6733eff93dccbc4b1c56405f69acb4f | [
"BSD-3-Clause"
] | null | null | null | ugv_sdk/src/tracer_base.cpp | Wataru-Oshima-Tokyo/ugv_sdk | 689a872af6733eff93dccbc4b1c56405f69acb4f | [
"BSD-3-Clause"
] | null | null | null | ugv_sdk/src/tracer_base.cpp | Wataru-Oshima-Tokyo/ugv_sdk | 689a872af6733eff93dccbc4b1c56405f69acb4f | [
"BSD-3-Clause"
] | null | null | null | #include "ugv_sdk/tracer/tracer_base.hpp"
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <array>
#include <chrono>
#include <cstdint>
#include <ratio>
#include <thread>
#include "stopwatch.hpp"
namespace westonrobot {
void TracerBase::SendRobotCmd() {
static uint8_t cmd_count = 0;
if (can_connected_) {
EnableCommandedMode();
SendMotionCmd(cmd_count++);
}
}
void TracerBase::EnableCommandedMode() {
AgxMessage c_msg;
c_msg.type = AgxMsgCtrlModeSelect;
memset(c_msg.body.ctrl_mode_select_msg.raw, 0, 8);
c_msg.body.ctrl_mode_select_msg.cmd.control_mode = CTRL_MODE_CMD_CAN;
// send to can bus
can_frame c_frame;
EncodeCanFrame(&c_msg, &c_frame);
can_if_->SendFrame(c_frame);
}
void TracerBase::SendMotionCmd(uint8_t count) {
// motion control message
AgxMessage m_msg;
m_msg.type = AgxMsgMotionCommand;
memset(m_msg.body.motion_command_msg.raw, 0, 8);
motion_cmd_mutex_.lock();
int16_t linear_cmd =
static_cast<int16_t>(current_motion_cmd_.linear_velocity * 1000);
int16_t angular_cmd =
static_cast<int16_t>(current_motion_cmd_.angular_velocity * 1000);
motion_cmd_mutex_.unlock();
// SendControlCmd();
m_msg.body.motion_command_msg.cmd.linear_velocity.high_byte =
(static_cast<uint16_t>(linear_cmd) >> 8) & 0x00ff;
m_msg.body.motion_command_msg.cmd.linear_velocity.low_byte =
(static_cast<uint16_t>(linear_cmd) >> 0) & 0x00ff;
m_msg.body.motion_command_msg.cmd.angular_velocity.high_byte =
(static_cast<uint16_t>(angular_cmd) >> 8) & 0x00ff;
m_msg.body.motion_command_msg.cmd.angular_velocity.low_byte =
(static_cast<uint16_t>(angular_cmd) >> 0) & 0x00ff;
// send to can bus
can_frame m_frame;
EncodeCanFrame(&m_msg, &m_frame);
can_if_->SendFrame(m_frame);
}
void TracerBase::SendLightCmd(const TracerLightCmd &lcmd, uint8_t count) {
AgxMessage l_msg;
l_msg.type = AgxMsgLightCommand;
memset(l_msg.body.light_command_msg.raw, 0, 8);
if (lcmd.enable_ctrl) {
l_msg.body.light_command_msg.cmd.light_ctrl_enabled = LIGHT_CTRL_ENABLE;
l_msg.body.light_command_msg.cmd.front_light_mode =
static_cast<uint8_t>(lcmd.front_mode);
l_msg.body.light_command_msg.cmd.front_light_custom =
lcmd.front_custom_value;
l_msg.body.light_command_msg.cmd.rear_light_mode =
static_cast<uint8_t>(lcmd.rear_mode);
l_msg.body.light_command_msg.cmd.rear_light_custom = lcmd.rear_custom_value;
} else {
l_msg.body.light_command_msg.cmd.light_ctrl_enabled = LIGHT_CTRL_DISABLE;
}
l_msg.body.light_command_msg.cmd.count = count;
// send to can bus
can_frame l_frame;
EncodeCanFrame(&l_msg, &l_frame);
can_if_->SendFrame(l_frame);
}
TracerState TracerBase::GetTracerState() {
std::lock_guard<std::mutex> guard(tracer_state_mutex_);
return tracer_state_;
}
void TracerBase::SetMotionCommand(double linear_vel, double angular_vel) {
// make sure cmd thread is started before attempting to send commands
if (!cmd_thread_started_) StartCmdThread();
if (linear_vel < TracerMotionCmd::min_linear_velocity)
linear_vel = TracerMotionCmd::min_linear_velocity;
if (linear_vel > TracerMotionCmd::max_linear_velocity)
linear_vel = TracerMotionCmd::max_linear_velocity;
if (angular_vel < TracerMotionCmd::min_angular_velocity)
angular_vel = TracerMotionCmd::min_angular_velocity;
if (angular_vel > TracerMotionCmd::max_angular_velocity)
angular_vel = TracerMotionCmd::max_angular_velocity;
std::lock_guard<std::mutex> guard(motion_cmd_mutex_);
current_motion_cmd_.linear_velocity = linear_vel;
current_motion_cmd_.angular_velocity = angular_vel;
FeedCmdTimeoutWatchdog();
}
void TracerBase::SetLightCommand(const TracerLightCmd &cmd) {
static uint8_t light_cmd_count = 0;
SendLightCmd(cmd, light_cmd_count++);
}
void TracerBase::ParseCANFrame(can_frame *rx_frame) {
AgxMessage status_msg;
DecodeCanFrame(rx_frame, &status_msg);
NewStatusMsgReceivedCallback(status_msg);
}
void TracerBase::NewStatusMsgReceivedCallback(const AgxMessage &msg) {
// std::cout << "new status msg received" << std::endl;
std::lock_guard<std::mutex> guard(tracer_state_mutex_);
UpdateTracerState(msg, tracer_state_);
}
void TracerBase::UpdateTracerState(const AgxMessage &status_msg,
TracerState &state) {
switch (status_msg.type) {
case AgxMsgSystemState: {
// std::cout << "system status feedback received" << std::endl;
const SystemStateMessage &msg = status_msg.body.system_state_msg;
state.control_mode = msg.state.control_mode;
state.base_state = msg.state.vehicle_state;
state.battery_voltage =
(static_cast<uint16_t>(msg.state.battery_voltage.low_byte) |
static_cast<uint16_t>(msg.state.battery_voltage.high_byte) << 8) /
10.0;
state.fault_code = msg.state.fault_code;
break;
}
case AgxMsgMotionState: {
// std::cout << "motion control feedback received" << std::endl;
const MotionStateMessage &msg = status_msg.body.motion_state_msg;
state.linear_velocity =
static_cast<int16_t>(
static_cast<uint16_t>(msg.state.linear_velocity.low_byte) |
static_cast<uint16_t>(msg.state.linear_velocity.high_byte) << 8) /
1000.0;
state.angular_velocity =
static_cast<int16_t>(
static_cast<uint16_t>(msg.state.angular_velocity.low_byte) |
static_cast<uint16_t>(msg.state.angular_velocity.high_byte)
<< 8) /
1000.0;
break;
}
case AgxMsgLightState: {
// std::cout << "light control feedback received" << std::endl;
const LightStateMessage &msg = status_msg.body.light_state_msg;
if (msg.state.light_ctrl_enabled == LIGHT_CTRL_DISABLE)
state.light_control_enabled = false;
else
state.light_control_enabled = true;
state.front_light_state.mode = msg.state.front_light_mode;
state.front_light_state.custom_value = msg.state.front_light_custom;
break;
}
case AgxMsgActuatorHSState: {
// std::cout << "actuator hs feedback received" << std::endl;
const ActuatorHSStateMessage &msg = status_msg.body.actuator_hs_state_msg;
state.actuator_states[msg.motor_id].motor_current =
(static_cast<uint16_t>(msg.data.state.current.low_byte) |
static_cast<uint16_t>(msg.data.state.current.high_byte) << 8) /
10.0;
state.actuator_states[msg.motor_id].motor_rpm = static_cast<int16_t>(
static_cast<uint16_t>(msg.data.state.rpm.low_byte) |
static_cast<uint16_t>(msg.data.state.rpm.high_byte) << 8);
state.actuator_states[msg.motor_id].motor_pulses = static_cast<int16_t>(
static_cast<uint16_t>(msg.data.state.pulse_count.low_byte) |
static_cast<uint16_t>(msg.data.state.pulse_count.high_byte) << 8);
break;
}
case AgxMsgActuatorLSState: {
// std::cout << "actuator ls feedback received" << std::endl;
const ActuatorLSStateMessage &msg = status_msg.body.actuator_ls_state_msg;
for (int i = 0; i < 2; ++i) {
state.actuator_states[msg.motor_id].driver_voltage =
(static_cast<uint16_t>(msg.data.state.driver_voltage.low_byte) |
static_cast<uint16_t>(msg.data.state.driver_voltage.high_byte)
<< 8) /
10.0;
state.actuator_states[msg.motor_id]
.driver_temperature = static_cast<int16_t>(
static_cast<uint16_t>(msg.data.state.driver_temperature.low_byte) |
static_cast<uint16_t>(msg.data.state.driver_temperature.high_byte)
<< 8);
state.actuator_states[msg.motor_id].motor_temperature =
msg.data.state.motor_temperature;
state.actuator_states[msg.motor_id].driver_state =
msg.data.state.driver_state;
}
break;
}
case AgxMsgOdometry: {
// std::cout << "Odometer msg feedback received" << std::endl;
const OdometryMessage &msg = status_msg.body.odometry_msg;
state.right_odometry = static_cast<int32_t>(
(static_cast<uint32_t>(msg.state.right_wheel.lsb)) |
(static_cast<uint32_t>(msg.state.right_wheel.low_byte) << 8) |
(static_cast<uint32_t>(msg.state.right_wheel.high_byte) << 16) |
(static_cast<uint32_t>(msg.state.right_wheel.msb) << 24));
state.left_odometry = static_cast<int32_t>(
(static_cast<uint32_t>(msg.state.left_wheel.lsb)) |
(static_cast<uint32_t>(msg.state.left_wheel.low_byte) << 8) |
(static_cast<uint32_t>(msg.state.left_wheel.high_byte) << 16) |
(static_cast<uint32_t>(msg.state.left_wheel.msb) << 24));
}
}
}
} // namespace westonrobot
| 38.458515 | 80 | 0.704326 | Wataru-Oshima-Tokyo |
6a38ab70f815e485508e36391dad7176a16c3975 | 12,197 | hpp | C++ | include/codegen/include/RootMotion/FinalIK/IKSolverVR.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/RootMotion/FinalIK/IKSolverVR.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/RootMotion/FinalIK/IKSolverVR.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:09:17 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: RootMotion.FinalIK.IKSolver
#include "RootMotion/FinalIK/IKSolver.hpp"
// Including type: RootMotion.FinalIK.VRIK
#include "RootMotion/FinalIK/VRIK.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: RootMotion::FinalIK
namespace RootMotion::FinalIK {
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Transform
class Transform;
// Forward declaring type: Keyframe
struct Keyframe;
// Skipping declaration: Quaternion because it is already included!
}
// Completed forward declares
// Type namespace: RootMotion.FinalIK
namespace RootMotion::FinalIK {
// Autogenerated type: RootMotion.FinalIK.IKSolverVR
class IKSolverVR : public RootMotion::FinalIK::IKSolver {
public:
// Nested type: RootMotion::FinalIK::IKSolverVR::Arm
class Arm;
// Nested type: RootMotion::FinalIK::IKSolverVR::BodyPart
class BodyPart;
// Nested type: RootMotion::FinalIK::IKSolverVR::Footstep
class Footstep;
// Nested type: RootMotion::FinalIK::IKSolverVR::Leg
class Leg;
// Nested type: RootMotion::FinalIK::IKSolverVR::Locomotion
class Locomotion;
// Nested type: RootMotion::FinalIK::IKSolverVR::Spine
class Spine;
// Nested type: RootMotion::FinalIK::IKSolverVR::PositionOffset
struct PositionOffset;
// Nested type: RootMotion::FinalIK::IKSolverVR::RotationOffset
struct RotationOffset;
// Nested type: RootMotion::FinalIK::IKSolverVR::VirtualBone
class VirtualBone;
// private UnityEngine.Transform[] solverTransforms
// Offset: 0x58
::Array<UnityEngine::Transform*>* solverTransforms;
// private System.Boolean hasChest
// Offset: 0x60
bool hasChest;
// private System.Boolean hasNeck
// Offset: 0x61
bool hasNeck;
// private System.Boolean hasShoulders
// Offset: 0x62
bool hasShoulders;
// private System.Boolean hasToes
// Offset: 0x63
bool hasToes;
// private System.Boolean hasLegs
// Offset: 0x64
bool hasLegs;
// private UnityEngine.Vector3[] readPositions
// Offset: 0x68
::Array<UnityEngine::Vector3>* readPositions;
// private UnityEngine.Quaternion[] readRotations
// Offset: 0x70
::Array<UnityEngine::Quaternion>* readRotations;
// private UnityEngine.Vector3[] solvedPositions
// Offset: 0x78
::Array<UnityEngine::Vector3>* solvedPositions;
// private UnityEngine.Quaternion[] solvedRotations
// Offset: 0x80
::Array<UnityEngine::Quaternion>* solvedRotations;
// private UnityEngine.Quaternion[] defaultLocalRotations
// Offset: 0x88
::Array<UnityEngine::Quaternion>* defaultLocalRotations;
// private UnityEngine.Vector3[] defaultLocalPositions
// Offset: 0x90
::Array<UnityEngine::Vector3>* defaultLocalPositions;
// private UnityEngine.Vector3 rootV
// Offset: 0x98
UnityEngine::Vector3 rootV;
// private UnityEngine.Vector3 rootVelocity
// Offset: 0xA4
UnityEngine::Vector3 rootVelocity;
// private UnityEngine.Vector3 bodyOffset
// Offset: 0xB0
UnityEngine::Vector3 bodyOffset;
// private System.Int32 supportLegIndex
// Offset: 0xBC
int supportLegIndex;
// private System.Int32 lastLOD
// Offset: 0xC0
int lastLOD;
// public System.Int32 LOD
// Offset: 0xC4
int LOD;
// public System.Boolean plantFeet
// Offset: 0xC8
bool plantFeet;
// private RootMotion.FinalIK.IKSolverVR/VirtualBone <rootBone>k__BackingField
// Offset: 0xD0
RootMotion::FinalIK::IKSolverVR::VirtualBone* rootBone;
// public RootMotion.FinalIK.IKSolverVR/Spine spine
// Offset: 0xD8
RootMotion::FinalIK::IKSolverVR::Spine* spine;
// public RootMotion.FinalIK.IKSolverVR/Arm leftArm
// Offset: 0xE0
RootMotion::FinalIK::IKSolverVR::Arm* leftArm;
// public RootMotion.FinalIK.IKSolverVR/Arm rightArm
// Offset: 0xE8
RootMotion::FinalIK::IKSolverVR::Arm* rightArm;
// public RootMotion.FinalIK.IKSolverVR/Leg leftLeg
// Offset: 0xF0
RootMotion::FinalIK::IKSolverVR::Leg* leftLeg;
// public RootMotion.FinalIK.IKSolverVR/Leg rightLeg
// Offset: 0xF8
RootMotion::FinalIK::IKSolverVR::Leg* rightLeg;
// public RootMotion.FinalIK.IKSolverVR/Locomotion locomotion
// Offset: 0x100
RootMotion::FinalIK::IKSolverVR::Locomotion* locomotion;
// private RootMotion.FinalIK.IKSolverVR/Leg[] legs
// Offset: 0x108
::Array<RootMotion::FinalIK::IKSolverVR::Leg*>* legs;
// private RootMotion.FinalIK.IKSolverVR/Arm[] arms
// Offset: 0x110
::Array<RootMotion::FinalIK::IKSolverVR::Arm*>* arms;
// private UnityEngine.Vector3 headPosition
// Offset: 0x118
UnityEngine::Vector3 headPosition;
// private UnityEngine.Vector3 headDeltaPosition
// Offset: 0x124
UnityEngine::Vector3 headDeltaPosition;
// private UnityEngine.Vector3 raycastOriginPelvis
// Offset: 0x130
UnityEngine::Vector3 raycastOriginPelvis;
// private UnityEngine.Vector3 lastOffset
// Offset: 0x13C
UnityEngine::Vector3 lastOffset;
// private UnityEngine.Vector3 debugPos1
// Offset: 0x148
UnityEngine::Vector3 debugPos1;
// private UnityEngine.Vector3 debugPos2
// Offset: 0x154
UnityEngine::Vector3 debugPos2;
// private UnityEngine.Vector3 debugPos3
// Offset: 0x160
UnityEngine::Vector3 debugPos3;
// private UnityEngine.Vector3 debugPos4
// Offset: 0x16C
UnityEngine::Vector3 debugPos4;
// public System.Void SetToReferences(RootMotion.FinalIK.VRIK/References references)
// Offset: 0x133BDB4
void SetToReferences(RootMotion::FinalIK::VRIK::References* references);
// public System.Void GuessHandOrientations(RootMotion.FinalIK.VRIK/References references, System.Boolean onlyIfZero)
// Offset: 0x133C248
void GuessHandOrientations(RootMotion::FinalIK::VRIK::References* references, bool onlyIfZero);
// public System.Void DefaultAnimationCurves()
// Offset: 0x133C0D0
void DefaultAnimationCurves();
// public System.Void AddPositionOffset(RootMotion.FinalIK.IKSolverVR/PositionOffset positionOffset, UnityEngine.Vector3 value)
// Offset: 0x133CC34
void AddPositionOffset(RootMotion::FinalIK::IKSolverVR::PositionOffset positionOffset, UnityEngine::Vector3 value);
// public System.Void AddRotationOffset(RootMotion.FinalIK.IKSolverVR/RotationOffset rotationOffset, UnityEngine.Vector3 value)
// Offset: 0x133CF10
void AddRotationOffset(RootMotion::FinalIK::IKSolverVR::RotationOffset rotationOffset, UnityEngine::Vector3 value);
// public System.Void AddRotationOffset(RootMotion.FinalIK.IKSolverVR/RotationOffset rotationOffset, UnityEngine.Quaternion value)
// Offset: 0x133CFB4
void AddRotationOffset(RootMotion::FinalIK::IKSolverVR::RotationOffset rotationOffset, UnityEngine::Quaternion value);
// public System.Void AddPlatformMotion(UnityEngine.Vector3 deltaPosition, UnityEngine.Quaternion deltaRotation, UnityEngine.Vector3 platformPivot)
// Offset: 0x133D148
void AddPlatformMotion(UnityEngine::Vector3 deltaPosition, UnityEngine::Quaternion deltaRotation, UnityEngine::Vector3 platformPivot);
// public System.Void Reset()
// Offset: 0x133D2D4
void Reset();
// private UnityEngine.Vector3 GetNormal(UnityEngine.Transform[] transforms)
// Offset: 0x133E1D0
UnityEngine::Vector3 GetNormal(::Array<UnityEngine::Transform*>* transforms);
// private UnityEngine.Vector3 GuessWristToPalmAxis(UnityEngine.Transform hand, UnityEngine.Transform forearm)
// Offset: 0x133C4E8
UnityEngine::Vector3 GuessWristToPalmAxis(UnityEngine::Transform* hand, UnityEngine::Transform* forearm);
// private UnityEngine.Vector3 GuessPalmToThumbAxis(UnityEngine.Transform hand, UnityEngine.Transform forearm)
// Offset: 0x133C6C0
UnityEngine::Vector3 GuessPalmToThumbAxis(UnityEngine::Transform* hand, UnityEngine::Transform* forearm);
// static private UnityEngine.Keyframe[] GetSineKeyframes(System.Single mag)
// Offset: 0x133CB10
static ::Array<UnityEngine::Keyframe>* GetSineKeyframes(float mag);
// private System.Void UpdateSolverTransforms()
// Offset: 0x133D44C
void UpdateSolverTransforms();
// private System.Void WriteTransforms()
// Offset: 0x133FBFC
void WriteTransforms();
// private System.Void Read(UnityEngine.Vector3[] positions, UnityEngine.Quaternion[] rotations, System.Boolean hasChest, System.Boolean hasNeck, System.Boolean hasShoulders, System.Boolean hasToes, System.Boolean hasLegs)
// Offset: 0x133D5B4
void Read(::Array<UnityEngine::Vector3>* positions, ::Array<UnityEngine::Quaternion>* rotations, bool hasChest, bool hasNeck, bool hasShoulders, bool hasToes, bool hasLegs);
// private System.Void Solve()
// Offset: 0x133E9C0
void Solve();
// private UnityEngine.Vector3 GetPosition(System.Int32 index)
// Offset: 0x133FFE8
UnityEngine::Vector3 GetPosition(int index);
// private UnityEngine.Quaternion GetRotation(System.Int32 index)
// Offset: 0x1340030
UnityEngine::Quaternion GetRotation(int index);
// public RootMotion.FinalIK.IKSolverVR/VirtualBone get_rootBone()
// Offset: 0x1340674
RootMotion::FinalIK::IKSolverVR::VirtualBone* get_rootBone();
// private System.Void set_rootBone(RootMotion.FinalIK.IKSolverVR/VirtualBone value)
// Offset: 0x134067C
void set_rootBone(RootMotion::FinalIK::IKSolverVR::VirtualBone* value);
// private System.Void Write()
// Offset: 0x133FAAC
void Write();
// private UnityEngine.Vector3 GetPelvisOffset()
// Offset: 0x1340074
UnityEngine::Vector3 GetPelvisOffset();
// public override System.Void StoreDefaultLocalState()
// Offset: 0x133DB4C
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: System.Void IKSolver::StoreDefaultLocalState()
void StoreDefaultLocalState();
// public override System.Void FixTransforms()
// Offset: 0x133DCC0
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: System.Void IKSolver::FixTransforms()
void FixTransforms();
// public override RootMotion.FinalIK.IKSolver/Point[] GetPoints()
// Offset: 0x133DEC8
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: RootMotion.FinalIK.IKSolver/Point[] IKSolver::GetPoints()
::Array<RootMotion::FinalIK::IKSolver::Point*>* GetPoints();
// public override RootMotion.FinalIK.IKSolver/Point GetPoint(UnityEngine.Transform transform)
// Offset: 0x133DF3C
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: RootMotion.FinalIK.IKSolver/Point IKSolver::GetPoint(UnityEngine.Transform transform)
RootMotion::FinalIK::IKSolver::Point* GetPoint(UnityEngine::Transform* transform);
// public override System.Boolean IsValid(System.String message)
// Offset: 0x133DFB0
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: System.Boolean IKSolver::IsValid(System.String message)
bool IsValid(::Il2CppString*& message);
// protected override System.Void OnInitiate()
// Offset: 0x133E4B0
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: System.Void IKSolver::OnInitiate()
void OnInitiate();
// protected override System.Void OnUpdate()
// Offset: 0x133E4F8
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: System.Void IKSolver::OnUpdate()
void OnUpdate();
// public System.Void .ctor()
// Offset: 0x1340684
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: System.Void IKSolver::.ctor()
// Base method: System.Void Object::.ctor()
static IKSolverVR* New_ctor();
}; // RootMotion.FinalIK.IKSolverVR
}
DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::IKSolverVR*, "RootMotion.FinalIK", "IKSolverVR");
#pragma pack(pop)
| 45.342007 | 226 | 0.729852 | Futuremappermydud |
6a39cf622bf398dc2d2cc623f01369fb5a6fd9f8 | 405 | cpp | C++ | cpp/beginner_contest_154/c.cpp | kitoko552/atcoder | a1e18b6d855baefb90ae6df010bcf1ffa8ff5562 | [
"MIT"
] | 1 | 2020-03-31T05:53:38.000Z | 2020-03-31T05:53:38.000Z | cpp/beginner_contest_154/c.cpp | kitoko552/atcoder | a1e18b6d855baefb90ae6df010bcf1ffa8ff5562 | [
"MIT"
] | null | null | null | cpp/beginner_contest_154/c.cpp | kitoko552/atcoder | a1e18b6d855baefb90ae6df010bcf1ffa8ff5562 | [
"MIT"
] | null | null | null | // https://atcoder.jp/contests/abc154/tasks/abc154_c
#include<iostream>
using namespace std;
int main() {
int N;
cin >> N;
int A[N];
for (int i = 0; i < N; i++) {
cin >> A[i];
}
sort(A, A + N);
string ans = "YES";
for (int i = 0; i < N - 1; i++) {
if (A[i] == A[i+1]) {
ans = "NO";
}
}
cout << ans << endl;
return 0;
}
| 15 | 52 | 0.419753 | kitoko552 |
6a3aaef882072ae2fa24cf766f8c279e89491b31 | 13,845 | cpp | C++ | flang/runtime/findloc.cpp | lxbndr/llvm-project | 2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34 | [
"Apache-2.0"
] | null | null | null | flang/runtime/findloc.cpp | lxbndr/llvm-project | 2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34 | [
"Apache-2.0"
] | null | null | null | flang/runtime/findloc.cpp | lxbndr/llvm-project | 2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34 | [
"Apache-2.0"
] | null | null | null | //===-- runtime/findloc.cpp -----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Implements FINDLOC for all required operand types and shapes and result
// integer kinds.
#include "reduction-templates.h"
#include "flang/Common/long-double.h"
#include "flang/Runtime/character.h"
#include "flang/Runtime/reduction.h"
#include <cinttypes>
#include <complex>
namespace Fortran::runtime {
template <TypeCategory CAT1, int KIND1, TypeCategory CAT2, int KIND2>
struct Equality {
using Type1 = CppTypeFor<CAT1, KIND1>;
using Type2 = CppTypeFor<CAT2, KIND2>;
bool operator()(const Descriptor &array, const SubscriptValue at[],
const Descriptor &target) const {
return *array.Element<Type1>(at) == *target.OffsetElement<Type2>();
}
};
template <int KIND1, int KIND2>
struct Equality<TypeCategory::Complex, KIND1, TypeCategory::Complex, KIND2> {
using Type1 = CppTypeFor<TypeCategory::Complex, KIND1>;
using Type2 = CppTypeFor<TypeCategory::Complex, KIND2>;
bool operator()(const Descriptor &array, const SubscriptValue at[],
const Descriptor &target) const {
const Type1 &xz{*array.Element<Type1>(at)};
const Type2 &tz{*target.OffsetElement<Type2>()};
return xz.real() == tz.real() && xz.imag() == tz.imag();
}
};
template <int KIND1, TypeCategory CAT2, int KIND2>
struct Equality<TypeCategory::Complex, KIND1, CAT2, KIND2> {
using Type1 = CppTypeFor<TypeCategory::Complex, KIND1>;
using Type2 = CppTypeFor<CAT2, KIND2>;
bool operator()(const Descriptor &array, const SubscriptValue at[],
const Descriptor &target) const {
const Type1 &z{*array.Element<Type1>(at)};
return z.imag() == 0 && z.real() == *target.OffsetElement<Type2>();
}
};
template <TypeCategory CAT1, int KIND1, int KIND2>
struct Equality<CAT1, KIND1, TypeCategory::Complex, KIND2> {
using Type1 = CppTypeFor<CAT1, KIND1>;
using Type2 = CppTypeFor<TypeCategory::Complex, KIND2>;
bool operator()(const Descriptor &array, const SubscriptValue at[],
const Descriptor &target) const {
const Type2 &z{*target.OffsetElement<Type2>()};
return *array.Element<Type1>(at) == z.real() && z.imag() == 0;
}
};
template <int KIND> struct CharacterEquality {
using Type = CppTypeFor<TypeCategory::Character, KIND>;
bool operator()(const Descriptor &array, const SubscriptValue at[],
const Descriptor &target) const {
return CharacterScalarCompare<Type>(array.Element<Type>(at),
target.OffsetElement<Type>(),
array.ElementBytes() / static_cast<unsigned>(KIND),
target.ElementBytes() / static_cast<unsigned>(KIND)) == 0;
}
};
struct LogicalEquivalence {
bool operator()(const Descriptor &array, const SubscriptValue at[],
const Descriptor &target) const {
return IsLogicalElementTrue(array, at) ==
IsLogicalElementTrue(target, at /*ignored*/);
}
};
template <typename EQUALITY> class LocationAccumulator {
public:
LocationAccumulator(
const Descriptor &array, const Descriptor &target, bool back)
: array_{array}, target_{target}, back_{back} {
Reinitialize();
}
void Reinitialize() {
// per standard: result indices are all zero if no data
for (int j{0}; j < rank_; ++j) {
location_[j] = 0;
}
}
template <typename A> void GetResult(A *p, int zeroBasedDim = -1) {
if (zeroBasedDim >= 0) {
*p = location_[zeroBasedDim] -
array_.GetDimension(zeroBasedDim).LowerBound() + 1;
} else {
for (int j{0}; j < rank_; ++j) {
p[j] = location_[j] - array_.GetDimension(j).LowerBound() + 1;
}
}
}
template <typename IGNORED> bool AccumulateAt(const SubscriptValue at[]) {
if (equality_(array_, at, target_)) {
for (int j{0}; j < rank_; ++j) {
location_[j] = at[j];
}
return back_;
} else {
return true;
}
}
private:
const Descriptor &array_;
const Descriptor &target_;
const bool back_{false};
const int rank_{array_.rank()};
SubscriptValue location_[maxRank];
const EQUALITY equality_{};
};
template <TypeCategory XCAT, int XKIND, TypeCategory TARGET_CAT>
struct TotalNumericFindlocHelper {
template <int TARGET_KIND> struct Functor {
void operator()(Descriptor &result, const Descriptor &x,
const Descriptor &target, int kind, int dim, const Descriptor *mask,
bool back, Terminator &terminator) const {
using Eq = Equality<XCAT, XKIND, TARGET_CAT, TARGET_KIND>;
using Accumulator = LocationAccumulator<Eq>;
Accumulator accumulator{x, target, back};
DoTotalReduction<void>(x, dim, mask, accumulator, "FINDLOC", terminator);
ApplyIntegerKind<LocationResultHelper<Accumulator>::template Functor,
void>(kind, terminator, accumulator, result);
}
};
};
template <TypeCategory CAT,
template <TypeCategory XCAT, int XKIND, TypeCategory TARGET_CAT>
class HELPER>
struct NumericFindlocHelper {
template <int KIND> struct Functor {
void operator()(TypeCategory targetCat, int targetKind, Descriptor &result,
const Descriptor &x, const Descriptor &target, int kind, int dim,
const Descriptor *mask, bool back, Terminator &terminator) const {
switch (targetCat) {
case TypeCategory::Integer:
ApplyIntegerKind<
HELPER<CAT, KIND, TypeCategory::Integer>::template Functor, void>(
targetKind, terminator, result, x, target, kind, dim, mask, back,
terminator);
break;
case TypeCategory::Real:
ApplyFloatingPointKind<
HELPER<CAT, KIND, TypeCategory::Real>::template Functor, void>(
targetKind, terminator, result, x, target, kind, dim, mask, back,
terminator);
break;
case TypeCategory::Complex:
ApplyFloatingPointKind<
HELPER<CAT, KIND, TypeCategory::Complex>::template Functor, void>(
targetKind, terminator, result, x, target, kind, dim, mask, back,
terminator);
break;
default:
terminator.Crash(
"FINDLOC: bad target category %d for array category %d",
static_cast<int>(targetCat), static_cast<int>(CAT));
}
}
};
};
template <int KIND> struct CharacterFindlocHelper {
void operator()(Descriptor &result, const Descriptor &x,
const Descriptor &target, int kind, const Descriptor *mask, bool back,
Terminator &terminator) {
using Accumulator = LocationAccumulator<CharacterEquality<KIND>>;
Accumulator accumulator{x, target, back};
DoTotalReduction<void>(x, 0, mask, accumulator, "FINDLOC", terminator);
ApplyIntegerKind<LocationResultHelper<Accumulator>::template Functor, void>(
kind, terminator, accumulator, result);
}
};
static void LogicalFindlocHelper(Descriptor &result, const Descriptor &x,
const Descriptor &target, int kind, const Descriptor *mask, bool back,
Terminator &terminator) {
using Accumulator = LocationAccumulator<LogicalEquivalence>;
Accumulator accumulator{x, target, back};
DoTotalReduction<void>(x, 0, mask, accumulator, "FINDLOC", terminator);
ApplyIntegerKind<LocationResultHelper<Accumulator>::template Functor, void>(
kind, terminator, accumulator, result);
}
extern "C" {
void RTNAME(Findloc)(Descriptor &result, const Descriptor &x,
const Descriptor &target, int kind, const char *source, int line,
const Descriptor *mask, bool back) {
int rank{x.rank()};
SubscriptValue extent[1]{rank};
result.Establish(TypeCategory::Integer, kind, nullptr, 1, extent,
CFI_attribute_allocatable);
result.GetDimension(0).SetBounds(1, extent[0]);
Terminator terminator{source, line};
if (int stat{result.Allocate()}) {
terminator.Crash(
"FINDLOC: could not allocate memory for result; STAT=%d", stat);
}
CheckIntegerKind(terminator, kind, "FINDLOC");
auto xType{x.type().GetCategoryAndKind()};
auto targetType{target.type().GetCategoryAndKind()};
RUNTIME_CHECK(terminator, xType.has_value() && targetType.has_value());
switch (xType->first) {
case TypeCategory::Integer:
ApplyIntegerKind<NumericFindlocHelper<TypeCategory::Integer,
TotalNumericFindlocHelper>::template Functor,
void>(xType->second, terminator, targetType->first, targetType->second,
result, x, target, kind, 0, mask, back, terminator);
break;
case TypeCategory::Real:
ApplyFloatingPointKind<NumericFindlocHelper<TypeCategory::Real,
TotalNumericFindlocHelper>::template Functor,
void>(xType->second, terminator, targetType->first, targetType->second,
result, x, target, kind, 0, mask, back, terminator);
break;
case TypeCategory::Complex:
ApplyFloatingPointKind<NumericFindlocHelper<TypeCategory::Complex,
TotalNumericFindlocHelper>::template Functor,
void>(xType->second, terminator, targetType->first, targetType->second,
result, x, target, kind, 0, mask, back, terminator);
break;
case TypeCategory::Character:
RUNTIME_CHECK(terminator,
targetType->first == TypeCategory::Character &&
targetType->second == xType->second);
ApplyCharacterKind<CharacterFindlocHelper, void>(xType->second, terminator,
result, x, target, kind, mask, back, terminator);
break;
case TypeCategory::Logical:
RUNTIME_CHECK(terminator, targetType->first == TypeCategory::Logical);
LogicalFindlocHelper(result, x, target, kind, mask, back, terminator);
break;
default:
terminator.Crash(
"FINDLOC: bad data type code (%d) for array", x.type().raw());
}
}
} // extern "C"
// FINDLOC with DIM=
template <TypeCategory XCAT, int XKIND, TypeCategory TARGET_CAT>
struct PartialNumericFindlocHelper {
template <int TARGET_KIND> struct Functor {
void operator()(Descriptor &result, const Descriptor &x,
const Descriptor &target, int kind, int dim, const Descriptor *mask,
bool back, Terminator &terminator) const {
using Eq = Equality<XCAT, XKIND, TARGET_CAT, TARGET_KIND>;
using Accumulator = LocationAccumulator<Eq>;
Accumulator accumulator{x, target, back};
ApplyIntegerKind<PartialLocationHelper<Accumulator>::template Functor,
void>(kind, terminator, result, x, dim, mask, terminator, "FINDLOC",
accumulator);
}
};
};
template <int KIND> struct PartialCharacterFindlocHelper {
void operator()(Descriptor &result, const Descriptor &x,
const Descriptor &target, int kind, int dim, const Descriptor *mask,
bool back, Terminator &terminator) {
using Accumulator = LocationAccumulator<CharacterEquality<KIND>>;
Accumulator accumulator{x, target, back};
ApplyIntegerKind<PartialLocationHelper<Accumulator>::template Functor,
void>(kind, terminator, result, x, dim, mask, terminator, "FINDLOC",
accumulator);
}
};
static void PartialLogicalFindlocHelper(Descriptor &result, const Descriptor &x,
const Descriptor &target, int kind, int dim, const Descriptor *mask,
bool back, Terminator &terminator) {
using Accumulator = LocationAccumulator<LogicalEquivalence>;
Accumulator accumulator{x, target, back};
ApplyIntegerKind<PartialLocationHelper<Accumulator>::template Functor, void>(
kind, terminator, result, x, dim, mask, terminator, "FINDLOC",
accumulator);
}
extern "C" {
void RTNAME(FindlocDim)(Descriptor &result, const Descriptor &x,
const Descriptor &target, int kind, int dim, const char *source, int line,
const Descriptor *mask, bool back) {
Terminator terminator{source, line};
CheckIntegerKind(terminator, kind, "FINDLOC");
auto xType{x.type().GetCategoryAndKind()};
auto targetType{target.type().GetCategoryAndKind()};
RUNTIME_CHECK(terminator, xType.has_value() && targetType.has_value());
switch (xType->first) {
case TypeCategory::Integer:
ApplyIntegerKind<NumericFindlocHelper<TypeCategory::Integer,
PartialNumericFindlocHelper>::template Functor,
void>(xType->second, terminator, targetType->first, targetType->second,
result, x, target, kind, dim, mask, back, terminator);
break;
case TypeCategory::Real:
ApplyFloatingPointKind<NumericFindlocHelper<TypeCategory::Real,
PartialNumericFindlocHelper>::template Functor,
void>(xType->second, terminator, targetType->first, targetType->second,
result, x, target, kind, dim, mask, back, terminator);
break;
case TypeCategory::Complex:
ApplyFloatingPointKind<NumericFindlocHelper<TypeCategory::Complex,
PartialNumericFindlocHelper>::template Functor,
void>(xType->second, terminator, targetType->first, targetType->second,
result, x, target, kind, dim, mask, back, terminator);
break;
case TypeCategory::Character:
RUNTIME_CHECK(terminator,
targetType->first == TypeCategory::Character &&
targetType->second == xType->second);
ApplyCharacterKind<PartialCharacterFindlocHelper, void>(xType->second,
terminator, result, x, target, kind, dim, mask, back, terminator);
break;
case TypeCategory::Logical:
RUNTIME_CHECK(terminator, targetType->first == TypeCategory::Logical);
PartialLogicalFindlocHelper(
result, x, target, kind, dim, mask, back, terminator);
break;
default:
terminator.Crash(
"FINDLOC: bad data type code (%d) for array", x.type().raw());
}
}
} // extern "C"
} // namespace Fortran::runtime
| 40.364431 | 80 | 0.680318 | lxbndr |
6a3c03312997bc4325a4dc78961ed30277123281 | 8,319 | cpp | C++ | src/behaviortree/nodes/composites/referencebehavior.cpp | pjkui/behaviac_2.0.7 | db4bec559c184c4af125005bf07bc0b25e2c6e66 | [
"BSD-3-Clause"
] | null | null | null | src/behaviortree/nodes/composites/referencebehavior.cpp | pjkui/behaviac_2.0.7 | db4bec559c184c4af125005bf07bc0b25e2c6e66 | [
"BSD-3-Clause"
] | null | null | null | src/behaviortree/nodes/composites/referencebehavior.cpp | pjkui/behaviac_2.0.7 | db4bec559c184c4af125005bf07bc0b25e2c6e66 | [
"BSD-3-Clause"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// 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 "behaviac/base/base.h"
#include "behaviac/behaviortree/nodes/composites/referencebehavior.h"
#include "behaviac/agent/agent.h"
#include "behaviac/agent/taskmethod.h"
#include "behaviac/behaviortree/nodes/actions/action.h"
#include "behaviac/htn/planner.h"
#include "behaviac/htn/plannertask.h"
#include "behaviac/htn/task.h"
#include "behaviac/fsm/state.h"
#include "behaviac/fsm/transitioncondition.h"
namespace behaviac
{
ReferencedBehavior::ReferencedBehavior() : m_taskNode(0), m_taskMethod(0), m_transitions(0)
{}
ReferencedBehavior::~ReferencedBehavior()
{
BEHAVIAC_DELETE this->m_transitions;
}
void ReferencedBehavior::load(int version, const char* agentType, const properties_t& properties)
{
super::load(version, agentType, properties);
for (propertie_const_iterator_t it = properties.begin(); it != properties.end(); ++it)
{
const property_t& p = (*it);
if (strcmp(p.name, "ReferenceFilename") == 0)
{
this->m_referencedBehaviorPath = p.value;
bool bOk = Workspace::GetInstance()->Load(this->m_referencedBehaviorPath.c_str());
BEHAVIAC_UNUSED_VAR(bOk);
BEHAVIAC_ASSERT(bOk);
}
else if (strcmp(p.name, "Task") == 0)
{
BEHAVIAC_ASSERT(!StringUtils::IsNullOrEmpty(p.value));
CMethodBase* m = Action::LoadMethod(p.value);
//BEHAVIAC_ASSERT(m is CTaskMethod);
this->m_taskMethod = (CTaskMethod*)m;
}
else
{
//BEHAVIAC_ASSERT(0, "unrecognised property %s", p.name);
}
}
}
bool ReferencedBehavior::decompose(BehaviorNode* node, PlannerTaskComplex* seqTask, int depth, Planner* planner)
{
bool bOk = false;
ReferencedBehavior* taskSubTree = (ReferencedBehavior*)node;// as ReferencedBehavior;
BEHAVIAC_ASSERT(taskSubTree != 0);
int depth2 = planner->GetAgent()->m_variables.Depth();
BEHAVIAC_UNUSED_VAR(depth2);
{
AgentState::AgentStateScope scopedState(planner->GetAgent()->m_variables.Push(false));
//planner.agent.Variables.Log(planner.agent, true);
taskSubTree->SetTaskParams(planner->GetAgent());
Task* task = taskSubTree->RootTaskNode();
if (task != 0)
{
planner->LogPlanReferenceTreeEnter(planner->GetAgent(), taskSubTree);
const BehaviorNode* tree = task->GetParent();
tree->InstantiatePars(planner->GetAgent());
PlannerTask* childTask = planner->decomposeNode(task, depth);
if (childTask != 0)
{
seqTask->AddChild(childTask);
bOk = true;
}
tree->UnInstantiatePars(planner->GetAgent());
planner->LogPlanReferenceTreeExit(planner->GetAgent(), taskSubTree);
BEHAVIAC_ASSERT(true);
}
}
BEHAVIAC_ASSERT(planner->GetAgent()->m_variables.Depth() == depth2);
return bOk;
}
void ReferencedBehavior::Attach(BehaviorNode* pAttachment, bool bIsPrecondition, bool bIsEffector, bool bIsTransition)
{
if (bIsTransition)
{
BEHAVIAC_ASSERT(!bIsEffector && !bIsPrecondition);
if (this->m_transitions == 0)
{
this->m_transitions = BEHAVIAC_NEW behaviac::vector<Transition*>();
}
BEHAVIAC_ASSERT(Transition::DynamicCast(pAttachment) != 0);
Transition* pTransition = (Transition*)pAttachment;
this->m_transitions->push_back(pTransition);
return;
}
BEHAVIAC_ASSERT(bIsTransition == false);
super::Attach(pAttachment, bIsPrecondition, bIsEffector, bIsTransition);
}
bool ReferencedBehavior::IsValid(Agent* pAgent, BehaviorTask* pTask) const
{
if (!ReferencedBehavior::DynamicCast(pTask->GetNode()))
{
return false;
}
return super::IsValid(pAgent, pTask);
}
BehaviorTask* ReferencedBehavior::createTask() const
{
ReferencedBehaviorTask* pTask = BEHAVIAC_NEW ReferencedBehaviorTask();
return pTask;
}
void ReferencedBehavior::SetTaskParams(Agent* pAgent)
{
if (this->m_taskMethod != 0)
{
this->m_taskMethod->SetTaskParams(pAgent);
}
}
Task* ReferencedBehavior::RootTaskNode()
{
if (this->m_taskNode == 0)
{
BehaviorTree* bt = Workspace::GetInstance()->LoadBehaviorTree(this->m_referencedBehaviorPath.c_str());
if (bt != 0 && bt->GetChildrenCount() == 1)
{
BehaviorNode* root = (BehaviorNode*)bt->GetChild(0);
this->m_taskNode = (Task*)root;
}
}
return this->m_taskNode;
}
const char* ReferencedBehavior::GetReferencedTree() const
{
return this->m_referencedBehaviorPath.c_str();
}
ReferencedBehaviorTask::ReferencedBehaviorTask() : SingeChildTask(), m_nextStateId(-1), m_subTree(0)
{
}
ReferencedBehaviorTask::~ReferencedBehaviorTask()
{
}
void ReferencedBehaviorTask::copyto(BehaviorTask* target) const
{
super::copyto(target);
// BEHAVIAC_ASSERT(ReferencedBehaviorTask::DynamicCast(target));
// ReferencedBehaviorTask* ttask = (ReferencedBehaviorTask*)target;
}
void ReferencedBehaviorTask::save(ISerializableNode* node) const
{
super::save(node);
}
void ReferencedBehaviorTask::load(ISerializableNode* node)
{
super::load(node);
}
void ReferencedBehaviorTask::Init(const BehaviorNode* node)
{
super::Init(node);
}
bool ReferencedBehaviorTask::onenter(Agent* pAgent)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_ASSERT(ReferencedBehavior::DynamicCast(this->m_node) != 0);
ReferencedBehavior* pNode = (ReferencedBehavior*)this->m_node;
BEHAVIAC_ASSERT(pNode != 0);
this->m_nextStateId = -1;
pNode->SetTaskParams(pAgent);
this->m_subTree = Workspace::GetInstance()->CreateBehaviorTreeTask(pNode->m_referencedBehaviorPath.c_str());
{
const char* pThisTree = pAgent->btgetcurrent()->GetName().c_str();
const char* pReferencedTree = pNode->m_referencedBehaviorPath.c_str();
behaviac::string msg = FormatString("%s[%d] %s", pThisTree, pNode->GetId(), pReferencedTree);
LogManager::GetInstance()->Log(pAgent, msg.c_str(), EAR_none, ELM_jump);
}
return true;
}
void ReferencedBehaviorTask::onexit(Agent* pAgent, EBTStatus s)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(s);
}
int ReferencedBehaviorTask::GetNextStateId() const
{
return this->m_nextStateId;
}
EBTStatus ReferencedBehaviorTask::update(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(childStatus);
BEHAVIAC_ASSERT(ReferencedBehavior::DynamicCast(this->GetNode()));
const ReferencedBehavior* pNode = (const ReferencedBehavior*)this->m_node;
BEHAVIAC_ASSERT(pNode);
EBTStatus result = this->m_subTree->exec(pAgent);
bool bTransitioned = State::UpdateTransitions(pAgent, pNode, pNode->m_transitions, this->m_nextStateId);
if (bTransitioned)
{
result = BT_SUCCESS;
}
return result;
}
}//namespace behaviac
| 31.392453 | 119 | 0.630484 | pjkui |
6a3d065597852b9a7f2a53df9617722c242192a7 | 1,169 | cc | C++ | src/linear/qr_unpack_pt.cc | Seeenman/Draco | 8540aeb8bbbf467c3aa1caa9521d0910e0ca7917 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | src/linear/qr_unpack_pt.cc | Seeenman/Draco | 8540aeb8bbbf467c3aa1caa9521d0910e0ca7917 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | src/linear/qr_unpack_pt.cc | Seeenman/Draco | 8540aeb8bbbf467c3aa1caa9521d0910e0ca7917 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | //--------------------------------------------*-C++-*---------------------------------------------//
/*!
* \file linear/qr_unpack_pt.cc
* \author Kent Budge
* \date Wed Aug 11 15:21:38 2004
* \brief Specializations of qr_unpack
* \note Copyright (C) 2016-2020 Triad National Security, LLC., All rights reserved. */
//------------------------------------------------------------------------------------------------//
#include "qr_unpack.i.hh"
#include <vector>
namespace rtt_linear {
using std::vector;
//------------------------------------------------------------------------------------------------//
// RandomContainer = vector<double>
//------------------------------------------------------------------------------------------------//
template void qr_unpack(vector<double> &r, const unsigned n, const vector<double> &c,
const vector<double> &d, vector<double> &qt);
} // end namespace rtt_linear
//------------------------------------------------------------------------------------------------//
// end of qr_unpack.cc
//------------------------------------------------------------------------------------------------//
| 41.75 | 100 | 0.328486 | Seeenman |
6a4471eccef3b3e1530eb42d4c61571c257a98e4 | 142 | cpp | C++ | Implementation/Task 2/src/exceptions/PlayerExceptions.cpp | migueldingli1997/CPS2004-Object-Oriented-Programming-Assignment | 8dfc9a43e073b5ad55f1021717657dc87b8bbdbb | [
"MIT"
] | 1 | 2022-01-19T09:41:56.000Z | 2022-01-19T09:41:56.000Z | Implementation/Task 2/src/exceptions/PlayerExceptions.cpp | migueldingli1997/CPS2004-Object-Oriented-Programming-Assignment | 8dfc9a43e073b5ad55f1021717657dc87b8bbdbb | [
"MIT"
] | null | null | null | Implementation/Task 2/src/exceptions/PlayerExceptions.cpp | migueldingli1997/CPS2004-Object-Oriented-Programming-Assignment | 8dfc9a43e073b5ad55f1021717657dc87b8bbdbb | [
"MIT"
] | null | null | null | #include "PlayerExceptions.h"
const char *NotEnoughMoneyException::what() const throw() {
return "Player did not have enough money.";
}
| 20.285714 | 59 | 0.725352 | migueldingli1997 |
6a455ed406a69917886c71789c57f47d9c9c50e2 | 1,246 | hh | C++ | enc_modules/crypto_mk/main/sha.hh | Tofuseng/Mylar | 852bbeb27e077e36cdc561803d33bafa5dc795a9 | [
"Apache-2.0"
] | 240 | 2015-01-04T10:47:28.000Z | 2022-03-17T10:50:34.000Z | enc_modules/crypto_mk/main/sha.hh | eternaltyro/mylar | 18e9d0e6ef8fd836073c8bc47d79bb76c5405da5 | [
"Apache-2.0"
] | 8 | 2015-03-18T14:35:41.000Z | 2017-04-11T06:01:41.000Z | enc_modules/crypto_mk/main/sha.hh | eternaltyro/mylar | 18e9d0e6ef8fd836073c8bc47d79bb76c5405da5 | [
"Apache-2.0"
] | 42 | 2015-01-18T12:22:49.000Z | 2022-01-20T04:21:47.000Z | #pragma once
#include <openssl/sha.h>
#include <string>
template<class State,
int OutBytes,
int BlockBytes,
int (*Init)(State*),
int (*Update)(State*, const void*, size_t),
int (*Final)(uint8_t*, State*)>
class sha {
public:
sha() { Init(&s); }
void update(const void *data, size_t len) { Update(&s, data, len); }
void final(uint8_t *buf) {
Final(buf, &s);
}
std::string final() {
std::string v;
v.resize(hashsize);
final((uint8_t*) v.data());
return v;
}
static std::string hash(const std::string &s) {
sha x;
x.update(s.data(), s.length());
return x.final();
}
static const size_t hashsize = OutBytes;
static const size_t blocksize = BlockBytes;
private:
State s;
};
typedef sha<SHA_CTX, 20, 64, SHA1_Init, SHA1_Update, SHA1_Final> sha1;
typedef sha<SHA256_CTX, 28, 64, SHA224_Init, SHA224_Update, SHA224_Final> sha224;
typedef sha<SHA256_CTX, 32, 64, SHA256_Init, SHA256_Update, SHA256_Final> sha256;
typedef sha<SHA512_CTX, 48, 128, SHA384_Init, SHA384_Update, SHA384_Final> sha384;
typedef sha<SHA512_CTX, 64, 128, SHA512_Init, SHA512_Update, SHA512_Final> sha512;
| 27.086957 | 82 | 0.62199 | Tofuseng |
6a46229abe2ea1c1b2f81fa77e92a668d6ba487e | 4,336 | cc | C++ | lib/ts/ConsistentHash.cc | garfieldonly/ats_git | 940ff5c56bebabb96130a55c2a17212c5c518138 | [
"Apache-2.0"
] | 1 | 2022-01-19T14:34:34.000Z | 2022-01-19T14:34:34.000Z | lib/ts/ConsistentHash.cc | mingzym/trafficserver | a01c3a357b4ff9193f2e2a8aee48e3751ef2177a | [
"Apache-2.0"
] | 2 | 2017-12-05T23:48:37.000Z | 2017-12-20T01:22:07.000Z | lib/ts/ConsistentHash.cc | maskit/trafficserver | 3ffa19873f7cd7ced2fbdfed5a0ac8ddbbe70a68 | [
"Apache-2.0"
] | null | null | null | /** @file
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ConsistentHash.h"
#include <cstring>
#include <string>
#include <sstream>
#include <cmath>
#include <climits>
#include <cstdio>
std::ostream &operator<<(std::ostream &os, ATSConsistentHashNode &thing)
{
return os << thing.name;
}
ATSConsistentHash::ATSConsistentHash(int r, ATSHash64 *h) : replicas(r), hash(h)
{
}
void
ATSConsistentHash::insert(ATSConsistentHashNode *node, float weight, ATSHash64 *h)
{
int i;
char numstr[256];
ATSHash64 *thash;
std::ostringstream string_stream;
std::string std_string;
if (h) {
thash = h;
} else if (hash) {
thash = hash;
} else {
return;
}
string_stream << *node;
std_string = string_stream.str();
for (i = 0; i < (int)roundf(replicas * weight); i++) {
snprintf(numstr, 256, "%d-", i);
thash->update(numstr, strlen(numstr));
thash->update(std_string.c_str(), strlen(std_string.c_str()));
thash->final();
NodeMap.insert(std::pair<uint64_t, ATSConsistentHashNode *>(thash->get(), node));
thash->clear();
}
}
ATSConsistentHashNode *
ATSConsistentHash::lookup(const char *url, ATSConsistentHashIter *i, bool *w, ATSHash64 *h)
{
uint64_t url_hash;
ATSConsistentHashIter NodeMapIterUp, *iter;
ATSHash64 *thash;
bool *wptr, wrapped = false;
if (h) {
thash = h;
} else if (hash) {
thash = hash;
} else {
return NULL;
}
if (w) {
wptr = w;
} else {
wptr = &wrapped;
}
if (i) {
iter = i;
} else {
iter = &NodeMapIterUp;
}
if (url) {
thash->update(url, strlen(url));
thash->final();
url_hash = thash->get();
thash->clear();
*iter = NodeMap.lower_bound(url_hash);
if (*iter == NodeMap.end()) {
*wptr = true;
*iter = NodeMap.begin();
}
} else {
(*iter)++;
}
if (!(*wptr) && *iter == NodeMap.end()) {
*wptr = true;
*iter = NodeMap.begin();
}
if (*wptr && *iter == NodeMap.end()) {
return NULL;
}
return (*iter)->second;
}
ATSConsistentHashNode *
ATSConsistentHash::lookup_available(const char *url, ATSConsistentHashIter *i, bool *w, ATSHash64 *h)
{
uint64_t url_hash;
ATSConsistentHashIter NodeMapIterUp, *iter;
ATSHash64 *thash;
bool *wptr, wrapped = false;
if (h) {
thash = h;
} else if (hash) {
thash = hash;
} else {
return NULL;
}
if (w) {
wptr = w;
} else {
wptr = &wrapped;
}
if (i) {
iter = i;
} else {
iter = &NodeMapIterUp;
}
if (url) {
thash->update(url, strlen(url));
thash->final();
url_hash = thash->get();
thash->clear();
*iter = NodeMap.lower_bound(url_hash);
}
if (*iter == NodeMap.end()) {
*wptr = true;
*iter = NodeMap.begin();
}
while (!(*iter)->second->available) {
(*iter)++;
if (!(*wptr) && *iter == NodeMap.end()) {
*wptr = true;
*iter = NodeMap.begin();
} else if (*wptr && *iter == NodeMap.end()) {
return NULL;
}
}
return (*iter)->second;
}
ATSConsistentHashNode *
ATSConsistentHash::lookup_by_hashval(uint64_t hashval, ATSConsistentHashIter *i, bool *w)
{
ATSConsistentHashIter NodeMapIterUp, *iter;
bool *wptr, wrapped = false;
if (w) {
wptr = w;
} else {
wptr = &wrapped;
}
if (i) {
iter = i;
} else {
iter = &NodeMapIterUp;
}
*iter = NodeMap.lower_bound(hashval);
if (*iter == NodeMap.end()) {
*wptr = true;
*iter = NodeMap.begin();
}
return (*iter)->second;
}
ATSConsistentHash::~ATSConsistentHash()
{
if (hash) {
delete hash;
}
}
| 20.167442 | 101 | 0.622232 | garfieldonly |
6a466d6900d1e788292c0df3476c873f631e4f2d | 974 | hxx | C++ | libstudxml/libstudxml/details/config.hxx | pdpdds/yuza_thirdparty | 461b7481322df4f1c3f0d258c1b4ea4bad16f10c | [
"MIT"
] | null | null | null | libstudxml/libstudxml/details/config.hxx | pdpdds/yuza_thirdparty | 461b7481322df4f1c3f0d258c1b4ea4bad16f10c | [
"MIT"
] | null | null | null | libstudxml/libstudxml/details/config.hxx | pdpdds/yuza_thirdparty | 461b7481322df4f1c3f0d258c1b4ea4bad16f10c | [
"MIT"
] | null | null | null | // file : libstudxml/details/config.hxx
// license : MIT; see accompanying LICENSE file
#ifndef LIBSTUDXML_DETAILS_CONFIG_HXX
#define LIBSTUDXML_DETAILS_CONFIG_HXX
// C++11 support.
//
#ifdef _MSC_VER
# if _MSC_VER >= 1900
# define STUDXML_CXX11_NOEXCEPT
# endif
#else
# if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L
# ifdef __clang__ // Pretends to be a really old __GNUC__ on some platforms.
# define STUDXML_CXX11_NOEXCEPT
# elif defined(__GNUC__)
# if (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) || __GNUC__ > 4
# define STUDXML_CXX11_NOEXCEPT
# endif
# else
# define STUDXML_CXX11_NOEXCEPT
# endif
# endif
#endif
#ifdef STUDXML_CXX11_NOEXCEPT
# define STUDXML_NOTHROW_NOEXCEPT noexcept
#else
# define STUDXML_NOTHROW_NOEXCEPT throw()
#endif
#ifdef _MSC_VER
# include <libstudxml/details/config-vc.h>
#else
# include <libstudxml/details/config.h>
#endif
#endif // LIBSTUDXML_DETAILS_CONFIG_HXX
| 24.35 | 79 | 0.732033 | pdpdds |
6a4683a580bb07722e090ae5df87a17cfeb87fff | 378 | cpp | C++ | archive/codevs.6061.cpp | woshiluo/oi | 5637fb81b0e25013314783dc387f7fc93bf9d4b9 | [
"Apache-2.0"
] | null | null | null | archive/codevs.6061.cpp | woshiluo/oi | 5637fb81b0e25013314783dc387f7fc93bf9d4b9 | [
"Apache-2.0"
] | null | null | null | archive/codevs.6061.cpp | woshiluo/oi | 5637fb81b0e25013314783dc387f7fc93bf9d4b9 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
using namespace std;
int n,r,a[30];
bool x;
void dfs(int deep,int temp){
if(deep==r){
for(int i=0;i<r;i++) printf("%3d",a[i]);
printf("\n");
}
else for(int i=1;i<=n;i++){
x=false;
for(int j=0;j<deep;j++){
if(a[j]==i) x=true;
}
if(x) continue;
a[deep]=i;
dfs(deep+1,i);
a[deep]=0;
}
}
int main(){
scanf("%d%d",&n,&r);
dfs(0,0);
}
| 13.034483 | 42 | 0.521164 | woshiluo |
6a46a21f962427727c4faf617fcf83a19d2e221a | 3,405 | cpp | C++ | test/test_connection_adapter.cpp | iTuMaN4iK/asio_utils | 2182f14f46bdd3ab96cccf038ad925bf9b83e55f | [
"MIT"
] | null | null | null | test/test_connection_adapter.cpp | iTuMaN4iK/asio_utils | 2182f14f46bdd3ab96cccf038ad925bf9b83e55f | [
"MIT"
] | null | null | null | test/test_connection_adapter.cpp | iTuMaN4iK/asio_utils | 2182f14f46bdd3ab96cccf038ad925bf9b83e55f | [
"MIT"
] | null | null | null |
#include "asio_utils/connection_adapter.hpp"
#include "asio_utils/testing/stub_connection.h"
#include <asio.hpp>
#include <gtest/gtest.h>
#include <cstdint>
#include <numeric>
#include <vector>
namespace e_testing = eld::testing;
template<typename ConnectionT>
class connection_wrapper
{
public:
using connection_type = ConnectionT;
using config_type = typename eld::traits::connection<connection_type>::config_type;
explicit connection_wrapper(connection_type &connection) //
: connection_(connection)
{
}
template<typename ConstBuffer, typename CompletionT>
auto async_send(ConstBuffer &&constBuffer, CompletionT &&a_completion)
{
return connection_.async_send(std::forward<ConstBuffer>(constBuffer),
std::forward<CompletionT>(a_completion));
}
template<typename ConstBuffer, typename CompletionT>
auto async_receive(ConstBuffer &&constBuffer, CompletionT &&a_completion)
{
return connection_.async_receive(std::forward<ConstBuffer>(constBuffer),
std::forward<CompletionT>(a_completion));
}
void configure(const config_type &config) { connection_.configure(config); }
config_type get_config() const { return connection_.get_config(); }
void cancel() { connection_.cancel(); }
private:
connection_type &connection_;
};
template<typename ConnectionT>
connection_wrapper<ConnectionT> wrap_connection(ConnectionT &connection)
{
return connection_wrapper<ConnectionT>(connection);
}
/*
* destination (to emulate receiving) -> source -> adapter -> destination -> source (to emulate
* sending)
* 1. make connections
* 2. make wrappers to send and receive
* 3. make adapter from wrappers
* 4. send data with future
* 5. wait for data with future
* 6. compare data
*/
TEST(connection_adapter, stub_connection)
{
using namespace e_testing;
std::vector<uint32_t> send(size_t(512)), //
receive(size_t(512));
std::iota(send.begin(), send.end(), 0);
asio::thread_pool context{ 2 };
stub_connection connectionSourceRemote{ context, stub_config{ 0, 1 } },
connectionSource{ context, stub_config{ 1, 2 } },
connectionDest{ context, stub_config{ 2, 3 } },
connectionDestRemote{ context, stub_config{ 3, 4 } };
connectionSourceRemote.set_remote_host(connectionSource);
connectionDest.set_remote_host(connectionDestRemote);
{
auto adapter = eld::make_connection_adapter(wrap_connection(connectionSource),
wrap_connection(connectionDest));
adapter.async_run(eld::direction::a_to_b,
[](const asio::error_code &errorCode) { //
EXPECT_EQ(errorCode, asio::error_code());
});
auto futureSent = connectionSourceRemote.async_send(asio::buffer(send), asio::use_future);
auto futureReceive =
connectionDestRemote.async_receive(asio::buffer(receive), asio::use_future);
// why does future not block on destruction?
futureSent.get();
futureReceive.get();
}
std::cout << "end of receiving data" << std::endl;
ASSERT_EQ(send, receive);
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 30.675676 | 98 | 0.666079 | iTuMaN4iK |
6a47fc453da7499b2886a29a657d767b06c0b7ec | 9,477 | cc | C++ | src/storage/blobfs/compression/decompressor_sandbox/decompressor_impl.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | src/storage/blobfs/compression/decompressor_sandbox/decompressor_impl.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 5 | 2019-12-04T15:13:37.000Z | 2020-02-19T08:11:38.000Z | src/storage/blobfs/compression/decompressor_sandbox/decompressor_impl.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef _ALL_SOURCE
#define _ALL_SOURCE // Enables thrd_create_with_name in <threads.h>.
#endif
#include "src/storage/blobfs/compression/decompressor_sandbox/decompressor_impl.h"
#include <fidl/fuchsia.blobfs.internal/cpp/wire.h>
#include <fuchsia/scheduler/cpp/fidl.h>
#include <lib/fdio/directory.h>
#include <lib/fzl/owned-vmo-mapper.h>
#include <lib/syslog/cpp/macros.h>
#include <lib/trace/event.h>
#include <lib/zx/thread.h>
#include <lib/zx/time.h>
#include <threads.h>
#include <zircon/errors.h>
#include <zircon/status.h>
#include <zircon/threads.h>
#include <zircon/types.h>
#include <src/lib/chunked-compression/chunked-decompressor.h>
#include "src/storage/blobfs/compression/decompressor.h"
#include "src/storage/blobfs/compression/external_decompressor.h"
#include "src/storage/blobfs/compression_settings.h"
namespace {
struct FifoInfo {
zx::fifo fifo;
fzl::OwnedVmoMapper compressed_mapper;
fzl::OwnedVmoMapper decompressed_mapper;
};
} // namespace
namespace blobfs {
// This will only decompress a set of complete chunks, if the beginning or end
// of the range are not chunk aligned this operation will fail.
zx_status_t DecompressChunkedPartial(const fzl::OwnedVmoMapper& decompressed_mapper,
const fzl::OwnedVmoMapper& compressed_mapper,
const fuchsia_blobfs_internal::wire::Range decompressed,
const fuchsia_blobfs_internal::wire::Range compressed,
size_t* bytes_decompressed) {
const uint8_t* src = static_cast<const uint8_t*>(compressed_mapper.start()) + compressed.offset;
uint8_t* dst = static_cast<uint8_t*>(decompressed_mapper.start()) + decompressed.offset;
chunked_compression::ChunkedDecompressor decompressor;
return decompressor.DecompressFrame(src, compressed.size, dst, decompressed.size,
bytes_decompressed);
}
zx_status_t DecompressFull(const fzl::OwnedVmoMapper& decompressed_mapper,
const fzl::OwnedVmoMapper& compressed_mapper, size_t decompressed_length,
size_t compressed_length, CompressionAlgorithm algorithm,
size_t* bytes_decompressed) {
std::unique_ptr<Decompressor> decompressor = nullptr;
if (zx_status_t status = Decompressor::Create(algorithm, &decompressor); status != ZX_OK) {
return status;
}
*bytes_decompressed = decompressed_length;
return decompressor->Decompress(decompressed_mapper.start(), bytes_decompressed,
compressed_mapper.start(), compressed_length);
}
// The actual handling of a request on the fifo.
void HandleFifo(const fzl::OwnedVmoMapper& compressed_mapper,
const fzl::OwnedVmoMapper& decompressed_mapper,
const fuchsia_blobfs_internal::wire::DecompressRequest* request,
fuchsia_blobfs_internal::wire::DecompressResponse* response) {
TRACE_DURATION("decompressor", "HandleFifo", "length", request->decompressed.size);
size_t bytes_decompressed = 0;
switch (request->algorithm) {
case fuchsia_blobfs_internal::wire::CompressionAlgorithm::kChunkedPartial:
response->status =
DecompressChunkedPartial(decompressed_mapper, compressed_mapper, request->decompressed,
request->compressed, &bytes_decompressed);
break;
case fuchsia_blobfs_internal::wire::CompressionAlgorithm::kLz4:
case fuchsia_blobfs_internal::wire::CompressionAlgorithm::kZstd:
case fuchsia_blobfs_internal::wire::CompressionAlgorithm::kZstdSeekable: {
response->status = ZX_ERR_NOT_SUPPORTED;
break;
}
case fuchsia_blobfs_internal::wire::CompressionAlgorithm::kChunked:
if (request->decompressed.offset != 0 || request->compressed.offset != 0) {
bytes_decompressed = 0;
response->status = ZX_ERR_NOT_SUPPORTED;
} else if (auto algorithm_or = ExternalDecompressorClient::CompressionAlgorithmFidlToLocal(
request->algorithm)) {
response->status =
DecompressFull(decompressed_mapper, compressed_mapper, request->decompressed.size,
request->compressed.size, *algorithm_or, &bytes_decompressed);
} else {
// Invalid compression algorithm.
bytes_decompressed = 0;
response->status = ZX_ERR_NOT_SUPPORTED;
}
break;
case fuchsia_blobfs_internal::wire::CompressionAlgorithm::kUncompressed:
response->status = ZX_ERR_NOT_SUPPORTED;
break;
}
response->size = bytes_decompressed;
}
// Watches a fifo for requests to take data from the compressed_vmo and
// extract the result into the memory region of decompressed_mapper.
void WatchFifo(zx::fifo fifo, fzl::OwnedVmoMapper compressed_mapper,
fzl::OwnedVmoMapper decompressed_mapper) {
constexpr zx_signals_t kFifoReadSignals = ZX_FIFO_READABLE | ZX_FIFO_PEER_CLOSED;
constexpr zx_signals_t kFifoWriteSignals = ZX_FIFO_WRITABLE | ZX_FIFO_PEER_CLOSED;
while (fifo.is_valid()) {
zx_signals_t signal;
fifo.wait_one(kFifoReadSignals, zx::time::infinite(), &signal);
// It doesn't matter if there's anything left in the queue, nobody is there
// to read the response.
if ((signal & ZX_FIFO_PEER_CLOSED) != 0) {
break;
}
fuchsia_blobfs_internal::wire::DecompressRequest request;
zx_status_t status = fifo.read(sizeof(request), &request, 1, nullptr);
if (status != ZX_OK) {
break;
}
fuchsia_blobfs_internal::wire::DecompressResponse response;
HandleFifo(compressed_mapper, decompressed_mapper, &request, &response);
fifo.wait_one(kFifoWriteSignals, zx::time::infinite(), &signal);
if ((signal & ZX_FIFO_WRITABLE) == 0 ||
fifo.write(sizeof(response), &response, 1, nullptr) != ZX_OK) {
break;
}
}
}
// A Wrapper around WatchFifo just to unwrap the data in the callback provided
// by thrd_create_With_name().
int WatchFifoWrapper(void* data) {
std::unique_ptr<FifoInfo> info(static_cast<FifoInfo*>(data));
WatchFifo(std::move(info->fifo), std::move(info->compressed_mapper),
std::move(info->decompressed_mapper));
return 0;
}
void SetDeadlineProfile(thrd_t* thread) {
zx::channel channel0, channel1;
zx_status_t status = zx::channel::create(0u, &channel0, &channel1);
if (status != ZX_OK) {
FX_LOGS(WARNING) << "[decompressor]: Could not create channel pair: "
<< zx_status_get_string(status);
return;
}
// Connect to the scheduler profile provider service.
status = fdio_service_connect(
(std::string("/svc/") + fuchsia::scheduler::ProfileProvider::Name_).c_str(),
channel0.release());
if (status != ZX_OK) {
FX_LOGS(WARNING) << "[decompressor]: Could not connect to scheduler profile provider: "
<< zx_status_get_string(status);
return;
}
fuchsia::scheduler::ProfileProvider_SyncProxy profile_provider(std::move(channel1));
// TODO(fxbug.dev/40858): Migrate to the role-based API when available, instead of hard
// coding parameters.
const zx_duration_t capacity = ZX_USEC(1000);
const zx_duration_t deadline = ZX_MSEC(2);
const zx_duration_t period = deadline;
zx::profile profile;
zx_status_t fidl_status = profile_provider.GetDeadlineProfile(
capacity, deadline, period, "decompressor-fifo-thread", &status, &profile);
if (status != ZX_OK || fidl_status != ZX_OK) {
FX_LOGS(WARNING) << "[decompressor]: Failed to get deadline profile: "
<< zx_status_get_string(status) << ", " << zx_status_get_string(fidl_status);
} else {
auto zx_thread = zx::unowned_thread(thrd_get_zx_handle(*thread));
// Set the deadline profile.
status = zx_thread->set_profile(profile, 0);
if (status != ZX_OK) {
FX_LOGS(WARNING) << "[decompressor]: Failed to set deadline profile: "
<< zx_status_get_string(status);
}
}
}
void DecompressorImpl::Create(zx::fifo server_end, zx::vmo compressed_vmo, zx::vmo decompressed_vmo,
CreateCallback callback) {
size_t vmo_size;
zx_status_t status = decompressed_vmo.get_size(&vmo_size);
if (status != ZX_OK) {
return callback(status);
}
fzl::OwnedVmoMapper decompressed_mapper;
status = decompressed_mapper.Map(std::move(decompressed_vmo), vmo_size);
if (status != ZX_OK) {
return callback(status);
}
status = compressed_vmo.get_size(&vmo_size);
if (status != ZX_OK) {
return callback(status);
}
fzl::OwnedVmoMapper compressed_mapper;
status = compressed_mapper.Map(std::move(compressed_vmo), vmo_size, ZX_VM_PERM_READ);
if (status != ZX_OK) {
return callback(status);
}
thrd_t handler_thread;
std::unique_ptr<FifoInfo> info = std::make_unique<FifoInfo>();
*info = {std::move(server_end), std::move(compressed_mapper), std::move(decompressed_mapper)};
if (thrd_create_with_name(&handler_thread, WatchFifoWrapper, info.release(),
"decompressor-fifo-thread") != thrd_success) {
return callback(ZX_ERR_INTERNAL);
}
SetDeadlineProfile(&handler_thread);
thrd_detach(handler_thread);
return callback(ZX_OK);
}
} // namespace blobfs
| 40.67382 | 100 | 0.697373 | allansrc |
6a489ef252197c20397dd7704bc0fe8677956fbe | 2,395 | cpp | C++ | Cappuccino/src/Cappuccino/AnimationSystem.cpp | Promethaes/CappuccinoEngine | e0e2dacaf14c8176d4fbc0d85645783e364a06a4 | [
"MIT"
] | 5 | 2019-10-25T11:51:08.000Z | 2020-01-09T00:56:24.000Z | Cappuccino/src/Cappuccino/AnimationSystem.cpp | Promethaes/CappuccinoEngine | e0e2dacaf14c8176d4fbc0d85645783e364a06a4 | [
"MIT"
] | 145 | 2019-09-10T18:33:49.000Z | 2020-02-02T09:59:23.000Z | Cappuccino/src/Cappuccino/AnimationSystem.cpp | Promethaes/CappuccinoEngine | e0e2dacaf14c8176d4fbc0d85645783e364a06a4 | [
"MIT"
] | null | null | null | #include "Cappuccino/AnimationSystem.h"
#include "Cappuccino/CappMath.h"
#include "glm/common.hpp"
#include "glm/gtx/compatibility.hpp"
namespace Cappuccino {
std::vector<Animation*> Animation::_allAnimations = {};
Animation::Animation(const std::vector<Mesh*>& keyFrames, AnimationType type)
: _type(type)
{
_keyFrames = keyFrames;
_allAnimations.push_back(this);
}
float Animation::play(float dt)
{
if (_animationShader == nullptr) {
printf("Animation shader not set! animations cannot be played!\n");
return -1.0f;
}
_animationShader->use();
if (!_shouldPlay)
return -1.0f;
if (t == 0.0f)
_keyFrames[0]->animationFunction(*_keyFrames[index], _shouldPlay);
t += dt * _speed;
//_animationShader->setUniform("dt",t);
if (t >= 1.0f) {
t = 0.0f;
_keyFrames[0]->_VBO = _keyFrames[index]->_VBO;
index++;
if (index > _keyFrames.size() - 1) {
if (!_loop)
_shouldPlay = false;
index = 1;
_keyFrames[0]->resetVertAttribPointers();
}
}
return t;
}
float Animator::_dt = 0.0f;
Animator::Animator()
{
for (unsigned i = 0; i < (int)AnimationType::NumTypes; i++)
_animations.push_back(nullptr);
}
void Animator::update(float dt)
{
_dt = dt;
for (auto x : _animations) {
if (x != nullptr && x->_shouldPlay) {
_currentT = x->play(dt);
break;
}
}
}
void Animator::addAnimation(Animation* animation)
{
_animations[(int)animation->getAnimationType()] = animation;
}
void Animator::playAnimation(AnimationType type)
{
_animations[(int)type]->_shouldPlay = true;
_playingAnimation = true;
}
bool Animator::isPlaying(AnimationType type)
{
return _animations[(int)type]->_shouldPlay;
}
void Animator::setAnimationShader(AnimationType type, Shader* shader)
{
_animations[(int)type]->_animationShader = shader;
}
void Animator::clearAnimation(AnimationType type)
{
delete _animations[(int)type];
_animations[(int)type] = nullptr;
}
void Animator::setLoop(AnimationType type, bool yn)
{
_animations[(int)type]->setLoop(yn);
}
void Animator::setSpeed(AnimationType type, float speed)
{
_animations[(int)type]->setSpeed(speed);
}
bool Animator::animationExists(AnimationType type)
{
if (_animations[(int)type] != nullptr)
return true;
return false;
}
} | 23.480392 | 79 | 0.650104 | Promethaes |
6a4956bcd6605b90e344f1b9889139e3abca2933 | 359 | cpp | C++ | AirFloat/NotificationObserver.cpp | davhelm/AirFloat | 460a97d57f9adf3372093e1e62a38b726ab08737 | [
"Unlicense"
] | 2 | 2015-07-20T17:09:11.000Z | 2017-02-05T11:08:34.000Z | AirFloat/NotificationObserver.cpp | davhelm/AirFloat | 460a97d57f9adf3372093e1e62a38b726ab08737 | [
"Unlicense"
] | null | null | null | AirFloat/NotificationObserver.cpp | davhelm/AirFloat | 460a97d57f9adf3372093e1e62a38b726ab08737 | [
"Unlicense"
] | null | null | null | //
// NotificationReceiver.cpp
// AirFloat
//
// Created by Kristian Trenskow on 2/8/12.
// Copyright (c) 2012 The Famous Software Company. All rights reserved.
//
#include "NotificationCenter.h"
#include "NotificationObserver.h"
NotificationObserver::~NotificationObserver() {
NotificationCenter::defaultCenter()->removeObserver(this);
}
| 21.117647 | 72 | 0.724234 | davhelm |
c69957b1b1efa65a9407875a3c1ac25975b74583 | 5,132 | cpp | C++ | Roguelike/Code/Game/Stats.cpp | cugone/Roguelike | 0f53a1ae2a37e683773c1707ce4aeb056973af13 | [
"MIT"
] | null | null | null | Roguelike/Code/Game/Stats.cpp | cugone/Roguelike | 0f53a1ae2a37e683773c1707ce4aeb056973af13 | [
"MIT"
] | 4 | 2021-05-04T03:21:49.000Z | 2021-10-06T05:21:24.000Z | Roguelike/Code/Game/Stats.cpp | cugone/Roguelike | 0f53a1ae2a37e683773c1707ce4aeb056973af13 | [
"MIT"
] | 2 | 2020-01-19T00:50:34.000Z | 2021-04-01T07:51:02.000Z | #include "Game/Stats.hpp"
#include <type_traits>
StatsID& operator++(StatsID& a) {
using underlying = std::underlying_type_t<StatsID>;
a = static_cast<StatsID>(static_cast<underlying>(a) + 1);
return a;
}
StatsID operator++(StatsID& a, int) {
auto result = a;
++a;
return result;
}
StatsID& operator--(StatsID& a) {
using underlying = std::underlying_type_t<StatsID>;
a = static_cast<StatsID>(static_cast<underlying>(a) - 1);
return a;
}
StatsID operator--(StatsID& a, int) {
auto result = a;
--a;
return result;
}
Stats Stats::operator+(const Stats& rhs) const {
auto result = *this;
result += rhs;
return result;
}
Stats& Stats::operator+=(const Stats& rhs) {
for(auto id = StatsID::First_; id != StatsID::Last_; ++id) {
AdjustStat(id, rhs.GetStat(id));
}
return *this;
}
Stats Stats::operator-(const Stats& rhs) const {
auto result = *this;
result -= rhs;
return result;
}
Stats& Stats::operator-=(const Stats& rhs) {
for(auto id = StatsID::First_; id != StatsID::Last_; ++id) {
AdjustStat(id, -rhs.GetStat(id));
}
return *this;
}
Stats Stats::operator-() {
auto result = *this;
for(auto id = StatsID::First_; id != StatsID::Last_; ++id) {
result.SetStat(id, -result.GetStat(id));
}
return result;
}
Stats::Stats(const XMLElement& elem) {
DataUtils::ValidateXmlElement(elem, "stats", "", "", "level,health,attack,defense,speed,accuracy,evasion,luck,experience");
if(auto* xml_level = elem.FirstChildElement("level")) {
auto id = StatsID::Level;
auto default_value = GetStat(id);
auto value = DataUtils::ParseXmlElementText(*xml_level, default_value);
SetStat(id, value);
} else {
auto value = 1L;
SetStat(StatsID::Level, value);
}
if(auto* xml_health = elem.FirstChildElement("health")) {
auto id = StatsID::Health;
auto default_value = GetStat(id);
auto value = DataUtils::ParseXmlElementText(*xml_health, default_value);
SetStat(id, value);
SetStat(StatsID::Health_Max, value);
} else {
auto value = 1L;
SetStat(StatsID::Health, value);
SetStat(StatsID::Health_Max, value);
}
if(auto* xml_attack = elem.FirstChildElement("attack")) {
auto id = StatsID::Attack;
auto default_value = GetStat(id);
auto value = DataUtils::ParseXmlElementText(*xml_attack, default_value);
SetStat(id, value);
}
if(auto* xml_defense = elem.FirstChildElement("defense")) {
auto id = StatsID::Defense;
auto default_value = GetStat(id);
auto value = DataUtils::ParseXmlElementText(*xml_defense, default_value);
SetStat(id, value);
}
if(auto* xml_speed = elem.FirstChildElement("speed")) {
auto id = StatsID::Speed;
auto default_value = GetStat(id);
auto value = DataUtils::ParseXmlElementText(*xml_speed, default_value);
SetStat(id, value);
}
if(auto* xml_evasion = elem.FirstChildElement("evasion")) {
auto id = StatsID::Evasion;
auto default_value = GetStat(id);
auto value = DataUtils::ParseXmlElementText(*xml_evasion, default_value);
SetStat(id, value);
}
if(auto* xml_luck = elem.FirstChildElement("luck")) {
auto id = StatsID::Luck;
auto default_value = GetStat(id);
auto value = DataUtils::ParseXmlElementText(*xml_luck, default_value);
SetStat(id, value);
} else {
auto value = 5L;
SetStat(StatsID::Luck, value);
}
if(auto* xml_experience = elem.FirstChildElement("experience")) {
auto id = StatsID::Experience;
auto default_value = GetStat(id);
auto value = DataUtils::ParseXmlElementText(*xml_experience, default_value);
SetStat(id, value);
}
}
Stats::Stats(std::initializer_list<decltype(_stats)::value_type> l) {
auto id = StatsID::First_;
for(const auto value : l) {
if(id < StatsID::Last_) {
SetStat(id++, value);
}
}
for(; id != StatsID::Last_; ++id) {
SetStat(id, decltype(_stats)::value_type{0});
}
}
auto Stats::GetStat(const StatsID& id) const noexcept -> decltype(_stats)::value_type{
return _stats[static_cast<std::size_t>(id)];
}
void Stats::SetStat(const StatsID& id, decltype(_stats)::value_type value) noexcept {
_stats[static_cast<std::size_t>(id)] = value;
}
decltype(Stats::_stats)::value_type Stats::AdjustStat(const StatsID& id, long value) noexcept {
const auto i = static_cast<std::size_t>(id);
_stats[i] += static_cast<decltype(_stats)::value_type>(value);
return _stats[i];
}
decltype(Stats::_stats)::value_type Stats::MultiplyStat(const StatsID& id, long double value) noexcept {
const auto i = static_cast<std::size_t>(id);
_stats[i] *= static_cast<decltype(_stats)::value_type>(std::floor(value));
return _stats[i];
}
| 32.687898 | 128 | 0.614186 | cugone |
c69a15080bf83cc00e321cffcbdd269a2804af65 | 527 | cpp | C++ | CodeChef/MOU2H/Mountain Holidays 2.cpp | QAQrz/ACM-Code | 7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7 | [
"Unlicense"
] | 2 | 2018-02-24T06:45:56.000Z | 2018-05-29T04:47:39.000Z | CodeChef/MOU2H/Mountain Holidays 2.cpp | QAQrz/ACM-Code | 7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7 | [
"Unlicense"
] | null | null | null | CodeChef/MOU2H/Mountain Holidays 2.cpp | QAQrz/ACM-Code | 7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7 | [
"Unlicense"
] | 2 | 2018-06-28T09:53:27.000Z | 2022-03-23T13:29:57.000Z | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL maxn=2123456,mod=1e9+9;
LL t,n,i,m,a[maxn],v[maxn*4],dp[maxn];
int main(){
scanf("%lld",&t);
while(t--){
scanf("%lld",&n);
for(i=1;i<=n;i++)
scanf("%lld",&a[i]);
for(i=1,m=0;i<n;i++)
a[i]=a[i+1]-a[i],m=min(m,a[i]);
for(i=1;i<n;i++)
a[i]-=m,v[a[i]]=-1;
for(i=1;i<n;i++){
if(~v[a[i]])
dp[i]=(dp[i-1]*2-dp[v[a[i]]-1]+mod)%mod;
else
dp[i]=(dp[i-1]*2+1)%mod;
v[a[i]]=i;
}
printf("%lld\n",dp[n-1]);
}
return 0;
} | 20.269231 | 44 | 0.493359 | QAQrz |
c69c8c79208ac5ee51f1c4b3c8baf7183842b2f8 | 12,448 | cc | C++ | src/mem/dtu/mem_unit.cc | utcs-scea/gem5-dtu | 0922df0e8f47fe3bd2fbad9f57b1b855181c64dd | [
"BSD-3-Clause"
] | 3 | 2016-03-23T09:21:51.000Z | 2019-07-22T22:07:26.000Z | src/mem/dtu/mem_unit.cc | TUD-OS/gem5-dtu | 0922df0e8f47fe3bd2fbad9f57b1b855181c64dd | [
"BSD-3-Clause"
] | null | null | null | src/mem/dtu/mem_unit.cc | TUD-OS/gem5-dtu | 0922df0e8f47fe3bd2fbad9f57b1b855181c64dd | [
"BSD-3-Clause"
] | 6 | 2018-01-01T02:15:26.000Z | 2021-11-03T10:54:04.000Z | /*
* Copyright (c) 2015, Christian Menard
* Copyright (c) 2015, Nils Asmussen
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the FreeBSD Project.
*/
#include "debug/Dtu.hh"
#include "debug/DtuBuf.hh"
#include "debug/DtuPackets.hh"
#include "debug/DtuSysCalls.hh"
#include "mem/dtu/mem_unit.hh"
#include "mem/dtu/xfer_unit.hh"
#include "mem/dtu/noc_addr.hh"
static uint cmdToXferFlags(uint flags) {
return flags & 1;
}
static uint cmdToNocFlags(uint flags) {
return flags & 1;
}
static uint nocToXferFlags(uint flags) {
return flags & 3;
}
static uint xferToNocFlags(uint flags) {
return flags & 3;
}
static void
finishReadWrite(Dtu &dtu, Addr size)
{
// change data register accordingly
DataReg data = dtu.regs().getDataReg();
data.size -= size;
data.addr += size;
dtu.regs().setDataReg(data);
// change command register
Dtu::Command::Bits cmd = dtu.regs().get(CmdReg::COMMAND);
cmd.arg = cmd.arg + size;
dtu.regs().set(CmdReg::COMMAND, cmd);
}
void
MemoryUnit::regStats()
{
readBytes
.init(8)
.name(dtu.name() + ".mem.readBytes")
.desc("Sent read requests (in bytes)")
.flags(Stats::nozero);
writtenBytes
.init(8)
.name(dtu.name() + ".mem.writtenBytes")
.desc("Sent write requests (in bytes)")
.flags(Stats::nozero);
receivedBytes
.init(8)
.name(dtu.name() + ".mem.receivedBytes")
.desc("Received read/write requests (in bytes)")
.flags(Stats::nozero);
wrongVPE
.name(dtu.name() + ".mem.wrongVPE")
.desc("Number of received requests that targeted the wrong VPE")
.flags(Stats::nozero);
}
void
MemoryUnit::startRead(const Dtu::Command::Bits& cmd)
{
MemEp ep = dtu.regs().getMemEp(cmd.epid);
if(!(ep.flags & Dtu::MemoryFlags::READ))
{
dtu.scheduleFinishOp(Cycles(1), Dtu::Error::INV_EP);
return;
}
DataReg data = dtu.regs().getDataReg();
Addr offset = cmd.arg;
Addr size = std::min(static_cast<Addr>(data.size), dtu.maxNocPacketSize);
readBytes.sample(size);
DPRINTFS(Dtu, (&dtu),
"\e[1m[rd -> %u]\e[0m at %#018lx+%#lx with EP%u into %#018lx:%lu\n",
ep.targetCore, ep.remoteAddr, offset,
cmd.epid, data.addr, size);
if(size == 0)
{
dtu.scheduleFinishOp(Cycles(1), Dtu::Error::NONE);
return;
}
// TODO error handling
assert(size + offset >= size);
assert(size + offset <= ep.remoteSize);
NocAddr nocAddr(ep.targetCore, ep.remoteAddr + offset);
uint flags = cmdToNocFlags(cmd.flags);
if (dtu.coherent && !dtu.mmioRegion.contains(nocAddr.offset) &&
dtu.isMemPE(nocAddr.coreId))
{
flags |= XferUnit::NOXLATE;
auto xfer = new LocalReadTransferEvent(nocAddr.getAddr(),
data.addr,
size,
flags);
dtu.startTransfer(xfer, Cycles(1));
}
else
{
auto pkt = dtu.generateRequest(nocAddr.getAddr(),
size,
MemCmd::ReadReq);
dtu.sendNocRequest(Dtu::NocPacketType::READ_REQ,
pkt,
ep.vpeId,
flags,
dtu.commandToNocRequestLatency);
}
}
void
MemoryUnit::LocalReadTransferEvent::transferDone(Dtu::Error result)
{
Cycles delay(1);
if (result != Dtu::Error::NONE)
{
dtu().scheduleFinishOp(delay, result);
return;
}
uint wflags = flags() & ~XferUnit::NOXLATE;
uint8_t *tmp = new uint8_t[size()];
memcpy(tmp, data(), size());
auto xfer = new LocalWriteTransferEvent(dest, tmp, size(), wflags);
dtu().startTransfer(xfer, delay);
}
void
MemoryUnit::LocalWriteTransferEvent::transferStart()
{
memcpy(data(), tmp, tmpSize);
delete[] tmp;
}
void
MemoryUnit::LocalWriteTransferEvent::transferDone(Dtu::Error result)
{
if (result == Dtu::Error::NONE)
finishReadWrite(dtu(), tmpSize);
dtu().scheduleFinishOp(Cycles(1), result);
}
void
MemoryUnit::readComplete(const Dtu::Command::Bits& cmd, PacketPtr pkt, Dtu::Error error)
{
dtu.printPacket(pkt);
const DataReg data = dtu.regs().getDataReg();
// since the transfer is done in steps, we can start after the header
// delay here
Cycles delay = dtu.ticksToCycles(pkt->headerDelay);
if (error != Dtu::Error::NONE)
{
dtu.scheduleFinishOp(delay, error);
return;
}
uint flags = cmdToXferFlags(cmd.flags);
auto xfer = new ReadTransferEvent(data.addr, flags, pkt);
dtu.startTransfer(xfer, delay);
}
void
MemoryUnit::ReadTransferEvent::transferStart()
{
// here is also no additional delay, because we are doing that in
// parallel and are already paying for it at other places
memcpy(data(), pkt->getPtr<uint8_t>(), pkt->getSize());
}
void
MemoryUnit::ReadTransferEvent::transferDone(Dtu::Error result)
{
if (result == Dtu::Error::NONE)
finishReadWrite(dtu(), pkt->getSize());
dtu().scheduleFinishOp(Cycles(1), result);
dtu().freeRequest(pkt);
}
void
MemoryUnit::startWrite(const Dtu::Command::Bits& cmd)
{
MemEp ep = dtu.regs().getMemEp(cmd.epid);
if(!(ep.flags & Dtu::MemoryFlags::WRITE))
{
dtu.scheduleFinishOp(Cycles(1), Dtu::Error::INV_EP);
return;
}
DataReg data = dtu.regs().getDataReg();
Addr offset = cmd.arg;
Addr size = std::min(static_cast<Addr>(data.size), dtu.maxNocPacketSize);
writtenBytes.sample(size);
DPRINTFS(Dtu, (&dtu),
"\e[1m[wr -> %u]\e[0m at %#018lx+%#lx with EP%u from %#018lx:%lu\n",
ep.targetCore, ep.remoteAddr, offset,
cmd.epid, data.addr, size);
if(size == 0)
{
dtu.scheduleFinishOp(Cycles(1), Dtu::Error::NONE);
return;
}
// TODO error handling
assert(ep.flags & Dtu::MemoryFlags::WRITE);
assert(size + offset >= size);
assert(size + offset <= ep.remoteSize);
NocAddr dest(ep.targetCore, ep.remoteAddr + offset);
uint flags = cmdToXferFlags(cmd.flags);
auto xfer = new WriteTransferEvent(
data.addr, size, flags, dest, ep.vpeId);
dtu.startTransfer(xfer, Cycles(0));
}
void
MemoryUnit::WriteTransferEvent::transferDone(Dtu::Error result)
{
if (result != Dtu::Error::NONE)
{
dtu().scheduleFinishOp(Cycles(1), result);
}
else
{
auto pkt = dtu().generateRequest(dest.getAddr(),
size(),
MemCmd::WriteReq);
memcpy(pkt->getPtr<uint8_t>(), data(), size());
Cycles delay = dtu().transferToNocLatency;
dtu().printPacket(pkt);
if (dtu().coherent && !dtu().mmioRegion.contains(dest.offset) &&
dtu().isMemPE(dest.coreId))
{
uint rflags = (flags() & XferUnit::NOPF) | XferUnit::NOXLATE;
auto xfer = new ReadTransferEvent(dest.getAddr(), rflags, pkt);
dtu().startTransfer(xfer, delay);
}
else
{
Dtu::NocPacketType pktType;
if (flags() & XferUnit::MESSAGE)
pktType = Dtu::NocPacketType::MESSAGE;
else
pktType = Dtu::NocPacketType::WRITE_REQ;
uint rflags = xferToNocFlags(flags());
dtu().setCommandSent();
dtu().sendNocRequest(pktType, pkt, vpeId, rflags, delay);
}
}
}
void
MemoryUnit::writeComplete(const Dtu::Command::Bits& cmd, PacketPtr pkt, Dtu::Error error)
{
if (cmd.opcode == Dtu::Command::WRITE && error == Dtu::Error::NONE)
finishReadWrite(dtu, pkt->getSize());
// we don't need to pay the payload delay here because the message
// basically has no payload since we only receive an ACK back for
// writing
Cycles delay = dtu.ticksToCycles(pkt->headerDelay);
dtu.scheduleFinishOp(delay, error);
dtu.freeRequest(pkt);
}
void
MemoryUnit::recvFunctionalFromNoc(PacketPtr pkt)
{
// set the local address
pkt->setAddr(NocAddr(pkt->getAddr()).offset);
dtu.sendFunctionalMemRequest(pkt);
}
Dtu::Error
MemoryUnit::recvFromNoc(PacketPtr pkt, uint vpeId, uint flags)
{
NocAddr addr(pkt->getAddr());
DPRINTFS(Dtu, (&dtu), "\e[1m[%s <- ?]\e[0m %#018lx:%lu\n",
pkt->isWrite() ? "wr" : "rd",
addr.offset,
pkt->getSize());
if (pkt->isWrite())
dtu.printPacket(pkt);
receivedBytes.sample(pkt->getSize());
uint16_t ourVpeId = dtu.regs().get(DtuReg::VPE_ID);
if (vpeId != ourVpeId ||
(!(flags & Dtu::NocFlags::PRIV) &&
dtu.regs().hasFeature(Features::COM_DISABLED)))
{
DPRINTFS(Dtu, (&dtu),
"Received memory request for VPE %u, but VPE %u is running with"
" communication %sabled\n",
vpeId,
ourVpeId,
dtu.regs().hasFeature(Features::COM_DISABLED) ? "dis" : "en");
wrongVPE++;
dtu.sendNocResponse(pkt);
return Dtu::Error::VPE_GONE;
}
if (dtu.mmioRegion.contains(addr.offset))
{
pkt->setAddr(addr.offset);
dtu.forwardRequestToRegFile(pkt, false);
// as this is synchronous, we can restore the address right away
pkt->setAddr(addr.getAddr());
}
else
{
// the same as above: the transfer happens piece by piece and we can
// start after the header
Cycles delay = dtu.ticksToCycles(pkt->headerDelay);
pkt->headerDelay = 0;
auto type = pkt->isWrite() ? Dtu::TransferType::REMOTE_WRITE
: Dtu::TransferType::REMOTE_READ;
uint xflags = nocToXferFlags(flags);
auto *ev = new ReceiveTransferEvent(type, addr.offset, xflags, pkt);
dtu.startTransfer(ev, delay);
}
return Dtu::Error::NONE;
}
void
MemoryUnit::ReceiveTransferEvent::transferStart()
{
if (pkt->isWrite())
{
// here is also no additional delay, because we are doing that in
// parallel and are already paying for it at other places
memcpy(data(), pkt->getPtr<uint8_t>(), pkt->getSize());
}
}
void
MemoryUnit::ReceiveTransferEvent::transferDone(Dtu::Error result)
{
// some requests from the cache (e.g. cleanEvict) do not need a
// response
if (pkt->needsResponse())
{
pkt->makeResponse();
if (pkt->isRead())
memcpy(pkt->getPtr<uint8_t>(), data(), size());
// set result
auto state = dynamic_cast<Dtu::NocSenderState*>(pkt->senderState);
if (result != Dtu::Error::NONE &&
dtu().regs().hasFeature(Features::COM_DISABLED))
state->result = Dtu::Error::VPE_GONE;
else
state->result = result;
Cycles delay = dtu().transferToNocLatency;
dtu().schedNocResponse(pkt, dtu().clockEdge(delay));
}
}
| 28.881671 | 89 | 0.612147 | utcs-scea |
c69ce88cf26e990cf6771127199b3a484be47fea | 4,777 | cpp | C++ | Code/BellmanFord.cpp | RossieeyirouQian10/EE450-Lab1-Bellman-Ford-Algorithm | 383afe5c57672350643e2c774c751e80e46da7a7 | [
"MIT"
] | null | null | null | Code/BellmanFord.cpp | RossieeyirouQian10/EE450-Lab1-Bellman-Ford-Algorithm | 383afe5c57672350643e2c774c751e80e46da7a7 | [
"MIT"
] | null | null | null | Code/BellmanFord.cpp | RossieeyirouQian10/EE450-Lab1-Bellman-Ford-Algorithm | 383afe5c57672350643e2c774c751e80e46da7a7 | [
"MIT"
] | null | null | null | //
// BellmanFord.cpp
// LAB1
//
// Created by 钱依柔 on 5/30/19.
// Copyright © 2019 钱依柔. All rights reserved.
//
#include "BellmanFord.hpp"
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <sstream>
#include <vector>
#include <climits>
#include <regex>
#include <algorithm>
#include <stdio.h>
using namespace std;
const int INF = INT_MAX;
string srcFileName;
// read in file
vector<vector<int>> readFile(const string fileName){
vector<vector<int>> graph;
ifstream inFile(fileName,ios::in);
if(!inFile.is_open()){
cout << "File not found: " << fileName << endl;
exit(0);
}
//get line in file to string
string line;
while (getline(inFile, line)){
if (line.length() < 2){
continue;
}
stringstream ss(line);
string strIn;
ss >> strIn;
vector<int> vertex;
while (strIn.length() > 0){
transform(strIn.begin(), strIn.end(), strIn.begin(), ::toupper);
// store distance value
if (strIn.compare("INF") == 0) {
vertex.push_back(INF);
}else{
// multi-cost case
if (strIn[0] == '['){
int n1, n2, n3;
sscanf(strIn.c_str(), "[%d,%d,%d]", &n1, &n2, &n3);
vertex.push_back(n1 + n2 + n3);
}else{
vertex.push_back(stoi(strIn.c_str()));
}
}
strIn.clear();
ss >> strIn;
}
// store values into graph
graph.push_back(vertex);
}
return graph;
}
// do Bellman-Ford algorithm
void bellmanFord(vector<vector<int>> graph){
int numNode = (int)graph.size();
int count = 0;
vector<int> distance;
distance.push_back(0);
//initialize the distance
for (int i = 1; i < numNode; i++){
distance.push_back(INT_MAX);
}
//last node having done relax calcution
vector<int> preNode(numNode, -1);
bool distUpdate;
//do relax and save the shortest distance value
for (int i = 0; i < numNode - 1; i++){
distUpdate = false;
count++;
for (int j = 0; j < numNode; j++){
for (int k = 0; k < graph[j].size(); k ++){
if (graph[j][k] != INT_MAX && distance[j] != INT_MAX && distance[j] + graph[j][k] < distance[k]){
distance[k] = distance[j] + graph[j][k];
preNode[k] = j;
distUpdate = true;
}
}
}
if (!distUpdate){
break;
}
}
//detect negative loop
count++;
bool bFlag = false;
for (int j = 0; j < numNode; j++){
if(bFlag){
break;
}
for (int k = 0; k < graph[j].size(); k++){
if (graph[j][k] != INT_MAX && distance[j] != INT_MAX && distance[j] + graph[j][k] < distance[k]){
bFlag = true;
break;
}
}
}
// output file with result
ofstream outFile;
outFile.open("output-" + srcFileName, ios::out);
if (bFlag){
outFile << "Negative Loop Detected" << endl;
//show negative iteration path
int nPre;
string strOut;
stringstream ssOut;
nPre = preNode[0];
ssOut << nPre << "->" << 0;
strOut = ssOut.str();
while (nPre){
nPre = preNode[nPre];
stringstream ssOut2;
ssOut2 << nPre << "->" << strOut;
strOut = ssOut2.str();
}
outFile << strOut << endl;
}else{
//show distance to each node
outFile << distance[0];
for (int i = 1; i < numNode; i++){
outFile << "," << distance[i];
}
outFile << endl << 0 << endl;
//show non-negative iteration path
int nPre;
string strOut;
for (int i = 1; i < numNode; i++){
stringstream ssOut;
nPre = preNode[i];
ssOut << nPre << "->" << i;
strOut = ssOut.str();
while (nPre){
nPre = preNode[nPre];
stringstream ssOut2;
ssOut2 << nPre << "->" << strOut;
strOut = ssOut2.str();
}
outFile << strOut << endl;
}
// times of iteration
outFile << "Iteration: " << count << endl;
}
outFile.close();
}
int main(int argc, char **argv){
if (argc != 2){
return 0;
}
srcFileName = argv[1];
vector<vector<int>> newGraph = readFile(argv[1]);
bellmanFord(newGraph);
return 0;
}
| 25.821622 | 113 | 0.472054 | RossieeyirouQian10 |
c69f75aae8890928f2433c8430db872e7a77a6c0 | 17,472 | cpp | C++ | fsck/source/toolkit/FsckTkEx.cpp | congweitao/congfs | 54cedf484f8a2cacab567fe182cc1f6413c25cf2 | [
"BSD-3-Clause"
] | null | null | null | fsck/source/toolkit/FsckTkEx.cpp | congweitao/congfs | 54cedf484f8a2cacab567fe182cc1f6413c25cf2 | [
"BSD-3-Clause"
] | null | null | null | fsck/source/toolkit/FsckTkEx.cpp | congweitao/congfs | 54cedf484f8a2cacab567fe182cc1f6413c25cf2 | [
"BSD-3-Clause"
] | null | null | null | #include "FsckTkEx.h"
#include <common/net/message/fsck/FsckSetEventLoggingMsg.h>
#include <common/net/message/fsck/FsckSetEventLoggingRespMsg.h>
#include <common/net/message/storage/StatStoragePathMsg.h>
#include <common/net/message/storage/StatStoragePathRespMsg.h>
#include <common/toolkit/ListTk.h>
#include <common/toolkit/FsckTk.h>
#include <common/toolkit/UnitTk.h>
#include <program/Program.h>
#include <mutex>
char FsckTkEx::progressChar = '-';
Mutex FsckTkEx::outputMutex;
/*
* check the reachability of all nodes in the system
*/
bool FsckTkEx::checkReachability()
{
NodeStore* metaNodes = Program::getApp()->getMetaNodes();
NodeStore* storageNodes = Program::getApp()->getStorageNodes();
StringList errors;
bool commSuccess = true;
FsckTkEx::fsckOutput("Step 1: Check reachability of nodes: ", OutputOptions_FLUSH);
if ( metaNodes->getSize() == 0 )
{
errors.push_back("No metadata nodes found");
commSuccess = false;
}
if ( storageNodes->getSize() == 0 )
{
errors.push_back("No storage nodes found");
commSuccess = false;
}
for (const auto& node : metaNodes->referenceAllNodes())
{
if ( !FsckTkEx::checkReachability(*node, NODETYPE_Meta) )
{
errors.push_back("Communication with metadata node failed: " + node->getID());
commSuccess = false;
}
}
for (const auto& node : storageNodes->referenceAllNodes())
{
if ( !FsckTkEx::checkReachability(*node, NODETYPE_Storage) )
{
errors.push_back("Communication with storage node failed: " + node->getID());
commSuccess = false;
}
}
if ( commSuccess )
FsckTkEx::fsckOutput("Finished", OutputOptions_LINEBREAK);
else
{
for ( StringListIter iter = errors.begin(); iter != errors.end(); iter++ )
{
FsckTkEx::fsckOutput(*iter,
OutputOptions_NONE | OutputOptions_LINEBREAK | OutputOptions_STDERR);
}
}
return commSuccess;
}
/*
* check reachability of a single node
*/
bool FsckTkEx::checkReachability(Node& node, NodeType nodetype)
{
bool retVal = false;
HeartbeatRequestMsg heartbeatRequestMsg;
std::string realNodeID = node.getID();
const auto respMsg = MessagingTk::requestResponse(node, heartbeatRequestMsg,
NETMSGTYPE_Heartbeat);
if (respMsg)
{
HeartbeatMsg *heartbeatMsg = (HeartbeatMsg *) respMsg.get();
std::string receivedNodeID = heartbeatMsg->getNodeID();
retVal = receivedNodeID.compare(realNodeID) == 0;
}
return retVal;
}
void FsckTkEx::fsckOutput(std::string text, int optionFlags)
{
const std::lock_guard<Mutex> lock(outputMutex);
static bool fileErrLogged = false; // to make sure we print logfile open err only once
Config* cfg = Program::getApp()->getConfig(); // might be NULL on app init failure
bool toLog = cfg && (!(OutputOptions_NOLOG & optionFlags)); // true if write to log file
FILE *logFile = NULL;
if (likely(toLog))
{
std::string logFilePath = cfg->getLogOutFile();
logFile = fopen(logFilePath.c_str(),"a+");
if (logFile == NULL)
{
toLog = false;
if(!fileErrLogged)
{
std::cerr << "Cannot open output file for writing: '" << logFilePath << "'"
<< std::endl;
fileErrLogged = true;
}
}
}
const char* colorNormal = OutputColor_NORMAL;
const char* color = OutputColor_NORMAL;
FILE *outFile = stdout;
if (OutputOptions_STDERR & optionFlags)
{
outFile = stderr;
}
else if (OutputOptions_NOSTDOUT & optionFlags)
{
outFile = NULL;
}
bool outFileIsTty;
if (outFile)
outFileIsTty = isatty(fileno(outFile));
else
outFileIsTty = false;
if (OutputOptions_COLORGREEN & optionFlags)
{
color = OutputColor_GREEN;
}
else if (OutputOptions_COLORRED & optionFlags)
{
color = OutputColor_RED;
}
else
{
color = OutputColor_NORMAL;
}
if (OutputOptions_LINEDELETE & optionFlags)
{
optionFlags = optionFlags | OutputOptions_FLUSH;
SAFE_FPRINTF(outFile, "\r");
SAFE_FPRINTF(outFile, " ");
SAFE_FPRINTF(outFile, "\r");
}
if (OutputOptions_ADDLINEBREAKBEFORE & optionFlags)
{
SAFE_FPRINTF(outFile, "\n");
if (likely(toLog)) SAFE_FPRINTF(logFile,"\n");
}
if (OutputOptions_HEADLINE & optionFlags)
{
SAFE_FPRINTF(outFile, "\n--------------------------------------------------------------------\n");
if (likely(toLog))
SAFE_FPRINTF(logFile,"\n--------------------------------------------------------------------\n");
if (likely(outFileIsTty))
SAFE_FPRINTF(outFile, "%s%s%s",color,text.c_str(),colorNormal);
else
SAFE_FPRINTF(outFile, "%s",text.c_str());
if (likely(toLog))
SAFE_FPRINTF(logFile,"%s",text.c_str());
SAFE_FPRINTF(outFile, "\n--------------------------------------------------------------------\n") ;
if (likely(toLog))
SAFE_FPRINTF(logFile,"\n--------------------------------------------------------------------\n");
}
else
{
if (likely(outFileIsTty))
SAFE_FPRINTF(outFile, "%s%s%s",color,text.c_str(),colorNormal);
else
SAFE_FPRINTF(outFile, "%s",text.c_str());
if (likely(toLog)) SAFE_FPRINTF(logFile,"%s",text.c_str());
}
if (OutputOptions_LINEBREAK & optionFlags)
{
SAFE_FPRINTF(outFile, "\n");
if (likely(toLog))
SAFE_FPRINTF(logFile,"\n");
}
if (OutputOptions_DOUBLELINEBREAK & optionFlags)
{
SAFE_FPRINTF(outFile, "\n\n");
if (likely(toLog))
SAFE_FPRINTF(logFile,"\n\n");
}
if (OutputOptions_FLUSH & optionFlags)
{
fflush(outFile);
if (likely(toLog))
fflush(logFile);
}
if (logFile != NULL)
{
fclose(logFile);
}
}
void FsckTkEx::printVersionHeader(bool toStdErr, bool noLogFile)
{
int optionFlags = OutputOptions_LINEBREAK;
if (toStdErr)
{
optionFlags = OutputOptions_LINEBREAK | OutputOptions_STDERR;
}
if (noLogFile)
{
optionFlags = optionFlags | OutputOptions_NOLOG;
}
FsckTkEx::fsckOutput("\n", optionFlags);
FsckTkEx::fsckOutput("ConGFS File System Check Version : " + std::string(CONGFS_VERSION),
optionFlags);
FsckTkEx::fsckOutput("----", optionFlags);
}
void FsckTkEx::progressMeter()
{
const std::lock_guard<Mutex> lock(outputMutex);
printf("\b%c",progressChar);
fflush(stdout);
switch(progressChar)
{
case '-' :
{
progressChar = '\\';
break;
}
case '\\' :
{
progressChar = '|';
break;
}
case '|' :
{
progressChar = '/';
break;
}
case '/' :
{
progressChar = '-';
break;
}
default:
{
progressChar = '-';
break;
}
}
}
/*
* this is only a rough approximation
*/
int64_t FsckTkEx::calcNeededSpace()
{
const char* logContext = "FsckTkEx (calcNeededSpace)";
int64_t neededSpace = 0;
// get used inodes from all meta data servers and sum them up
NodeStore* metaNodes = Program::getApp()->getMetaNodes();
for (const auto& metaNode : metaNodes->referenceAllNodes())
{
NumNodeID nodeID = metaNode->getNumID();
StatStoragePathMsg statStoragePathMsg(0);
const auto respMsg = MessagingTk::requestResponse(*metaNode, statStoragePathMsg,
NETMSGTYPE_StatStoragePathResp);
if (respMsg)
{
StatStoragePathRespMsg* statStoragePathRespMsg = (StatStoragePathRespMsg *) respMsg.get();
int64_t usedInodes = statStoragePathRespMsg->getInodesTotal()
- statStoragePathRespMsg->getInodesFree();
neededSpace += usedInodes * NEEDED_DISKSPACE_META_INODE;
}
else
{
LogContext(logContext).logErr(
"Unable to calculate needed disk space; Communication error with node: "
+ nodeID.str());
return 0;
}
}
// get used inodes from all storage servers and sum them up
NodeStore* storageNodes = Program::getApp()->getStorageNodes();
TargetMapper* targetMapper = Program::getApp()->getTargetMapper();
for (const auto& storageNode : storageNodes->referenceAllNodes())
{
NumNodeID nodeID = storageNode->getNumID();
UInt16List targetIDs;
targetMapper->getTargetsByNode(nodeID, targetIDs);
for ( UInt16ListIter targetIDIter = targetIDs.begin(); targetIDIter != targetIDs.end();
targetIDIter++ )
{
uint16_t targetID = *targetIDIter;
StatStoragePathMsg statStoragePathMsg(targetID);
const auto respMsg = MessagingTk::requestResponse(*storageNode, statStoragePathMsg,
NETMSGTYPE_StatStoragePathResp);
if (respMsg)
{
auto* statStoragePathRespMsg = (StatStoragePathRespMsg *) respMsg.get();
int64_t usedInodes = statStoragePathRespMsg->getInodesTotal()
- statStoragePathRespMsg->getInodesFree();
neededSpace += usedInodes * NEEDED_DISKSPACE_STORAGE_INODE;
}
else
{
LogContext(logContext).logErr(
"Unable to calculate needed disk space; Communication error with node: "
+ nodeID.str());
return -1;
}
}
}
// now we take the calculated approximation and double it to have a lot of space for errors
return neededSpace*2;
}
bool FsckTkEx::checkDiskSpace(Path& dbPath)
{
int64_t neededDiskSpace = FsckTkEx::calcNeededSpace();
if ( unlikely(neededDiskSpace < 0) )
{
FsckTkEx::fsckOutput("Could not determine needed disk space. Aborting now.",
OutputOptions_LINEBREAK | OutputOptions_ADDLINEBREAKBEFORE);
return false;
}
int64_t sizeTotal;
int64_t sizeFree;
int64_t inodesTotal;
int64_t inodesFree;
bool statRes = StorageTk::statStoragePath(dbPath, true, &sizeTotal, &sizeFree,
&inodesTotal, &inodesFree);
if (!statRes)
{
FsckTkEx::fsckOutput(
"Could not stat database file path to determine free space; database file: "
+ dbPath.str());
return false;
}
if ( neededDiskSpace >= sizeFree )
{
std::string neededDiskSpaceUnit;
double neededDiskSpaceValue = UnitTk::byteToXbyte(neededDiskSpace, &neededDiskSpaceUnit);
std::string sizeFreeUnit;
double sizeFreeValue = UnitTk::byteToXbyte(sizeFree, &sizeFreeUnit);
FsckTkEx::fsckOutput(
"Not enough disk space to create database file: " + dbPath.str()
+ "; Recommended free space: " + StringTk::doubleToStr(neededDiskSpaceValue)
+ neededDiskSpaceUnit + "; Free space: " + StringTk::doubleToStr(sizeFreeValue)
+ sizeFreeUnit, OutputOptions_LINEBREAK | OutputOptions_ADDLINEBREAKBEFORE);
bool ignoreDBDiskSpace = Program::getApp()->getConfig()->getIgnoreDBDiskSpace();
if(!ignoreDBDiskSpace)
return false;
}
return true;
}
std::string FsckTkEx::getRepairActionDesc(FsckRepairAction repairAction, bool shortDesc)
{
for (size_t i = 0; __FsckRepairActions[i].actionDesc != nullptr; i++)
{
if( repairAction == __FsckRepairActions[i].action )
{ // we have a match
if (shortDesc)
return __FsckRepairActions[i].actionShortDesc;
else
return __FsckRepairActions[i].actionDesc;
}
}
return "";
}
FhgfsOpsErr FsckTkEx::startModificationLogging(NodeStore* metaNodes, Node& localNode,
bool forceRestart)
{
const char* logContext = "FsckTkEx (startModificationLogging)";
FhgfsOpsErr retVal = FhgfsOpsErr_SUCCESS;
NicAddressList localNicList = localNode.getNicList();
unsigned localPortUDP = localNode.getPortUDP();
FsckTkEx::fsckOutput("-----",
OutputOptions_ADDLINEBREAKBEFORE | OutputOptions_FLUSH | OutputOptions_LINEBREAK);
FsckTkEx::fsckOutput(
"Waiting for metadata servers to start modification logging. This might take some time.",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
FsckTkEx::fsckOutput("-----", OutputOptions_FLUSH | OutputOptions_DOUBLELINEBREAK);
NumNodeIDList nodeIDs;
auto metaNodeList = metaNodes->referenceAllNodes();
for (auto iter = metaNodeList.begin(); iter != metaNodeList.end(); iter++)
{
auto node = metaNodes->referenceNode((*iter)->getNumID());
NicAddressList nicList;
FsckSetEventLoggingMsg fsckSetEventLoggingMsg(true, localPortUDP,
&localNicList, forceRestart);
const auto respMsg = MessagingTk::requestResponse(*node, fsckSetEventLoggingMsg,
NETMSGTYPE_FsckSetEventLoggingResp);
if (respMsg)
{
auto* fsckSetEventLoggingRespMsg = (FsckSetEventLoggingRespMsg*) respMsg.get();
bool started = fsckSetEventLoggingRespMsg->getLoggingEnabled();
if (!started) // EventFlusher was already running on this node!
{
LogContext(logContext).logErr("Modification logging already running on node: "
+ node->getID());
retVal = FhgfsOpsErr_INUSE;
break;
}
}
else
{
LogContext(logContext).logErr("Communication error occured with node: " + node->getID());
retVal = FhgfsOpsErr_COMMUNICATION;
}
}
return retVal;
}
bool FsckTkEx::stopModificationLogging(NodeStore* metaNodes)
{
const char* logContext = "FsckTkEx (stopModificationLogging)";
bool retVal = true;
FsckTkEx::fsckOutput("-----",
OutputOptions_ADDLINEBREAKBEFORE | OutputOptions_FLUSH | OutputOptions_LINEBREAK);
FsckTkEx::fsckOutput(
"Waiting for metadata servers to stop modification logging. This might take some time.",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
FsckTkEx::fsckOutput("-----", OutputOptions_FLUSH | OutputOptions_DOUBLELINEBREAK);
NumNodeIDList nodeIDs;
auto metaNodeList = metaNodes->referenceAllNodes();
for (auto iter = metaNodeList.begin(); iter != metaNodeList.end(); iter++)
nodeIDs.push_back((*iter)->getNumID());
NumNodeIDListIter nodeIdIter = nodeIDs.begin();
while (! nodeIDs.empty())
{
NumNodeID nodeID = *nodeIdIter;
auto node = metaNodes->referenceNode(nodeID);
NicAddressList nicList;
FsckSetEventLoggingMsg fsckSetEventLoggingMsg(false, 0, &nicList, false);
const auto respMsg = MessagingTk::requestResponse(*node, fsckSetEventLoggingMsg,
NETMSGTYPE_FsckSetEventLoggingResp);
if (respMsg)
{
auto* fsckSetEventLoggingRespMsg = (FsckSetEventLoggingRespMsg*) respMsg.get();
bool result = fsckSetEventLoggingRespMsg->getResult();
bool missedEvents = fsckSetEventLoggingRespMsg->getMissedEvents();
if ( result )
{
nodeIdIter = nodeIDs.erase(nodeIdIter);
if ( missedEvents )
{
retVal = false;
}
}
else
nodeIdIter++; // keep in list and try again later
}
else
{
LogContext(logContext).logErr("Communication error occured with node: " + node->getID());
retVal = false;
}
if (nodeIdIter == nodeIDs.end())
{
nodeIdIter = nodeIDs.begin();
sleep(5);
}
}
return retVal;
}
bool FsckTkEx::checkConsistencyStates()
{
auto mgmtdNode = Program::getApp()->getMgmtNodes()->referenceFirstNode();
if (!mgmtdNode)
throw std::runtime_error("Management node not found");
std::list<uint8_t> storageReachabilityStates;
std::list<uint8_t> storageConsistencyStates;
std::list<uint16_t> storageTargetIDs;
std::list<uint8_t> metaReachabilityStates;
std::list<uint8_t> metaConsistencyStates;
std::list<uint16_t> metaTargetIDs;
if (!NodesTk::downloadTargetStates(*mgmtdNode, NODETYPE_Storage, &storageTargetIDs,
&storageReachabilityStates, &storageConsistencyStates, false)
|| !NodesTk::downloadTargetStates(*mgmtdNode, NODETYPE_Meta, &metaTargetIDs,
&metaReachabilityStates, &metaConsistencyStates, false))
{
throw std::runtime_error("Could not download target states from management.");
}
bool result = true;
{
auto idIt = storageTargetIDs.begin();
auto stateIt = storageConsistencyStates.begin();
for (; idIt != storageTargetIDs.end() && stateIt != storageConsistencyStates.end();
idIt++, stateIt++)
{
if (*stateIt == TargetConsistencyState_NEEDS_RESYNC)
{
FsckTkEx::fsckOutput("Storage target " + StringTk::uintToStr(*idIt) + " is set to "
"NEEDS_RESYNC.", OutputOptions_LINEBREAK);
result = false;
}
}
}
{
auto idIt = metaTargetIDs.begin();
auto stateIt = metaConsistencyStates.begin();
for (; idIt != metaTargetIDs.end() && stateIt != metaConsistencyStates.end();
idIt++, stateIt++)
{
if (*stateIt == TargetConsistencyState_NEEDS_RESYNC)
{
FsckTkEx::fsckOutput("Meta node " + StringTk::uintToStr(*idIt) + " is set to "
"NEEDS_RESYNC.", OutputOptions_LINEBREAK);
result = false;
}
}
}
return result;
}
| 28.879339 | 106 | 0.627862 | congweitao |
c69fb2596c3c21a93b42faa98573b71d49655a99 | 4,302 | cpp | C++ | Game_exe/release_mode/windows/obj/src/flixel/input/actions/FlxInputDeviceID.cpp | hisatsuga/Salty-Psyche-Engine-Port-Main | 0c6afc6ef57f6f6a8b83ff23bb6a26bb05117ab7 | [
"Apache-2.0"
] | 1 | 2021-07-19T05:10:43.000Z | 2021-07-19T05:10:43.000Z | export/release/windows/obj/src/flixel/input/actions/FlxInputDeviceID.cpp | Tyrcnex/tai-mod | b83152693bb3139ee2ae73002623934f07d35baf | [
"Apache-2.0"
] | null | null | null | export/release/windows/obj/src/flixel/input/actions/FlxInputDeviceID.cpp | Tyrcnex/tai-mod | b83152693bb3139ee2ae73002623934f07d35baf | [
"Apache-2.0"
] | null | null | null | #include <hxcpp.h>
#ifndef INCLUDED_flixel_input_actions_FlxInputDeviceID
#include <flixel/input/actions/FlxInputDeviceID.h>
#endif
HX_LOCAL_STACK_FRAME(_hx_pos_8815d627a254acc2_117_boot,"flixel.input.actions.FlxInputDeviceID","boot",0x9ec96ab0,"flixel.input.actions.FlxInputDeviceID.boot","flixel/input/actions/FlxActionInput.hx",117,0x5d496a72)
HX_LOCAL_STACK_FRAME(_hx_pos_8815d627a254acc2_122_boot,"flixel.input.actions.FlxInputDeviceID","boot",0x9ec96ab0,"flixel.input.actions.FlxInputDeviceID.boot","flixel/input/actions/FlxActionInput.hx",122,0x5d496a72)
HX_LOCAL_STACK_FRAME(_hx_pos_8815d627a254acc2_127_boot,"flixel.input.actions.FlxInputDeviceID","boot",0x9ec96ab0,"flixel.input.actions.FlxInputDeviceID.boot","flixel/input/actions/FlxActionInput.hx",127,0x5d496a72)
namespace flixel{
namespace input{
namespace actions{
void FlxInputDeviceID_obj::__construct() { }
Dynamic FlxInputDeviceID_obj::__CreateEmpty() { return new FlxInputDeviceID_obj; }
void *FlxInputDeviceID_obj::_hx_vtable = 0;
Dynamic FlxInputDeviceID_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< FlxInputDeviceID_obj > _hx_result = new FlxInputDeviceID_obj();
_hx_result->__construct();
return _hx_result;
}
bool FlxInputDeviceID_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x10dfec1c;
}
int FlxInputDeviceID_obj::ALL;
int FlxInputDeviceID_obj::FIRST_ACTIVE;
int FlxInputDeviceID_obj::NONE;
FlxInputDeviceID_obj::FlxInputDeviceID_obj()
{
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *FlxInputDeviceID_obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo FlxInputDeviceID_obj_sStaticStorageInfo[] = {
{::hx::fsInt,(void *) &FlxInputDeviceID_obj::ALL,HX_("ALL",01,95,31,00)},
{::hx::fsInt,(void *) &FlxInputDeviceID_obj::FIRST_ACTIVE,HX_("FIRST_ACTIVE",55,71,b1,b1)},
{::hx::fsInt,(void *) &FlxInputDeviceID_obj::NONE,HX_("NONE",b8,da,ca,33)},
{ ::hx::fsUnknown, 0, null()}
};
#endif
static void FlxInputDeviceID_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(FlxInputDeviceID_obj::ALL,"ALL");
HX_MARK_MEMBER_NAME(FlxInputDeviceID_obj::FIRST_ACTIVE,"FIRST_ACTIVE");
HX_MARK_MEMBER_NAME(FlxInputDeviceID_obj::NONE,"NONE");
};
#ifdef HXCPP_VISIT_ALLOCS
static void FlxInputDeviceID_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(FlxInputDeviceID_obj::ALL,"ALL");
HX_VISIT_MEMBER_NAME(FlxInputDeviceID_obj::FIRST_ACTIVE,"FIRST_ACTIVE");
HX_VISIT_MEMBER_NAME(FlxInputDeviceID_obj::NONE,"NONE");
};
#endif
::hx::Class FlxInputDeviceID_obj::__mClass;
static ::String FlxInputDeviceID_obj_sStaticFields[] = {
HX_("ALL",01,95,31,00),
HX_("FIRST_ACTIVE",55,71,b1,b1),
HX_("NONE",b8,da,ca,33),
::String(null())
};
void FlxInputDeviceID_obj::__register()
{
FlxInputDeviceID_obj _hx_dummy;
FlxInputDeviceID_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("flixel.input.actions.FlxInputDeviceID",b0,0a,ac,bf);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = FlxInputDeviceID_obj_sMarkStatics;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(FlxInputDeviceID_obj_sStaticFields);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = ::hx::TCanCast< FlxInputDeviceID_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = FlxInputDeviceID_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = FlxInputDeviceID_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = FlxInputDeviceID_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
void FlxInputDeviceID_obj::__boot()
{
{
HX_STACKFRAME(&_hx_pos_8815d627a254acc2_117_boot)
HXDLIN( 117) ALL = -1;
}
{
HX_STACKFRAME(&_hx_pos_8815d627a254acc2_122_boot)
HXDLIN( 122) FIRST_ACTIVE = -2;
}
{
HX_STACKFRAME(&_hx_pos_8815d627a254acc2_127_boot)
HXDLIN( 127) NONE = -3;
}
}
} // end namespace flixel
} // end namespace input
} // end namespace actions
| 35.262295 | 214 | 0.77801 | hisatsuga |
c6a0bd9e00e6362f6eae1c600a020a063cf55fc6 | 6,880 | cpp | C++ | src/difont/opengl/OpenGLInterface.windows.cpp | cdave1/difont | 2c38726cc3b7a6e06b920accef4ce752967fa61d | [
"MIT"
] | 3 | 2015-03-09T05:51:02.000Z | 2019-07-29T10:33:32.000Z | src/difont/opengl/OpenGLInterface.windows.cpp | cdave1/difont | 2c38726cc3b7a6e06b920accef4ce752967fa61d | [
"MIT"
] | null | null | null | src/difont/opengl/OpenGLInterface.windows.cpp | cdave1/difont | 2c38726cc3b7a6e06b920accef4ce752967fa61d | [
"MIT"
] | null | null | null | /*
Copyright (c) 2010 David Petrie
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 "OpenGLInterface.h"
#include <string.h>
#define DIFONT_GLUE_MAX_VERTICES 32768
#define DIFONT_GLUE_MAX_MESHES 64
typedef struct
{
GLfloat position[4];
GLfloat color[4];
GLfloat texCoord[2];
} difontVertex_t;
typedef struct {
difontVertex_t vertices[DIFONT_GLUE_MAX_VERTICES];
short quadIndices[DIFONT_GLUE_MAX_VERTICES * 3 / 2];
difontVertex_t currVertex;
unsigned int currIndex;
} difontGlueArrays_t;
difontGlueArrays_t difontGlueArrays;
GLenum difontCurrentPrimitive = GL_TRIANGLES;
bool DIFONTQuadIndicesInitted = false;
void difontBindPositionAttribute(GLint attributeHandle) {
glVertexAttribPointer(attributeHandle, 4, GL_FLOAT, 0, sizeof(difontVertex_t), difontGlueArrays.vertices[0].position);
glEnableVertexAttribArray(attributeHandle);
}
void difontBindColorAttribute(GLint attributeHandle) {
glVertexAttribPointer(attributeHandle, 4, GL_FLOAT, 0, sizeof(difontVertex_t), difontGlueArrays.vertices[0].color);
glEnableVertexAttribArray(attributeHandle);
}
void difontBindTextureAttribute(GLint attributeHandle) {
glVertexAttribPointer(attributeHandle, 2, GL_FLOAT, 0, sizeof(difontVertex_t), difontGlueArrays.vertices[0].texCoord);
glEnableVertexAttribArray(attributeHandle);
}
GLvoid difont::gl::Begin(GLenum prim) {
if (!DIFONTQuadIndicesInitted) {
for (int i = 0; i < DIFONT_GLUE_MAX_VERTICES * 3 / 2; i += 6) {
int q = i / 6 * 4;
difontGlueArrays.quadIndices[i + 0] = q + 0;
difontGlueArrays.quadIndices[i + 1] = q + 1;
difontGlueArrays.quadIndices[i + 2] = q + 2;
difontGlueArrays.quadIndices[i + 3] = q + 0;
difontGlueArrays.quadIndices[i + 4] = q + 2;
difontGlueArrays.quadIndices[i + 5] = q + 3;
}
DIFONTQuadIndicesInitted = true;
}
difontGlueArrays.currIndex = 0;
difontCurrentPrimitive = prim;
}
GLvoid difont::gl::Vertex3f(float x, float y, float z) {
if (difontGlueArrays.currIndex >= DIFONT_GLUE_MAX_VERTICES) {
return;
}
difontGlueArrays.currVertex.position[0] = x;
difontGlueArrays.currVertex.position[1] = y;
difontGlueArrays.currVertex.position[2] = z;
difontGlueArrays.currVertex.position[3] = 1.0f;
difontGlueArrays.vertices[difontGlueArrays.currIndex] = difontGlueArrays.currVertex;
difontGlueArrays.currIndex++;
}
GLvoid difont::gl::Vertex2f(float x, float y) {
if (difontGlueArrays.currIndex >= DIFONT_GLUE_MAX_VERTICES) {
return;
}
difontGlueArrays.currVertex.position[0] = x;
difontGlueArrays.currVertex.position[1] = y;
difontGlueArrays.currVertex.position[2] = 0.0f;
difontGlueArrays.currVertex.position[3] = 1.0f;
difontGlueArrays.vertices[difontGlueArrays.currIndex] = difontGlueArrays.currVertex;
difontGlueArrays.currIndex++;
}
GLvoid difont::gl::Color4f(GLfloat r, GLfloat g, GLfloat b, GLfloat a) {
difontGlueArrays.currVertex.color[0] = r;
difontGlueArrays.currVertex.color[1] = g;
difontGlueArrays.currVertex.color[2] = b;
difontGlueArrays.currVertex.color[3] = a;
}
GLvoid difont::gl::TexCoord2f(GLfloat s, GLfloat t) {
difontGlueArrays.currVertex.texCoord[0] = s;
difontGlueArrays.currVertex.texCoord[1] = t;
}
GLvoid bindArrayBuffers() {}
GLvoid difont::gl::BindTexture(unsigned int textureId) {
GLint activeTextureID;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &activeTextureID);
if ((unsigned int)activeTextureID != textureId) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
}
GLvoid difont::gl::End() {
/*
if (difontGlueArrays.currIndex == 0) {
DIFONTCurrentPrimitive = 0;
return;
}
if (DIFONTCurrentPrimitive == GL_QUADS) {
glDrawElements(GL_TRIANGLES, difontGlueArrays.currIndex / 4 * 6, GL_UNSIGNED_SHORT, difontGlueArrays.quadIndices);
} else {
glDrawArrays(DIFONTCurrentPrimitive, 0, difontGlueArrays.currIndex);
}*/
}
uint32_t difont::gl::VertexSize() {
return sizeof(difontVertex_t);
}
uint32_t difont::gl::VertexCount() {
return difontGlueArrays.currIndex;
}
/*
void difont::gl::CopyMesh(void *dataPointer, uint32_t *dataLen, uint32_t *vertexCount) {
if (difontCurrentPrimitive == 0 || difontGlueArrays.currIndex == 0) {
dataPointer = NULL;
dataLen = 0;
vertexCount = 0;
return;
}
memcpy(dataPointer, difontGlueArrays.vertices, sizeof(difontVertex_t) * difontGlueArrays.currIndex);
*vertexCount = difontGlueArrays.currIndex;
*dataLen = sizeof(difontVertex_t) * difontGlueArrays.currIndex;
}*/
GLvoid difont::gl::Error(const char *source) {
GLenum error = glGetError();
switch (error) {
case GL_NO_ERROR:
break;
case GL_INVALID_ENUM:
printf("GL Error (%x): GL_INVALID_ENUM. %s\n\n", error, source);
break;
case GL_INVALID_VALUE:
printf("GL Error (%x): GL_INVALID_VALUE. %s\n\n", error, source);
break;
case GL_INVALID_OPERATION:
printf("GL Error (%x): GL_INVALID_OPERATION. %s\n\n", error, source);
break;/*
case GL_STACK_OVERFLOW:
printf("GL Error (%x): GL_STACK_OVERFLOW. %s\n\n", error, source);
break;
case GL_STACK_UNDERFLOW:
printf("GL Error (%x): GL_STACK_UNDERFLOW. %s\n\n", error, source);
break;*/
case GL_OUT_OF_MEMORY:
printf("GL Error (%x): GL_OUT_OF_MEMORY. %s\n\n", error, source);
break;
default:
printf("GL Error (%x): %s\n\n", error, source);
break;
}
}
| 31.851852 | 122 | 0.717733 | cdave1 |
c6a19712a8b861c524279e8944be9b1da81d32a2 | 1,381 | cpp | C++ | sim/Character3D.cpp | snumrl/VSports | c35bc82db31cd7252ab3d0f78c3f941bae5e799b | [
"Apache-2.0"
] | null | null | null | sim/Character3D.cpp | snumrl/VSports | c35bc82db31cd7252ab3d0f78c3f941bae5e799b | [
"Apache-2.0"
] | null | null | null | sim/Character3D.cpp | snumrl/VSports | c35bc82db31cd7252ab3d0f78c3f941bae5e799b | [
"Apache-2.0"
] | null | null | null | #include "Character3D.h"
#include "../model/SkelMaker.h"
#include <dart/dart.hpp>
#include <iostream>
Character3D::
Character3D(const std::string& name)
:mName(name)
{
curLeftFingerPosition = 0.0;
curRightFingerPosition = 0.0;
curLeftFingerBallPosition = 0.0;
curRightFingerBallPosition = 0.0;
blocked = false;
inputActionType = 0;
availableActionTypes.resize(5);
// prevSkelPositions.resize(mSkeleton->getNumDofs());
// prevSkelPositions
prevKeyJointPositions.resize(6*3);
prevKeyJointPositions.setZero();
prevRootT.setIdentity();
}
const dart::dynamics::SkeletonPtr&
Character3D::
getSkeleton()
{
return mSkeleton;
}
void
Character3D::
copy(Character3D *c3d)
{
this->mSkeleton->setPositions(c3d->mSkeleton->getPositions());
this->mSkeleton->setVelocities(c3d->mSkeleton->getVelocities());
this->mName = c3d->mName;
this->curLeftFingerPosition = c3d->curLeftFingerPosition;
this->curRightFingerPosition = c3d->curRightFingerPosition;
this->curLeftFingerBallPosition = c3d->curLeftFingerBallPosition;
this->curRightFingerBallPosition = c3d->curRightFingerBallPosition;
this->blocked = c3d->blocked;
this->inputActionType = c3d->inputActionType;
this->availableActionTypes = c3d->availableActionTypes;
this->prevSkelPositions = c3d->prevSkelPositions;
this->prevKeyJointPositions = c3d->prevKeyJointPositions;
this->prevRootT = c3d->prevRootT;
}
| 25.109091 | 68 | 0.772629 | snumrl |
c6a699f8bab50b56270512da3d65508174783456 | 63,273 | cpp | C++ | src/basetestsealbfv.cpp | YiJingGuo/HEBenchmark | 3154b4b638b32c97d307c598a2dd2fbf0a543de2 | [
"MIT"
] | 27 | 2019-07-27T10:32:24.000Z | 2021-05-17T12:32:30.000Z | src/basetestsealbfv.cpp | YiJingGuo/HEBenchmark | 3154b4b638b32c97d307c598a2dd2fbf0a543de2 | [
"MIT"
] | null | null | null | src/basetestsealbfv.cpp | YiJingGuo/HEBenchmark | 3154b4b638b32c97d307c598a2dd2fbf0a543de2 | [
"MIT"
] | 11 | 2019-07-28T03:57:06.000Z | 2021-04-27T09:24:52.000Z | #include "basetestsealbfv.h"
#include "ui_basetestsealbfv.h"
#include "mainwindow.h"
#include <QHBoxLayout>
#include <QValueAxis>
BaseTestSealBFV::BaseTestSealBFV(QWidget *parent) :
QWidget(parent),
ui(new Ui::BaseTestSealBFV)
{
ui->setupUi(this);
QPalette bgpal = palette();
bgpal.setColor (QPalette::Background, QColor (0, 0 , 0, 255));
bgpal.setColor (QPalette::Foreground, QColor (255,255,255,255)); setPalette (bgpal);
}
BaseTestSealBFV::~BaseTestSealBFV()
{
delete ui;
}
void BaseTestSealBFV::charts()
{
QLineSeries *series = new QLineSeries();
*series << QPointF(1, noise_budget_initial) << QPointF(2, noise_budget_end);
QChart *chart = new QChart();
chart->legend()->hide();
chart->addSeries(series);
//chart->createDefaultAxes(); //自动化建立XY轴
QValueAxis *axisX = new QValueAxis();//轴变量、数据系列变量,都不能声明为局部临时变量
QValueAxis *axisY = new QValueAxis();//创建X/Y轴
axisX->setRange(1, 2);
axisY->setRange(noise_budget_end-5, noise_budget_initial+5);//设置X/Y显示的区间
chart->setAxisX(axisX);
chart->setAxisY(axisY);//设置chart的坐标轴
series->attachAxis(axisX);//连接数据集与坐标轴。
series->attachAxis(axisY);
chart->setTitle("噪音剩余空间");
ui->graphicsView->setChart(chart);
ui->graphicsView->setRenderHint(QPainter::Antialiasing);
}
void BaseTestSealBFV::print_parameters(shared_ptr<SEALContext> context)
{
QString result = "";
// Verify parameters
if (!context)
{
throw invalid_argument("context is not set");
}
auto &context_data = *context->context_data();
/*
Which scheme are we using?
*/
QString scheme_name;
switch (context_data.parms().scheme())
{
case scheme_type::BFV:
scheme_name = "BFV";
break;
case scheme_type::CKKS:
scheme_name = "CKKS";
break;
default:
throw invalid_argument("unsupported scheme");
}
result += "/ Encryption parameters:\n";
result += "| scheme: ";
result += scheme_name;
result += "\n| poly_modulus_degree: ";
int temp_int;
temp_int = context_data.parms().poly_modulus_degree();
QString temp = QString::number(temp_int);
result += temp;
/*
Print the size of the true (product) coefficient modulus.
*/
result += "\n| coeff_modulus size: ";
temp_int = context_data.
total_coeff_modulus_bit_count();
temp = QString::number(temp_int);
result += temp;
result += " bits\n";
/*
For the BFV scheme print the plain_modulus parameter.
*/
if (context_data.parms().scheme() == scheme_type::BFV)
{
result += "| plain_modulus: ";
temp_int = context_data.
parms().plain_modulus().value();
temp = QString::number(temp_int);
result += temp;
}
result += "\n\\ noise_standard_deviation: ";
temp_int = context_data.
parms().noise_standard_deviation();
temp = QString::number(temp_int);
result += temp;
ui->param->setText(result);
}
void BaseTestSealBFV::test_add(shared_ptr<SEALContext> context)
{
ui->graphicsView->show();
chrono::high_resolution_clock::time_point time_start, time_end;
QString result = "";
print_parameters(context);
auto &curr_parms = context->context_data()->parms();
auto &plain_modulus = curr_parms.plain_modulus();
/*
Set up keys.
*/
result += "Generating secret/public keys: ";
KeyGenerator keygen(context);
result += "Done\n" ;
auto secret_key = keygen.secret_key();
auto public_key = keygen.public_key();
/*
生成relinearization keys时间.
*/
int dbc = DefaultParams::dbc_max();
result += "Generating relinearization keys (dbc = ";
QString temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto relin_keys = keygen.relin_keys(dbc);
time_end = chrono::high_resolution_clock::now();
auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
int time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
/*
生成Galois keys时间.
*/
if (!context->context_data()->qualifiers().using_batching)
{
result += "Given encryption parameters do not support batching.";
return;
}
result += "Generating Galois keys (dbc = ";
temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto gal_keys = keygen.galois_keys(dbc);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
IntegerEncoder encoder(context);
chrono::microseconds time_add_sum(0);
/*
Populate a vector of values to batch.
*/
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < batch_encoder.slot_count(); i++)
{
pod_vector.push_back(rd() % plain_modulus.value());
}
result += "\n";
for (int i = 0; i < test_number; i++)
{
/*
[Add]
*/
Ciphertext encrypted1(context);
encryptor.encrypt(encoder.encode(i), encrypted1);
Ciphertext encrypted2(context);
encryptor.encrypt(encoder.encode(i+1), encrypted2);
noise_budget_initial = decryptor.invariant_noise_budget(encrypted1);
time_start = chrono::high_resolution_clock::now();
evaluator.add_inplace(encrypted1, encrypted1);
time_end = chrono::high_resolution_clock::now();
time_add_sum += chrono::duration_cast<
chrono::microseconds>(time_end - time_start) ;
noise_budget_end = decryptor.invariant_noise_budget(encrypted1);
}
result += "Initial noise budget: ";
temp = QString::number(noise_budget_initial);
result += temp;
result += " bits\n";
result += "The residual noise: ";
temp = QString::number(noise_budget_end);
result += temp;
result += " bits\n";
auto avg_add = time_add_sum.count() / test_number;
result += "Average add: ";
temp = QString::number(avg_add);
result += temp;
result += " microseconds\n";
ui->result->setText(result);
charts();
}
void BaseTestSealBFV::test_add_plain(shared_ptr<SEALContext> context)
{
ui->graphicsView->show();
chrono::high_resolution_clock::time_point time_start, time_end;
QString result = "";
print_parameters(context);
auto &curr_parms = context->context_data()->parms();
auto &plain_modulus = curr_parms.plain_modulus();
/*
Set up keys.
*/
result += "Generating secret/public keys: ";
KeyGenerator keygen(context);
result += "Done\n" ;
auto secret_key = keygen.secret_key();
auto public_key = keygen.public_key();
/*
生成relinearization keys时间.
*/
int dbc = DefaultParams::dbc_max();
result += "Generating relinearization keys (dbc = ";
QString temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto relin_keys = keygen.relin_keys(dbc);
time_end = chrono::high_resolution_clock::now();
auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
int time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
/*
生成Galois keys时间.
*/
if (!context->context_data()->qualifiers().using_batching)
{
result += "Given encryption parameters do not support batching.";
return;
}
result += "Generating Galois keys (dbc = ";
temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto gal_keys = keygen.galois_keys(dbc);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
IntegerEncoder encoder(context);
chrono::microseconds time_add_plain_sum(0);
/*
Populate a vector of values to batch.
*/
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < batch_encoder.slot_count(); i++)
{
pod_vector.push_back(rd() % plain_modulus.value());
}
result += "\n";
Plaintext plain(curr_parms.poly_modulus_degree(), 0);
batch_encoder.encode(pod_vector, plain);
for (int i = 0; i < test_number; i++)
{
/*
[Add Plain]
*/
Ciphertext encrypted1(context);
encryptor.encrypt(encoder.encode(i), encrypted1);
Ciphertext encrypted2(context);
encryptor.encrypt(encoder.encode(i + 1), encrypted2);
noise_budget_initial = decryptor.invariant_noise_budget(encrypted1);
time_start = chrono::high_resolution_clock::now();
evaluator.add_plain_inplace(encrypted1, plain);
time_end = chrono::high_resolution_clock::now();
time_add_plain_sum += chrono::duration_cast<
chrono::microseconds>(time_end - time_start);
noise_budget_end = decryptor.invariant_noise_budget(encrypted1);
}
result += "Initial noise budget: ";
temp = QString::number(noise_budget_initial);
result += temp;
result += " bits\n";
result += "The residual noise: ";
temp = QString::number(noise_budget_end);
result += temp;
result += " bits\n";
auto avg_add_plain = time_add_plain_sum.count() / test_number;
result += "Average add plain: ";
temp = QString::number(avg_add_plain);
result += temp;
result += " microseconds\n";
ui->result->setText(result);
charts();
}
void BaseTestSealBFV::test_mult(shared_ptr<SEALContext> context)
{
ui->graphicsView->show();
chrono::high_resolution_clock::time_point time_start, time_end;
QString result = "";
print_parameters(context);
auto &curr_parms = context->context_data()->parms();
auto &plain_modulus = curr_parms.plain_modulus();
/*
Set up keys.
*/
result += "Generating secret/public keys: ";
KeyGenerator keygen(context);
result += "Done\n" ;
auto secret_key = keygen.secret_key();
auto public_key = keygen.public_key();
/*
生成relinearization keys时间.
*/
int dbc = DefaultParams::dbc_max();
result += "Generating relinearization keys (dbc = ";
QString temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto relin_keys = keygen.relin_keys(dbc);
time_end = chrono::high_resolution_clock::now();
auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
int time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
/*
生成Galois keys时间.
*/
if (!context->context_data()->qualifiers().using_batching)
{
result += "Given encryption parameters do not support batching.";
return;
}
result += "Generating Galois keys (dbc = ";
temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto gal_keys = keygen.galois_keys(dbc);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
IntegerEncoder encoder(context);
chrono::microseconds time_mult_sum(0);
/*
Populate a vector of values to batch.
*/
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < batch_encoder.slot_count(); i++)
{
pod_vector.push_back(rd() % plain_modulus.value());
}
result += "\n";
for (int i = 0; i < test_number; i++)
{
/*
[Multiply]
*/
Ciphertext encrypted1(context);
encryptor.encrypt(encoder.encode(i), encrypted1);
Ciphertext encrypted2(context);
encryptor.encrypt(encoder.encode(i + 1), encrypted2);
encrypted1.reserve(3);
noise_budget_initial = decryptor.invariant_noise_budget(encrypted1);
time_start = chrono::high_resolution_clock::now();
evaluator.multiply_inplace(encrypted1, encrypted2);
time_end = chrono::high_resolution_clock::now();
time_mult_sum += chrono::duration_cast<
chrono::microseconds>(time_end - time_start);
noise_budget_end = decryptor.invariant_noise_budget(encrypted1);
}
result += "Initial noise budget: ";
temp = QString::number(noise_budget_initial);
result += temp;
result += " bits\n";
result += "The residual noise: ";
temp = QString::number(noise_budget_end);
result += temp;
result += " bits\n";
auto avg_mult = time_mult_sum.count() / test_number;
result += "Average multiply: ";
temp = QString::number(avg_mult);
result += temp;
result += " microseconds\n";
ui->result->setText(result);
charts();
}
void BaseTestSealBFV::test_mult_plain(shared_ptr<SEALContext> context)
{
ui->graphicsView->show();
chrono::high_resolution_clock::time_point time_start, time_end;
QString result = "";
print_parameters(context);
auto &curr_parms = context->context_data()->parms();
auto &plain_modulus = curr_parms.plain_modulus();
/*
Set up keys.
*/
result += "Generating secret/public keys: ";
KeyGenerator keygen(context);
result += "Done\n" ;
auto secret_key = keygen.secret_key();
auto public_key = keygen.public_key();
/*
生成relinearization keys时间.
*/
int dbc = DefaultParams::dbc_max();
result += "Generating relinearization keys (dbc = ";
QString temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto relin_keys = keygen.relin_keys(dbc);
time_end = chrono::high_resolution_clock::now();
auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
int time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
/*
生成Galois keys时间.
*/
if (!context->context_data()->qualifiers().using_batching)
{
result += "Given encryption parameters do not support batching.";
return;
}
result += "Generating Galois keys (dbc = ";
temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto gal_keys = keygen.galois_keys(dbc);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
IntegerEncoder encoder(context);
chrono::microseconds time_mult_plain_sum(0);
/*
Populate a vector of values to batch.
*/
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < batch_encoder.slot_count(); i++)
{
pod_vector.push_back(rd() % plain_modulus.value());
}
result += "\n";
Plaintext plain(curr_parms.poly_modulus_degree(), 0);
batch_encoder.encode(pod_vector, plain);
for (int i = 0; i < test_number; i++)
{
/*
[Multiply Plain]
*/
Ciphertext encrypted1(context);
encryptor.encrypt(encoder.encode(i), encrypted1);
noise_budget_initial = decryptor.invariant_noise_budget(encrypted1);
time_start = chrono::high_resolution_clock::now();
evaluator.multiply_plain_inplace(encrypted1, plain);
time_end = chrono::high_resolution_clock::now();
time_mult_plain_sum += chrono::duration_cast<
chrono::microseconds>(time_end - time_start);
noise_budget_end = decryptor.invariant_noise_budget(encrypted1);
}
result += "Initial noise budget: ";
temp = QString::number(noise_budget_initial);
result += temp;
result += " bits\n";
result += "The residual noise: ";
temp = QString::number(noise_budget_end);
result += temp;
result += " bits\n";
auto avg_mult_plain = time_mult_plain_sum.count() / test_number;
result += "Average multiply plain: ";
temp = QString::number(avg_mult_plain);
result += temp;
result += " microseconds\n";
ui->result->setText(result);
charts();
}
void BaseTestSealBFV::test_sub(shared_ptr<SEALContext> context)
{
ui->graphicsView->show();
chrono::high_resolution_clock::time_point time_start, time_end;
QString result = "";
print_parameters(context);
auto &curr_parms = context->context_data()->parms();
auto &plain_modulus = curr_parms.plain_modulus();
/*
Set up keys.
*/
result += "Generating secret/public keys: ";
KeyGenerator keygen(context);
result += "Done\n" ;
auto secret_key = keygen.secret_key();
auto public_key = keygen.public_key();
/*
生成relinearization keys时间.
*/
int dbc = DefaultParams::dbc_max();
result += "Generating relinearization keys (dbc = ";
QString temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto relin_keys = keygen.relin_keys(dbc);
time_end = chrono::high_resolution_clock::now();
auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
int time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
/*
生成Galois keys时间.
*/
if (!context->context_data()->qualifiers().using_batching)
{
result += "Given encryption parameters do not support batching.";
return;
}
result += "Generating Galois keys (dbc = ";
temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto gal_keys = keygen.galois_keys(dbc);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
IntegerEncoder encoder(context);
chrono::microseconds time_sub_sum(0);
/*
Populate a vector of values to batch.
*/
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < batch_encoder.slot_count(); i++)
{
pod_vector.push_back(rd() % plain_modulus.value());
}
result += "\n";
for (int i = 0; i < test_number; i++)
{
/*
[Sub]
*/
Ciphertext encrypted1(context);
encryptor.encrypt(encoder.encode(i), encrypted1);
Ciphertext encrypted2(context);
encryptor.encrypt(encoder.encode(i+1), encrypted2);
noise_budget_initial = decryptor.invariant_noise_budget(encrypted1);
time_start = chrono::high_resolution_clock::now();
evaluator.sub_inplace(encrypted1, encrypted2);
time_end = chrono::high_resolution_clock::now();
time_sub_sum += chrono::duration_cast<
chrono::microseconds>(time_end - time_start);
noise_budget_end = decryptor.invariant_noise_budget(encrypted1);
}
result += "Initial noise budget: ";
temp = QString::number(noise_budget_initial);
result += temp;
result += " bits\n";
result += "The residual noise: ";
temp = QString::number(noise_budget_end);
result += temp;
result += " bits\n";
auto avg_sub = time_sub_sum.count() / test_number;
result += "Average subtraction: ";
temp = QString::number(avg_sub);
result += temp;
result += " microseconds\n";
ui->result->setText(result);
charts();
}
void BaseTestSealBFV::test_sub_plain(shared_ptr<SEALContext> context)
{
ui->graphicsView->show();
chrono::high_resolution_clock::time_point time_start, time_end;
QString result = "";
print_parameters(context);
auto &curr_parms = context->context_data()->parms();
auto &plain_modulus = curr_parms.plain_modulus();
/*
Set up keys.
*/
result += "Generating secret/public keys: ";
KeyGenerator keygen(context);
result += "Done\n" ;
auto secret_key = keygen.secret_key();
auto public_key = keygen.public_key();
/*
生成relinearization keys时间.
*/
int dbc = DefaultParams::dbc_max();
result += "Generating relinearization keys (dbc = ";
QString temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto relin_keys = keygen.relin_keys(dbc);
time_end = chrono::high_resolution_clock::now();
auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
result += "Done [";
result += QString::number(time_diff.count());
result += " microseconds]\n";
/*
生成Galois keys时间.
*/
if (!context->context_data()->qualifiers().using_batching)
{
result += "Given encryption parameters do not support batching.";
return;
}
result += "Generating Galois keys (dbc = ";
temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto gal_keys = keygen.galois_keys(dbc);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
result += "Done [";
result += QString::number(time_diff.count());
result += " microseconds]\n";
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
IntegerEncoder encoder(context);
chrono::microseconds time_sub_plain_sum(0);
/*
Populate a vector of values to batch.
*/
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < batch_encoder.slot_count(); i++)
{
pod_vector.push_back(rd() % plain_modulus.value());
}
result += "\n";
Plaintext plain(curr_parms.poly_modulus_degree(), 0);
batch_encoder.encode(pod_vector, plain);
for (int i = 0; i < test_number; i++)
{
/*
[Sub Plain]
*/
Ciphertext encrypted1(context);
encryptor.encrypt(encoder.encode(i), encrypted1);
Ciphertext encrypted2(context);
encryptor.encrypt(encoder.encode(i + 1), encrypted2);
noise_budget_initial = decryptor.invariant_noise_budget(encrypted1);
time_start = chrono::high_resolution_clock::now();
evaluator.sub_plain_inplace(encrypted1, plain);
time_end = chrono::high_resolution_clock::now();
time_sub_plain_sum += chrono::duration_cast<
chrono::microseconds>(time_end - time_start);
noise_budget_end = decryptor.invariant_noise_budget(encrypted1);
}
result += "Initial noise budget: ";
result += QString::number(noise_budget_initial);
result += " bits\n";
result += "The residual noise: ";
result += QString::number(noise_budget_end);
result += " bits\n";
auto avg_sub_plain = time_sub_plain_sum.count() / test_number;
result += "Average sub plain: ";
result += QString::number(avg_sub_plain);
result += " microseconds\n";
ui->result->setText(result);
charts();
}
void BaseTestSealBFV::test_square(shared_ptr<SEALContext> context)
{
ui->graphicsView->show();
chrono::high_resolution_clock::time_point time_start, time_end;
QString result = "";
print_parameters(context);
auto &curr_parms = context->context_data()->parms();
auto &plain_modulus = curr_parms.plain_modulus();
/*
Set up keys.
*/
result += "Generating secret/public keys: ";
KeyGenerator keygen(context);
result += "Done\n" ;
auto secret_key = keygen.secret_key();
auto public_key = keygen.public_key();
/*
生成relinearization keys时间.
*/
int dbc = DefaultParams::dbc_max();
result += "Generating relinearization keys (dbc = ";
QString temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto relin_keys = keygen.relin_keys(dbc);
time_end = chrono::high_resolution_clock::now();
auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
int time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
/*
生成Galois keys时间.
*/
if (!context->context_data()->qualifiers().using_batching)
{
result += "Given encryption parameters do not support batching.";
return;
}
result += "Generating Galois keys (dbc = ";
temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto gal_keys = keygen.galois_keys(dbc);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
IntegerEncoder encoder(context);
chrono::microseconds time_square_sum(0);
/*
Populate a vector of values to batch.
*/
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < batch_encoder.slot_count(); i++)
{
pod_vector.push_back(rd() % plain_modulus.value());
}
result += "\n";
for (int i = 0; i < test_number; i++)
{
/*
[Square]
*/
Ciphertext encrypted1(context);
encryptor.encrypt(encoder.encode(i), encrypted1);
noise_budget_initial = decryptor.invariant_noise_budget(encrypted1);
time_start = chrono::high_resolution_clock::now();
evaluator.square_inplace(encrypted1);
time_end = chrono::high_resolution_clock::now();
time_square_sum += chrono::duration_cast<
chrono::microseconds>(time_end - time_start);
noise_budget_end = decryptor.invariant_noise_budget(encrypted1);
}
result += "Initial noise budget: ";
temp = QString::number(noise_budget_initial);
result += temp;
result += " bits\n";
result += "The residual noise: ";
temp = QString::number(noise_budget_end);
result += temp;
result += " bits\n";
auto avg_square = time_square_sum.count() / test_number;
result += "Average multiply: ";
temp = QString::number(avg_square);
result += temp;
result += " microseconds\n";
ui->result->setText(result);
charts();
}
void BaseTestSealBFV::test_negation(shared_ptr<SEALContext> context)
{
ui->graphicsView->show();
chrono::high_resolution_clock::time_point time_start, time_end;
QString result = "";
print_parameters(context);
auto &curr_parms = context->context_data()->parms();
auto &plain_modulus = curr_parms.plain_modulus();
/*
Set up keys.
*/
result += "Generating secret/public keys: ";
KeyGenerator keygen(context);
result += "Done\n" ;
auto secret_key = keygen.secret_key();
auto public_key = keygen.public_key();
/*
生成relinearization keys时间.
*/
int dbc = DefaultParams::dbc_max();
result += "Generating relinearization keys (dbc = ";
QString temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto relin_keys = keygen.relin_keys(dbc);
time_end = chrono::high_resolution_clock::now();
auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
int time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
/*
生成Galois keys时间.
*/
if (!context->context_data()->qualifiers().using_batching)
{
result += "Given encryption parameters do not support batching.";
return;
}
result += "Generating Galois keys (dbc = ";
temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto gal_keys = keygen.galois_keys(dbc);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
IntegerEncoder encoder(context);
chrono::microseconds time_negation_sum(0);
/*
Populate a vector of values to batch.
*/
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < batch_encoder.slot_count(); i++)
{
pod_vector.push_back(rd() % plain_modulus.value());
}
result += "\n";
for (int i = 0; i < test_number; i++)
{
/*
[Negation]
*/
Ciphertext encrypted1(context);
encryptor.encrypt(encoder.encode(i), encrypted1);
noise_budget_initial = decryptor.invariant_noise_budget(encrypted1);
time_start = chrono::high_resolution_clock::now();
evaluator.negate_inplace(encrypted1);
time_end = chrono::high_resolution_clock::now();
time_negation_sum += chrono::duration_cast<
chrono::microseconds>(time_end - time_start);
noise_budget_end = decryptor.invariant_noise_budget(encrypted1);
}
result += "Initial noise budget: ";
temp = QString::number(noise_budget_initial);
result += temp;
result += " bits\n";
result += "The residual noise: ";
temp = QString::number(noise_budget_end);
result += temp;
result += " bits\n";
auto avg_negation = time_negation_sum.count() / test_number;
result += "Average negation: ";
temp = QString::number(avg_negation);
result += temp;
result += " microseconds\n";
ui->result->setText(result);
charts();
}
void BaseTestSealBFV::test_rotate_rows_one_step(shared_ptr<SEALContext> context)
{
ui->graphicsView->show();
chrono::high_resolution_clock::time_point time_start, time_end;
QString result = "";
print_parameters(context);
auto &curr_parms = context->context_data()->parms();
auto &plain_modulus = curr_parms.plain_modulus();
/*
Set up keys.
*/
result += "Generating secret/public keys: ";
KeyGenerator keygen(context);
result += "Done\n" ;
auto secret_key = keygen.secret_key();
auto public_key = keygen.public_key();
/*
生成relinearization keys时间.
*/
int dbc = DefaultParams::dbc_max();
result += "Generating relinearization keys (dbc = ";
QString temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto relin_keys = keygen.relin_keys(dbc);
time_end = chrono::high_resolution_clock::now();
auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
int time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
/*
生成Galois keys时间.
*/
if (!context->context_data()->qualifiers().using_batching)
{
result += "Given encryption parameters do not support batching.";
return;
}
result += "Generating Galois keys (dbc = ";
temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto gal_keys = keygen.galois_keys(dbc);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
IntegerEncoder encoder(context);
chrono::microseconds time_rotate_rows_one_step_sum(0);
/*
Populate a vector of values to batch.
*/
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < batch_encoder.slot_count(); i++)
{
pod_vector.push_back(rd() % plain_modulus.value());
}
result += "\n";
for (int i = 0; i < test_number; i++)
{
/*
[Rotate Rows One Step]
*/
Ciphertext encrypted1(context);
encryptor.encrypt(encoder.encode(i), encrypted1);
noise_budget_initial = decryptor.invariant_noise_budget(encrypted1);
time_start = chrono::high_resolution_clock::now();
evaluator.rotate_rows_inplace(encrypted1, 1, gal_keys); time_end = chrono::high_resolution_clock::now();
time_rotate_rows_one_step_sum += chrono::duration_cast<
chrono::microseconds>(time_end - time_start);
noise_budget_end = decryptor.invariant_noise_budget(encrypted1);
}
result += "Initial noise budget: ";
temp = QString::number(noise_budget_initial);
result += temp;
result += " bits\n";
result += "The residual noise: ";
temp = QString::number(noise_budget_end);
result += temp;
result += " bits\n";
auto avg_rotate_rows_one_step = time_rotate_rows_one_step_sum.count() / test_number;
result += "Average rotate rows one step: ";
temp = QString::number(avg_rotate_rows_one_step);
result += temp;
result += " microseconds\n";
ui->result->setText(result);
charts();
}
void BaseTestSealBFV::test_rotate_rows_random(shared_ptr<SEALContext> context)
{
ui->graphicsView->show();
chrono::high_resolution_clock::time_point time_start, time_end;
QString result = "";
print_parameters(context);
auto &curr_parms = context->context_data()->parms();
auto &plain_modulus = curr_parms.plain_modulus();
/*
Set up keys.
*/
result += "Generating secret/public keys: ";
KeyGenerator keygen(context);
result += "Done\n" ;
auto secret_key = keygen.secret_key();
auto public_key = keygen.public_key();
/*
生成relinearization keys时间.
*/
int dbc = DefaultParams::dbc_max();
result += "Generating relinearization keys (dbc = ";
QString temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto relin_keys = keygen.relin_keys(dbc);
time_end = chrono::high_resolution_clock::now();
auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
int time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
/*
生成Galois keys时间.
*/
if (!context->context_data()->qualifiers().using_batching)
{
result += "Given encryption parameters do not support batching.";
return;
}
result += "Generating Galois keys (dbc = ";
temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto gal_keys = keygen.galois_keys(dbc);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
IntegerEncoder encoder(context);
chrono::microseconds time_rotate_rows_random_sum(0);
/*
Populate a vector of values to batch.
*/
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < batch_encoder.slot_count(); i++)
{
pod_vector.push_back(rd() % plain_modulus.value());
}
result += "\n";
for (int i = 0; i < test_number; i++)
{
/*
[Rotate Rows Random]
*/
Ciphertext encrypted1(context);
encryptor.encrypt(encoder.encode(i), encrypted1);
noise_budget_initial = decryptor.invariant_noise_budget(encrypted1);
size_t row_size = batch_encoder.slot_count() / 2;
int random_rotation = static_cast<int>(rd() % row_size);
time_start = chrono::high_resolution_clock::now();
evaluator.rotate_rows_inplace(encrypted1, random_rotation, gal_keys);
time_end = chrono::high_resolution_clock::now();
time_rotate_rows_random_sum += chrono::duration_cast<
chrono::microseconds>(time_end - time_start);
noise_budget_end = decryptor.invariant_noise_budget(encrypted1);
}
result += "Initial noise budget: ";
temp = QString::number(noise_budget_initial);
result += temp;
result += " bits\n";
result += "The residual noise: ";
temp = QString::number(noise_budget_end);
result += temp;
result += " bits\n";
auto avg_rotate_rows_random = time_rotate_rows_random_sum.count() / test_number;
result += "Average rotate rows random: ";
temp = QString::number(avg_rotate_rows_random);
result += temp;
result += " microseconds\n";
ui->result->setText(result);
charts();
}
void BaseTestSealBFV::test_rotate_columns(shared_ptr<SEALContext> context)
{
ui->graphicsView->show();
chrono::high_resolution_clock::time_point time_start, time_end;
QString result = "";
print_parameters(context);
auto &curr_parms = context->context_data()->parms();
auto &plain_modulus = curr_parms.plain_modulus();
/*
Set up keys.
*/
result += "Generating secret/public keys: ";
KeyGenerator keygen(context);
result += "Done\n" ;
auto secret_key = keygen.secret_key();
auto public_key = keygen.public_key();
/*
生成relinearization keys时间.
*/
int dbc = DefaultParams::dbc_max();
result += "Generating relinearization keys (dbc = ";
QString temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto relin_keys = keygen.relin_keys(dbc);
time_end = chrono::high_resolution_clock::now();
auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
int time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
/*
生成Galois keys时间.
*/
if (!context->context_data()->qualifiers().using_batching)
{
result += "Given encryption parameters do not support batching.";
return;
}
result += "Generating Galois keys (dbc = ";
temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto gal_keys = keygen.galois_keys(dbc);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
IntegerEncoder encoder(context);
chrono::microseconds time_rotate_columns_sum(0);
/*
Populate a vector of values to batch.
*/
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < batch_encoder.slot_count(); i++)
{
pod_vector.push_back(rd() % plain_modulus.value());
}
result += "\n";
for (int i = 0; i < test_number; i++)
{
/*
[Rotate Columns]
*/
Ciphertext encrypted1(context);
encryptor.encrypt(encoder.encode(i), encrypted1);
noise_budget_initial = decryptor.invariant_noise_budget(encrypted1);
time_start = chrono::high_resolution_clock::now();
evaluator.rotate_columns_inplace(encrypted1, gal_keys);
time_end = chrono::high_resolution_clock::now();
time_rotate_columns_sum += chrono::duration_cast<
chrono::microseconds>(time_end - time_start);
noise_budget_end = decryptor.invariant_noise_budget(encrypted1);
}
result += "Initial noise budget: ";
temp = QString::number(noise_budget_initial);
result += temp;
result += " bits\n";
result += "The residual noise: ";
temp = QString::number(noise_budget_end);
result += temp;
result += " bits\n";
auto avg_rotate_columns = time_rotate_columns_sum.count() / test_number;
result += "Average rotate columns: ";
temp = QString::number(avg_rotate_columns);
result += temp;
result += " microseconds\n";
ui->result->setText(result);
charts();
}
void BaseTestSealBFV::test_encryption(shared_ptr<SEALContext> context)
{
ui->graphicsView->hide();
chrono::high_resolution_clock::time_point time_start, time_end;
QString result = "";
print_parameters(context);
auto &curr_parms = context->context_data()->parms();
auto &plain_modulus = curr_parms.plain_modulus();
/*
Set up keys.
*/
result += "Generating secret/public keys: ";
KeyGenerator keygen(context);
result += "Done\n" ;
auto secret_key = keygen.secret_key();
auto public_key = keygen.public_key();
/*
生成relinearization keys时间.
*/
int dbc = DefaultParams::dbc_max();
result += "Generating relinearization keys (dbc = ";
QString temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto relin_keys = keygen.relin_keys(dbc);
time_end = chrono::high_resolution_clock::now();
auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
int time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
/*
生成Galois keys时间.
*/
if (!context->context_data()->qualifiers().using_batching)
{
result += "Given encryption parameters do not support batching.";
return;
}
result += "Generating Galois keys (dbc = ";
temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto gal_keys = keygen.galois_keys(dbc);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
IntegerEncoder encoder(context);
chrono::microseconds time_encrypt_sum(0);
/*
Populate a vector of values to batch.
*/
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < batch_encoder.slot_count(); i++)
{
pod_vector.push_back(rd() % plain_modulus.value());
}
result += "\n";
Plaintext plain(curr_parms.poly_modulus_degree(), 0);
batch_encoder.encode(pod_vector, plain);
for (int i = 0; i < test_number; i++){
/*
[Encryption]
*/
Ciphertext encrypted(context);
time_start = chrono::high_resolution_clock::now();
encryptor.encrypt(plain, encrypted);
time_end = chrono::high_resolution_clock::now();
time_encrypt_sum += chrono::duration_cast<
chrono::microseconds>(time_end - time_start);
}
auto avg_encrypt = time_encrypt_sum.count() / test_number;
result += "Average encrypt: ";
temp = QString::number(avg_encrypt);
result += temp;
result += " microseconds\n";
ui->result->setText(result);
}
void BaseTestSealBFV::test_decryption(shared_ptr<SEALContext> context)
{
ui->graphicsView->hide();
chrono::high_resolution_clock::time_point time_start, time_end;
QString result = "";
print_parameters(context);
auto &curr_parms = context->context_data()->parms();
auto &plain_modulus = curr_parms.plain_modulus();
/*
Set up keys.
*/
result += "Generating secret/public keys: ";
KeyGenerator keygen(context);
result += "Done\n" ;
auto secret_key = keygen.secret_key();
auto public_key = keygen.public_key();
/*
生成relinearization keys时间.
*/
int dbc = DefaultParams::dbc_max();
result += "Generating relinearization keys (dbc = ";
QString temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto relin_keys = keygen.relin_keys(dbc);
time_end = chrono::high_resolution_clock::now();
auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
int time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
/*
生成Galois keys时间.
*/
if (!context->context_data()->qualifiers().using_batching)
{
result += "Given encryption parameters do not support batching.";
return;
}
result += "Generating Galois keys (dbc = ";
temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto gal_keys = keygen.galois_keys(dbc);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
IntegerEncoder encoder(context);
chrono::microseconds time_decrypt_sum(0);
/*
Populate a vector of values to batch.
*/
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < batch_encoder.slot_count(); i++)
{
pod_vector.push_back(rd() % plain_modulus.value());
}
result += "\n";
Plaintext plain(curr_parms.poly_modulus_degree(), 0);
batch_encoder.encode(pod_vector, plain);
for (int i = 0; i < test_number; i++){
/*
[Encryption]
*/
Ciphertext encrypted(context);
encryptor.encrypt(plain, encrypted);
/*
[Decryption]
*/
Plaintext plain2(poly_modulus_degree, 0);
time_start = chrono::high_resolution_clock::now();
decryptor.decrypt(encrypted, plain2);
time_end = chrono::high_resolution_clock::now();
time_decrypt_sum += chrono::duration_cast<
chrono::microseconds>(time_end - time_start);
if (plain2 != plain)
{
throw runtime_error("Encrypt/decrypt failed. Something is wrong.");
}
}
auto avg_decrypt = time_decrypt_sum.count() / test_number;
result += "Average decrypt: ";
temp = QString::number(avg_decrypt);
result += temp;
result += " microseconds\n";
ui->result->setText(result);
}
void BaseTestSealBFV::test_batching(shared_ptr<SEALContext> context)
{
ui->graphicsView->hide();
chrono::high_resolution_clock::time_point time_start, time_end;
QString result = "";
print_parameters(context);
auto &curr_parms = context->context_data()->parms();
auto &plain_modulus = curr_parms.plain_modulus();
/*
Set up keys.
*/
result += "Generating secret/public keys: ";
KeyGenerator keygen(context);
result += "Done\n" ;
auto secret_key = keygen.secret_key();
auto public_key = keygen.public_key();
/*
生成relinearization keys时间.
*/
int dbc = DefaultParams::dbc_max();
result += "Generating relinearization keys (dbc = ";
QString temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto relin_keys = keygen.relin_keys(dbc);
time_end = chrono::high_resolution_clock::now();
auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
int time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
/*
生成Galois keys时间.
*/
if (!context->context_data()->qualifiers().using_batching)
{
result += "Given encryption parameters do not support batching.";
return;
}
result += "Generating Galois keys (dbc = ";
temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto gal_keys = keygen.galois_keys(dbc);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
IntegerEncoder encoder(context);
chrono::microseconds time_batch_sum(0);
/*
Populate a vector of values to batch.
*/
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < batch_encoder.slot_count(); i++)
{
pod_vector.push_back(rd() % plain_modulus.value());
}
result += "\n";
for (int i = 0; i < test_number; i++){
/*
[Batching]
*/
Plaintext plain(curr_parms.poly_modulus_degree(), 0);
time_start = chrono::high_resolution_clock::now();
batch_encoder.encode(pod_vector, plain);
time_end = chrono::high_resolution_clock::now();
time_batch_sum += chrono::duration_cast<
chrono::microseconds>(time_end - time_start);
}
auto avg_batch = time_batch_sum.count() / test_number;
result += "Average batch: ";
temp = QString::number(avg_batch);
result += temp;
result += " microseconds\n";
ui->result->setText(result);
}
void BaseTestSealBFV::test_unbatching(shared_ptr<SEALContext> context)
{
ui->graphicsView->hide();
chrono::high_resolution_clock::time_point time_start, time_end;
QString result = "";
print_parameters(context);
auto &curr_parms = context->context_data()->parms();
auto &plain_modulus = curr_parms.plain_modulus();
/*
Set up keys.
*/
result += "Generating secret/public keys: ";
KeyGenerator keygen(context);
result += "Done\n" ;
auto secret_key = keygen.secret_key();
auto public_key = keygen.public_key();
/*
生成relinearization keys时间.
*/
int dbc = DefaultParams::dbc_max();
result += "Generating relinearization keys (dbc = ";
QString temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto relin_keys = keygen.relin_keys(dbc);
time_end = chrono::high_resolution_clock::now();
auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
int time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
/*
生成Galois keys时间.
*/
if (!context->context_data()->qualifiers().using_batching)
{
result += "Given encryption parameters do not support batching.";
return;
}
result += "Generating Galois keys (dbc = ";
temp = QString::number(dbc);
result += temp;
result += "): ";
time_start = chrono::high_resolution_clock::now();
auto gal_keys = keygen.galois_keys(dbc);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
time_temp = time_diff.count();
temp = QString::number(time_temp);
result += "Done [";
result += temp;
result += " microseconds]\n";
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
IntegerEncoder encoder(context);
chrono::microseconds time_unbatch_sum(0);
/*
Populate a vector of values to batch.
*/
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < batch_encoder.slot_count(); i++)
{
pod_vector.push_back(rd() % plain_modulus.value());
}
result += "\n";
Plaintext plain(curr_parms.poly_modulus_degree(), 0);
batch_encoder.encode(pod_vector, plain);
for (int i = 0; i < test_number; i++){
/*
[Unbatching]
*/
vector<uint64_t> pod_vector2(batch_encoder.slot_count());
time_start = chrono::high_resolution_clock::now();
batch_encoder.decode(plain, pod_vector2);
time_end = chrono::high_resolution_clock::now();
time_unbatch_sum += chrono::duration_cast<
chrono::microseconds>(time_end - time_start);
if (pod_vector2 != pod_vector)
{
throw runtime_error("Batch/unbatch failed. Something is wrong.");
}
}
auto avg_unbatch = time_unbatch_sum.count() / test_number;
result += "Average batch: ";
temp = QString::number(avg_unbatch);
result += temp;
result += " microseconds\n";
ui->result->setText(result);
}
void BaseTestSealBFV::BaseBFV128(int poly_modulus_degree, int coeff_modulus, int plain_modulus)
{
EncryptionParameters parms(scheme_type::BFV);
parms.set_poly_modulus_degree(poly_modulus_degree);
parms.set_coeff_modulus(DefaultParams::coeff_modulus_128(coeff_modulus));
parms.set_plain_modulus(plain_modulus);
if(test_type == "Add测试")
test_add(SEALContext::Create(parms));
if(test_type == "Add Plain测试")
test_add_plain(SEALContext::Create(parms));
if(test_type == "Mult测试")
test_mult(SEALContext::Create(parms));
if(test_type == "Mult Plain测试")
test_mult_plain(SEALContext::Create(parms));
if(test_type == "Sub测试")
test_sub(SEALContext::Create(parms));
if(test_type == "Sub Plain测试")
test_sub_plain(SEALContext::Create(parms));
if(test_type == "Square测试")
test_square(SEALContext::Create(parms));
if(test_type == "Negation测试")
test_negation(SEALContext::Create(parms));
if(test_type == "Rotate rows one step测试")
test_rotate_rows_one_step(SEALContext::Create(parms));
if(test_type == "Rotate rows random测试")
test_rotate_rows_random(SEALContext::Create(parms));
if(test_type == "Rotate columns测试")
test_rotate_columns(SEALContext::Create(parms));
if(test_type == "Encryption测试")
test_encryption(SEALContext::Create(parms));
if(test_type == "Decryption测试")
test_decryption(SEALContext::Create(parms));
if(test_type == "Batching测试")
test_batching(SEALContext::Create(parms));
if(test_type == "Unbatching测试")
test_unbatching(SEALContext::Create(parms));
}
void BaseTestSealBFV::BaseBFV192(int poly_modulus_degree, int coeff_modulus, int plain_modulus)
{
EncryptionParameters parms(scheme_type::BFV);
parms.set_poly_modulus_degree(poly_modulus_degree);
parms.set_coeff_modulus(DefaultParams::coeff_modulus_192(coeff_modulus));
parms.set_plain_modulus(plain_modulus);
if(test_type == "Add测试")
test_add(SEALContext::Create(parms));
if(test_type == "Add Plain测试")
test_add_plain(SEALContext::Create(parms));
if(test_type == "Mult测试")
test_mult(SEALContext::Create(parms));
if(test_type == "Mult Plain测试")
test_mult_plain(SEALContext::Create(parms));
if(test_type == "Sub测试")
test_sub(SEALContext::Create(parms));
if(test_type == "Sub Plain测试")
test_sub_plain(SEALContext::Create(parms));
if(test_type == "Square测试")
test_square(SEALContext::Create(parms));
if(test_type == "Negation测试")
test_negation(SEALContext::Create(parms));
if(test_type == "Rotate rows one step测试")
test_rotate_rows_one_step(SEALContext::Create(parms));
if(test_type == "Rotate rows random测试")
test_rotate_rows_random(SEALContext::Create(parms));
if(test_type == "Rotate columns测试")
test_rotate_columns(SEALContext::Create(parms));
if(test_type == "Encryption测试")
test_encryption(SEALContext::Create(parms));
if(test_type == "Decryption测试")
test_decryption(SEALContext::Create(parms));
if(test_type == "Batching测试")
test_batching(SEALContext::Create(parms));
if(test_type == "Unbatching测试")
test_unbatching(SEALContext::Create(parms));
}
void BaseTestSealBFV::BaseBFV256(int poly_modulus_degree, int coeff_modulus, int plain_modulus)
{
EncryptionParameters parms(scheme_type::BFV);
parms.set_poly_modulus_degree(poly_modulus_degree);
parms.set_coeff_modulus(DefaultParams::coeff_modulus_256(coeff_modulus));
parms.set_plain_modulus(plain_modulus);
if(test_type == "Add测试")
test_add(SEALContext::Create(parms));
if(test_type == "Add Plain测试")
test_add_plain(SEALContext::Create(parms));
if(test_type == "Mult测试")
test_mult(SEALContext::Create(parms));
if(test_type == "Mult Plain测试")
test_mult_plain(SEALContext::Create(parms));
if(test_type == "Sub测试")
test_sub(SEALContext::Create(parms));
if(test_type == "Sub Plain测试")
test_sub_plain(SEALContext::Create(parms));
if(test_type == "Square测试")
test_square(SEALContext::Create(parms));
if(test_type == "Negation测试")
test_negation(SEALContext::Create(parms));
if(test_type == "Rotate rows one step测试")
test_rotate_rows_one_step(SEALContext::Create(parms));
if(test_type == "Rotate rows random测试")
test_rotate_rows_random(SEALContext::Create(parms));
if(test_type == "Rotate columns测试")
test_rotate_columns(SEALContext::Create(parms));
if(test_type == "Encryption测试")
test_encryption(SEALContext::Create(parms));
if(test_type == "Decryption测试")
test_decryption(SEALContext::Create(parms));
if(test_type == "Batching测试")
test_batching(SEALContext::Create(parms));
if(test_type == "Unbatching测试")
test_unbatching(SEALContext::Create(parms));
}
void BaseTestSealBFV::on_TestType_activated(const QString &arg1)
{
test_type = arg1;
}
void BaseTestSealBFV::on_ToBeginTesting_clicked()
{
if (security_parameters == 128)
BaseBFV128(poly_modulus_degree, coeff_modulus, plain_modulus);
if (security_parameters == 192)
BaseBFV192(poly_modulus_degree, coeff_modulus, plain_modulus);
if (security_parameters == 256)
BaseBFV256(poly_modulus_degree, coeff_modulus, plain_modulus);
}
void BaseTestSealBFV::on_Return_clicked()
{
MainWindow *win = new MainWindow;
this->hide();
win->show();
}
void BaseTestSealBFV::on_lineEdit_textChanged(const QString &arg1)
{
ui->lineEdit->setValidator(new QRegExpValidator(QRegExp("[0-9]+$")));
test_number = arg1.toInt();
}
void BaseTestSealBFV::on_security_parameters_activated(const QString &arg1)
{
QMap<QString, int> map_security_parameters;
map_security_parameters.insert("128(默认)",128);
map_security_parameters.insert("192",192);
map_security_parameters.insert("256",256);
security_parameters = map_security_parameters[arg1];
}
void BaseTestSealBFV::on_poly_modulus_degree_activated(const QString &arg1)
{
QMap<QString, int> map_poly_modulus_degree;
map_poly_modulus_degree.insert("1024(默认)",1024);
map_poly_modulus_degree.insert("2048",2048);
map_poly_modulus_degree.insert("4096",4096);
map_poly_modulus_degree.insert("8192",8192);
map_poly_modulus_degree.insert("16384",16384);
map_poly_modulus_degree.insert("32768",32768);
poly_modulus_degree = map_poly_modulus_degree[arg1];
}
void BaseTestSealBFV::on_coeff_modulus_activated(const QString &arg1)
{
QMap<QString, int> map_coeff_modulus;
map_coeff_modulus.insert("4096(默认)",4096);
map_coeff_modulus.insert("8192",8192);
map_coeff_modulus.insert("16384",16384);
map_coeff_modulus.insert("32768",32768);
coeff_modulus = map_coeff_modulus[arg1];
}
void BaseTestSealBFV::on_plain_modulus_activated(const QString &arg1)
{
QMap<QString, int> map_plain_modulus;
map_plain_modulus.insert("786433(默认)",786433);
plain_modulus = map_plain_modulus[arg1];
}
| 30.317681 | 119 | 0.650593 | YiJingGuo |
c6a733a50739af5698ff6b9effb7d5fed8075c8b | 397 | cpp | C++ | src/server/quantum_chess/pseudo_random_coin.cpp | Santoi/quantum-chess | a2f5a0f322c6aa51488c52c8ebacbe0ad75ca9f9 | [
"MIT"
] | 9 | 2021-12-22T02:10:34.000Z | 2021-12-30T17:14:25.000Z | src/server/quantum_chess/pseudo_random_coin.cpp | Santoi/quantum-chess | a2f5a0f322c6aa51488c52c8ebacbe0ad75ca9f9 | [
"MIT"
] | null | null | null | src/server/quantum_chess/pseudo_random_coin.cpp | Santoi/quantum-chess | a2f5a0f322c6aa51488c52c8ebacbe0ad75ca9f9 | [
"MIT"
] | null | null | null | #include "pseudo_random_coin.h"
#include <ctime>
#include <iostream>
PseudoRandomCoin::PseudoRandomCoin() : engine(clock() * time(nullptr)),
random(true) {}
PseudoRandomCoin::PseudoRandomCoin(bool random_) : engine(), random(random_) {
}
bool PseudoRandomCoin::flip() {
if (!random)
return true;
uint64_t number = engine();
return number % 2;
}
| 23.352941 | 78 | 0.639798 | Santoi |
c6a90fcbd48c975e4310a5d04905f7fe56798da4 | 224 | cpp | C++ | ChanSpreadsheet/chartSettings.cpp | ChanJLee/ChanSpreadSheet | ea61246387b0243030e7facf822077f28f73917e | [
"Apache-2.0"
] | null | null | null | ChanSpreadsheet/chartSettings.cpp | ChanJLee/ChanSpreadSheet | ea61246387b0243030e7facf822077f28f73917e | [
"Apache-2.0"
] | null | null | null | ChanSpreadsheet/chartSettings.cpp | ChanJLee/ChanSpreadSheet | ea61246387b0243030e7facf822077f28f73917e | [
"Apache-2.0"
] | null | null | null | #include "chartSettings.h"
chartSettings::chartSettings(const QChar x,const QChar y,
const QString& xTitle,const QString& yTitle,
const QString& chartTitle):
m_settings(std::make_tuple(x,y,xTitle,yTitle,chartTitle))
{
}
| 22.4 | 57 | 0.776786 | ChanJLee |
c6abce6e3958e03498b21c32fb67ae8accaf256f | 2,219 | hpp | C++ | include/re_fft/Hann_window.hpp | reBass/reFFT | 96f83a7b62d8329ac8d6304706c4ab981851807e | [
"MIT"
] | null | null | null | include/re_fft/Hann_window.hpp | reBass/reFFT | 96f83a7b62d8329ac8d6304706c4ab981851807e | [
"MIT"
] | null | null | null | include/re_fft/Hann_window.hpp | reBass/reFFT | 96f83a7b62d8329ac8d6304706c4ab981851807e | [
"MIT"
] | null | null | null | // Copyright (c) 2016 Roman Beránek. All rights reserved.
//
// 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.
#pragma once
#include <cmath>
#include <algorithm>
#include <array>
#include <iterator>
#include <functional>
#include "common.hpp"
namespace reFFT
{
template<typename T, std::ptrdiff_t N>
class Hann_window {
static_assert(std::is_floating_point<T>::value);
public:
Hann_window()
noexcept {
encache();
}
template <class InputIt, class OutputIt>
void
cut(InputIt in, OutputIt out)
const noexcept {
std::transform(
std::cbegin(cache),
std::cend(cache),
in,
out,
std::multiplies<>()
);
}
static constexpr T
norm_correction() {
return 0.5f;
}
private:
void
encache()
noexcept {
for (auto i = 0; i < N; ++i) {
cache[i] = window_function(i);
}
}
static constexpr T
window_function(std::ptrdiff_t position)
noexcept {
auto relative_position = static_cast<T>(position) / N;
return (1 - std::cos(relative_position * 2 * pi<T>)) / 2;
}
std::array<T, N> cache;
};
}
| 27.395062 | 80 | 0.666066 | reBass |
c6ad9b376203cda37a8b26abcf028d1281c25a73 | 682 | hpp | C++ | libs/input/include/sge/input/create_multi_system.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/input/include/sge/input/create_multi_system.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/input/include/sge/input/create_multi_system.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_INPUT_CREATE_MULTI_SYSTEM_HPP_INCLUDED
#define SGE_INPUT_CREATE_MULTI_SYSTEM_HPP_INCLUDED
#include <sge/input/system_unique_ptr.hpp>
#include <sge/input/detail/symbol.hpp>
#include <sge/input/plugin/collection_fwd.hpp>
#include <fcppt/log/context_reference_fwd.hpp>
namespace sge::input
{
SGE_INPUT_DETAIL_SYMBOL
sge::input::system_unique_ptr
create_multi_system(fcppt::log::context_reference, sge::input::plugin::collection const &);
}
#endif
| 28.416667 | 91 | 0.777126 | cpreh |
c6af03499b54760a000f85da0145ab3d9f65f68d | 10,062 | cxx | C++ | panda/src/express/zStreamBuf.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/express/zStreamBuf.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/express/zStreamBuf.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file zStreamBuf.cxx
* @author drose
* @date 2002-08-05
*/
#include "zStreamBuf.h"
#ifdef HAVE_ZLIB
#include "pnotify.h"
#include "config_express.h"
#if !defined(USE_MEMORY_NOWRAPPERS) && !defined(CPPPARSER)
// Define functions that hook zlib into panda's memory allocation system.
static void *
do_zlib_alloc(voidpf opaque, uInt items, uInt size) {
return PANDA_MALLOC_ARRAY(items * size);
}
static void
do_zlib_free(voidpf opaque, voidpf address) {
PANDA_FREE_ARRAY(address);
}
#endif // !USE_MEMORY_NOWRAPPERS
/**
*
*/
ZStreamBuf::
ZStreamBuf() {
_source = (istream *)NULL;
_owns_source = false;
_dest = (ostream *)NULL;
_owns_dest = false;
#ifdef PHAVE_IOSTREAM
_buffer = (char *)PANDA_MALLOC_ARRAY(4096);
char *ebuf = _buffer + 4096;
setg(_buffer, ebuf, ebuf);
setp(_buffer, ebuf);
#else
allocate();
setg(base(), ebuf(), ebuf());
setp(base(), ebuf());
#endif
}
/**
*
*/
ZStreamBuf::
~ZStreamBuf() {
close_read();
close_write();
#ifdef PHAVE_IOSTREAM
PANDA_FREE_ARRAY(_buffer);
#endif
}
/**
*
*/
void ZStreamBuf::
open_read(istream *source, bool owns_source) {
_source = source;
_owns_source = owns_source;
_z_source.next_in = Z_NULL;
_z_source.avail_in = 0;
_z_source.next_out = Z_NULL;
_z_source.avail_out = 0;
#ifdef USE_MEMORY_NOWRAPPERS
_z_source.zalloc = Z_NULL;
_z_source.zfree = Z_NULL;
#else
_z_source.zalloc = (alloc_func)&do_zlib_alloc;
_z_source.zfree = (free_func)&do_zlib_free;
#endif
_z_source.opaque = Z_NULL;
_z_source.msg = (char *)"no error message";
int result = inflateInit2(&_z_source, 32 + 15);
if (result < 0) {
show_zlib_error("inflateInit2", result, _z_source);
close_read();
}
thread_consider_yield();
}
/**
*
*/
void ZStreamBuf::
close_read() {
if (_source != (istream *)NULL) {
int result = inflateEnd(&_z_source);
if (result < 0) {
show_zlib_error("inflateEnd", result, _z_source);
}
thread_consider_yield();
if (_owns_source) {
delete _source;
_owns_source = false;
}
_source = (istream *)NULL;
}
}
/**
*
*/
void ZStreamBuf::
open_write(ostream *dest, bool owns_dest, int compression_level) {
_dest = dest;
_owns_dest = owns_dest;
_z_dest.next_in = Z_NULL;
_z_dest.avail_in = 0;
_z_dest.next_out = Z_NULL;
_z_dest.avail_out = 0;
#ifdef USE_MEMORY_NOWRAPPERS
_z_dest.zalloc = Z_NULL;
_z_dest.zfree = Z_NULL;
#else
_z_dest.zalloc = (alloc_func)&do_zlib_alloc;
_z_dest.zfree = (free_func)&do_zlib_free;
#endif
_z_dest.opaque = Z_NULL;
_z_dest.msg = (char *)"no error message";
int result = deflateInit(&_z_dest, compression_level);
if (result < 0) {
show_zlib_error("deflateInit", result, _z_dest);
close_write();
}
thread_consider_yield();
}
/**
*
*/
void ZStreamBuf::
close_write() {
if (_dest != (ostream *)NULL) {
size_t n = pptr() - pbase();
write_chars(pbase(), n, Z_FINISH);
pbump(-(int)n);
int result = deflateEnd(&_z_dest);
if (result < 0) {
show_zlib_error("deflateEnd", result, _z_dest);
}
thread_consider_yield();
if (_owns_dest) {
delete _dest;
_owns_dest = false;
}
_dest = (ostream *)NULL;
}
}
/**
* Implements seeking within the stream. ZStreamBuf only allows seeking back
* to the beginning of the stream.
*/
streampos ZStreamBuf::
seekoff(streamoff off, ios_seekdir dir, ios_openmode which) {
if (which != ios::in) {
// We can only do this with the input stream.
return -1;
}
// Determine the current position.
size_t n = egptr() - gptr();
streampos gpos = _z_source.total_out - n;
// Implement tellg() and seeks to current position.
if ((dir == ios::cur && off == 0) ||
(dir == ios::beg && off == gpos)) {
return gpos;
}
if (off != 0 || dir != ios::beg) {
// We only know how to reposition to the beginning.
return -1;
}
gbump(n);
_source->seekg(0, ios::beg);
if (_source->tellg() == (streampos)0) {
_z_source.next_in = Z_NULL;
_z_source.avail_in = 0;
_z_source.next_out = Z_NULL;
_z_source.avail_out = 0;
int result = inflateReset(&_z_source);
if (result < 0) {
show_zlib_error("inflateReset", result, _z_source);
}
return 0;
}
return -1;
}
/**
* Implements seeking within the stream. ZStreamBuf only allows seeking back
* to the beginning of the stream.
*/
streampos ZStreamBuf::
seekpos(streampos pos, ios_openmode which) {
return seekoff(pos, ios::beg, which);
}
/**
* Called by the system ostream implementation when its internal buffer is
* filled, plus one character.
*/
int ZStreamBuf::
overflow(int ch) {
size_t n = pptr() - pbase();
if (n != 0) {
write_chars(pbase(), n, 0);
pbump(-(int)n);
}
if (ch != EOF) {
// Write one more character.
char c = ch;
write_chars(&c, 1, 0);
}
return 0;
}
/**
* Called by the system iostream implementation to implement a flush
* operation.
*/
int ZStreamBuf::
sync() {
if (_source != (istream *)NULL) {
size_t n = egptr() - gptr();
gbump(n);
}
if (_dest != (ostream *)NULL) {
size_t n = pptr() - pbase();
write_chars(pbase(), n, Z_SYNC_FLUSH);
pbump(-(int)n);
}
_dest->flush();
return 0;
}
/**
* Called by the system istream implementation when its internal buffer needs
* more characters.
*/
int ZStreamBuf::
underflow() {
// Sometimes underflow() is called even if the buffer is not empty.
if (gptr() >= egptr()) {
size_t buffer_size = egptr() - eback();
gbump(-(int)buffer_size);
size_t num_bytes = buffer_size;
size_t read_count = read_chars(gptr(), buffer_size);
if (read_count != num_bytes) {
// Oops, we didn't read what we thought we would.
if (read_count == 0) {
gbump(num_bytes);
return EOF;
}
// Slide what we did read to the top of the buffer.
nassertr(read_count < num_bytes, EOF);
size_t delta = num_bytes - read_count;
memmove(gptr() + delta, gptr(), read_count);
gbump(delta);
}
}
return (unsigned char)*gptr();
}
/**
* Gets some characters from the source stream.
*/
size_t ZStreamBuf::
read_chars(char *start, size_t length) {
_z_source.next_out = (Bytef *)start;
_z_source.avail_out = length;
bool eof = (_source->eof() || _source->fail());
int flush = 0;
while (_z_source.avail_out > 0) {
if (_z_source.avail_in == 0 && !eof) {
_source->read(decompress_buffer, decompress_buffer_size);
size_t read_count = _source->gcount();
eof = (read_count == 0 || _source->eof() || _source->fail());
_z_source.next_in = (Bytef *)decompress_buffer;
_z_source.avail_in = read_count;
}
int result = inflate(&_z_source, flush);
thread_consider_yield();
size_t bytes_read = length - _z_source.avail_out;
if (result == Z_STREAM_END) {
// Here's the end of the file.
return bytes_read;
} else if (result == Z_BUF_ERROR && flush == 0) {
// We might get this if no progress is possible, for instance if the
// input stream is truncated. In this case, tell zlib to dump
// everything it's got.
flush = Z_FINISH;
} else if (result < 0) {
show_zlib_error("inflate", result, _z_source);
return bytes_read;
}
}
return length;
}
/**
* Sends some characters to the dest stream. The flush parameter is passed to
* deflate().
*/
void ZStreamBuf::
write_chars(const char *start, size_t length, int flush) {
static const size_t compress_buffer_size = 4096;
char compress_buffer[compress_buffer_size];
_z_dest.next_in = (Bytef *)(char *)start;
_z_dest.avail_in = length;
_z_dest.next_out = (Bytef *)compress_buffer;
_z_dest.avail_out = compress_buffer_size;
int result = deflate(&_z_dest, flush);
if (result < 0 && result != Z_BUF_ERROR) {
show_zlib_error("deflate", result, _z_dest);
}
thread_consider_yield();
while (_z_dest.avail_in != 0) {
if (_z_dest.avail_out != compress_buffer_size) {
_dest->write(compress_buffer, compress_buffer_size - _z_dest.avail_out);
_z_dest.next_out = (Bytef *)compress_buffer;
_z_dest.avail_out = compress_buffer_size;
}
result = deflate(&_z_dest, flush);
if (result < 0) {
show_zlib_error("deflate", result, _z_dest);
}
thread_consider_yield();
}
while (_z_dest.avail_out != compress_buffer_size) {
_dest->write(compress_buffer, compress_buffer_size - _z_dest.avail_out);
_z_dest.next_out = (Bytef *)compress_buffer;
_z_dest.avail_out = compress_buffer_size;
result = deflate(&_z_dest, flush);
if (result < 0 && result != Z_BUF_ERROR) {
show_zlib_error("deflate", result, _z_dest);
}
thread_consider_yield();
}
}
/**
* Reports a recent error code returned by zlib.
*/
void ZStreamBuf::
show_zlib_error(const char *function, int error_code, z_stream &z) {
stringstream error_line;
error_line
<< "zlib error in " << function << ": ";
switch (error_code) {
case Z_OK:
error_line << "Z_OK";
break;
case Z_STREAM_END:
error_line << "Z_STREAM_END";
break;
case Z_NEED_DICT:
error_line << "Z_NEED_DICT";
break;
case Z_ERRNO:
error_line << "Z_ERRNO";
break;
case Z_STREAM_ERROR:
error_line << "Z_STREAM_ERROR";
break;
case Z_DATA_ERROR:
error_line << "Z_DATA_ERROR";
break;
case Z_MEM_ERROR:
error_line << "Z_MEM_ERROR";
break;
case Z_BUF_ERROR:
error_line << "Z_BUF_ERROR";
break;
case Z_VERSION_ERROR:
error_line << "Z_VERSION_ERROR";
break;
default:
error_line << error_code;
}
if (z.msg != (char *)NULL) {
error_line
<< " = " << z.msg;
}
express_cat.warning() << error_line.str() << "\n";
}
#endif // HAVE_ZLIB
| 22.920273 | 78 | 0.648579 | sean5470 |
c6b0e199676eee64235a813a1e02e4265db3266f | 16,371 | cpp | C++ | libpharos/typedb.cpp | CyberFlameGO/pharos | af54b6ada58d50c046fa899452addce80e9ce8da | [
"RSA-MD"
] | 1,247 | 2015-06-15T17:51:31.000Z | 2022-03-31T10:24:47.000Z | libpharos/typedb.cpp | CyberFlameGO/pharos | af54b6ada58d50c046fa899452addce80e9ce8da | [
"RSA-MD"
] | 191 | 2017-07-05T19:06:28.000Z | 2022-03-20T14:31:10.000Z | libpharos/typedb.cpp | CyberFlameGO/pharos | af54b6ada58d50c046fa899452addce80e9ce8da | [
"RSA-MD"
] | 180 | 2015-06-25T21:34:54.000Z | 2022-03-21T04:25:04.000Z | // Copyright 2016-2021 Carnegie Mellon University. See LICENSE file for terms.
#include "typedb.hpp"
#include "descriptors.hpp"
#include <stdexcept>
#include <cassert>
#include <locale>
#include <boost/locale/encoding_utf.hpp>
#include <boost/range/adaptor/reversed.hpp>
namespace bf = boost::filesystem;
namespace pharos {
template<> char const* EnumStrings<types::Signedness>::data[] = {
"Top",
"Signed",
"Unsigned",
"Bottom"
};
template<> char const* EnumStrings<types::Pointerness>::data[] = {
"Top",
"Pointer",
"NotPointer",
"Bottom"
};
namespace typedb {
using boost::locale::conv::utf_to_utf;
using ParseError = std::runtime_error;
Value Type::get_value(
const SymbolicValuePtr & value,
const Memory & img,
const SymbolicState * memory) const
{
return Value(img, ptr(), value, memory);
}
void Pointer::update(const DB & db) {
if (pointed_to->is_unknown()) {
pointed_to = db.lookup(pointed_to->get_name());
}
}
void Struct::update(const DB & db) {
for (auto & value : members) {
if (value.type->is_unknown()) {
value.type = db.lookup(value.type->get_name());
}
}
}
std::string Pointer::generate_name(const TypeRef & t)
{
return t->get_name() + "*";
}
void Struct::init()
{
align = 0;
size = 0;
for (auto & param : members) {
size_t t_size = param.type->get_size();
size_t t_align = param.type->get_align();
if (size & (t_align - 1)) {
size = (size & ~(t_align - 1)) + t_align;
}
param.offset = size;
size += t_size;
align = std::max(align, t_align);
}
}
bool handle_node(DB & db, const YAML::Node & node, DB::handle_error_t handle)
{
switch (node.Type()) {
case YAML::NodeType::Scalar:
{
auto path = bf::path(node.Scalar());
if (!path.has_root_directory()) {
path = get_library_path() / path;
}
if (is_directory(path)) {
// Assume the directory contains per-DLL json files
// Currently these are ignored
return true;
}
try {
// Determine whether this is a sqlite file or a json file
std::ifstream file(path.native());
if (!file) {
throw std::runtime_error("Could not open for read");
}
// Read the first few bytes to see of the file match the SQLite magic prologue
static constexpr char sqlite_magic[] = "SQLite";
constexpr auto len = sizeof(sqlite_magic) - 1;
char prologue[len];
file.read(prologue, len);
bool correct_size = file.gcount() == len;
file.close();
if (correct_size && std::equal(prologue, prologue + len, sqlite_magic)) {
// Ignore this file, as the sqlite apidb does't yet have type information
return true;
} else {
// Assume a json file
db.load_json(path);
return true;
}
} catch (const std::runtime_error & e) {
std::ostringstream os;
os << "Unable to load type database: " << path << '\n'
<< "Reason: " << e.what();
switch (handle) {
case DB::IGNORE:
break;
case DB::LOG_WARN:
GWARN << os.str() << LEND;
break;
case DB::LOG_ERROR:
GERROR << os.str() << LEND;
break;
case DB::THROW:
throw std::runtime_error(os.str());
}
return false;
}
}
case YAML::NodeType::Sequence:
{
std::vector<YAML::Node> nodes;
std::copy(node.begin(), node.end(), std::back_inserter(nodes));
bool all_success = true;
for (auto item : boost::adaptors::reverse(nodes)) {
all_success &= handle_node(db, item, handle);
}
return all_success;
}
case YAML::NodeType::Map:
try {
db.load_json(node, "<internal>");
return true;
} catch (const std::runtime_error & e) {
switch (handle) {
case DB::IGNORE:
break;
case DB::LOG_WARN:
case DB::LOG_ERROR:
{
auto & err = glog[(handle == DB::LOG_WARN)
? Sawyer::Message::WARN : Sawyer::Message::ERROR];
err && err << "Error in type database\n"
<< "Reason: " << e.what() << LEND;
}
break;
case DB::THROW:
throw;
}
return false;
}
default:
throw ParseError("Illegal type of node in pharos.typedb parsing");
}
}
DB DB::create_standard(const ProgOptVarMap &vm, handle_error_t handle)
{
auto db = DB();
if (vm.count("typedb")) {
// If it's listed on the command line, use that.
for (auto & filename : vm["typedb"].as<std::vector<bf::path>>()) {
handle_node(db, YAML::Node(filename.native()), THROW);
}
}
auto typedb = vm.config().path_get("pharos.typedb");
if (typedb) {
handle_node(db, typedb.as_node(), handle);
}
return db;
}
TypeRef DB::lookup(const std::string & name) const {
DB * mdb = const_cast<DB *>(this);
return mdb->internal_lookup(name);
}
const std::shared_ptr<Type> & DB::internal_lookup(const std::string & name) {
auto found = db.find(name);
if (found != db.end()) {
return found->second;
}
DB * mdb = const_cast<DB *>(this);
auto result = mdb->db.emplace(name, std::make_shared<UnknownType>(name));
return result.first->second;
}
void DB::load_json(const bf::path & path)
{
auto filename = path.native();
const auto filenode = YAML::LoadFile(filename);
if (!filenode.IsMap()) {
throw ParseError("File is not a map: " + filename);
}
auto types = filenode["config"]["types"];
if (types) {
load_json(types, filename);
}
}
struct CouldNotFind : public std::runtime_error
{
CouldNotFind(const std::string & n, const std::string & v)
: std::runtime_error(generate(n, v)), name(n), value(v)
{}
static std::string generate(const std::string & n, const std::string & v) {
std::ostringstream os;
os << "Could not find definition of " << v << " when defining " << n;
return os.str();
}
std::string name;
std::string value;
};
void DB::load_json(const YAML::Node & typemap, const std::string & filename)
{
if (!typemap.IsMap()) {
throw ParseError("\"types\" is not a map or doesn't exist: " + filename);
}
std::list<CouldNotFind> failed;
for (auto value : typemap) {
auto nname = value.first;
if (!nname.IsScalar()) {
throw ParseError("non-string type-name: " + filename);
}
try {
add_type(nname.Scalar(), value.second);
} catch (const CouldNotFind & cnf) {
failed.push_back(cnf);
}
}
// Re-lookup failed lookups
bool modified = true;
while (modified && !failed.empty()) {
modified = false;
auto cur = failed.begin();
while (cur != failed.end()) {
auto found = db.find(cur->value);
if (found == db.end()) {
++cur;
} else {
db[cur->name] = found->second;
auto del = cur;
++cur;
failed.erase(del);
modified = true;
}
}
}
if (!failed.empty()) {
throw(failed.front());
}
update();
}
void DB::add_type(const std::string & name, const YAML::Node & node)
{
try {
std::shared_ptr<Type> type;
if (node.IsScalar()) {
const std::string & nname = node.Scalar();
if (nname == "string") {
// Ascii string
type = std::make_shared<String>(name, String::CHAR);
} else if (nname == "wstring") {
// Wide String
type = std::make_shared<String>(name, String::WCHAR);
} else if (nname == "tstring") {
// Variable string
type = std::make_shared<String>(name, String::TCHAR);
} else if (nname == "void*") {
// Void *
type = std::make_shared<Pointer>(name, lookup("void"));
} else if (nname == "bool") {
// Bool
type = std::make_shared<Bool>(name);
} else {
auto found = db.find(nname);
if (found != db.end()) {
type = found->second;
} else {
throw CouldNotFind(name, nname);
}
}
} else if (node.IsMap()) {
auto ftype = node["type"];
if (!ftype.IsScalar()) {
throw ParseError("Non-string or no \"type\" field parsing " + name);
}
const std::string & ftname = ftype.Scalar();
if (ftname == "unsigned" || ftname == "signed" || ftname == "float") {
// Unsigned, Signed, and Float
auto nsize = node["size"];
if (!nsize.IsScalar()) {
throw ParseError("Non-integer or no \"size\" field parsing " + name);
}
size_t size;
if (nsize.Scalar() == "arch") {
size = global_arch_bytes;
} else {
size = nsize.as<size_t>();
}
if (ftname == "unsigned") {
type = std::make_shared<Unsigned>(name, size);
} else if (ftname == "signed") {
type = std::make_shared<Signed>(name, size);
} else if (ftname == "float") {
type = std::make_shared<Float>(name, size);
} else {
assert(false);
abort();
}
} else if (ftname == "pointer") {
// Pointer
auto vnode = node["value"];
if (!vnode.IsScalar()) {
throw ParseError("Non-string or no \"value\" field parsing " + name);
}
const std::string & value = vnode.Scalar();
type = std::make_shared<Pointer>(name, lookup(value));
} else if (ftname == "struct") {
auto vnode = node["value"];
if (!vnode.IsSequence()) {
throw ParseError("Non-array or no \"value\" field parsing " + name);
}
ParamList params;
for (auto pnode : vnode) {
if (!pnode.IsMap()) {
throw ParseError("Non-map element in \"value\" field parsing " + name);
}
auto pnnode = pnode["name"];
if (!pnnode.IsScalar()) {
throw ParseError("Non-string element name in \"value\" field parsing " + name);
}
auto ptnode = pnode["type"];
if (!ptnode.IsScalar()) {
throw ParseError("Non-string element type in \"value\" field parsing " + name);
}
params.emplace_back(lookup(ptnode.Scalar()), pnnode.Scalar());
}
type = std::make_shared<Struct>(name, std::move(params));
} else if (ftname == "unknown") {
auto nsize = node["size"];
size_t size = 1;
if (nsize) {
if (!nsize.IsScalar()) {
throw ParseError("Non-integer \"size\" field parsing " + name);
}
size = nsize.as<size_t>();
type = std::make_shared<UnknownType>(name, size);
}
} else {
throw ParseError("Unknown type: " + ftname + " parsing " + name);
}
} else {
throw ParseError("Non-string, non-map type node parsing " + name);
}
db[name] = type;
} catch (const YAML::BadConversion & b) {
throw ParseError("Bad conversion parsing " + name + ": " + b.what());
}
}
void DB::update()
{
for (auto & data : db) {
data.second->update(*this);
}
}
bool Value::is_pointer() const {
return dynamic_cast<const Pointer *>(type.get());
}
bool Value::is_string() const {
return dynamic_cast<const String *>(type.get());
}
bool Value::is_unsigned() const {
return dynamic_cast<const Unsigned *>(type.get());
}
bool Value::is_signed() const {
return dynamic_cast<const Signed *>(type.get());
}
bool Value::is_bool() const {
return dynamic_cast<const Bool *>(type.get());
}
bool Value::is_struct() const {
return dynamic_cast<const Struct *>(type.get());
}
template <typename T>
boost::optional<T> interpret(const TreeNodePtr & tn);
template <>
boost::optional<uint64_t> interpret<uint64_t>(const TreeNodePtr & tn)
{
if (tn && tn->isIntegerConstant() && tn->nBits() <= 64) {
return *tn->toUnsigned();
}
return boost::none;
}
template <>
boost::optional<int64_t> interpret<int64_t>(const TreeNodePtr & tn)
{
auto x = interpret<uint64_t>(tn);
if (x) {
return int64_t(*x);
}
return boost::none;
}
template <>
boost::optional<bool> interpret<bool>(const TreeNodePtr & tn)
{
auto x = interpret<uint64_t>(tn);
if (x) {
return bool(*x);
}
return boost::none;
}
boost::optional<uint64_t> Value::as_unsigned() const
{
if (!is_unsigned()) {
throw IllegalConversion("Cannot call as_unsigned on non-Unsigned");
}
if (node) {
return interpret<uint64_t>(node->get_expression());
}
return boost::none;
}
boost::optional<int64_t> Value::as_signed() const
{
if (!is_signed()) {
throw IllegalConversion("Cannot call as_signed on non-Signed");
}
if (node) {
return interpret<int64_t>(node->get_expression());
}
return boost::none;
}
boost::optional<bool> Value::as_bool() const
{
if (!is_bool()) {
throw IllegalConversion("Cannot call as_bool on non-Bool");
}
if (node) {
return interpret<bool>(node->get_expression());
}
return boost::none;
}
template <typename Char>
boost::optional<std::basic_string<Char>> parse_string_value(
const Memory& image,
const SymbolicState & memory,
const TreeNodePtr & base)
{
std::basic_string<Char> result;
for (size_t i = 0; true; i += sizeof(Char)) {
auto addr = base + i;
auto sym = SymbolicValue::treenode_instance(addr);
auto c = image.read_value(memory, sym, Bytes(sizeof(Char)));
if (c) {
auto & cexp = c->get_expression();
if (cexp && cexp->isIntegerConstant()) {
Char n = std::char_traits<Char>::to_char_type(
(typename std::char_traits<Char>::int_type)(*cexp->toUnsigned()));
if (n) {
result.push_back(n);
continue;
} else {
return result;
}
}
}
break;
}
return boost::none;
}
boost::optional<std::string> Value::as_string(bool wide) const
{
if (!node) {
return boost::none;
}
const String * s = dynamic_cast<const String *>(type.get());
if (!s) {
throw IllegalConversion("Illegal call on non-string");
}
auto & exp = node->get_expression();
if (exp && exp->isIntegerConstant() && exp->isLeafNode()->bits().isAllClear()) {
return boost::none;
} else if (memory) {
if (s->get_string_type() == String::WCHAR ||
(s->get_string_type() == String::TCHAR && wide))
{
auto result = parse_string_value<char16_t>(image, *memory, exp);
if (result) {
return utf_to_utf<char>(*result);
}
} else {
return parse_string_value<char>(image, *memory, exp);
}
}
return boost::none;
}
Value Value::val_from_param(const Param & param) const
{
auto ptr = std::make_shared<Pointer>(param.type);
auto val = ptr->get_value(node + param.offset, image, memory).dereference();
return val;
}
Value::type_range Value::member_types() const
{
const Struct * s = dynamic_cast<const Struct *>(type.get());
if (!s) {
throw IllegalConversion("Illegal call on non-Struct");
}
return boost::make_iterator_range(s->begin(), s->end());
}
Value::value_range Value::member_values() const
{
return (member_types() | boost::adaptors::transformed(
val_from_param_wrapper(this)));
}
Value::vpair_range Value::members() const
{
return (member_types() | boost::adaptors::transformed(
vpair_from_param_wrapper(this)));
}
bool Value::is_nullptr() const
{
if (node && (is_pointer() || is_string())) {
auto & exp = node->get_expression();
return exp && exp->isIntegerConstant() && exp->isLeafNode()->bits().isAllClear();
}
return false;
}
Value Value::dereference() const
{
auto p = dynamic_cast<const Pointer *>(type.get());
if (!p) {
throw IllegalConversion("Cannot dereference non-pointer");
}
auto & t = p->get_contained();
if (!node) {
return t->get_value(node, image, memory);
}
auto & exp = node->get_expression();
if (exp && exp->isIntegerConstant() && exp->isLeafNode()->bits().isAllClear()) {
throw IllegalConversion("Cannot dereference NULL");
}
if (!memory) {
return Value(image, t);
}
if (dynamic_cast<const Struct *>(t.get())) {
return Value(image, t, node, memory);
}
auto v = image.read_value(*memory, node, Bytes(t->get_size()));
return Value(image, t, v, memory);
}
} // namespace typedb
} // namespace pharos
/* Local Variables: */
/* mode: c++ */
/* fill-column: 95 */
/* comment-column: 0 */
/* End: */
| 26.837705 | 91 | 0.583532 | CyberFlameGO |
c6b1f0820d1be7cff2557652df4b47a71ca9ada0 | 889 | cpp | C++ | examples/xtd.core.examples/date_time/date_time_day_of_year/src/date_time_day_of_year.cpp | BaderEddineOuaich/xtd | 6f28634c7949a541d183879d2de18d824ec3c8b1 | [
"MIT"
] | 1 | 2022-02-25T16:53:06.000Z | 2022-02-25T16:53:06.000Z | examples/xtd.core.examples/date_time/date_time_day_of_year/src/date_time_day_of_year.cpp | leanid/xtd | 2e1ea6537218788ca08901faf8915d4100990b53 | [
"MIT"
] | null | null | null | examples/xtd.core.examples/date_time/date_time_day_of_year/src/date_time_day_of_year.cpp | leanid/xtd | 2e1ea6537218788ca08901faf8915d4100990b53 | [
"MIT"
] | null | null | null | #include <xtd/xtd>
using namespace xtd;
class program {
public:
static void main() {
date_time dec31(2010, 12, 31);
for (uint32_t ctr = 0U; ctr <= 10U; ctr++) {
date_time date_to_display = dec31.add_years(ctr);
console::write_line("{0:d}: day {1} of {2} {3}", date_to_display, date_to_display.day_of_year(), date_to_display.year(), date_time::is_leap_year(date_to_display.year()) ? "(Leap Year)" : "");
}
}
};
startup_(program);
// This code can produces the following output:
//
// 12/31/2010: day 365 of 2010
// 12/31/2011: day 365 of 2011
// 12/31/2012: day 366 of 2012 (Leap Year)
// 12/31/2013: day 365 of 2013
// 12/31/2014: day 365 of 2014
// 12/31/2015: day 365 of 2015
// 12/31/2016: day 366 of 2016 (Leap Year)
// 12/31/2017: day 365 of 2017
// 12/31/2018: day 365 of 2018
// 12/31/2019: day 365 of 2019
// 12/31/2020: day 366 of 2020 (Leap Year)
| 28.677419 | 197 | 0.653543 | BaderEddineOuaich |
c6b4fd5f70a929a64d9b841502b8c66910df2ca5 | 1,309 | cpp | C++ | CodeForces/Complete/400-499/430B-BallsGame.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | CodeForces/Complete/400-499/430B-BallsGame.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | CodeForces/Complete/400-499/430B-BallsGame.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | #include <cstdio>
#include <vector>
int main(){
int n, k, x; scanf("%d %d %d", &n, &k, &x);
std::vector<int> ballVec(n, 0);
std::vector<std::pair<int,int> > locations;
int start(-1), stop(-1);
for(int p = 0; p < n; p++){
scanf("%d", &ballVec[p]);
if(ballVec[p] == x){if(start < 0){start = p;} else{stop = p;}}
else{
if(start > 0 && stop > start){locations.push_back(std::pair<int, int>(start,stop));}
start = -1; stop = -1;
}
}
int maxDestroyed(0);
for(int p = 0; p < locations.size(); p++){
int left = locations[p].first, right = locations[p].second;
if(left > 0 && right < n - 1){
bool action;
do{ action = 0;
int col = ballVec[left - 1];
if(ballVec[right + 1] == col && ((left > 1 && ballVec[left - 2] == col) || (right < n - 1 && ballVec[right + 2] == col))){
action = 1;
while(left > 0 && ballVec[left - 1] == col){--left;}
while(right < n - 1 && ballVec[right + 1] == col){++right;}
}
}while(action);
}
if(right - left + 1> maxDestroyed){maxDestroyed = right - left + 1;}
}
printf("%d\n", maxDestroyed);
return 0;
}
| 28.456522 | 138 | 0.453782 | Ashwanigupta9125 |
c6b5381f26390ab20db9de13b6e6dbbe7d4ea86b | 4,553 | hpp | C++ | irohad/network/impl/channel_factory.hpp | Insafin/iroha | 5e3c3252b2a62fa887274bdf25547dc264c10c26 | [
"Apache-2.0"
] | 1,467 | 2016-10-25T12:27:19.000Z | 2022-03-28T04:32:05.000Z | irohad/network/impl/channel_factory.hpp | Insafin/iroha | 5e3c3252b2a62fa887274bdf25547dc264c10c26 | [
"Apache-2.0"
] | 2,366 | 2016-10-25T10:07:57.000Z | 2022-03-31T22:03:24.000Z | irohad/network/impl/channel_factory.hpp | Insafin/iroha | 5e3c3252b2a62fa887274bdf25547dc264c10c26 | [
"Apache-2.0"
] | 662 | 2016-10-26T04:41:22.000Z | 2022-03-31T04:15:02.000Z | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_CHANNEL_FACTORY_HPP
#define IROHA_CHANNEL_FACTORY_HPP
#include "network/impl/channel_provider.hpp"
#include <memory>
#include <set>
#include <string>
#include <grpc++/grpc++.h>
#include "common/result.hpp"
#include "interfaces/common_objects/types.hpp"
#include "network/impl/grpc_channel_params.hpp"
namespace iroha {
namespace network {
namespace detail {
grpc::ChannelArguments makeChannelArguments(
const std::set<std::string> &services,
const GrpcChannelParams ¶ms);
grpc::ChannelArguments makeInterPeerChannelArguments(
const std::set<std::string> &services,
const GrpcChannelParams ¶ms);
} // namespace detail
/**
* Creates channel arguments for inter-peer communication.
* @tparam Service type for gRPC stub, e.g. proto::Yac
* @param params grpc channel params
* @return gRPC channel arguments
*/
template <typename Service>
grpc::ChannelArguments makeInterPeerChannelArguments(
const GrpcChannelParams ¶ms) {
return detail::makeInterPeerChannelArguments(
{Service::service_full_name()}, params);
}
/**
* Creates a channel
* @tparam Service type for gRPC stub, e.g. proto::Yac
* @param address ip address and port for connection, ipv4:port
* @param maybe_params grpc channel params
* @return grpc channel with provided params
*/
template <typename Service>
std::shared_ptr<grpc::Channel> createInsecureChannel(
const shared_model::interface::types::AddressType &address,
std::optional<std::reference_wrapper<GrpcChannelParams const>>
maybe_params) {
return createInsecureChannel(
address, Service::service_full_name(), maybe_params);
}
/**
* Creates a channel
* @param address ip address and port to connect to, ipv4:port
* @param service_full_name gRPC service full name,
* e.g. iroha.consensus.yac.proto.Yac
* @param maybe_params grpc channel params
* @return grpc channel with provided params
*/
std::shared_ptr<grpc::Channel> createInsecureChannel(
const shared_model::interface::types::AddressType &address,
const std::string &service_full_name,
std::optional<std::reference_wrapper<GrpcChannelParams const>>
maybe_params);
/**
* Creates client
* @tparam Service type for gRPC stub, e.g. proto::Yac
* @param address ip address and port for connection, ipv4:port
* @param maybe_params grpc channel params
* @return gRPC stub of parametrized type
*/
template <typename Service>
std::unique_ptr<typename Service::StubInterface> createInsecureClient(
const std::string &address,
std::optional<std::reference_wrapper<GrpcChannelParams const>> params) {
return Service::NewStub(createInsecureChannel<Service>(address, params));
}
/**
* Creates client
* @tparam Service type for gRPC stub, e.g. proto::Yac
* @param address ip address to connect to
* @param port port to connect to
* @param params grpc channel params
* @return gRPC stub of parametrized type
*/
template <typename Service>
std::unique_ptr<typename Service::StubInterface> createInsecureClient(
const std::string &ip,
size_t port,
std::optional<std::reference_wrapper<GrpcChannelParams const>>
maybe_params) {
return createInsecureClient<Service>(ip + ":" + std::to_string(port),
maybe_params);
}
class ChannelFactory : public ChannelProvider {
public:
/// @param params grpc channel params
ChannelFactory(
std::optional<std::shared_ptr<const GrpcChannelParams>> maybe_params);
~ChannelFactory() override;
iroha::expected::Result<std::shared_ptr<grpc::Channel>, std::string>
getChannel(const std::string &service_full_name,
const shared_model::interface::Peer &peer) override;
protected:
virtual iroha::expected::Result<std::shared_ptr<grpc::ChannelCredentials>,
std::string>
getChannelCredentials(const shared_model::interface::Peer &) const;
private:
class ChannelArgumentsProvider;
std::unique_ptr<ChannelArgumentsProvider> args_;
};
} // namespace network
} // namespace iroha
#endif
| 33.977612 | 80 | 0.670327 | Insafin |
c6b70c4430ac01a93cb0d5f4ff6d031c0de4bcc7 | 616 | cpp | C++ | sorting-the-sentence/sorting-the-sentence.cpp | sharmishtha2401/leetcode | 0c7389877afb64b3ff277f075ed9c87b24cb587b | [
"MIT"
] | 1 | 2022-02-14T07:57:07.000Z | 2022-02-14T07:57:07.000Z | sorting-the-sentence/sorting-the-sentence.cpp | sharmishtha2401/leetcode | 0c7389877afb64b3ff277f075ed9c87b24cb587b | [
"MIT"
] | null | null | null | sorting-the-sentence/sorting-the-sentence.cpp | sharmishtha2401/leetcode | 0c7389877afb64b3ff277f075ed9c87b24cb587b | [
"MIT"
] | null | null | null | class Solution {
public:
string sortSentence(string s) {
vector<string> pos(10,"");
for(int i=0; i<s.size(); i++)
{
int j=i;
string temp="";
while(!isdigit(s[j]))
{
temp+=s[j];
j++;
}
pos[s[j]-'0']=temp;
i=j+1;
}
string res="";
for(int i=1; i<10; i++)
{
if(pos[i].size()>0)
{
res+=pos[i];
res+=" ";
}
}
res.pop_back();
return res;
}
}; | 20.533333 | 37 | 0.303571 | sharmishtha2401 |
c6b8ae276ea89ab55e574431b759ea716580fd79 | 2,781 | cpp | C++ | 3rdParty/fuerte/src/loop.cpp | snykiotcubedev/arangodb-3.7.6 | fce8f85f1c2f070c8e6a8e76d17210a2117d3833 | [
"Apache-2.0"
] | 1 | 2020-10-27T12:19:33.000Z | 2020-10-27T12:19:33.000Z | 3rdParty/fuerte/src/loop.cpp | charity1475/arangodb | 32bef3ed9abef6f41a11466fe6361ae3e6d99b5e | [
"Apache-2.0"
] | 109 | 2022-01-06T07:05:24.000Z | 2022-03-21T01:39:35.000Z | 3rdParty/fuerte/src/loop.cpp | charity1475/arangodb | 32bef3ed9abef6f41a11466fe6361ae3e6d99b5e | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Christoph Uhde
////////////////////////////////////////////////////////////////////////////////
#include <memory>
#include <fuerte/FuerteLogger.h>
#include <fuerte/loop.h>
#include <fuerte/types.h>
#ifdef __linux__
#include <sys/prctl.h>
#endif
namespace arangodb { namespace fuerte { inline namespace v1 {
EventLoopService::EventLoopService(unsigned int threadCount, char const* name)
: _lastUsed(0), _sslContext(nullptr) {
for (unsigned i = 0; i < threadCount; i++) {
_ioContexts.emplace_back(std::make_shared<asio_ns::io_context>(1));
_guards.emplace_back(asio_ns::make_work_guard(*_ioContexts.back()));
asio_ns::io_context* ctx = _ioContexts.back().get();
_threads.emplace_back([=]() {
#ifdef __linux__
// set name of threadpool thread, so threads can be distinguished from each other
if (name != nullptr && *name != '\0') {
prctl(PR_SET_NAME, name, 0, 0, 0);
}
#endif
ctx->run();
});
}
}
EventLoopService::~EventLoopService() {
stop();
}
asio_ns::ssl::context& EventLoopService::sslContext() {
std::lock_guard<std::mutex> guard(_sslContextMutex);
if (!_sslContext) {
#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
_sslContext.reset(new asio_ns::ssl::context(asio_ns::ssl::context::tls));
#else
_sslContext.reset(new asio_ns::ssl::context(asio_ns::ssl::context::sslv23));
#endif
_sslContext->set_default_verify_paths();
}
return *_sslContext;
}
void EventLoopService::stop() {
// allow run() to exit, wait for threads to finish only then stop the context
std::for_each(_guards.begin(), _guards.end(), [](auto& g) { g.reset(); });
std::this_thread::sleep_for(std::chrono::milliseconds(50));
std::for_each(_ioContexts.begin(), _ioContexts.end(), [](auto& c) { c->stop(); });
std::this_thread::sleep_for(std::chrono::milliseconds(50));
std::for_each(_threads.begin(), _threads.end(), [](auto& t) { if (t.joinable()) { t.join(); } });
}
}}} // namespace arangodb::fuerte::v1
| 34.333333 | 99 | 0.649407 | snykiotcubedev |
c6b9f983c4908cb1ff9056095c77fae0053f4658 | 22,103 | cpp | C++ | tools/dump_combinator/dump_combinator.cpp | arthurp/lapis2 | 1c0644cf1eeb2ddc5a735ca002d561e308ed6014 | [
"BSD-2-Clause"
] | null | null | null | tools/dump_combinator/dump_combinator.cpp | arthurp/lapis2 | 1c0644cf1eeb2ddc5a735ca002d561e308ed6014 | [
"BSD-2-Clause"
] | null | null | null | tools/dump_combinator/dump_combinator.cpp | arthurp/lapis2 | 1c0644cf1eeb2ddc5a735ca002d561e308ed6014 | [
"BSD-2-Clause"
] | null | null | null | #include <glib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <string>
#include <sstream>
#include <cuda.h>
#include <driver_types.h>
#include <fatbinary.h>
#include "debug.h"
#include <atomic>
struct fatbin_wrapper {
uint32_t magic;
uint32_t seq;
uint64_t ptr;
uint64_t data_ptr;
};
struct kernel_arg {
char is_handle;
uint32_t size;
};
#define MAX_KERNEL_ARG 25
#define MAX_KERNEL_NAME_LEN 1024
struct fatbin_function {
int argc;
struct kernel_arg args[MAX_KERNEL_ARG];
CUfunction cufunc;
void *hostfunc;
CUmodule module; // unneeded
};
int fatfunction_fd_load = 0;
int fatfunction_fd_dump = 0;
GPtrArray *global_fatbin_funcs = NULL;
int global_num_fatbins = 0;
ssize_t read_all(int fd, void* buf_in, size_t len) {
char* buf = (char*) buf_in;
ssize_t ret;
while (len != 0 && (ret = read (fd, buf, len)) != 0) {
if (ret == -1) {
if (errno == EINTR)
continue;
break;
}
len -= ret;
buf += ret;
}
return ret;
}
ssize_t write_all(int fd, char* buf, size_t len)
{
ssize_t ret;
while (len != 0 && (ret = write (fd, buf, len)) != 0) {
if (ret == -1) {
if (errno == EINTR)
continue;
break;
}
len -= ret;
buf += ret;
}
return ret;
}
/**
* Loads the function argument information from dump.
*/
GHashTable *__helper_load_function_arg_info(char * load_dir, char* dump_dir, int fatbin_num) {
GPtrArray *fatbin_funcs;
if (global_fatbin_funcs == NULL) {
global_fatbin_funcs = g_ptr_array_new_with_free_func(g_free);
g_ptr_array_add(global_fatbin_funcs, (gpointer)NULL); // func_id starts from 1
}
fatbin_funcs = global_fatbin_funcs;
GHashTable *ht = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
int fd, fd_w, read_ret, write_ret;
std::stringstream ss;
ss << load_dir << "/function_arg-" << fatbin_num << ".ava";
std::string filename = ss.str();
fd = open(filename.c_str(), O_RDONLY, 0666);
ss.str(std::string());
ss.clear();
ss << dump_dir << "/function_arg-" << global_num_fatbins << ".ava";
filename = ss.str();
fd_w = open(filename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0666);
DEBUG_PRINT("Dump function argument info to %s\n", filename.c_str());
ss.str(std::string());
ss.clear();
struct fatbin_function *func;
size_t name_size = 0;
char func_name[MAX_KERNEL_NAME_LEN];
while (1) {
read_ret = read_all(fd, (void *)&name_size, sizeof(size_t));
if (read_ret == 0)
break;
if (read_ret == -1) {
fprintf(stderr, "read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
assert(name_size < MAX_KERNEL_NAME_LEN && "name_size >= MAX_KERNEL_NAME_LEN");
read_ret = read_all(fd, (void *)func_name, name_size);
if (read_ret == -1) {
fprintf(stderr, "read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
func = g_new(struct fatbin_function, 1);
read_ret = read_all(fd, (void *)func, sizeof(struct fatbin_function));
if (read_ret == -1) {
fprintf(stderr, "read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
DEBUG_PRINT("function %d (%s) has argc = %d\n",
fatbin_funcs->len - 1, func_name, func->argc);
/* Insert into the function table */
g_ptr_array_add(fatbin_funcs, (gpointer)func);
/* Add name->index mapping */
if (g_hash_table_lookup(ht, func_name) == NULL) {
assert(fatbin_funcs->len > 1 && "fatbin_funcs->len <= 1");
g_hash_table_insert(ht, g_strdup(func_name), (gpointer)((uintptr_t)fatbin_funcs->len - 1));
}
/* Dump the function argument sizes to file */
write_ret = write(fd_w, (void *)&name_size, sizeof(size_t));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
write_ret = write(fd_w, (void *)func_name, name_size);
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
write_ret = write(fd_w, (void *)func, sizeof(struct fatbin_function));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
}
close(fd);
return ht;
}
void __helper_load_and_dump_fatbin(char* load_dir, char* dump_dir, int fatbin_num, void *fatCubin) {
/* Read fatbin dump */
int fd;
int read_ret, write_ret;
struct stat file_stat;
struct fatbin_wrapper *wp = (struct fatbin_wrapper *)fatCubin;
// load fatbin
std::stringstream ss;
ss << load_dir << "/fatbin-" << fatbin_num << ".ava";
std::string filename = ss.str();
DEBUG_PRINT("loading %s\n", filename.c_str());
fd = open(filename.c_str(), O_RDONLY, 0666);
ss.str(std::string());
ss.clear();
fstat(fd, &file_stat);
size_t fatbin_size = (size_t)file_stat.st_size;
void *fatbin = malloc(fatbin_size);
read_ret = read_all(fd, fatbin, fatbin_size);
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
close(fd);
struct fatBinaryHeader *fbh = (struct fatBinaryHeader *)fatbin;
DEBUG_PRINT("Read fatbin-%d.ava size = %lu, should be %llu\n",
fatbin_num,
fatbin_size,
fbh->headerSize + fbh->fatSize);
assert(fatbin_size == fbh->headerSize + fbh->fatSize && "fatbin size is wrong");
(void)fbh;
wp->ptr = (uint64_t)fatbin;
/* Dump fat binary to a file */
ss << dump_dir << "/fatbin-" << global_num_fatbins << ".ava";
std::string fatbin_filename = ss.str();
fd = open(fatbin_filename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0666);
if (fd == -1) {
fprintf(stderr, "Unexpected error open [errno=%d, errstr=%s] at %s:%d",
fd, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
DEBUG_PRINT("Dump fatbinary to %s\n", fatbin_filename.c_str());
write_ret = write(fd, (const void *)wp->ptr, fbh->headerSize + fbh->fatSize);
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
close(fd);
ss.str(std::string());
ss.clear();
if (fatfunction_fd_dump == 0) {
ss << dump_dir << "/fatfunction.ava";
filename = ss.str();
DEBUG_PRINT("fatfunction ava file to dump is %s\n", filename.c_str());
fatfunction_fd_dump = open(filename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0666);
ss.str(std::string());
ss.clear();
}
/* Load function argument information */
GHashTable *ht = __helper_load_function_arg_info(load_dir, dump_dir, fatbin_num);
/* Register CUDA functions */
GPtrArray *fatbin_funcs = global_fatbin_funcs;
struct fatbin_function *func;
if (fatfunction_fd_load == 0) {
ss << load_dir << "/fatfunction.ava";
filename = ss.str();
fprintf(stderr, "fatfunction ava file is %s\n", filename.c_str());
fatfunction_fd_load = open(filename.c_str(), O_RDONLY, 0666);
fprintf(stderr, "fatfunction_fd is %d\n", fatfunction_fd_load);
ss.str(std::string());
ss.clear();
}
fd = fatfunction_fd_load;
void *func_id = NULL;
size_t size = 0;
int exists = 0;
char *deviceFun = NULL;
char *deviceName = NULL;
int thread_limit;
uint3 *tid = NULL;
uint3 *bid = NULL;
dim3 *bDim = NULL;
dim3 *gDim = NULL;
int *wSize = NULL;
while (1) {
// load size and deviceFun
read_ret = read_all(fd, (void *)&size, sizeof(size_t));
if (read_ret == 0) { // EOF
close(fd);
break;
}
if (size == 0) { // Meet separator
DEBUG_PRINT("Finish reading functions for fatbin-%d.ava\n", fatbin_num);
break;
}
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
deviceFun = (char *)malloc(size);
read_ret = read_all(fd, (void *)deviceFun, size);
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
// dump size and deviceFun
write_ret = write(fatfunction_fd_dump, (const void *)&size, sizeof(size_t));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
write_ret = write(fatfunction_fd_dump, (const void *)deviceFun, size);
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
// load size and deviceName
read_ret = read_all(fd, (void *)&size, sizeof(size_t));
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
deviceName = (char *)malloc(size);
read_ret = read_all(fd, (void *)deviceName, size);
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
// dump size and deviceName
write_ret = write(fatfunction_fd_dump, (const void *)&size, sizeof(size_t));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
write_ret = write(fatfunction_fd_dump, (const void *)deviceName, size);
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
read_ret = read_all(fd, (void *)&thread_limit, sizeof(int));
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
write_ret = write(fatfunction_fd_dump, (const void *)&thread_limit, sizeof(int));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
read_ret = read_all(fd, (void *)&exists, sizeof(int));
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
write_ret = write(fatfunction_fd_dump, (const void *)&exists, sizeof(int));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
if (exists) {
tid = (uint3 *)malloc(sizeof(uint3));
read_ret = read_all(fd, (void *)tid, sizeof(uint3));
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
write_ret = write(fatfunction_fd_dump, (const void *)tid, sizeof(uint3));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
}
else
tid = NULL;
read_ret = read_all(fd, (void *)&exists, sizeof(int));
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
write_ret = write(fatfunction_fd_dump, (const void *)&exists, sizeof(int));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
if (exists) {
bid = (uint3 *)malloc(sizeof(uint3));
read_ret = read_all(fd, (void *)bid, sizeof(uint3));
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
write_ret = write(fatfunction_fd_dump, (const void *)bid, sizeof(uint3));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
}
else
bid = NULL;
read_ret = read_all(fd, (void *)&exists, sizeof(int));
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
write_ret = write(fatfunction_fd_dump, (const void *)&exists, sizeof(int));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
if (exists) {
bDim = (dim3 *)malloc(sizeof(dim3));
read_ret = read_all(fd, (void *)bDim, sizeof(dim3));
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
write_ret = write(fatfunction_fd_dump, (const void *)bDim, sizeof(dim3));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
}
else
bDim = NULL;
read_ret = read_all(fd, (void *)&exists, sizeof(int));
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
write_ret = write(fatfunction_fd_dump, (const void *)&exists, sizeof(int));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
if (exists) {
gDim = (dim3 *)malloc(sizeof(dim3));
read_ret = read_all(fd, (void *)gDim, sizeof(dim3));
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
write_ret = write(fatfunction_fd_dump, (const void *)gDim, sizeof(dim3));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
}
else
gDim = NULL;
read_ret = read_all(fd, (void *)&exists, sizeof(int));
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
write_ret = write(fatfunction_fd_dump, (const void *)&exists, sizeof(int));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
if (exists) {
wSize = (int *)malloc(sizeof(int));
read_ret = read_all(fd, (void *)wSize, sizeof(int));
if (read_ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
read_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
write_ret = write(fatfunction_fd_dump, (const void *)wSize, sizeof(int));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
}
else
wSize = NULL;
DEBUG_PRINT("Register function deviceName = %s\n", deviceName);
func_id = (void *)g_hash_table_lookup(ht, deviceName);
assert(func_id != NULL && "func_id should not be NULL");
func = (fatbin_function*)g_ptr_array_index(fatbin_funcs, (intptr_t)func_id);
// __helper_register_function(func, (const char *)func_id, mod, deviceName);
free(deviceFun);
free(deviceName);
if (tid) free(tid);
if (bid) free(bid);
if (bDim) free(bDim);
if (gDim) free(gDim);
if (wSize) free(wSize);
}
size = 0;
write_ret = write(fatfunction_fd_dump, (const void*)&size, sizeof(size_t));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
++(global_num_fatbins);
// dump size and wrapper to fatbin-info
ss << dump_dir << "/fatbin-info.ava";
filename = ss.str();
fd = open(filename.c_str(), O_RDWR | O_CREAT, 0666);
DEBUG_PRINT("Fatbinary counter = %d\n", global_num_fatbins);
write_ret = write(fd, (const void *)&global_num_fatbins, sizeof(int));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
lseek(fd, 0, SEEK_END);
write_ret = write(fd, (const void *)wp, sizeof(struct fatbin_wrapper));
if (write_ret == -1) {
fprintf(stderr, "Unexpected error write [errno=%d, errstr=%s] at %s:%d",
write_ret, strerror(errno), __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
close(fd);
g_hash_table_destroy(ht);
// return fatbin_handle;
}
void load_dump_fatbin(char * load_dir, char* dump_dir)
{
/* Read cubin number */
int fd = 0, ret = 0, fatbin_num = 0;
std::stringstream ss;
ss << load_dir << "/fatbin-info.ava";
std::string filename = ss.str();
fd = open(filename.c_str(), O_RDONLY, 0666);
ret = read_all(fd, (void *)&fatbin_num, sizeof(int));
if (ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
ret, strerror(errno), __FILE__, __LINE__);
}
DEBUG_PRINT("%s fatbin num is %d\n", load_dir, fatbin_num);
int i;
void *fatCubin;
// void **fatbin_handle;
for (i = 0; i < fatbin_num; i++) {
fatCubin = malloc(sizeof(struct fatbin_wrapper));
ret = read_all(fd, fatCubin, sizeof(struct fatbin_wrapper));
if (ret == -1) {
fprintf(stderr, "Unexpected error read [errno=%d, errstr=%s] at %s:%d",
ret, strerror(errno), __FILE__, __LINE__);
}
__helper_load_and_dump_fatbin(load_dir, dump_dir, i, fatCubin);
}
close(fd);
// reset metadata
fatfunction_fd_load = 0;
}
int main(int argc, char** argv)
{
if (argc != 4) {
fprintf(stderr, "<usage>: %s <load_dir1> <load_dir2> <dump_dir>\n", argv[0]);
exit(EXIT_FAILURE);
}
char* load_dir1 = argv[1];
char* load_dir2 = argv[2];
char* dump_dir = argv[3];
load_dump_fatbin(load_dir1, dump_dir);
fprintf(stderr, "done loading to %s and dumping to %s\n", load_dir1, dump_dir);
load_dump_fatbin(load_dir2, dump_dir);
fprintf(stderr, "done loading to %s and dumping to %s\n", load_dir2, dump_dir);
}
| 37.273187 | 103 | 0.563362 | arthurp |
c6bbb40d95571820d1ce00e1c360cfe93bc39512 | 2,759 | cpp | C++ | src/move.cpp | hang-sun1/spareduck | d56c5174c6e8e21b8845af100e7147e272a88b2a | [
"MIT"
] | 1 | 2022-02-19T03:19:33.000Z | 2022-02-19T03:19:33.000Z | src/move.cpp | hang-sun1/spareduck | d56c5174c6e8e21b8845af100e7147e272a88b2a | [
"MIT"
] | null | null | null | src/move.cpp | hang-sun1/spareduck | d56c5174c6e8e21b8845af100e7147e272a88b2a | [
"MIT"
] | null | null | null | #include "move.hpp"
#include "piece.hpp"
#include <optional>
Move::Move(uint16_t from, uint16_t to, MoveType type) {
move_repr = (from << 10) | (to << 4) | static_cast<uint16_t>(type);
this->t = type;
captured = std::nullopt;
}
// New move from algebraic notation.
Move::Move(std::string from, std::string to) {
uint16_t from_square = (from[0] - 'a') | 7 | (from[1] - '1') << 3;
uint16_t to_square = (to[0] - 'a') | 7 | (from[1] - '1') << 3;
MoveType type = MoveType::QUIET;
move_repr = (from_square << 10) | (to_square << 4) | static_cast<uint16_t>(type);
this->t = type;
captured = std::nullopt;
}
Move::Move() {
}
std::ostream& operator<<(std::ostream& strm, const Move& move) {
return strm << " (" << move.origin_square_algebraic() << ", " << move.destination_square_algebraic() << ") ";
}
bool operator==(const Move& lhs, const Move& rhs) {
return lhs.get_move_repr() == rhs.get_move_repr();
}
uint16_t Move::get_move_repr() const {
return this->move_repr;
}
uint16_t Move::origin_square() const {
return move_repr >> 10;
}
uint16_t Move::destination_square() const {
return (move_repr >> 4) & 63;
}
MoveType Move::type() const {
return t;
}
bool Move::is_capture() const {
auto as_integer = static_cast<uint16_t>(t);
return as_integer == 2 || as_integer > 8 || t == MoveType::EN_PASSANT;
}
bool Move::is_promotion() const {
auto as_integer = static_cast<uint16_t>(t);
return as_integer >= 5 && as_integer <= 12;
}
std::string Move::origin_square_algebraic() const{
uint16_t origin = origin_square();
char algebraic_move[3] = {(char)((origin & 7) + 'a'),
(char)((origin >> 3) + '1'),
'\0'};
return std::string(algebraic_move);
}
std::string Move::destination_square_algebraic() const {
uint16_t destination = destination_square();
char algebraic_move[3] = {(char)((destination & 7) + 'a'),
(char)((destination >> 3) + '1'),
'\0'};
return std::string(algebraic_move);
}
std::array<uint16_t, 2> Move::origin_square_cartesian() const {
uint16_t origin = origin_square();
return {static_cast<uint16_t>(origin & 7), static_cast<uint16_t>(origin >> 3)};
}
std::array<uint16_t, 2> Move::destination_square_cartesian()const {
uint16_t destination = destination_square();
return {static_cast<uint16_t>(destination & 7), static_cast<uint16_t>(destination >> 3)};
}
void Move::set_moved(Piece p) {
moved = p;
}
void Move::set_captured(Piece p) {
captured = std::make_optional(p);
}
Piece Move::get_moved() {
return moved;
}
std::optional<Piece> Move::get_captured() {
return captured;
}
| 27.316832 | 113 | 0.617253 | hang-sun1 |
c6bdf5d5e926d440fe637a9d40543f8e06b74ba3 | 316 | cc | C++ | math/float.cc | cbiffle/etl | 2d00ac79ec13632e6c10df11f4623938cfdc2dd4 | [
"BSD-2-Clause"
] | 57 | 2015-06-10T12:06:54.000Z | 2021-07-02T18:54:01.000Z | math/float.cc | cbiffle/etl | 2d00ac79ec13632e6c10df11f4623938cfdc2dd4 | [
"BSD-2-Clause"
] | 3 | 2016-04-26T18:18:56.000Z | 2021-01-25T04:11:58.000Z | math/float.cc | cbiffle/etl | 2d00ac79ec13632e6c10df11f4623938cfdc2dd4 | [
"BSD-2-Clause"
] | 14 | 2015-07-31T12:34:03.000Z | 2022-03-22T17:02:24.000Z | #include "etl/math/float.h"
#include "etl/prediction.h"
#include "etl/math/inline_fsplit.h"
namespace etl {
namespace math {
SplitFloat fsplit(float value) {
/*
* Just instantiate the inline definition as a non-inlined function.
*/
return fsplit_inl(value);
}
} // namespace math
} // namespace etl
| 16.631579 | 70 | 0.699367 | cbiffle |
c6c029596c3c4f0e210f56f60c0bbd58859ab3bf | 1,615 | cpp | C++ | _investigacion/contests/UTP-Regional/DNA_School.cpp | civilian/competitive_programing | a6ae7ad0db84240667c1dd6231c51c586ba040c7 | [
"MIT"
] | 1 | 2016-02-11T21:28:22.000Z | 2016-02-11T21:28:22.000Z | _investigacion/contests/UTP-Regional/DNA_School.cpp | civilian/competitive_programing | a6ae7ad0db84240667c1dd6231c51c586ba040c7 | [
"MIT"
] | null | null | null | _investigacion/contests/UTP-Regional/DNA_School.cpp | civilian/competitive_programing | a6ae7ad0db84240667c1dd6231c51c586ba040c7 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
string s, t;
while (cin >> s >> t) {
int n = s.size();
int m = t.size();
int best = 0;
string ans = "No matches";
for (int space = 0; space < n; space++) {
int curr = 0;
string curr_str;
for (int i = 0; i < space; i++)
curr_str.push_back(s[i]);
int i;
for (i = 0; i < m; i++) {
if (i+space >= n)
break;
if (t[i] == s[i+space]) {
curr++;
curr_str.push_back(t[i]);
}
else {
curr_str.push_back('X');
}
}
for (; i+space < n; i++)
curr_str.push_back(s[i+space]);
for (; i < m; i++)
curr_str.push_back(t[i]);
if (curr > best) {
best = curr;
ans = curr_str;
}
}
for (int space = 0; space < m; space++) {
int curr = 0;
string curr_str;
int start = m-1-space;
for (int i = 0; i < start; i++)
curr_str.push_back(t[i]);
for (int i = 0; i < n && i <= space; i++) {
if (s[i] == t[start]) {
curr++;
curr_str.push_back(s[i]);
}
else
curr_str.push_back('X');
start++;
}
for (int i = space+1; i < n; i++)
curr_str.push_back(s[i]);
for (; start < m; start++)
curr_str.push_back(t[start]);
if (curr > best) {
best = curr;
ans = curr_str;
}
}
cout << best << '\n';
cout << ans << '\n';
cout << '\n';
}
return 0;
}
| 19.457831 | 49 | 0.427864 | civilian |
c6c2ab7497289fe7aa4f864189e0d82de8f62fc0 | 2,856 | cpp | C++ | hd2605/Driver.cpp | flowerinthenight/tidrv2605-haptic-driver-umdf | 51ee51aae1536079e22b20b84e9a3daad38df016 | [
"MIT"
] | null | null | null | hd2605/Driver.cpp | flowerinthenight/tidrv2605-haptic-driver-umdf | 51ee51aae1536079e22b20b84e9a3daad38df016 | [
"MIT"
] | null | null | null | hd2605/Driver.cpp | flowerinthenight/tidrv2605-haptic-driver-umdf | 51ee51aae1536079e22b20b84e9a3daad38df016 | [
"MIT"
] | null | null | null | #include "Internal.h"
// #include "SpbAccelerometer.h" // IDL Generated File
#include "LenHapticDriverDrv2605.h" // IDL Generated File
#include "Device.h"
#include "__dump.h"
#include "Driver.h"
#include "Driver.tmh"
/////////////////////////////////////////////////////////////////////////
//
// CMyDriver::CMyDriver
//
// Object constructor function
//
/////////////////////////////////////////////////////////////////////////
CMyDriver::CMyDriver()
{
}
/////////////////////////////////////////////////////////////////////////
//
// CMyDriver::OnDeviceAdd
//
// The framework call this function when device is detected. This driver
// creates a device callback object
//
// Parameters:
// pDriver - pointer to an IWDFDriver object
// pDeviceInit - pointer to a device initialization object
//
// Return Values:
// S_OK: device initialized successfully
//
/////////////////////////////////////////////////////////////////////////
HRESULT CMyDriver::OnDeviceAdd(_In_ IWDFDriver *pDriver, _In_ IWDFDeviceInitialize *pDeviceInit)
{
CComObject<CMyDevice>* pMyDevice = nullptr;
HRESULT hr;
L2(WFN, L"Called.");
hr = CMyDevice::CreateInstance(pDriver, pDeviceInit, &pMyDevice);
if (FAILED(hr)) {
Trace(
TRACE_LEVEL_ERROR,
"Failed to create instance of CMyDevice, %!HRESULT!",
hr);
}
if (SUCCEEDED(hr)) {
hr = pMyDevice->Configure();
if (FAILED(hr)) {
Trace(
TRACE_LEVEL_ERROR,
"Failed to configure CMyDevice %p, %!HRESULT!",
pMyDevice,
hr);
}
// Release the pMyDevice pointer when done.
// Note: UMDF holds a reference to it above
SAFE_RELEASE(pMyDevice);
}
return hr;
}
/////////////////////////////////////////////////////////////////////////
//
// CMyDriver::OnInitialize
//
// The framework calls this function just after loading the driver. The driver
// can perform any global, device independent intialization in this routine.
//
/////////////////////////////////////////////////////////////////////////
HRESULT CMyDriver::OnInitialize(_In_ IWDFDriver *pDriver)
{
UNREFERENCED_PARAMETER(pDriver);
L2(WFN, L"Called.");
return S_OK;
}
/////////////////////////////////////////////////////////////////////////
//
// CMyDriver::OnDeinitialize
//
// The framework calls this function just before de-initializing itself. All
// WDF framework resources should be released by driver before returning
// from this call.
//
/////////////////////////////////////////////////////////////////////////
void CMyDriver::OnDeinitialize(_In_ IWDFDriver *pDriver)
{
UNREFERENCED_PARAMETER(pDriver);
return;
}
| 28.56 | 97 | 0.496849 | flowerinthenight |
c6c5d3e0c26b326a4521eb3e434f5550a1526f0e | 1,502 | cpp | C++ | source/idf/SingleInput.cpp | greck2908/IDF | 0882cc35d88b96b0aea55e112060779654f040a6 | [
"NASA-1.3"
] | 84 | 2016-06-15T21:26:02.000Z | 2022-03-12T15:09:57.000Z | source/idf/SingleInput.cpp | greck2908/IDF | 0882cc35d88b96b0aea55e112060779654f040a6 | [
"NASA-1.3"
] | 44 | 2016-10-19T17:35:01.000Z | 2022-03-11T17:20:51.000Z | source/idf/SingleInput.cpp | greck2908/IDF | 0882cc35d88b96b0aea55e112060779654f040a6 | [
"NASA-1.3"
] | 46 | 2016-06-25T00:18:52.000Z | 2019-12-19T11:13:15.000Z | #include "idf/SingleInput.hh"
#include <stdexcept>
#include <sstream>
namespace idf {
SingleInput::SingleInput(double min, double max) {
configure(min, max);
}
SingleInput::SingleInput(double min, double max, double middle) {
configure(min, max, middle);
}
void SingleInput::configure(double min, double max) {
configure(min, max, (min + max) / 2);
}
void SingleInput::configure(double min, double max, double middle) {
if (min > max) {
std::ostringstream stream;
stream << " Minimum (" << min << ") must not be greater than maximum (" << max << ").";
throw std::logic_error(stream.str());
}
if (middle < min) {
std::ostringstream stream;
stream << " Neutral (" << middle << ") must not be less than minimum (" << min << ").";
throw std::logic_error(stream.str());
}
if (middle > max) {
std::ostringstream stream;
stream << " Neutral (" << middle << ") must not be greater than maximum (" << max << ").";
throw std::logic_error(stream.str());
}
minimum = min;
maximum = max;
neutral = middle;
value = neutral;
}
double SingleInput::getMinimumValue() const {
return minimum;
}
double SingleInput::getNeutralValue() const {
return neutral;
}
double SingleInput::getMaximumValue() const {
return maximum;
}
double SingleInput::getValue() const {
return applyDeadbands(value);
}
void SingleInput::setValue(double rawValue) {
value = rawValue;
}
}
| 23.107692 | 98 | 0.620506 | greck2908 |
c6c67d3323f57998d6a6d0ea87b9d9d8e3568e6b | 3,679 | cpp | C++ | src/Engine/App/Component.cpp | NeroBurner/osre | 20d3510222cebcfc5241fda3936eabef01cc969b | [
"MIT"
] | null | null | null | src/Engine/App/Component.cpp | NeroBurner/osre | 20d3510222cebcfc5241fda3936eabef01cc969b | [
"MIT"
] | null | null | null | src/Engine/App/Component.cpp | NeroBurner/osre | 20d3510222cebcfc5241fda3936eabef01cc969b | [
"MIT"
] | null | null | null | /*-----------------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2015-2019 OSRE ( Open Source Render Engine ) by Kim Kulling
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 <osre/App/Component.h>
#include <osre/App/Entity.h>
#include <osre/RenderBackend/RenderBackendService.h>
#include <osre/RenderBackend/RenderCommon.h>
namespace OSRE {
namespace App {
using namespace ::OSRE::RenderBackend;
using namespace ::CPPCore;
static const glm::vec3 Dummy = glm::vec3( -1, -1, -1);
Component::Component( Entity *owner, ui32 id )
: m_owner( owner )
, m_id( id ) {
OSRE_ASSERT( nullptr != owner );
}
Component::~Component() {
// empty
}
void Component::update( Time dt ) {
onUpdate( dt );
}
void Component::render( RenderBackend::RenderBackendService *renderBackendSrv ) {
onRender(renderBackendSrv);
}
RenderComponent::RenderComponent(Entity *owner, ui32 id )
: Component( owner, id )
, m_newGeo() {
// empty
}
RenderComponent::~RenderComponent() {
// empty
}
void RenderComponent::addStaticMesh( Mesh *geo ) {
if ( nullptr == geo ) {
return;
}
m_newGeo.add( geo );
}
void RenderComponent::addStaticMeshArray( const RenderBackend::MeshArray &array ) {
if ( array.isEmpty() ) {
return;
}
for ( size_t i=0; i<array.size(); ++i ) {
m_newGeo.add(array[i]);
}
}
size_t RenderComponent::getNumGeometry() const {
return m_newGeo.size();
}
Mesh *RenderComponent::getMeshAt( size_t idx) const {
return m_newGeo[idx];
}
bool RenderComponent::onPreprocess() {
return true;
}
bool RenderComponent::onUpdate( Time ) {
return true;
}
bool RenderComponent::onRender( RenderBackendService *renderBackendSrv ) {
if (!m_newGeo.isEmpty()) {
for (ui32 i = 0; i < m_newGeo.size(); i++) {
renderBackendSrv->addMesh( m_newGeo[ i ], 0 );
}
m_newGeo.resize( 0 );
}
return true;
}
bool RenderComponent::onPostprocess() {
return true;
}
TransformComponent::TransformComponent( Entity *owner, ui32 id )
: Component( owner, id )
, m_mb() {
// empty
}
TransformComponent::~TransformComponent() {
// empty
}
void TransformComponent::update( Time ) {
}
bool TransformComponent::onPreprocess() {
return true;
}
bool TransformComponent::onUpdate( Time dt ) {
return true;
}
bool TransformComponent::onRender( RenderBackend::RenderBackendService* ) {
return true;
}
bool TransformComponent::onPostprocess() {
return true;
}
} // Namespace Scene
} // Namespace OSREB
| 25.027211 | 97 | 0.66866 | NeroBurner |
c6c6f33acb1fc50ae971467181fab017ae005126 | 593 | cc | C++ | src/extensions/compact/compact16_unweighted_acceptor-fst.cc | unixnme/openfst | 159ee426d79485f6769a122a264e94f73da88642 | [
"Apache-2.0"
] | 1 | 2020-05-11T00:44:54.000Z | 2020-05-11T00:44:54.000Z | src/extensions/compact/compact16_unweighted_acceptor-fst.cc | unixnme/openfst | 159ee426d79485f6769a122a264e94f73da88642 | [
"Apache-2.0"
] | null | null | null | src/extensions/compact/compact16_unweighted_acceptor-fst.cc | unixnme/openfst | 159ee426d79485f6769a122a264e94f73da88642 | [
"Apache-2.0"
] | null | null | null | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#include <fst/compact-fst.h>
#include <fst/fst.h>
namespace fst {
static FstRegisterer<
CompactUnweightedAcceptorFst<StdArc, uint16>>
CompactUnweightedAcceptorFst_StdArc_uint16_registerer;
static FstRegisterer<
CompactUnweightedAcceptorFst<LogArc, uint16>>
CompactUnweightedAcceptorFst_LogArc_uint16_registerer;
static FstRegisterer<
CompactUnweightedAcceptorFst<Log64Arc, uint16>>
CompactUnweightedAcceptorFst_Log64Arc_uint16_registerer;
} // namespace fst
| 26.954545 | 67 | 0.812816 | unixnme |
c6c6f6da4b1fd326fa5d7a0196f2e98745e9aa28 | 17,225 | cpp | C++ | Source/DlgSystemEditor/Private/Commandlets/DlgExportTwineCommandlet.cpp | derossm/DlgSystem | 69d4539067fa4c5c8cc26cdb7cc019cf0576cd5a | [
"MIT"
] | 97 | 2020-03-09T11:37:10.000Z | 2022-03-31T23:45:00.000Z | Source/DlgSystemEditor/Private/Commandlets/DlgExportTwineCommandlet.cpp | derossm/DlgSystem | 69d4539067fa4c5c8cc26cdb7cc019cf0576cd5a | [
"MIT"
] | 1 | 2020-03-06T07:35:35.000Z | 2020-03-07T15:31:13.000Z | Source/DlgSystemEditor/Private/Commandlets/DlgExportTwineCommandlet.cpp | derossm/DlgSystem | 69d4539067fa4c5c8cc26cdb7cc019cf0576cd5a | [
"MIT"
] | 16 | 2021-03-20T17:29:13.000Z | 2022-03-30T08:28:42.000Z | // Copyright Csaba Molnar, Daniel Butum. All Rights Reserved.
#include "DlgExportTwineCommandlet.h"
#include "Misc/Paths.h"
#include "Misc/FileHelper.h"
#if ENGINE_MAJOR_VERSION >= 5
#include "HAL/PlatformFileManager.h"
#else
#include "HAL/PlatformFilemanager.h"
#endif
#include "GenericPlatform/GenericPlatformFile.h"
#include "UObject/Package.h"
#include "FileHelpers.h"
#include "DlgManager.h"
#include "Nodes/DlgNode_Speech.h"
#include "Nodes/DlgNode_SpeechSequence.h"
#include "DialogueEditor/Nodes/DialogueGraphNode.h"
#include "DlgCommandletHelper.h"
#include "DlgHelper.h"
DEFINE_LOG_CATEGORY(LogDlgExportTwineCommandlet);
const FString UDlgExportTwineCommandlet::TagNodeStart(TEXT("node-start"));
const FString UDlgExportTwineCommandlet::TagNodeEnd(TEXT("node-end"));
const FString UDlgExportTwineCommandlet::TagNodeVirtualParent(TEXT("node-virtual-parent"));
const FString UDlgExportTwineCommandlet::TagNodeSpeech(TEXT("node-speech"));
const FString UDlgExportTwineCommandlet::TagNodeSpeechSequence(TEXT("node-speech-sequence"));
const FString UDlgExportTwineCommandlet::TagNodeSelectorFirst(TEXT("node-selector-first"));
const FString UDlgExportTwineCommandlet::TagNodeSelectorRandom(TEXT("node-selector-random"));
const FIntPoint UDlgExportTwineCommandlet::SizeSmall(100, 100);
const FIntPoint UDlgExportTwineCommandlet::SizeWide(200, 100);
const FIntPoint UDlgExportTwineCommandlet::SizeTall(100, 200);
const FIntPoint UDlgExportTwineCommandlet::SizeLarge(200, 200);
TMap<FString, FString> UDlgExportTwineCommandlet::TwineTagNodesColorsMap;
UDlgExportTwineCommandlet::UDlgExportTwineCommandlet()
{
IsClient = false;
IsEditor = true;
IsServer = false;
LogToConsole = true;
ShowErrorCount = true;
}
int32 UDlgExportTwineCommandlet::Main(const FString& Params)
{
UE_LOG(LogDlgExportTwineCommandlet, Display, TEXT("Starting"));
InitTwinetagNodesColors();
// Parse command line - we're interested in the param vals
TArray<FString> Tokens;
TArray<FString> Switches;
TMap<FString, FString> ParamVals;
UCommandlet::ParseCommandLine(*Params, Tokens, Switches, ParamVals);
if (Switches.Contains(TEXT("Flatten")))
{
bFlatten = true;
}
// Set the output directory
const FString* OutputDirectoryVal = ParamVals.Find(FString(TEXT("OutputDirectory")));
if (OutputDirectoryVal == nullptr)
{
UE_LOG(LogDlgExportTwineCommandlet, Error, TEXT("Did not provide argument -OutputDirectory=<Path>"));
return -1;
}
OutputDirectory = *OutputDirectoryVal;
if (OutputDirectory.IsEmpty())
{
UE_LOG(LogDlgExportTwineCommandlet, Error, TEXT("OutputDirectory is empty, please provide a non empty one with -OutputDirectory=<Path>"));
return -1;
}
// Make it absolute
if (FPaths::IsRelative(OutputDirectory))
{
OutputDirectory = FPaths::Combine(FPaths::ProjectDir(), OutputDirectory);
}
// Create destination directory
IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile();
if (!PlatformFile.DirectoryExists(*OutputDirectory) && PlatformFile.CreateDirectoryTree(*OutputDirectory))
{
UE_LOG(LogDlgExportTwineCommandlet, Display, TEXT("Creating OutputDirectory = `%s`"), *OutputDirectory);
}
UDlgManager::LoadAllDialoguesIntoMemory();
UE_LOG(LogDlgExportTwineCommandlet, Display, TEXT("Exporting to = `%s`"), *OutputDirectory);
// Some Dialogues may be unclean?
//FDlgCommandletHelper::SaveAllDialogues();
// Keep track of all created files so that we don't have duplicates
TSet<FString> CreateFiles;
// Export to twine
const TArray<UDlgDialogue*> AllDialogues = UDlgManager::GetAllDialoguesFromMemory();
for (const UDlgDialogue* Dialogue : AllDialogues)
{
UPackage* Package = Dialogue->GetOutermost();
check(Package);
const FString OriginalDialoguePath = Package->GetPathName();
FString DialoguePath = OriginalDialoguePath;
// Only export game dialogues
if (!FDlgHelper::IsPathInProjectDirectory(DialoguePath))
{
UE_LOG(LogDlgExportTwineCommandlet, Warning, TEXT("Dialogue = `%s` is not in the game directory, ignoring"), *DialoguePath);
continue;
}
verify(DialoguePath.RemoveFromStart(TEXT("/Game")));
const FString FileName = FPaths::GetBaseFilename(DialoguePath);
const FString Directory = FPaths::GetPath(DialoguePath);
FString FileSystemFilePath;
if (bFlatten)
{
// Create in root of output directory
// Make sure file does not exist
FString FlattenedFileName = FileName;
int32 CurrentTryIndex = 1;
while (CreateFiles.Contains(FlattenedFileName) && CurrentTryIndex < 100)
{
FlattenedFileName = FString::Printf(TEXT("%s-%d"), *FileName, CurrentTryIndex);
CurrentTryIndex++;
}
// Give up :(
if (CreateFiles.Contains(FlattenedFileName))
{
UE_LOG(LogDlgExportTwineCommandlet, Warning, TEXT("Dialogue = `%s` could not generate unique flattened file, ignoring"), *DialoguePath);
continue;
}
CreateFiles.Add(FlattenedFileName);
FileSystemFilePath = OutputDirectory / FlattenedFileName + TEXT(".html");
}
else
{
// Ensure directory tree
const FString FileSystemDirectoryPath = OutputDirectory / Directory;
if (!PlatformFile.DirectoryExists(*FileSystemDirectoryPath) && PlatformFile.CreateDirectoryTree(*FileSystemDirectoryPath))
{
UE_LOG(LogDlgExportTwineCommandlet, Display, TEXT("Creating directory = `%s`"), *FileSystemDirectoryPath);
}
FileSystemFilePath = FileSystemDirectoryPath / FileName + TEXT(".html");
}
// Compute minimum graph node positions
const TArray<UDlgNode*>& Nodes = Dialogue->GetNodes();
MinimumGraphX = 0;
MinimumGraphY = 0;
if (const UDialogueGraphNode* DialogueGraphNode = Cast<UDialogueGraphNode>(Dialogue->GetStartNode().GetGraphNode()))
{
MinimumGraphX = FMath::Min(MinimumGraphX, DialogueGraphNode->NodePosX);
MinimumGraphY = FMath::Min(MinimumGraphY, DialogueGraphNode->NodePosY);
}
for (const UDlgNode* Node : Nodes)
{
const UDialogueGraphNode* DialogueGraphNode = Cast<UDialogueGraphNode>(Node->GetGraphNode());
if (DialogueGraphNode == nullptr)
{
continue;
}
MinimumGraphX = FMath::Min(MinimumGraphX, DialogueGraphNode->NodePosX);
MinimumGraphY = FMath::Min(MinimumGraphY, DialogueGraphNode->NodePosY);
}
//UE_LOG(LogDlgExportTwineCommandlet, Verbose, TEXT("MinimumGraphX = %d, MinimumGraphY = %d"), MinimumGraphX, MinimumGraphY);
// Gather passages data
CurrentNodesAreas.Empty();
FString PassagesData;
PassagesData += CreateTwinePassageDataFromNode(*Dialogue, Dialogue->GetStartNode(), INDEX_NONE) + TEXT("\n");
// The rest of the nodes
for (int32 NodeIndex = 0; NodeIndex < Nodes.Num(); NodeIndex++)
{
PassagesData += CreateTwinePassageDataFromNode(*Dialogue, *Nodes[NodeIndex], NodeIndex) + TEXT("\n");
}
// Export file
const FString TwineFileContent = CreateTwineStoryData(Dialogue->GetDialogueName(), Dialogue->GetGUID(), INDEX_NONE, PassagesData);
if (FFileHelper::SaveStringToFile(TwineFileContent, *FileSystemFilePath, FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM))
{
UE_LOG(LogDlgExportTwineCommandlet, Display, TEXT("Writing file = `%s` for Dialogue = `%s` "), *FileSystemFilePath, *OriginalDialoguePath);
}
else
{
UE_LOG(LogDlgExportTwineCommandlet, Error, TEXT("FAILED to write file = `%s` for Dialogue = `%s`"), *FileSystemFilePath, *OriginalDialoguePath);
}
}
return 0;
}
FString UDlgExportTwineCommandlet::CreateTwineStoryData(const FString& Name, const FGuid& DialogueGUID, int32 StartNodeIndex, const FString& PassagesData)
{
static const FString Creator = TEXT("UE-NotYetDlgSystem");
static const FString CreatorVersion = TEXT("5.0"); // TODO
static constexpr int32 Zoom = 1;
static const FString Format = TEXT("Harlowe");
static const FString FormatVersion = TEXT("2.1.0");
//const FGuid UUID = FGuid::NewGuid();
return FString::Printf(
TEXT("<tw-storydata name=\"%s\" startnode=\"%d\" creator=\"%s\" creator-version=\"%s\"")
TEXT(" ifid=\"%s\" zoom=\"%d\" format=\"%s\" format-version=\"%s\" options=\"\" hidden>\n")
TEXT("<style role=\"stylesheet\" id=\"twine-user-stylesheet\" type=\"text/twine-css\">%s</style>\n")
TEXT("<script role=\"script\" id=\"twine-user-script\" type=\"text/twine-javascript\"></script>\n")
// tags colors data
TEXT("\n%s\n")
// Special tag to identify the dialogue id
//TEXT("<tw-passagedata pid=\"-1\" tags=\"\" name=\"DialogueGUID\" position=\"0,0\" size=\"10,10\">%s</tw-passagedata>\n")
TEXT("%s\n")
TEXT("</tw-storydata>"),
*Name, StartNodeIndex + 2, *Creator, *CreatorVersion,
*DialogueGUID.ToString(EGuidFormats::DigitsWithHyphens), Zoom, *Format, *FormatVersion,
*CreateTwineCustomCss(),
*CreateTwineTagColorsData(),
*PassagesData
);
}
bool UDlgExportTwineCommandlet::GetBoxThatConflicts(const FBox2D& Box, FBox2D& OutConflict)
{
for (const FBox2D& CurrentBox : CurrentNodesAreas)
{
if (CurrentBox.Intersect(Box))
{
OutConflict = CurrentBox;
return true;
}
}
return false;
}
FIntPoint UDlgExportTwineCommandlet::GetNonConflictingPointFor(const FIntPoint& Point, const FIntPoint& Size, const FIntPoint& Padding)
{
FVector2D MinVector(Point + Padding);
FVector2D MaxVector(MinVector + Size);
FBox2D NewBox(MinVector, MaxVector);
FBox2D ConflictBox;
while (GetBoxThatConflicts(NewBox, ConflictBox))
{
//UE_LOG(LogDlgExportTwineCommandlet, Warning, TEXT("Found conflict in rectangle: %s for Point: %s"), *ConflictRect.ToString(), *NewPoint.ToString());
// Assume the curent box is a child, adjust
FVector2D Center, Extent;
ConflictBox.GetCenterAndExtents(Center, Extent);
// Update on vertical
MinVector.Y += Extent.Y / 2.f;
MaxVector = MinVector + Size;
NewBox = FBox2D(MinVector, MaxVector);
}
CurrentNodesAreas.Add(NewBox);
return MinVector.IntPoint();
}
FString UDlgExportTwineCommandlet::CreateTwinePassageDataFromNode(const UDlgDialogue& Dialogue, const UDlgNode& Node, int32 NodeIndex)
{
const UDialogueGraphNode* DialogueGraphNode = Cast<UDialogueGraphNode>(Node.GetGraphNode());
if (DialogueGraphNode == nullptr)
{
UE_LOG(LogDlgExportTwineCommandlet, Warning, TEXT("Invalid UDialogueGraphNode for Node index = %d in Dialogue = `%s`. Ignoring."), NodeIndex, *Dialogue.GetPathName());
return "";
}
const bool bIsRootNode = DialogueGraphNode->IsRootNode();
const FString NodeName = GetNodeNameFromNode(Node, NodeIndex, bIsRootNode);
FString Tags;
FIntPoint Position = GraphNodeToTwineCanvas(DialogueGraphNode->NodePosX, DialogueGraphNode->NodePosY);
// TODO fix this
TSharedPtr<SGraphNode> NodeWidget = DialogueGraphNode->GetNodeWidget();
FIntPoint Size = SizeLarge;
if (NodeWidget.IsValid())
{
Size = FIntPoint(NodeWidget->GetDesiredSize().X, NodeWidget->GetDesiredSize().Y);
}
FString NodeContent;
const FIntPoint Padding(20, 20);
if (DialogueGraphNode->IsRootNode())
{
verify(NodeIndex == INDEX_NONE);
Tags += TagNodeStart;
Size = SizeSmall;
Position = GetNonConflictingPointFor(Position, Size, Padding);
NodeContent += CreateTwinePassageDataLinksFromEdges(Dialogue, Node.GetNodeChildren());
return CreateTwinePassageData(NodeIndex, NodeName, Tags, Position, Size, NodeContent);
}
verify(NodeIndex >= 0);
if (DialogueGraphNode->IsVirtualParentNode())
{
// Edges from this node do not matter
Tags += TagNodeVirtualParent;
Position = GetNonConflictingPointFor(Position, Size, Padding);
//CurrentNodesAreas.Add(FIntRect(Position + Padding, Position + Size + Padding));
const UDlgNode_Speech& NodeSpeech = DialogueGraphNode->GetDialogueNode<UDlgNode_Speech>();
NodeContent += EscapeHtml(NodeSpeech.GetNodeUnformattedText().ToString());
NodeContent += TEXT("\n\n\n") + CreateTwinePassageDataLinksFromEdges(Dialogue, Node.GetNodeChildren(), true);
return CreateTwinePassageData(NodeIndex, NodeName, Tags, Position, Size, NodeContent);
}
if (DialogueGraphNode->IsSpeechNode())
{
Tags += TagNodeSpeech;
Position = GetNonConflictingPointFor(Position, Size, Padding);
//CurrentNodesAreas.Add(FIntRect(Position + Padding, Position + Size + Padding));
const UDlgNode_Speech& NodeSpeech = DialogueGraphNode->GetDialogueNode<UDlgNode_Speech>();
NodeContent += EscapeHtml(NodeSpeech.GetNodeUnformattedText().ToString());
NodeContent += TEXT("\n\n\n") + CreateTwinePassageDataLinksFromEdges(Dialogue, Node.GetNodeChildren());
return CreateTwinePassageData(NodeIndex, NodeName, Tags, Position, Size, NodeContent);
}
if (DialogueGraphNode->IsEndNode())
{
// Does not have any children/text
Tags += TagNodeEnd;
Size = SizeSmall;
Position = GetNonConflictingPointFor(Position, Size, Padding);
//CurrentNodesAreas.Add(FIntRect(Position + Padding, Position + Size + Padding));
NodeContent += TEXT("END");
return CreateTwinePassageData(NodeIndex, NodeName, Tags, Position, Size, NodeContent);
}
if (DialogueGraphNode->IsSelectorNode())
{
// Does not have any text and text for edges does not matter
if (DialogueGraphNode->IsSelectorFirstNode())
{
Tags += TagNodeSelectorFirst;
}
if (DialogueGraphNode->IsSelectorRandomNode())
{
Tags += TagNodeSelectorRandom;
}
Size = SizeSmall;
Position = GetNonConflictingPointFor(Position, Size, Padding);
NodeContent += TEXT("SELECTOR\n");
NodeContent += CreateTwinePassageDataLinksFromEdges(Dialogue, Node.GetNodeChildren(), true);
return CreateTwinePassageData(NodeIndex, NodeName, Tags, Position, Size, NodeContent);
}
if (DialogueGraphNode->IsSpeechSequenceNode())
{
Tags += TagNodeSpeechSequence;
Position = GetNonConflictingPointFor(Position, Size, Padding);
const UDlgNode_SpeechSequence& NodeSpeechSequence = DialogueGraphNode->GetDialogueNode<UDlgNode_SpeechSequence>();
// Fill sequence
const TArray<FDlgSpeechSequenceEntry>& Sequence = NodeSpeechSequence.GetNodeSpeechSequence();
for (int32 EntryIndex = 0; EntryIndex < Sequence.Num(); EntryIndex++)
{
const FDlgSpeechSequenceEntry& Entry = Sequence[EntryIndex];
NodeContent += FString::Printf(
TEXT("``Speaker:`` //%s//\n")
TEXT("``Text:`` //%s//\n")
TEXT("``EdgeText:`` //%s//\n"),
*EscapeHtml(Entry.Speaker.ToString()),
*EscapeHtml(Entry.Text.ToString()),
*EscapeHtml(Entry.EdgeText.ToString())
);
if (EntryIndex != Sequence.Num() - 1)
{
NodeContent += TEXT("---\n");
}
}
NodeContent += TEXT("\n\n\n") + CreateTwinePassageDataLinksFromEdges(Dialogue, Node.GetNodeChildren());
return CreateTwinePassageData(NodeIndex, NodeName, Tags, Position, Size, NodeContent);
}
UE_LOG(LogDlgExportTwineCommandlet, Warning, TEXT("Node index = %d not handled in Dialogue = `%s`. Ignoring."), NodeIndex, *Dialogue.GetPathName());
return "";
}
FString UDlgExportTwineCommandlet::GetNodeNameFromNode(const UDlgNode& Node, int32 NodeIndex, bool bIsRootNode)
{
return FString::Printf(TEXT("%d. %s"), NodeIndex, bIsRootNode ? TEXT("START") : *Node.GetNodeParticipantName().ToString());
}
FString UDlgExportTwineCommandlet::CreateTwinePassageDataLinksFromEdges(const UDlgDialogue& Dialogue, const TArray<FDlgEdge>& Edges, bool bNoTextOnEdges)
{
FString Links;
const TArray<UDlgNode*>& Nodes = Dialogue.GetNodes();
for (const FDlgEdge& Edge : Edges)
{
if (!Edge.IsValid())
{
continue;
}
if (!Nodes.IsValidIndex(Edge.TargetIndex))
{
UE_LOG(LogDlgExportTwineCommandlet, Warning, TEXT("Target index = %d not valid. Ignoring"), Edge.TargetIndex);
continue;
}
FString EdgeText;
if (bNoTextOnEdges || Edge.GetUnformattedText().IsEmpty())
{
EdgeText = FString::Printf(TEXT("~ignore~ To Node %d"), Edge.TargetIndex);
}
else
{
EdgeText = EscapeHtml(Edge.GetUnformattedText().ToString());
}
Links += FString::Printf(TEXT("[[%s|%s]]\n"), *EdgeText, *GetNodeNameFromNode(*Nodes[Edge.TargetIndex], Edge.TargetIndex, false));
}
Links.RemoveFromEnd(TEXT("\n"));
return Links;
}
FString UDlgExportTwineCommandlet::CreateTwinePassageData(int32 Pid, const FString& Name, const FString& Tags, const FIntPoint& Position, const FIntPoint& Size, const FString& Content)
{
return FString::Printf(
TEXT("<tw-passagedata pid=\"%d\" name=\"%s\" tags=\"%s\" position=\"%d, %d\" size=\"%d, %d\">%s</tw-passagedata>"),
Pid + 2, *Name, *Tags, Position.X, Position.Y, Size.X, Size.Y, *Content
);
}
FString UDlgExportTwineCommandlet::CreateTwineCustomCss()
{
return TEXT("#storyEditView.passage.tags div.cyan { background: #19e5e6; }");
}
FString UDlgExportTwineCommandlet::CreateTwineTagColorsData()
{
InitTwinetagNodesColors();
FString TagColorsString;
for (const auto& Elem : TwineTagNodesColorsMap)
{
TagColorsString += FString::Printf(
TEXT("<tw-tag name=\"%s\" color=\"%s\"></tw-tag>\n"),
*Elem.Key, *Elem.Value
);
}
return TagColorsString;
}
void UDlgExportTwineCommandlet::InitTwinetagNodesColors()
{
if (TwineTagNodesColorsMap.Num() > 0)
{
return;
}
TwineTagNodesColorsMap.Add(TagNodeStart, TEXT("green"));
TwineTagNodesColorsMap.Add(TagNodeEnd, TEXT("red"));
TwineTagNodesColorsMap.Add(TagNodeVirtualParent, TEXT("blue"));
TwineTagNodesColorsMap.Add(TagNodeSpeech, TEXT("blue"));
TwineTagNodesColorsMap.Add(TagNodeSpeechSequence, TEXT("blue"));
TwineTagNodesColorsMap.Add(TagNodeSelectorFirst, TEXT("purple"));
TwineTagNodesColorsMap.Add(TagNodeSelectorRandom, TEXT("yellow"));
}
| 35.36961 | 184 | 0.743745 | derossm |
c6ca0d727904f77b73da4471badfb5bdca03db13 | 2,235 | cpp | C++ | Plataformer_2D/Motor2D/UI_button.cpp | marcpt98/Plataformer-2D | edeb43bc3c886293bcc6bdece9e831d5e5eecdf0 | [
"Unlicense"
] | 1 | 2020-02-24T11:14:38.000Z | 2020-02-24T11:14:38.000Z | Plataformer_2D/Motor2D/UI_button.cpp | marcpt98/Plataformer-2D | edeb43bc3c886293bcc6bdece9e831d5e5eecdf0 | [
"Unlicense"
] | null | null | null | Plataformer_2D/Motor2D/UI_button.cpp | marcpt98/Plataformer-2D | edeb43bc3c886293bcc6bdece9e831d5e5eecdf0 | [
"Unlicense"
] | null | null | null | #include "UI_Button.h"
#include "j1App.h"
#include "j1Render.h"
#include "UI_Button.h"
#include "j1App.h"
#include "j1Scene_UI.h"
#include "j1Render.h"
#include "j1Input.h"
#include "p2Log.h"
#include "j1Audio.h"
void UI_button::BlitElement()
{
BROFILER_CATEGORY("Blitbutton", Profiler::Color::OldLace)
iPoint globalPos = calculateAbsolutePosition();
App->input->GetMousePosition(x, y);
ChangeVolume();
switch (state)
{
case STANDBY:
if (element_action != SLIDER_BUTTON && element_action != SLIDER_FX_BUTTON) {
App->render->Blit(texture, globalPos.x, globalPos.y, §ion, false);
}
else {
App->render->Blit(texture, localPosition.x, globalPos.y, §ion, false);
}
break;
case MOUSEOVER:
if (element_action != SLIDER_BUTTON && element_action != SLIDER_FX_BUTTON) {
App->render->Blit(texture, globalPos.x - 10, globalPos.y - 3, &OnMouse, false);
}
else {
App->render->Blit(texture, localPosition.x, globalPos.y, §ion, false);
}
break;
case CLICKED:
if (element_action != SLIDER_BUTTON && element_action != SLIDER_FX_BUTTON) {
App->render->Blit(texture, globalPos.x, globalPos.y, &OnClick, false);
}
else {
newposition = x;
App->render->Blit(texture, localPosition.x -10, globalPos.y, §ion, false);
}
break;
}
}
void UI_button::ChangeVolume()
{
if (App->sceneui->slider_volume == true && x > 206 && x < 760 && element_action == SLIDER_BUTTON)//206 760
{
localPosition.x = x-10;
save_position = x;
OnMouse.x = x;
Tick.x = x;
OnClick.x = x;
iPoint globalPos=calculateAbsolutePosition();
LOG("position: %i", localPosition.x);//197 746
musicvolume = (((localPosition.x - 197) * 1.) / 552);
App->audio->setMusicVolume(musicvolume);
LOG("position: %f", musicvolume);
}
if (App->sceneui->fx_volume == true && x > 206 && x < 760 && element_action == SLIDER_FX_BUTTON)//206 760
{
localPosition.x = x - 10;
save_position = x;
OnMouse.x = x;
Tick.x = x;
OnClick.x = x;
iPoint globalPos = calculateAbsolutePosition();
LOG("position: %i", localPosition.x);//197 746
fxvolume = (((localPosition.x-197) * 1.) / 552);
App->audio->setFxVolume(fxvolume);
LOG("position: %f", musicvolume);
}
}//App->audio->setMusicVolume(0.2);
| 27.592593 | 107 | 0.672036 | marcpt98 |
c6caae90dcdd350a46bab6e49dcd4efccbbd6b18 | 1,457 | cc | C++ | code/qttoolkit/contentbrowser/code/widgets/models/physicsnodehandler.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/qttoolkit/contentbrowser/code/widgets/models/physicsnodehandler.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/qttoolkit/contentbrowser/code/widgets/models/physicsnodehandler.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z | //------------------------------------------------------------------------------
// physicsnodehandler.cc
// (C) 2016 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "physicsnodehandler.h"
namespace Widgets
{
__ImplementClass(Widgets::PhysicsNodeHandler, 'PHNR', Core::RefCounted);
//------------------------------------------------------------------------------
/**
*/
PhysicsNodeHandler::PhysicsNodeHandler()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
PhysicsNodeHandler::~PhysicsNodeHandler()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void
PhysicsNodeHandler::AddNode(const Util::String& name)
{
QLabel* label = new QLabel;
label->setAlignment(Qt::AlignRight);
label->setText(name.AsCharPtr());
this->ui->nodeFrame->layout()->addWidget(label);
this->labels.Append(label);
}
//------------------------------------------------------------------------------
/**
*/
void
PhysicsNodeHandler::Discard()
{
IndexT i;
for (i = 0; i < this->labels.Size(); i++)
{
delete this->labels[i];
}
this->labels.Clear();
}
//------------------------------------------------------------------------------
/**
*/
void
PhysicsNodeHandler::OnMaterialChanged(int index)
{
//this->modelHandler->GetPhysics()->set
}
} // namespace Widgets | 22.765625 | 80 | 0.423473 | gscept |
c6cda49d327bf72afc71dab3d78fba575e97af35 | 229 | inl | C++ | include/beluga/tcp/tcp_server.inl | Stazer/beluga | 38232796669524c4f6b08f281e5a367390de24d0 | [
"MIT"
] | 1 | 2021-04-16T08:37:37.000Z | 2021-04-16T08:37:37.000Z | include/beluga/tcp/tcp_server.inl | Stazer/beluga | 38232796669524c4f6b08f281e5a367390de24d0 | [
"MIT"
] | null | null | null | include/beluga/tcp/tcp_server.inl | Stazer/beluga | 38232796669524c4f6b08f281e5a367390de24d0 | [
"MIT"
] | null | null | null | template <typename... args>
std::shared_ptr<beluga::tcp_server> beluga::tcp_server::create(args&&... params)
{
// TODO std::make_shared
return std::shared_ptr<tcp_server>(new tcp_server(std::forward<args>(params)...));
}
| 32.714286 | 86 | 0.703057 | Stazer |
c6d03f1cbec76c59ab232b04369b88501a5eaad8 | 4,712 | cpp | C++ | unicorn-bios/UB/FAT/DAP.cpp | macmade/unicorn-bios | 97a53ff5c8c418e79f0f5798da3d365b2ceaa7f2 | [
"MIT"
] | 96 | 2019-07-23T20:32:38.000Z | 2022-02-13T23:55:27.000Z | unicorn-bios/UB/FAT/DAP.cpp | macmade/unicorn-bios | 97a53ff5c8c418e79f0f5798da3d365b2ceaa7f2 | [
"MIT"
] | null | null | null | unicorn-bios/UB/FAT/DAP.cpp | macmade/unicorn-bios | 97a53ff5c8c418e79f0f5798da3d365b2ceaa7f2 | [
"MIT"
] | 20 | 2019-07-30T03:46:45.000Z | 2022-02-03T12:03:26.000Z | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019 Jean-David Gadina - www.xs-labs.com
*
* 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 "UB/FAT/DAP.hpp"
#include "UB/BinaryStream.hpp"
namespace UB
{
namespace FAT
{
class DAP::IMPL
{
public:
IMPL( void );
IMPL( const IMPL & o );
IMPL( BinaryStream & stream );
~IMPL( void );
uint8_t _size;
uint8_t _zero;
uint16_t _numberOfSectors;
uint16_t _destinationOffset;
uint16_t _destinationSegment;
uint64_t _logicalBlockAddress;
};
size_t DAP::DataSize( void )
{
return 16;
}
DAP::DAP( void ):
impl( std::make_unique< IMPL >() )
{}
DAP::DAP( const DAP & o ):
impl( std::make_unique< IMPL >( *( o.impl ) ) )
{}
DAP::DAP( BinaryStream & stream ):
impl( std::make_unique< IMPL >( stream ) )
{}
DAP::DAP( DAP && o ) noexcept:
impl( std::move( o.impl ) )
{}
DAP::~DAP( void )
{}
DAP & DAP::operator =( DAP o )
{
swap( *( this ), o );
return *( this );
}
uint8_t DAP::size( void ) const
{
return this->impl->_size;
}
uint8_t DAP::zero( void ) const
{
return this->impl->_zero;
}
uint16_t DAP::numberOfSectors( void ) const
{
return this->impl->_numberOfSectors;
}
uint16_t DAP::destinationOffset( void ) const
{
return this->impl->_destinationOffset;
}
uint16_t DAP::destinationSegment( void ) const
{
return this->impl->_destinationSegment;
}
uint64_t DAP::logicalBlockAddress( void ) const
{
return this->impl->_logicalBlockAddress;
}
void swap( DAP & o1, DAP & o2 )
{
using std::swap;
swap( o1.impl, o2.impl );
}
DAP::IMPL::IMPL( void ):
_size( 0 ),
_zero( 0 ),
_numberOfSectors( 0 ),
_destinationOffset( 0 ),
_destinationSegment( 0 ),
_logicalBlockAddress( 0 )
{}
DAP::IMPL::IMPL( BinaryStream & stream ):
_size( stream.readUInt8() ),
_zero( stream.readUInt8() ),
_numberOfSectors( stream.readLittleEndianUInt16() ),
_destinationOffset( stream.readLittleEndianUInt16() ),
_destinationSegment( stream.readLittleEndianUInt16() ),
_logicalBlockAddress( stream.readLittleEndianUInt16() )
{}
DAP::IMPL::IMPL( const IMPL & o ):
_size( o._size ),
_zero( o._zero ),
_numberOfSectors( o._numberOfSectors ),
_destinationOffset( o._destinationOffset ),
_destinationSegment( o._destinationSegment ),
_logicalBlockAddress( o._logicalBlockAddress )
{}
DAP::IMPL::~IMPL( void )
{}
}
}
| 31.837838 | 80 | 0.500212 | macmade |
c6d16090d4b50170b20214d663036fdd6c2a0041 | 14,482 | hh | C++ | dune/hdd/linearelliptic/discreteproblem.hh | tobiasleibner/dune-hdd | 35a122c1c6fd019aebbdbb8ee1eb8a36ae2f2b26 | [
"BSD-2-Clause"
] | null | null | null | dune/hdd/linearelliptic/discreteproblem.hh | tobiasleibner/dune-hdd | 35a122c1c6fd019aebbdbb8ee1eb8a36ae2f2b26 | [
"BSD-2-Clause"
] | null | null | null | dune/hdd/linearelliptic/discreteproblem.hh | tobiasleibner/dune-hdd | 35a122c1c6fd019aebbdbb8ee1eb8a36ae2f2b26 | [
"BSD-2-Clause"
] | null | null | null | // This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_DISCRETEPROBLEM_HH
#define DUNE_HDD_LINEARELLIPTIC_DISCRETEPROBLEM_HH
#include <memory>
#include <limits>
#include <boost/numeric/conversion/cast.hpp>
#include <dune/stuff/common/disable_warnings.hh>
# include <dune/common/mpihelper.hh>
# include <dune/common/timer.hh>
# if HAVE_DUNE_FEM
# include <dune/fem/misc/mpimanager.hh>
# endif
#include <dune/stuff/common/reenable_warnings.hh>
#if HAVE_DUNE_GRID_MULTISCALE
# include <dune/grid/multiscale/provider.hh>
#endif
#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/grid/provider.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/grid/layers.hh>
#include <dune/stuff/common/memory.hh>
#include "problems.hh"
namespace Dune {
namespace HDD {
namespace LinearElliptic {
template< class GridImp >
class DiscreteProblem
{
public:
typedef GridImp GridType;
typedef Stuff::Grid::ProviderInterface< GridType > GridProviderType;
private:
typedef Stuff::GridProviders< GridType > GridProviders;
typedef typename GridType::LeafIntersection IntersectionType;
typedef Stuff::Grid::BoundaryInfoProvider< IntersectionType > BoundaryInfoProvider;
typedef typename GridType::template Codim< 0 >::Entity EntityType;
typedef typename GridType::ctype DomainFieldType;
static const unsigned int dimDomain = GridType::dimension;
public:
typedef double RangeFieldType;
static const unsigned int dimRange = 1;
typedef LinearElliptic::ProblemInterface< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType;
typedef LinearElliptic::ProblemsProvider< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemsProvider;
static void write_config(const std::string filename, const std::string id)
{
std::ofstream file;
file.open(filename);
file << "[" << id << "]" << std::endl;
write_keys_to_file("gridprovider", GridProviders::available(), file);
write_keys_to_file("boundaryinfo", BoundaryInfoProvider::available(), file);
write_keys_to_file("problem", ProblemsProvider::available(), file);
file << "[logging]" << std::endl;
file << "info = true" << std::endl;
file << "debug = true" << std::endl;
file << "file = false" << std::endl;
file << "visualize = true" << std::endl;
file << "[parameter]" << std::endl;
file << "0.diffusion_factor = [0.1 0.1 1.0 1.0]" << std::endl;
file << "1.diffusion_factor = [1.0 1.0 0.1 0.1]" << std::endl;
write_config_to_file< GridProviders >(file);
write_config_to_file< BoundaryInfoProvider >(file);
write_config_to_file< ProblemsProvider >(file);
file.close();
} // ... write_config(...)
DiscreteProblem(const std::string id, const std::vector< std::string >& arguments)
{
// mpi
assert(arguments.size() < std::numeric_limits< int >::max());
int argc = boost::numeric_cast< int >(arguments.size());
char** argv = Stuff::Common::String::vectorToMainArgs(arguments);
#if HAVE_DUNE_FEM
Fem::MPIManager::initialize(argc, argv);
#else
MPIHelper::instance(argc, argv);
#endif
// configuration
config_ = Stuff::Common::Configuration(argc, argv, id + ".cfg");
if (!config_.has_sub(id))
DUNE_THROW(Stuff::Exceptions::configuration_error,
"Missing sub '" << id << "' in the following Configuration:\n\n" << config_);
filename_ = config_.get(id + ".filename", id);
// logger
const Stuff::Common::Configuration logger_config = config_.sub("logging");
int log_flags = Stuff::Common::LOG_CONSOLE;
debug_logging_ = logger_config.get< bool >("debug", false);
if (logger_config.get< bool >("info"))
log_flags = log_flags | Stuff::Common::LOG_INFO;
if (debug_logging_)
log_flags = log_flags | Stuff::Common::LOG_DEBUG;
if (logger_config.get< bool >("file", false))
log_flags = log_flags | Stuff::Common::LOG_FILE;
Stuff::Common::Logger().create(log_flags, id, "", "");
auto& info = Stuff::Common::Logger().info();
Timer timer;
const std::string griprovider_type = config_.get< std::string >(id + ".gridprovider");
info << "creating grid with '" << griprovider_type << "'... " << std::flush;
grid_provider_ = GridProviders::create(griprovider_type, config_);
const auto grid_view = grid_provider_->leaf_view();
info << " done (took " << timer.elapsed()
<< "s, has " << grid_view.indexSet().size(0) << " element";
if (grid_view.indexSet().size(0) > 1)
info << "s";
info << ")" << std::endl;
const std::string boundary_info_type = config_.get< std::string >(id + ".boundaryinfo");
if (config_.has_sub(boundary_info_type))
boundary_info_ = config_.sub(boundary_info_type);
else
boundary_info_ = Stuff::Common::Configuration("type", boundary_info_type);
info << "setting up ";
timer.reset();
const std::string problem_type = config_.get< std::string >(id + ".problem");
if (!debug_logging_)
info << "'" << problem_type << "'... " << std::flush;
problem_ = ProblemsProvider::create(problem_type, config_);
if (debug_logging_)
info << *problem_ << std::endl;
else
info << "done (took " << timer.elapsed() << "s)" << std::endl;
if (logger_config.get("visualize", true)) {
info << "visualizing grid and problem... " << std::flush;
timer.reset();
grid_provider_->visualize(boundary_info_, filename_ + ".grid");
problem_->visualize(grid_view, filename_ + ".problem");
info << "done (took " << timer.elapsed() << "s)" << std::endl;
} // if (visualize)
} // DiscreteProblem
std::string filename() const
{
return filename_;
}
const Stuff::Common::Configuration& config() const
{
return config_;
}
bool debug_logging() const
{
return debug_logging_;
}
GridProviderType& grid_provider()
{
return *grid_provider_;
}
const GridProviderType& grid_provider() const
{
return *grid_provider_;
}
const Stuff::Common::Configuration& boundary_info() const
{
return boundary_info_;
}
const ProblemType& problem() const
{
return *problem_;
}
private:
static void write_keys_to_file(const std::string name, const std::vector< std::string > keys, std::ofstream& file)
{
std::string whitespace = Stuff::Common::whitespaceify(name + " = ");
file << name << " = " << keys[0] << std::endl;
for (size_t ii = 1; ii < keys.size(); ++ii)
file << whitespace << keys[ii] << std::endl;
} // ... write_keys_to_file(...)
template< class ConfigProvider >
static void write_config_to_file(std::ofstream& file)
{
for (const auto& type : ConfigProvider::available()) {
auto config = ConfigProvider::default_config(type, type);
if (!config.empty())
file << config;
}
} // ... write_config_to_file(...)
std::string filename_;
Stuff::Common::Configuration config_;
bool debug_logging_;
std::unique_ptr< GridProviderType > grid_provider_;
Stuff::Common::Configuration boundary_info_;
std::unique_ptr< const ProblemType > problem_;
}; // class DiscreteProblem
#if HAVE_DUNE_GRID_MULTISCALE
template< class GridImp >
class DiscreteBlockProblem
{
public:
typedef GridImp GridType;
typedef grid::Multiscale::ProviderInterface< GridType > GridProviderType;
typedef grid::Multiscale::MsGridProviders< GridType > GridProviders;
typedef typename GridType::LeafIntersection IntersectionType;
typedef Stuff::Grid::BoundaryInfoProvider< IntersectionType > BoundaryInfoProvider;
typedef typename GridType::template Codim< 0 >::Entity EntityType;
typedef typename GridType::ctype DomainFieldType;
static const unsigned int dimDomain = GridType::dimension;
typedef double RangeFieldType;
static const unsigned int dimRange = 1;
typedef LinearElliptic::ProblemInterface
< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType;
typedef LinearElliptic::ProblemsProvider
< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemsProvider;
static void write_config(const std::string filename,
const std::string id,
const Stuff::Common::Configuration& problem_cfg = Stuff::Common::Configuration(),
const Stuff::Common::Configuration& grid_cfg = Stuff::Common::Configuration(),
const Stuff::Common::Configuration& additional_cfg = Stuff::Common::Configuration())
{
std::ofstream file;
file.open(filename);
file << "[" << id << "]" << std::endl;
if (grid_cfg.has_key("type"))
file << "gridprovider = " << grid_cfg.get< std::string >("type") << std::endl;
else
write_keys_to_file("gridprovider", GridProviders::available(), file);
if (problem_cfg.has_key("type"))
file << "problem = " << problem_cfg.get< std::string >("type") << std::endl;
else
write_keys_to_file("problem", ProblemsProvider::available(), file);
file << "[logging]" << std::endl;
file << "info = true" << std::endl;
file << "debug = false" << std::endl;
file << "file = false" << std::endl;
file << "visualize = true" << std::endl;
if (grid_cfg.has_key("type"))
file << Stuff::Common::Configuration(grid_cfg, grid_cfg.get< std::string >("type"));
else
write_config_to_file< GridProviders >(file);
if (problem_cfg.has_key("type"))
file << Stuff::Common::Configuration(problem_cfg, problem_cfg.get< std::string >("type"));
else
write_config_to_file< ProblemsProvider >(file);
file << additional_cfg;
file.close();
} // ... write_config(...)
DiscreteBlockProblem(const std::string id, const std::vector< std::string >& arguments)
{
// mpi
int argc = boost::numeric_cast< int >(arguments.size());
char** argv = Stuff::Common::String::vectorToMainArgs(arguments);
#if HAVE_DUNE_FEM
Fem::MPIManager::initialize(argc, argv);
#else
MPIHelper::instance(argc, argv);
#endif
// configuration
config_ = Stuff::Common::Configuration(argc, argv, id + ".cfg");
if (!config_.has_sub(id))
DUNE_THROW(Stuff::Exceptions::configuration_error,
"Missing sub '" << id << "' in the following Configuration:\n\n" << config_);
filename_ = config_.get(id + ".filename", id);
// logger
const Stuff::Common::Configuration logger_config = config_.sub("logging");
int log_flags = Stuff::Common::LOG_CONSOLE;
debug_logging_ = logger_config.get< bool >("debug", false);
if (logger_config.get< bool >("info"))
log_flags = log_flags | Stuff::Common::LOG_INFO;
if (debug_logging_)
log_flags = log_flags | Stuff::Common::LOG_DEBUG;
if (logger_config.get< bool >("file", false))
log_flags = log_flags | Stuff::Common::LOG_FILE;
Stuff::Common::Logger().create(log_flags, id, "", "");
auto& info = Stuff::Common::Logger().info();
Timer timer;
const std::string griprovider_type = config_.get< std::string >(id + ".gridprovider");
info << "creating grid with '" << griprovider_type << "'..." << std::flush;
grid_provider_ = GridProviders::create(griprovider_type, config_);
const auto grid_view = grid_provider_->leaf_view();
info << " done (took " << timer.elapsed()
<< "s, has " << grid_view.indexSet().size(0) << " element";
if (grid_view.indexSet().size(0) > 1)
info << "s";
info << ")" << std::endl;
boundary_info_ = Stuff::Grid::BoundaryInfoConfigs::AllDirichlet::default_config();
// info << "setting up ";
// timer.reset();
const std::string problem_type = config_.get< std::string >(id + ".problem");
// if (!debug_logging_)
// info << "'" << problem_type << "'... " << std::flush;
problem_ = ProblemsProvider::create(problem_type, config_);
// if (debug_logging_)
// info << *problem_ << std::endl;
// else
// info << "done (took " << timer.elapsed() << "s)" << std::endl;
if (logger_config.get("visualize", true)) {
info << "visualizing grid and problem... " << std::flush;
timer.reset();
grid_provider_->visualize(filename_ + ".ms_grid", false);
grid_provider_->visualize(boundary_info_, filename_ + ".grid");
problem_->visualize(grid_view, filename_ + ".problem");
info << "done (took " << timer.elapsed() << "s)" << std::endl;
} // if (visualize)
} // DiscreteBlockProblem
std::string filename() const
{
return filename_;
}
const Stuff::Common::Configuration& config() const
{
return config_;
}
bool debug_logging() const
{
return debug_logging_;
}
GridProviderType& grid_provider()
{
return *grid_provider_;
}
const GridProviderType& grid_provider() const
{
return *grid_provider_;
}
const Stuff::Common::Configuration& boundary_info() const
{
return boundary_info_;
}
const ProblemType& problem() const
{
return *problem_;
}
private:
static void write_keys_to_file(const std::string name, const std::vector< std::string > keys, std::ofstream& file)
{
std::string whitespace = Stuff::Common::whitespaceify(name + " = ");
file << name << " = " << keys[0] << std::endl;
for (size_t ii = 1; ii < keys.size(); ++ii)
file << whitespace << keys[ii] << std::endl;
} // ... write_keys_to_file(...)
template< class ConfigProvider >
static void write_config_to_file(std::ofstream& file)
{
for (const auto& type : ConfigProvider::available()) {
auto config = ConfigProvider::default_config(type, type);
if (!config.empty())
file << config;
}
} // ... write_config_to_file(...)
std::string filename_;
Stuff::Common::Configuration config_;
bool debug_logging_;
std::unique_ptr< GridProviderType > grid_provider_;
Stuff::Common::Configuration boundary_info_;
std::unique_ptr< const ProblemType > problem_;
}; // class DiscreteBlockProblem
#endif // HAVE_DUNE_GRID_MULTISCALE
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_DISCRETEPROBLEM_HH
| 35.408313 | 128 | 0.66593 | tobiasleibner |
c6d4482769886d70fab3078b6cab93305126ed75 | 2,721 | hpp | C++ | Axis.Capsicum/services/memory/gpu/BcBlockLayout.hpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | 2 | 2021-07-23T08:49:54.000Z | 2021-07-29T22:07:30.000Z | Axis.Capsicum/services/memory/gpu/BcBlockLayout.hpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | null | null | null | Axis.Capsicum/services/memory/gpu/BcBlockLayout.hpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | null | null | null | #pragma once
#include "services/memory/MemoryLayout.hpp"
namespace axis { namespace services { namespace memory { namespace gpu {
/**
* Describes memory layout of a boundary condition descriptor block.
*/
class BcBlockLayout : public axis::services::memory::MemoryLayout
{
public:
/**
* Constructor.
*
* @param specificDataSize Total length of data that is specific to boundary
* condition implementation.
*/
BcBlockLayout(int specificDataSize);
virtual ~BcBlockLayout(void);
virtual MemoryLayout& Clone( void ) const;
/**
* Initialises the memory block.
*
* @param [in,out] targetBlock Base memory address of the target block.
* @param dofId Unique identifier of the associated degree of
* freedom.
*/
void InitMemoryBlock(void *targetBlock, uint64 dofId);
/**
* Returns the base address of boundary condition implementation-related data.
*
* @param [in,out] bcBaseAddress Base memory address of the boundary condition
* descriptor block.
*
* @return The custom data base address.
*/
void *GetCustomDataAddress(void *bcBaseAddress) const;
/**
* Returns the base address of boundary condition implementation-related data.
*
* @param [in,out] bcBaseAddress Base memory address of the boundary condition
* descriptor block.
*
* @return The custom data base address.
*/
const void *GetCustomDataAddress(const void *bcBaseAddress) const;
/**
* Returns the address of the output slot where the boundary condition shall
* write its updated value.
*
* @param [in,out] bcBaseAddress Base memory address of the boundary condition
* descriptor block.
*
* @return The output slot address.
*/
real *GetOutputBucketAddress(void *bcBaseAddress) const;
/**
* Returns the address of the output slot where the boundary condition shall
* write its updated value.
*
* @param [in,out] bcBaseAddress Base memory address of the boundary condition
* descriptor block.
*
* @return The output slot address.
*/
const real *GetOutputBucketAddress(const void *bcBaseAddress) const;
/**
* Returns the unique identifier of the degree of freedom associated to this
* boundary condition.
*
* @param [in,out] bcBaseAddress Base memory address of the boundary condition
* descriptor block.
*
* @return The degree of freedom identifier.
*/
uint64 GetDofId(void *bcBaseAddress) const;
private:
virtual size_type DoGetSegmentSize( void ) const;
real blockSize_;
};
} } } } // namespace axis::services::memory::gpu
| 29.901099 | 80 | 0.670342 | renato-yuzup |
c6d6869a2c901168d82504b9f3d7aa7a31c4f8dc | 453 | cpp | C++ | 18_minimum_path_sum.cpp | Mohit-Nathrani/30-day-leetcoding-challenge | 7eff9bb3faee8b7a720b6a712226319b9a56d588 | [
"MIT"
] | null | null | null | 18_minimum_path_sum.cpp | Mohit-Nathrani/30-day-leetcoding-challenge | 7eff9bb3faee8b7a720b6a712226319b9a56d588 | [
"MIT"
] | null | null | null | 18_minimum_path_sum.cpp | Mohit-Nathrani/30-day-leetcoding-challenge | 7eff9bb3faee8b7a720b6a712226319b9a56d588 | [
"MIT"
] | null | null | null | class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int n=grid.size();
int m=grid[0].size();
for(int i=n-1;i>=0;i--){
for(int j=m-1;j>=0;j--){
if(j<m-1 && i<n-1) grid[i][j]+=min(grid[i][j+1], grid[i+1][j]);
else if(j<m-1) grid[i][j]+=grid[i][j+1];
else if(i<n-1) grid[i][j]+=grid[i+1][j];
}
}
return grid[0][0];
}
}; | 30.2 | 79 | 0.412804 | Mohit-Nathrani |
c6d7410ecf178a28f536f0694339d7380d7e4c84 | 1,561 | cpp | C++ | C++/prison-cells-after-n-days.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/prison-cells-after-n-days.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/prison-cells-after-n-days.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(1)
// Space: O(1)
class Solution {
public:
vector<int> prisonAfterNDays(vector<int>& cells, int N) {
for (N = (N - 1) % 14 + 1; N > 0; --N) {
vector<int> cells2(8);
for (int i = 1; i < 7; ++i) {
cells2[i] = static_cast<int>(cells[i - 1] == cells[i + 1]);
}
cells = move(cells2);
}
return cells;
}
};
// Time: O(1)
// Space: O(1)
class Solution2 {
public:
vector<int> prisonAfterNDays(vector<int>& cells, int N) {
unordered_map<vector<int>, int, VectorHash<int>> lookup;
while (N) {
lookup[cells] = N--;
vector<int> cells2(8);
for (int i = 1; i < 7; ++i) {
cells2[i] = static_cast<int>(cells[i - 1] == cells[i + 1]);
}
cells = move(cells2);
if (lookup.count(cells)) {
N %= lookup[cells] - N;
break;
}
}
while (N--) {
vector<int> cells2(8);
for (int i = 1; i < 7; ++i) {
cells2[i] = static_cast<int>(cells[i - 1] == cells[i + 1]);
}
cells = move(cells2);
}
return cells;
}
private:
template<typename T>
struct VectorHash {
size_t operator()(const std::vector<T>& v) const {
size_t seed = 0;
for (const auto& i : v) {
seed ^= std::hash<T>{}(i) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}
return seed;
}
};
};
| 26.457627 | 80 | 0.424728 | jaiskid |
c6d82bcc9c0861f6854916b85589305a014d48e5 | 199 | cpp | C++ | NetServer/MessageParser.cpp | CRAFTSTARCN/PlayBall-Server | c50974a2e688ad0834e5381a6a202d7e2b896799 | [
"Apache-2.0"
] | 1 | 2021-06-14T16:14:43.000Z | 2021-06-14T16:14:43.000Z | NetServer/MessageParser.cpp | CRAFTSTARCN/PlayBall-Server | c50974a2e688ad0834e5381a6a202d7e2b896799 | [
"Apache-2.0"
] | null | null | null | NetServer/MessageParser.cpp | CRAFTSTARCN/PlayBall-Server | c50974a2e688ad0834e5381a6a202d7e2b896799 | [
"Apache-2.0"
] | null | null | null | /*
MessageParser.cpp Created 2021/6/14
By: Ag2S
*/
#include "MessageParser.h"
DataObject* MessageParser::generalStrParser(const std::string str, int& st) {
//TODO
return nullptr;
} | 16.583333 | 77 | 0.678392 | CRAFTSTARCN |
c6d947fe9fe3a2c82918b29766a7d62042f8bf2e | 259 | cpp | C++ | tests/test.cpp | CrestoniX/Lab3.0 | 7c01142ca420628cd97d5e053d17b79870214de0 | [
"MIT"
] | null | null | null | tests/test.cpp | CrestoniX/Lab3.0 | 7c01142ca420628cd97d5e053d17b79870214de0 | [
"MIT"
] | null | null | null | tests/test.cpp | CrestoniX/Lab3.0 | 7c01142ca420628cd97d5e053d17b79870214de0 | [
"MIT"
] | 1 | 2019-12-27T11:28:32.000Z | 2019-12-27T11:28:32.000Z | // Copyright 2019 CrestoniX <loltm.crav4enko@gmail.com>
#include <gtest/gtest.h>
#include <SharedPtr.hpp>
TEST(Control_Block, Test) {
EXPECT_EQ(counter, 0);
}
TEST(SharedPtr, Tests) {
EXPECT_EQ(ptr, nullptr);
EXPECT_EQ(control_block, nullptr);
}
| 21.583333 | 55 | 0.714286 | CrestoniX |
c6dfbbc588926fc16cfdd360435abba247d4b596 | 813 | cpp | C++ | WrecklessEngine/PixelShader.cpp | ThreadedStream/WrecklessEngine | 735ac601914c2445b8eef72a14ec0fcd4d0d12d2 | [
"MIT"
] | 9 | 2021-02-07T21:33:41.000Z | 2022-03-20T18:48:06.000Z | WrecklessEngine/PixelShader.cpp | ThreadedStream/WrecklessEngine | 735ac601914c2445b8eef72a14ec0fcd4d0d12d2 | [
"MIT"
] | null | null | null | WrecklessEngine/PixelShader.cpp | ThreadedStream/WrecklessEngine | 735ac601914c2445b8eef72a14ec0fcd4d0d12d2 | [
"MIT"
] | 4 | 2021-02-11T15:05:35.000Z | 2022-02-20T15:26:35.000Z | #include "PixelShader.h"
#include "BindableCodex.h"
#include "Renderer.h"
using namespace Graphics;
namespace Bindable
{
PixelShader::PixelShader(const std::string& path)
{
m_pShader = Renderer::GetDevice()->CreatePixelShader(path);
}
void* PixelShader::GetByteCode() const noexcept
{
return m_pShader->GetByteCode();
}
Ref<PixelShader> PixelShader::Resolve(const std::string& path)
{
return Codex::Resolve<PixelShader>("Shaders/Bin/" + path);
}
std::string PixelShader::GenerateUID(const std::string& path)
{
using namespace std::string_literals;
return typeid(PixelShader).name() + "#"s + path;
}
std::string PixelShader::GetUID() const noexcept
{
return GenerateUID(m_Path);
}
void PixelShader::Bind() noxnd
{
Renderer::GetRenderContext()->BindPixelShader(m_pShader);
}
} | 20.846154 | 63 | 0.722017 | ThreadedStream |
c6e00c8d0d85c4247d5a39e261881883adf09d11 | 769 | cpp | C++ | examples/example.cpp | PDB-REDO/libcifpp | f97e742daa7c1cfd0670ad00d3aef004708a3461 | [
"BSD-2-Clause"
] | 7 | 2021-01-12T07:00:04.000Z | 2022-03-11T08:44:14.000Z | examples/example.cpp | PDB-REDO/libcifpp | f97e742daa7c1cfd0670ad00d3aef004708a3461 | [
"BSD-2-Clause"
] | 12 | 2021-03-11T17:53:45.000Z | 2022-02-09T15:06:04.000Z | examples/example.cpp | PDB-REDO/libcifpp | f97e742daa7c1cfd0670ad00d3aef004708a3461 | [
"BSD-2-Clause"
] | 7 | 2021-02-08T00:45:31.000Z | 2021-12-06T22:37:22.000Z | #include <iostream>
#include <filesystem>
#include <cif++/Cif++.hpp>
namespace fs = std::filesystem;
int main()
{
fs::path in("1cbs.cif.gz");
cif::File file;
file.loadDictionary("mmcif_pdbx_v50");
file.load("1cbs.cif.gz");
auto& db = file.firstDatablock()["atom_site"];
auto n = db.find(cif::Key("label_atom_id") == "OXT").size();
std::cout << "File contains " << db.size() << " atoms of which " << n << (n == 1 ? " is" : " are") << " OXT" << std::endl
<< "residues with an OXT are:" << std::endl;
for (const auto& [asym, comp, seqnr]: db.find<std::string,std::string,int>(
cif::Key("label_atom_id") == "OXT", "label_asym_id", "label_comp_id", "label_seq_id"))
{
std::cout << asym << ' ' << comp << ' ' << seqnr << std::endl;
}
return 0;
}
| 24.03125 | 122 | 0.590377 | PDB-REDO |
c6e38afb28a00f2a9a672c2613737b8e572c26fb | 238 | cpp | C++ | layout/buttons/main.cpp | janbodnar/Qt5-Code-Examples | 404a3789d6d815c6aac4a87a5b91ef3604246c06 | [
"BSD-2-Clause"
] | 5 | 2020-11-30T13:19:47.000Z | 2021-06-16T13:44:06.000Z | layout/buttons/main.cpp | janbodnar/Qt5-Code-Examples | 404a3789d6d815c6aac4a87a5b91ef3604246c06 | [
"BSD-2-Clause"
] | null | null | null | layout/buttons/main.cpp | janbodnar/Qt5-Code-Examples | 404a3789d6d815c6aac4a87a5b91ef3604246c06 | [
"BSD-2-Clause"
] | 3 | 2020-11-30T13:20:33.000Z | 2021-01-14T17:57:55.000Z | #include <QApplication>
#include "buttons.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
Buttons window;
window.resize(290, 170);
window.setWindowTitle("Buttons");
window.show();
return app.exec();
}
| 14.875 | 35 | 0.672269 | janbodnar |
c6e482539f28ec4dcc06e8671a02a7f88205cdf1 | 3,510 | cpp | C++ | webkit/WebCore/bindings/js/JSEventSourceConstructor.cpp | s1rcheese/nintendo-3ds-internetbrowser-sourcecode | 3dd05f035e0a5fc9723300623e9b9b359be64e11 | [
"Unlicense"
] | 15 | 2016-01-05T12:43:41.000Z | 2022-03-15T10:34:47.000Z | webkit/WebCore/bindings/js/JSEventSourceConstructor.cpp | s1rcheese/nintendo-3ds-internetbrowser-sourcecode | 3dd05f035e0a5fc9723300623e9b9b359be64e11 | [
"Unlicense"
] | null | null | null | webkit/WebCore/bindings/js/JSEventSourceConstructor.cpp | s1rcheese/nintendo-3ds-internetbrowser-sourcecode | 3dd05f035e0a5fc9723300623e9b9b359be64e11 | [
"Unlicense"
] | 2 | 2020-11-30T18:36:01.000Z | 2021-02-05T23:20:24.000Z | /*
* Copyright (C) 2009 Ericsson AB
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of Ericsson nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(EVENTSOURCE)
#include "JSEventSourceConstructor.h"
#include "EventSource.h"
#include "ExceptionCode.h"
#include "JSEventSource.h"
#include "ScriptExecutionContext.h"
#include <runtime/Error.h>
using namespace JSC;
namespace WebCore {
ASSERT_CLASS_FITS_IN_CELL(JSEventSourceConstructor);
const ClassInfo JSEventSourceConstructor::s_info = { "EventSourceContructor", 0, 0, 0 };
JSEventSourceConstructor::JSEventSourceConstructor(ExecState* exec, JSDOMGlobalObject* globalObject)
: DOMConstructorObject(JSEventSourceConstructor::createStructure(globalObject->objectPrototype()), globalObject)
{
putDirect(exec->propertyNames().prototype, JSEventSourcePrototype::self(exec, globalObject), None);
putDirect(exec->propertyNames().length, jsNumber(exec, 1), ReadOnly|DontDelete|DontEnum);
}
static JSObject* constructEventSource(ExecState* exec, JSObject* constructor, const ArgList& args)
{
if (args.size() < 1)
return throwError(exec, SyntaxError, "Not enough arguments");
UString url = args.at(0).toString(exec);
if (exec->hadException())
return 0;
JSEventSourceConstructor* jsConstructor = static_cast<JSEventSourceConstructor*>(constructor);
ScriptExecutionContext* context = jsConstructor->scriptExecutionContext();
if (!context)
return throwError(exec, ReferenceError, "EventSource constructor associated document is unavailable");
ExceptionCode ec = 0;
RefPtr<EventSource> eventSource = EventSource::create(url, context, ec);
if (ec) {
setDOMException(exec, ec);
return 0;
}
return asObject(toJS(exec, jsConstructor->globalObject(), eventSource.release()));
}
ConstructType JSEventSourceConstructor::getConstructData(ConstructData& constructData)
{
constructData.native.function = constructEventSource;
return ConstructTypeHost;
}
} // namespace WebCore
#endif // ENABLE(EVENTSOURCE)
| 38.152174 | 116 | 0.758405 | s1rcheese |
c6e7580b8051d09b7d05da670517da8de65da8fc | 702 | cpp | C++ | lldb/test/API/lang/cpp/namespace/ns3.cpp | AnthonyLatsis/llvm-project | 2acd6cdb9a4bfb2c34b701527e04dd4ffe791d74 | [
"Apache-2.0"
] | 21 | 2021-02-08T15:42:18.000Z | 2022-02-23T03:25:10.000Z | lldb/test/API/lang/cpp/namespace/ns3.cpp | AnthonyLatsis/llvm-project | 2acd6cdb9a4bfb2c34b701527e04dd4ffe791d74 | [
"Apache-2.0"
] | 3 | 2021-02-20T14:24:45.000Z | 2021-08-04T04:20:05.000Z | lldb/test/API/lang/cpp/namespace/ns3.cpp | AnthonyLatsis/llvm-project | 2acd6cdb9a4bfb2c34b701527e04dd4ffe791d74 | [
"Apache-2.0"
] | 6 | 2021-02-08T16:57:07.000Z | 2022-01-13T11:32:34.000Z | #include "ns.h"
extern int func();
// Note: the following function must be before the using.
void test_lookup_before_using_directive()
{
// BP_before_using_directive
std::printf("before using directive: func() = %d\n", func()); // eval func(), exp: 1
}
using namespace A;
void test_lookup_after_using_directive()
{
// BP_after_using_directive
//printf("func() = %d\n", func()); // eval func(), exp: error, amiguous
std::printf("after using directive: func2() = %d\n", func2()); // eval func2(), exp: 3
std::printf("after using directive: ::func() = %d\n", ::func()); // eval ::func(), exp: 1
std::printf("after using directive: B::func() = %d\n", B::func()); // eval B::func(), exp: 4
}
| 36.947368 | 94 | 0.645299 | AnthonyLatsis |
c6e85502a7c6d5db7ff0ef92ee83967fbc545f78 | 6,300 | cpp | C++ | src/record/SkRecordDraw.cpp | llluiop/skia | 0dd01ee5b5abc06935dced8430d5290c6ac3f958 | [
"BSD-3-Clause"
] | 1 | 2015-11-06T00:05:58.000Z | 2015-11-06T00:05:58.000Z | src/record/SkRecordDraw.cpp | llluiop/skia | 0dd01ee5b5abc06935dced8430d5290c6ac3f958 | [
"BSD-3-Clause"
] | null | null | null | src/record/SkRecordDraw.cpp | llluiop/skia | 0dd01ee5b5abc06935dced8430d5290c6ac3f958 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkRecordDraw.h"
namespace {
// This is an SkRecord visitor that will draw that SkRecord to an SkCanvas.
class Draw : SkNoncopyable {
public:
explicit Draw(SkCanvas* canvas) : fCanvas(canvas), fIndex(0), fClipEmpty(false) {}
unsigned index() const { return fIndex; }
void next() { ++fIndex; }
template <typename T> void operator()(const T& r) {
if (!this->canSkip(r)) {
this->draw(r);
this->updateClip<T>();
}
}
private:
// Can we skip this command right now?
template <typename T> bool canSkip(const T&) const {
// We can skip most commands if the clip is empty. Exceptions are specialized below.
return fClipEmpty;
}
// No base case, so we'll be compile-time checked that we implemented all possibilities below.
template <typename T> void draw(const T&);
// Update fClipEmpty if necessary.
template <typename T> void updateClip() {
// Most commands don't change the clip. Exceptions are specialized below.
}
SkCanvas* fCanvas;
unsigned fIndex;
bool fClipEmpty;
};
// These commands may change the clip.
#define UPDATE_CLIP(T) template <> void Draw::updateClip<SkRecords::T>() \
{ fClipEmpty = fCanvas->isClipEmpty(); }
UPDATE_CLIP(Restore);
UPDATE_CLIP(SaveLayer);
UPDATE_CLIP(ClipPath);
UPDATE_CLIP(ClipRRect);
UPDATE_CLIP(ClipRect);
UPDATE_CLIP(ClipRegion);
#undef UPDATE_CLIP
// These commands must always run.
#define CAN_SKIP(T) template <> bool Draw::canSkip(const SkRecords::T&) const { return false; }
CAN_SKIP(Restore);
CAN_SKIP(Save);
CAN_SKIP(SaveLayer);
CAN_SKIP(Clear);
CAN_SKIP(PushCull);
CAN_SKIP(PopCull);
#undef CAN_SKIP
// We can skip these commands if they're intersecting with a clip that's already empty.
#define CAN_SKIP(T) template <> bool Draw::canSkip(const SkRecords::T& r) const \
{ return fClipEmpty && SkRegion::kIntersect_Op == r.op; }
CAN_SKIP(ClipPath);
CAN_SKIP(ClipRRect);
CAN_SKIP(ClipRect);
CAN_SKIP(ClipRegion);
#undef CAN_SKIP
static bool can_skip_text(const SkCanvas& c, const SkPaint& p, SkScalar minY, SkScalar maxY) {
// If we're drawing vertical text, none of the checks we're about to do make any sense.
// We'll need to call SkPaint::computeFastBounds() later, so bail out if that's not possible.
if (p.isVerticalText() || !p.canComputeFastBounds()) {
return false;
}
// Rather than checking the top and bottom font metrics, we guess. Actually looking up the top
// and bottom metrics is slow, and this overapproximation should be good enough.
const SkScalar buffer = p.getTextSize() * 1.5f;
SkDEBUGCODE(SkPaint::FontMetrics metrics;)
SkDEBUGCODE(p.getFontMetrics(&metrics);)
SkASSERT(-buffer <= metrics.fTop);
SkASSERT(+buffer >= metrics.fBottom);
// Let the paint adjust the text bounds. We don't care about left and right here, so we use
// 0 and 1 respectively just so the bounds rectangle isn't empty.
SkRect bounds;
bounds.set(0, -buffer, SK_Scalar1, buffer);
SkRect adjusted = p.computeFastBounds(bounds, &bounds);
return c.quickRejectY(minY + adjusted.fTop, maxY + adjusted.fBottom);
}
template <> bool Draw::canSkip(const SkRecords::DrawPosTextH& r) const {
return fClipEmpty || can_skip_text(*fCanvas, r.paint, r.y, r.y);
}
template <> bool Draw::canSkip(const SkRecords::DrawPosText& r) const {
if (fClipEmpty) {
return true;
}
// TODO(mtklein): may want to move this minY/maxY calculation into a one-time pass
const unsigned points = r.paint.countText(r.text, r.byteLength);
if (points == 0) {
return true;
}
SkScalar minY = SK_ScalarInfinity, maxY = SK_ScalarNegativeInfinity;
for (unsigned i = 0; i < points; i++) {
minY = SkTMin(minY, r.pos[i].fY);
maxY = SkTMax(maxY, r.pos[i].fY);
}
return can_skip_text(*fCanvas, r.paint, minY, maxY);
}
#define DRAW(T, call) template <> void Draw::draw(const SkRecords::T& r) { fCanvas->call; }
DRAW(Restore, restore());
DRAW(Save, save(r.flags));
DRAW(SaveLayer, saveLayer(r.bounds, r.paint, r.flags));
DRAW(PopCull, popCull());
DRAW(Clear, clear(r.color));
DRAW(Concat, concat(r.matrix));
DRAW(SetMatrix, setMatrix(r.matrix));
DRAW(ClipPath, clipPath(r.path, r.op, r.doAA));
DRAW(ClipRRect, clipRRect(r.rrect, r.op, r.doAA));
DRAW(ClipRect, clipRect(r.rect, r.op, r.doAA));
DRAW(ClipRegion, clipRegion(r.region, r.op));
DRAW(DrawBitmap, drawBitmap(r.bitmap, r.left, r.top, r.paint));
DRAW(DrawBitmapMatrix, drawBitmapMatrix(r.bitmap, r.matrix, r.paint));
DRAW(DrawBitmapNine, drawBitmapNine(r.bitmap, r.center, r.dst, r.paint));
DRAW(DrawBitmapRectToRect, drawBitmapRectToRect(r.bitmap, r.src, r.dst, r.paint, r.flags));
DRAW(DrawDRRect, drawDRRect(r.outer, r.inner, r.paint));
DRAW(DrawOval, drawOval(r.oval, r.paint));
DRAW(DrawPaint, drawPaint(r.paint));
DRAW(DrawPath, drawPath(r.path, r.paint));
DRAW(DrawPoints, drawPoints(r.mode, r.count, r.pts, r.paint));
DRAW(DrawPosText, drawPosText(r.text, r.byteLength, r.pos, r.paint));
DRAW(DrawPosTextH, drawPosTextH(r.text, r.byteLength, r.xpos, r.y, r.paint));
DRAW(DrawRRect, drawRRect(r.rrect, r.paint));
DRAW(DrawRect, drawRect(r.rect, r.paint));
DRAW(DrawSprite, drawSprite(r.bitmap, r.left, r.top, r.paint));
DRAW(DrawText, drawText(r.text, r.byteLength, r.x, r.y, r.paint));
DRAW(DrawTextOnPath, drawTextOnPath(r.text, r.byteLength, r.path, r.matrix, r.paint));
DRAW(DrawVertices, drawVertices(r.vmode, r.vertexCount, r.vertices, r.texs, r.colors,
r.xmode.get(), r.indices, r.indexCount, r.paint));
#undef DRAW
// PushCull is a bit of a oddball. We might be able to just skip until just past its popCull.
template <> void Draw::draw(const SkRecords::PushCull& r) {
if (r.popOffset != SkRecords::kUnsetPopOffset && fCanvas->quickReject(r.rect)) {
fIndex += r.popOffset;
} else {
fCanvas->pushCull(r.rect);
}
}
} // namespace
void SkRecordDraw(const SkRecord& record, SkCanvas* canvas) {
for (Draw draw(canvas); draw.index() < record.count(); draw.next()) {
record.visit(draw.index(), draw);
}
}
| 36.416185 | 99 | 0.688095 | llluiop |